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 |
|---|---|---|---|---|---|
ntop/ntopng | scripts/lua/rest/v1/get/host/custom_data.lua | 1 | 3840 | --
-- (C) 2013-22 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
local json = require ("dkjson")
local tracker = require("tracker")
local rest_utils = require("rest_utils")
--
-- Read information about a host and maps host fields into custom fields
-- Example: curl -s -u admin:admin -H "Content-Type: application/json" -H "Content-Type: application/json" -d '{"host": "192.168.2.222", "ifid":"0"}' http://localhost:3000/lua/rest/v1/get/host/custom_data.lua
--
-- NOTE: in case of invalid login, no error is returned but redirected to login
--
local rc = rest_utils.consts.success.ok
local res = {}
local field_aliases = {}
local ifid = _GET["ifid"]
local fields = _GET["field_alias"]
if isEmptyString(ifid) then
rest_utils.answer(rest_utils.consts.err.invalid_interface)
return
end
interface.select(ifid)
-- Valid fields:
-- 1) All: {"field_alias": "all"} - Dump all host stats.
-- -- Or --
-- All: Omit the "field_alias" parameter.
-- 2) Aliases: {"field_alias": "bytes.sent=tdb,packets.sent=tdp"}
-- 3) Mixed: {"field_alias": "bytes.sent=tdb,packets.sent,ndpi=dpi"}
--
-- If the 'fields' parameter is missing 'all' host stat
-- fields will be dumped...
if (fields == nil) then
field_aliases[#field_aliases + 1] = "all=all"
else
--
-- Invalid field alias...
if isEmptyString(fields) then
rest_utils.answer(rest_utils.consts.err.invalid_args)
return
end
--
-- Build host stats fields to use with potential aliases...
local field = fields:split(",") or {fields}
for _, fa in pairs(field) do
local comp = fa:split("=")
if (comp ~= nil) then
--
-- Field and alias...
field_aliases[#field_aliases + 1] = comp[1] .. "=" .. comp[2]
else
--
-- Alias same as field...
field_aliases[#field_aliases + 1] = fa .. "=" .. fa
end
end
end
local hostparam = _GET["host"]
if ((hostparam ~= nil) or (not isEmptyString(hostparam))) then
--
-- Single host:
local host_info = url2hostinfo(_GET)
local host = interface.getHostInfo(host_info["host"], host_info["vlan"])
if not host then
rest_utils.answer(rest_utils.consts.err.not_found)
return
else
--
-- Check for 'all' host stat fields...
if (field_aliases[1] == "all=all") then
res = host
else
--
-- Process selective host stat fields...
for _, fa in pairs(field_aliases) do
local comp = fa:split("=")
local field = comp[1]
local alias = comp[2]
if (host[field] ~= nil) then
--
-- Add host field stat with potential alias name...
res[alias] = host[field]
end
end
end
tracker.log("get_host_custom_data_json", {ifid, host_info["host"], host_info["vlan"], field_aliases})
rest_utils.answer(rc, res)
return
end
else
--
-- All hosts:
local hosts_stats = interface.getHostsInfo()
hosts_stats = hosts_stats["hosts"]
for key, value in pairs(hosts_stats) do
local host = interface.getHostInfo(key)
if (host ~= nil) then
local hdata = {}
if (field_aliases[1] == "all=all") then
hdata = host
else
for _, fa in pairs(field_aliases) do
local comp = fa:split("=")
local field = comp[1]
local alias = comp[2]
if (host[field] ~= nil) then
hdata[alias] = host[field]
end
end
end
res[#res + 1] = hdata
end
end
tracker.log("get_host_custom_data_json", {ifid, "All Hosts", field_aliases})
rest_utils.answer(rc, res)
return
end
| gpl-3.0 |
gajop/chiliui | luaui/chili/chili/controls/treeviewnode.lua | 1 | 8454 | --// =============================================================================
TreeViewNode = Control:Inherit{
classname = "treeviewnode",
padding = {16, 0, 0, 0},
labelFontsize = 14,
autosize = true,
caption = "node",
expanded = true,
clickTextToToggle = false,
root = false,
leaf = true,
nodes = {},
treeview = nil,
_nodes_hidden = {},
OnSelectChange = {},
OnCollapse = {},
OnExpand = {},
OnDraw = {},
}
local this = TreeViewNode
local inherited = this.inherited
--// =============================================================================
function TreeViewNode:New(obj)
if (obj.root) then
obj.padding = {0, 0, 0, 0}
end
assert(obj.treeview)
obj.treeview = MakeWeakLink(obj.treeview)
obj = inherited.New(self, obj)
self.labelFontsize = obj.labelFontsize
self.clickTextToToggle = obj.clickTextToToggle
return obj
end
function TreeViewNode:SetParent(obj)
obj = UnlinkSafe(obj)
local typ = type(obj)
if (typ ~= "table") then
self.treeview = nil --FIXME code below in this file doesn't check for nil!
end
inherited.SetParent(self, obj)
end
function TreeViewNode:AddChild(obj, isNode)
if (isNode~= false) then
self.nodes[#self.nodes + 1] = MakeWeakLink(obj)
end
if self.parent and self.parent.RequestRealign then
self.parent:RequestRealign()
end
return inherited.AddChild(self, obj)
end
function TreeViewNode:RemoveChild(obj)
local result = inherited.RemoveChild(self, obj)
local nodes = self.nodes
for i = 1, #nodes do
if CompareLinks(nodes[i], obj) then
table.remove(nodes, i)
return result
end
end
return result
end
function TreeViewNode:ClearChildren()
local caption
if not(self.root) then
caption = self.children[1]
self.children[1] = self.children[#self.children]
self.children[#self.children] = nil
end
self.leaf = true
local collapsed = not self.expanded
self:Expand()
inherited.ClearChildren(self)
if (collapsed) then
self:Collapse()
end
if not(self.root) then
self.children[1] = caption
end
end
TreeViewNode.Clear = TreeViewNode.ClearChildren
--// =============================================================================
function TreeViewNode:Add(item)
self.leaf = false
local newnode
if (type(item) == "string") then
local lbl = TextBox:New{text = item; width = "100%"; padding = {2, 3, 2, 2}; minHeight = self.minHeight; fontsize = self.labelFontsize}
newnode = TreeViewNode:New{caption = item; treeview = self.treeview; minHeight = self.minHeight; expanded = self.expandedt; labelFontsize = self.labelFontsize}
newnode:AddChild(lbl, false)
self:AddChild(newnode)
elseif (IsObject(item)) then
newnode = TreeViewNode:New{caption = ""; treeview = self.treeview; minHeight = self.minHeight; expanded = self.expandedt; labelFontsize = self.labelFontsize}
newnode:AddChild(item, false)
self:AddChild(newnode)
end
return newnode
end
function TreeViewNode:Select()
if (self.root) or (not self.treeview) then
return
end
if (not CompareLinks(self.treeview.selected, self)) then
--// treeview itself calls node:OnSelectChange !
self.treeview:Select(self)
end
end
function TreeViewNode:Toggle()
if (self.root) or (not self.treeview) then
return
end
if (self.expanded) then
self:Collapse()
else
self:Expand()
end
end
function TreeViewNode:Expand()
if (self.root) or (not self.treeview) then
return
end
self:CallListeners(self.OnExpand)
self.expanded = true
self.treeview:RequestRealign()
for i = #self._nodes_hidden, 1, -1 do
local c = self._nodes_hidden[i]
self.children[#self.children + 1] = c
end
for i = #self._nodes_hidden, 1, -1 do
self._nodes_hidden[i] = nil
end
end
function TreeViewNode:Collapse()
if (self.root) or (not self.treeview) then
return
end
self:CallListeners(self.OnCollapse)
self.expanded = false
self.treeview:RequestRealign()
for i = #self.children, 2, -1 do
local c = self.children[i]
self.children[i] = nil
self._nodes_hidden[#self._nodes_hidden + 1] = c
end
end
--// =============================================================================
function TreeViewNode:GetNodeByCaption(caption)
for i = 1, #self.nodes do
local n = self.nodes[i]
if (n.caption == caption) then
return n
end
local result = n:GetNodeByCaption(caption)
if (result) then
return result
end
end
end
function TreeViewNode:GetNodeByIndex(index, _i)
for i = 1, #self.nodes do
_i = _i + 1
if (_i == index) then
return self.nodes[i]
end
local result = self.nodes[i]:GetNodeByIndex(index, _i)
if (IsNumber(result)) then
_i = result
else
return result
end
end
return _i
end
--// =============================================================================
function TreeViewNode:UpdateLayout()
local clientWidth = self.clientWidth
local children = self.children
if (not self.expanded) and (not self.root) then
if (children[1]) then
local c = children[1]
c:_UpdateConstraints(0, 0, clientWidth)
c:Realign()
self:Resize(nil, c.height, true, true)
else
self:Resize(nil, 10, true, true)
end
return true
end
local y = 0
for i = 1, #children do
local c = children[i]
c:_UpdateConstraints(0, y, clientWidth)
c:Realign()
y = y + c.height
end
self:Resize(nil, y, true, true)
return true
end
--// =============================================================================
function TreeViewNode:_InNodeButton(x, y)
if self.root or self.leaf then
return false
end
if (x >= self.padding[1]) and not self.clickTextToToggle then
return false
end
local nodeTop = (self.children[1].height - self.padding[1])*0.5
return (nodeTop <= y) and (y-nodeTop < self.padding[1])
end
function TreeViewNode:HitTest(x, y, ...)
local obj = inherited.HitTest(self, x, y, ...)
if (obj) then
return obj
end
return self
end
function TreeViewNode:MouseDown(x, y, ...)
if (self.root) then
return inherited.MouseDown(self, x, y, ...)
end
--//FIXME this function is needed to recv MouseClick - > fail
if (self:_InNodeButton(x, y)) then
return self
end
if (x >= self.padding[1])then
--[[ FIXME inherited.MouseDown should be executed before Select()!
local obj = inherited.MouseDown(self, x, y, ...)
return obj
--]]
if (y < self.padding[2] + self.children[1].height) then
self:Select()
end
local obj = inherited.MouseDown(self, x, y, ...)
return obj
end
end
function TreeViewNode:MouseClick(x, y, ...)
if (self.root) then
return inherited.MouseClick(self, x, y, ...)
end
if (self:_InNodeButton(x, y)) then
self:Toggle()
return self
end
local obj = inherited.MouseClick(self, x, y, ...)
return obj
end
function TreeViewNode:MouseDblClick(x, y, ...)
--//FIXME doesn't get called, related to the FIXME above!
if (self.root) then
return inherited.MouseDblClick(self, x, y, ...)
end
local obj = inherited.MouseDblClick(self, x, y, ...)
if (not obj) then
self:Toggle()
obj = self
end
return obj
end
--// =============================================================================
function TreeViewNode:DrawNode()
if (self.treeview) then
self.treeview.DrawNode(self)
end
end
function TreeViewNode:DrawNodeTree()
if (self.treeview) then
self.treeview.DrawNodeTree(self)
end
end
function TreeViewNode:DrawControl()
if (self.root) then
return
end
local dontDraw = self:CallListeners(self.OnDraw, self)
if (not dontDraw) then
self:DrawNode()
end
self:DrawNodeTree()
end
function TreeViewNode:DrawChildren()
if not (self.expanded or self.root) then
self:_DrawInClientArea(self.children[1].Draw, self.children[1])
return
end
if (next(self.children)) then
self:_DrawChildrenInClientArea('Draw')
end
end
function TreeViewNode:DrawChildrenForList()
if not (self.expanded or self.root) then
self:_DrawInClientArea(self.children[1].DrawForList, self.children[1])
return
end
if (next(self.children)) then
self:_DrawChildrenInClientArea('DrawForList')
end
end
--// ============================================================================= | gpl-2.0 |
mega9/GTW-RPG | [resources]/GTWcivilians/civ-s.lua | 1 | 4065 | --[[
********************************************************************************
Project owner: GTWGames
Project name: GTW-RPG
Developers: GTWCode
Source code: https://github.com/GTWCode/GTW-RPG/
Bugtracker: http://forum.albonius.com/bug-reports/
Suggestions: http://forum.albonius.com/mta-servers-development/
Version: Open source
License: GPL v.3 or later
Status: Stable release
********************************************************************************
]]--
-- On accepting the job
function onAcceptJob( ID, skinID )
-- Get job data
local team, max_wl, description, skins = unpack(work_items[ID])
-- Check if a skin was passed
if not skinID then return end
local is_law_banned = exports.GTWpolicechief:isLawBanned(client)
if team == "Government" and is_law_banned then
exports.GTWtopbar:dm( "You are banned from the government team! choose another job.", client, 255, 0, 0 )
return
end
-- Note that -1 means default player skin
if skinID > -1 then
setElementModel( client, skinID )
elseif skinID == -1 then
skinID = exports.GTWclothes:getBoughtSkin( client ) or getElementModel( client ) or 0
setElementModel( client, skinID )
else
exports.GTWtopbar:dm( "Select a skin before applying for the job!", client, 255, 0, 0 )
return
end
-- Check if a player already have the job or not
if getElementData(client, "Occupation") ~= ID then
setElementData(client, "Occupation", ID)
setPlayerTeam(client, getTeamFromName(team))
local r,g,b = 255,255,255
if getTeamFromName(team) then
r,g,b = getTeamColor(getTeamFromName(team))
else
outputServerLog("GTWcivilians: Team: '"..team.."' does not exist!")
end
setPlayerNametagColor(client, r, g, b)
setElementData(client, "admin", nil)
exports.GTWtopbar:dm("("..ID..") Welcome to your new job!", client, 0, 255, 0)
end
end
addEvent( "GTWcivilians.accept", true )
addEventHandler( "GTWcivilians.accept", root, onAcceptJob )
-- Manage job tools
function onBuyTool(name, ammo, price, weapon_id)
if not name or not ammo or not price or not weapon_id then return end
if getPlayerMoney(client) >= tonumber(price) then
giveWeapon(client, weapon_id, ammo, true)
takePlayerMoney(client, price)
else
exports.GTWtopbar:dm("You cannot afford this tool!", client, 255, 0, 0)
end
end
addEvent( "GTWcivilians.buyTools", true )
addEventHandler( "GTWcivilians.buyTools", root, onBuyTool )
-- Team service and scoreboard
function addTeamData ( )
-- Add info columns to scoreboard
exports.scoreboard:scoreboardAddColumn("Occupation", root, 90)
exports.scoreboard:scoreboardAddColumn("Group", root, 130)
exports.scoreboard:scoreboardAddColumn("Money", root, 70)
exports.scoreboard:scoreboardAddColumn("Playtime", root, 50)
exports.scoreboard:scoreboardAddColumn("Jailed", root, 30)
-- Create teams
staffTeam = createTeam( "Staff", 255, 255, 255 )
govTeam = createTeam( "Government", 110, 110, 110 )
emergencyTeam = createTeam( "Emergency service", 0, 150, 200 )
civilianTeam = createTeam( "Civilians", 200, 150, 0 )
gangstersTeam = createTeam( "Gangsters", 135, 0, 135 )
criminalTeam = createTeam( "Criminals", 170, 0, 0 )
unemployedTeam = createTeam( "Unemployed", 255, 255, 0 )
-- Restore teams
for i,p in pairs(getElementsByType( "player" )) do
if not getElementData(p, "teamsystem_team") then
setPlayerTeam(p, getTeamFromName("Unemployed"))
setElementData(p, "Occupation", "")
else
setPlayerTeam(p, getTeamFromName( getElementData(p, "teamsystem_team")))
setElementData(p, "teamsystem_team", nil)
end
end
end
addEventHandler( "onResourceStart", getResourceRootElement(), addTeamData )
addEventHandler( "onResourceStop", getResourceRootElement(),
function ( resource )
for i,p in pairs(getElementsByType( "player" )) do
if getPlayerTeam(p) then
setElementData(p, "teamsystem_team", getTeamName(getPlayerTeam(p)))
end
end
end) | gpl-3.0 |
jprjr/luadbi-async | DBIasync.lua | 1 | 1851 | local _M = {}
_M._NAME = "DBIasync"
-- Driver to module mapping
local name_to_module = {
MySQL = 'dbdmysqlasync',
PostgreSQL = 'dbdpostgresqlasync',
SQLite3 = 'dbdsqlite3async',
}
local string = require('string')
-- Returns a list of available drivers
-- based on run time loading
local function available_drivers()
local available = {}
for driver, modulefile in pairs(name_to_module) do
local m, err = pcall(require, modulefile)
if m then
table.insert(available, driver)
end
end
-- no drivers available
if table.maxn(available) < 1 then
available = {'(None)'}
end
return available
end
-- High level DB connection function
-- This should be used rather than DBD.{Driver}.New
function _M.New(driver)
local modulefile = name_to_module[driver]
if not modulefile then
local available = table.concat(available_drivers(), ',')
error(string.format("Driver '%s' not found. Available drivers are: %s", driver, available))
end
local m, err = pcall(require, modulefile)
if not m then
-- cannot load the module, we cannot continue
local available = table.concat(available_drivers(), ',')
error(string.format('Cannot load driver %s. Available drivers are: %s', driver, available))
end
local class_str = string.format('DBD.%s.Connection', driver)
local connection_class = package.loaded[class_str]
return connection_class.New()
end
-- Help function to do prepare and execute in
-- a single step
function _M.Do(dbh, sql, ...)
local sth,err = dbh:prepare(sql)
if not sth then
return false, err
end
local ok, err = sth:execute(...)
if not ok then
return false, err
end
return sth:affected()
end
-- Lit drivers available on this system
function _M.Drivers()
return available_drivers()
end
return _M
| mit |
ntop/ntopng | scripts/lua/rest/v1/acknowledge/flow/alerts.lua | 1 | 1078 | --
-- (C) 2013-22 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
package.path = dirs.installdir .. "/scripts/lua/modules/alert_store/?.lua;" .. package.path
local alert_utils = require "alert_utils"
local alert_consts = require "alert_consts"
local alert_entities = require "alert_entities"
local rest_utils = require("rest_utils")
local flow_alert_store = require "flow_alert_store".new()
--
-- Read alerts data
-- Example: curl -u admin:admin -H "Content-Type: application/json" -d '{"ifid": "1"}' http://localhost:3000/lua/rest/v1/acknowledge/flow/alerts.lua
--
-- NOTE: in case of invalid login, no error is returned but redirected to login
--
local rc = rest_utils.consts.success.ok
local res = {}
local ifid = _GET["ifid"]
if isEmptyString(ifid) then
rc = rest_utils.consts.err.invalid_interface
rest_utils.answer(rc)
return
end
interface.select(ifid)
-- Add filters
flow_alert_store:add_request_filters(true)
flow_alert_store:acknowledge(_GET["label"])
rest_utils.answer(rc)
| gpl-3.0 |
Miigon/luvit | deps/stream/stream_passthrough.lua | 5 | 1105 | --[[
Copyright 2014 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--[[
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
--]]
local Transform = require('./stream_transform').Transform
local PassThrough = Transform:extend()
function PassThrough:initialize(options)
--[[
if (!(this instanceof PassThrough))
return new PassThrough(options)
--]]
Transform.initialize(self, options)
end
function PassThrough:_transform(chunk, cb)
cb(nil, chunk)
end
return { PassThrough = PassThrough }
| apache-2.0 |
spark051/bt.bot | plugins/bugzilla.lua | 611 | 3983 | do
local BASE_URL = "https://bugzilla.mozilla.org/rest/"
local function bugzilla_login()
local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password
print("accessing " .. url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_check(id)
-- data = bugzilla_login()
local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey
-- print(url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_listopened(email)
local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey
local res,code = https.request( url )
print(res)
local data = json:decode(res)
return data
end
local function run(msg, matches)
local response = ""
if matches[1] == "status" then
local data = bugzilla_check(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
response = response .. "\n Last update: "..data.bugs[1].last_change_time
response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
print(response)
end
elseif matches[1] == "list" then
local data = bugzilla_listopened(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
-- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
-- response = response .. "\n Last update: "..data.bugs[1].last_change_time
-- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
-- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
-- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
local total = table.map_length(data.bugs)
print("total bugs: " .. total)
local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2]
if total > 0 then
response = response .. ": "
for tableKey, bug in pairs(data.bugs) do
response = response .. "\n #" .. bug.id
response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution
response = response .. "\n Whiteboard: " .. bug.whiteboard
response = response .. "\n Summary: " .. bug.summary
end
end
end
end
return response
end
-- (table)
-- [bugs] = (table)
-- [1] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 927704
-- [whiteboard] = (string) [approved][full processed]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/
-- [2] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 1049337
-- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/
-- total bugs: 2
return {
description = "Lookup bugzilla status update",
usage = "/bot bugzilla [bug number]",
patterns = {
"^/bugzilla (status) (.*)$",
"^/bugzilla (list) (.*)$"
},
run = run
}
end | gpl-2.0 |
eaufavor/AwesomeWM-powerarrow-dark | drawer/cpuInfo.lua | 1 | 8298 | local setmetatable = setmetatable
local io = io
local ipairs = ipairs
local loadstring = loadstring
local print = print
local tonumber = tonumber
local beautiful = require( "beautiful" )
local button = require( "awful.button" )
local widget2 = require( "awful.widget" )
local config = require( "forgotten" )
local vicious = require( "extern.vicious" )
local menu = require( "radical.context" )
local util = require( "awful.util" )
local wibox = require( "wibox" )
local themeutils = require( "blind.common.drawing" )
local radtab = require( "radical.widgets.table" )
local embed = require( "radical.embed" )
local radical = require( "radical" )
local color = require( "gears.color" )
local cairo = require( "lgi" ).cairo
local allinone = require( "widgets.allinone" )
local data = {}
local procMenu = nil
local capi = { screen = screen , client = client ,
mouse = mouse , timer = timer }
local module = {}
local function match_icon(arr,name)
for k2,v2 in ipairs(arr) do
if k2:find(name) ~= nil then
return v2
end
end
end
local function reload_top(procMenu,data)
procMenu:clear()
if data.process then
local procIcon = {}
for k2,v2 in ipairs(capi.client.get()) do
if v2.icon then
procIcon[v2.class:lower()] = v2.icon
end
end
for i=1,#data.process do
local wdg = {}
wdg.percent = wibox.widget.textbox()
wdg.percent.fit = function()
return 42,procMenu.item_height
end
wdg.percent.draw = function(self,w, cr, width, height)
cr:save()
cr:set_source(color(procMenu.bg_alternate))
cr:rectangle(0,0,width-height/2,height)
cr:fill()
cr:set_source_surface(themeutils.get_beg_arrow2({bg_color=procMenu.bg_alternate}),width-height/2,0)
cr:paint()
cr:restore()
wibox.widget.textbox.draw(self,w, cr, width, height)
end
wdg.kill = wibox.widget.imagebox()
wdg.kill:set_image(config.iconPath .. "kill.png")
wdg.percent:set_text((data.process[i].percent or "N/A").."%")
procMenu:add_item({text=data.process[i].name,suffix_widget=wdg.kill,prefix_widget=wdg.percent})
end
end
end
--util.spawn("/bin/bash -c 'while true;do "..util.getdir("config") .."/Scripts/cpuInfo2.sh > /tmp/cpuStatistic.lua && sleep 5;done'")
--util.spawn("/bin/bash -c 'while true; do "..util.getdir("config") .."/Scripts/topCpu3.sh > /tmp/topCpu.lua;sleep 5;done'")
local function new(margin, args)
local cpuModel
local spacer1
local volUsage
local modelWl
local cpuWidgetArrayL
local main_table
local function loadData()
util.spawn("/bin/bash -c '"..util.getdir("config") .."/Scripts/cpuInfo2.sh > /tmp/cpuStatistic.lua'")
local f = io.open('/tmp/cpuStatistic.lua','r')
local cpuStat = {}
if f ~= nil then
local text3 = f:read("*all")
text3 = text3.." return cpuInfo"
f:close()
local afunction = loadstring(text3)
if afunction ~= nil then
cpuStat = afunction()
infoNotFound = nil
else
infoNotFound = "N/A"
end
else
infoNotFound = "N/A"
end
if cpuStat then
data.cpuStat = cpuStat
cpuModel:set_text(cpuStat.model or "")
end
local process = {}
util.spawn("/bin/bash -c '"..util.getdir("config") .."/Scripts/topCpu3.sh > /tmp/topCpu.lua'")
f = io.open('/tmp/topCpu.lua','r')
if f ~= nil then
text3 = f:read("*all")
text3 = text3.." return cpuStat"
f:close()
local afunction = loadstring(text3) or nil
if afunction ~= nil then
process = afunction()
else
process = nil
end
end
if process then
data.process = process
end
end
local function createDrawer()
cpuModel = wibox.widget.textbox()
spacer1 = wibox.widget.textbox()
volUsage = widget2.graph()
topCpuW = {}
local tab,widgets = radtab({
{"","",""},
{"","",""},
{"","",""},
{"","",""},
{"","",""},
{"","",""},
{"","",""},
{"","",""}},
{row_height=20,v_header = {"C1","C2","C3","C4","C5", "C6","C7","C8" },
h_header = {"MHz","Temp","Used"}
})
main_table = widgets
modelWl = wibox.layout.fixed.horizontal()
modelWl:add ( cpuModel )
loadData()
cpuWidgetArrayL = wibox.layout.margin()
cpuWidgetArrayL:set_margins(3)
cpuWidgetArrayL:set_bottom(10)
cpuWidgetArrayL:set_widget(tab)
cpuModel:set_text(data.cpuStat and data.cpuStat.model or "N/A")
cpuModel.width = 312
volUsage:set_width ( 312 )
volUsage:set_height ( 30 )
volUsage:set_scale ( true )
volUsage:set_border_color ( beautiful.fg_normal )
volUsage:set_color ( beautiful.fg_normal )
vicious.register ( volUsage, vicious.widgets.cpu,'$1',1 )
local f2 = io.popen("cat /proc/cpuinfo | grep processor | tail -n1 | grep -e'[0-9]*' -o")
local coreNb = f2:read("*all") or "0"
f2:close()
end
local function updateTable()
local cols = {
CLOCK = 1,
TEMP = 2,
USED = 3,
IO = 4,
IDLE = 5,
}
if data.cpuStat ~= nil and data.cpuStat["core0"] ~= nil and main_table ~= nil then
for i=0 , data.cpuStat["core"] do --TODO add some way to correct the number of core, it usually fail on load --Solved
if i <= (#main_table or 1) and main_table[i+1] then
main_table[i+1][cols[ "CLOCK" ]]:set_text(tonumber(data.cpuStat["core"..i]["speed"]) .. "Mhz" )
main_table[i+1][cols[ "TEMP" ]]:set_text(data.cpuStat["core"..i].temp )
main_table[i+1][cols[ "USED" ]]:set_text(data.cpuStat["core"..i].usage )
end
end
end
end
local function regenMenu()
local imb = wibox.widget.imagebox()
imb:set_image(beautiful.path .. "Icon/reload.png")
aMenu = menu({item_width=298,width=300,arrow_type=radical.base.arrow_type.CENTERED})
aMenu:add_widget(radical.widgets.header(aMenu,"INFO") , {height = 20 , width = 300})
aMenu:add_widget(modelWl , {height = 40 , width = 300})
aMenu:add_widget(radical.widgets.header(aMenu,"USAGE") , {height = 20 , width = 300})
aMenu:add_widget(volUsage , {height = 30 , width = 300})
aMenu:add_widget(cpuWidgetArrayL , {width = 300})
aMenu:add_widget(radical.widgets.header(aMenu,"PROCESS",{suffix_widget=imb}) , {height = 20 , width = 300})
procMenu = embed({max_items=6})
aMenu:add_embeded_menu(procMenu)
return aMenu
end
local function show()
if not data.menu then
createDrawer()
data.menu = regenMenu()
else
end
if not data.menu.visible then
loadData()
updateTable()
reload_top(procMenu,data)
end
data.menu.visible = not data.menu.visible
end
local volumewidget2 = allinone()
volumewidget2:set_icon(config.iconPath .. "brain.png")
vicious.register(volumewidget2, vicious.widgets.cpu,'$1',1)
volumewidget2:buttons (util.table.join(button({ }, 1, function (geo) show(); data.menu.parent_geometry = geo end)))
return volumewidget2
end
return setmetatable(module, { __call = function(_, ...) return new(...) end })
-- kate: space-indent on; indent-width 2; replace-tabs on;
| apache-2.0 |
ntop/ntopng | scripts/lua/iface_hosts_list.lua | 1 | 2310 | --
-- (C) 2013-22 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
sendHTTPContentTypeHeader('text/html')
interface.select(ifname)
hosts_stats = interface.getHostsInfo(false, "column_traffic")
hosts_stats = hosts_stats["hosts"]
ajax_format = _GET["ajax_format"]
tot = 0
_hosts_stats = {}
top_key = nil
top_value = 0
num = 0
for key, value in pairs(hosts_stats) do
host_info = hostkey2hostinfo(key);
value = hosts_stats[key]["bytes.sent"]+hosts_stats[key]["bytes.rcvd"]
if(value ~= nil) then
if(host_info["host"] == "255.255.255.255") then
key = "Broadcast"
end
_hosts_stats[value] = key -- ntop.getResolvedName(key)
if((top_value < value) or (top_key == nil)) then
top_key = key
top_value = value
end
tot = tot + value
end
end
-- Print up to this number of entries
max_num_entries = 10
-- Print entries whose value >= 5% of the total
threshold = (tot * 5) / 100
print "[\n"
num = 0
accumulate = 0
for key, value in pairsByKeys(_hosts_stats, rev) do
if(key < threshold) then
break
end
if(num > 0) then
print ",\n"
end
if((ajax_format == nil) or (ajax_format == "d3")) then
print("\t { \"label\": \"" .. value .."\", \"value\": ".. key ..", \"url\": \""..ntop.getHttpPrefix().."/lua/host_details.lua?"..hostinfo2url(value).."\" }")
else
print("\t [ \"" .. value .."\", ".. key .." ]")
end
accumulate = accumulate + key
num = num + 1
if(num == max_num_entries) then
break
end
end
if((num == 0) and (top_key ~= nil)) then
if((ajax_format == nil) or (ajax_format == "d3")) then
print("\t { \"label\": \"" .. top_key .."\", \"value\": ".. top_value ..", \"url\": \""..ntop.getHttpPrefix().."/lua/host_details.lua?"..hostinfo2url(top_key).."\" }")
else
print("\t [ \"" .. top_key .."\", ".. top_value .." ]")
end
accumulate = accumulate + top_value
end
-- In case there is some leftover do print it as "Other"
if(accumulate < tot) then
if((ajax_format == nil) or (ajax_format == "d3")) then
print(",\n\t { \"label\": \"Other\", \"value\": ".. (tot-accumulate) .." }")
else
print(",\n\t [ \"Other\", ".. (tot-accumulate) .." ]")
end
end
print "\n]"
| gpl-3.0 |
ntop/ntopng | scripts/lua/modules/alert_store/flow_alert_store.lua | 1 | 38077 | --
-- (C) 2021-22 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/alert_store/?.lua;" .. package.path
-- Import the classes library.
local classes = require "classes"
require "lua_utils"
local alert_store = require "alert_store"
local flow_risk_utils = require "flow_risk_utils"
local alert_consts = require "alert_consts"
local alert_utils = require "alert_utils"
local alert_entities = require "alert_entities"
local tag_utils = require "tag_utils"
local network_utils = require "network_utils"
local json = require "dkjson"
local pools = require "pools"
local historical_flow_utils = require "historical_flow_utils"
local flow_alert_keys = require "flow_alert_keys"
local href_icon = "<i class='fas fa-laptop'></i>"
-- ##############################################
local flow_alert_store = classes.class(alert_store)
-- ##############################################
function flow_alert_store:format_traffic_direction(traffic_direction)
if traffic_direction then
local list = split(traffic_direction, ',')
local value = self:strip_filter_operator(list[1])
if value == "0" then
self:add_filter_condition_list("cli_location", traffic_direction, "string", "0")
self:add_filter_condition_list("srv_location", traffic_direction, "string", "0")
elseif value == "1" then
self:add_filter_condition_list("cli_location", traffic_direction, "string", "1")
self:add_filter_condition_list("srv_location", traffic_direction, "string", "1")
elseif value == "2" then
self:add_filter_condition_list("cli_location", traffic_direction, "string", "0")
self:add_filter_condition_list("srv_location", traffic_direction, "string", "1")
elseif value == "3" then
self:add_filter_condition_list("cli_location", traffic_direction, "string", "1")
self:add_filter_condition_list("srv_location", traffic_direction, "string", "0")
end
end
end
-- ##############################################
function flow_alert_store:init(args)
local table_name = "flow_alerts"
self.super:init()
if ntop.isClickHouseEnabled() then
-- Alerts from historical flows (see also RecipientQueue::enqueue)
table_name = "flow_alerts_view"
self._write_table_name = "flows"
end
self._table_name = table_name
self._alert_entity = alert_entities.flow
end
-- ##############################################
-- Get the 'real' field name (used by flow alerts where the flow table is a view
-- and we write to the real table which has different column names)
function flow_alert_store:get_column_name(field, is_write, value)
local col = field
if is_write and self._write_table_name then
-- This is using the flow table, in write mode we have to remap columns
if field == 'cli_ip' or field == 'srv_ip' then
-- Note: there are separate V4 and V6 columns in the flow table,
-- we need to use the correct one based on the value
if string.match(value, ':') then
-- IPv6
if field == 'cli_ip' then col = 'IPV6_SRC_ADDR'
else col = 'IPV6_DST_ADDR' end
else
--IPv4
if field == 'cli_ip' then col = 'IPV4_SRC_ADDR'
else col = 'IPV4_DST_ADDR' end
end
else
col = historical_flow_utils.get_flow_column_by_tag(field)
end
if col then
return col
end
end
return field
end
-- ##############################################
--@brief Labels alerts according to specified filters
function flow_alert_store:acknowledge(label)
local table_name = self:get_write_table_name()
local where_clause = self:build_where_clause(true)
-- Prepare the final query
local q
if ntop.isClickHouseEnabled() then
-- This is using the historical 'flows' table
q = string.format("ALTER TABLE `%s` UPDATE `%s` = %u, `%s` = '%s', `%s` = %u WHERE %s",
table_name,
self:get_column_name('alert_status', true),
alert_consts.alert_status.acknowledged.alert_status_id,
self:get_column_name('user_label', true),
self:_escape(label),
self:get_column_name('user_label_tstamp', true),
os.time(),
where_clause)
else
q = string.format("UPDATE `%s` SET `alert_status` = %u, `user_label` = '%s', `user_label_tstamp` = %u WHERE %s", table_name, alert_consts.alert_status.acknowledged.alert_status_id, self:_escape(label), os.time(), where_clause)
end
local res = interface.alert_store_query(q)
return res and table.len(res) == 0
end
-- ##############################################
--@brief Deletes data according to specified filters
function flow_alert_store:delete()
local table_name = self:get_write_table_name()
local where_clause = self:build_where_clause(true)
-- Prepare the final query
local q
if ntop.isClickHouseEnabled() then
if self._write_table_name then
-- Fix column type conversion
where_clause = historical_flow_utils.fixWhereTypes(where_clause)
q = string.format("ALTER TABLE `%s` UPDATE `IS_ALERT_DELETED` = 1 WHERE %s", table_name, where_clause)
else
q = string.format("ALTER TABLE `%s` DELETE WHERE %s ", table_name, where_clause)
end
else
q = string.format("DELETE FROM `%s` WHERE %s ", table_name, where_clause)
end
local res = interface.alert_store_query(q)
return res and table.len(res) == 0
end
-- ##############################################
function flow_alert_store:_get_tstamp_column_name()
if ntop.isClickHouseEnabled() then
return "first_seen"
else
return "tstamp"
end
end
-- ##############################################
function flow_alert_store:insert(alert)
local hex_prefix = ''
local extra_columns = ''
local extra_values = ''
-- Note: this is no longer called when ClickHouse is enabled
-- as a view on the historical is used. See RecipientQueue::enqueue
if ntop.isClickHouseEnabled() then
return -- Safety check
end
if ntop.isClickHouseEnabled() then
extra_columns = "rowid, "
extra_values = "generateUUIDv4(), "
else
hex_prefix = "X"
end
-- Note
-- The database contains first_seen, tstamp, tstamp_end for historical reasons.
-- The time index is set on first_seen, thus:
-- - tstamp and first_seen contains the same value alert.first_seen
-- - tstamp_end is set to alert.tstamp (which is the time the alert has been emitted as there is no engage on flows)
-- - first_seen is used to lookups as this is the indexed field
-- - tstamp (instead of first_seen) is used in select and for visualization as it's in common to all tables
local insert_stmt = string.format("INSERT INTO %s "..
"(%salert_id, interface_id, tstamp, tstamp_end, severity, ip_version, cli_ip, srv_ip, cli_port, srv_port, vlan_id, "..
"is_cli_attacker, is_cli_victim, is_srv_attacker, is_srv_victim, proto, l7_proto, l7_master_proto, l7_cat, "..
"cli_name, srv_name, cli_country, srv_country, cli_blacklisted, srv_blacklisted, cli_location, srv_location, "..
"cli2srv_bytes, srv2cli_bytes, cli2srv_pkts, srv2cli_pkts, first_seen, community_id, score, "..
"flow_risk_bitmap, alerts_map, cli_host_pool_id, srv_host_pool_id, cli_network, srv_network, probe_ip, input_snmp, output_snmp, "..
"json, info) "..
"VALUES (%s%u, %u, %u, %u, %u, %u, '%s', '%s', %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, '%s', '%s', '%s', "..
"'%s', %u, %u, %u, %u, %u, %u, %u, %u, %u, '%s', %u, %u, %s'%s', %u, %u, %u, %u, '%s', %u, %u, '%s', '%s'); ",
self:get_write_table_name(),
extra_columns,
extra_values,
alert.alert_id,
self:_convert_ifid(interface.getId()),
alert.first_seen,
alert.tstamp,
map_score_to_severity(alert.score),
alert.ip_version,
alert.cli_ip,
alert.srv_ip,
alert.cli_port,
alert.srv_port,
alert.vlan_id,
ternary(alert.is_cli_attacker, 1, 0),
ternary(alert.is_cli_victim, 1, 0),
ternary(alert.is_srv_attacker, 1, 0),
ternary(alert.is_srv_victim, 1, 0),
alert.proto,
alert.l7_proto,
alert.l7_master_proto,
alert.l7_cat,
self:_escape(alert.cli_name),
self:_escape(alert.srv_name),
alert.cli_country_name,
alert.srv_country_name,
ternary(alert.cli_blacklisted, 1, 0),
ternary(alert.srv_blacklisted, 1, 0),
alert.cli_location or 0,
alert.srv_location or 0,
alert.cli2srv_bytes,
alert.srv2cli_bytes,
alert.cli2srv_packets,
alert.srv2cli_packets,
alert.first_seen,
alert.community_id,
alert.score,
alert.flow_risk_bitmap or 0,
hex_prefix,
alert.alerts_map,
alert.cli_host_pool_id or pools.DEFAULT_POOL_ID,
alert.srv_host_pool_id or pools.DEFAULT_POOL_ID,
alert.cli_network or network_utils.UNKNOWN_NETWORK,
alert.srv_network or network_utils.UNKNOWN_NETWORK,
alert.probe_ip,
alert.input_snmp,
alert.output_snmp,
self:_escape(alert.json),
self:_escape(alert.info or '')
)
-- traceError(TRACE_NORMAL, TRACE_CONSOLE, insert_stmt)
return interface.alert_store_query(insert_stmt)
end
-- ##############################################
--@brief Performs a query for the top l7_proto by alert count
function flow_alert_store:top_l7_proto_historical()
-- Preserve all the filters currently set
local where_clause = self:build_where_clause()
local q = string.format("SELECT l7_proto, count(*) count FROM %s WHERE %s GROUP BY l7_proto ORDER BY count DESC LIMIT %u",
self:get_table_name(), where_clause, self._top_limit)
local q_res = interface.alert_store_query(q) or {}
return q_res
end
-- ##############################################
--@brief Performs a query for the top client hosts by alert count
function flow_alert_store:top_cli_ip_historical()
-- Preserve all the filters currently set
local where_clause = self:build_where_clause()
local q
if ntop.isClickHouseEnabled() then
q = string.format("SELECT cli_ip, vlan_id, cli_name, count(*) count FROM %s WHERE %s GROUP BY cli_ip, vlan_id, cli_name ORDER BY count DESC LIMIT %u",
self:get_table_name(), where_clause, self._top_limit)
else
q = string.format("SELECT cli_ip, vlan_id, cli_name, count(*) count FROM %s WHERE %s GROUP BY cli_ip ORDER BY count DESC LIMIT %u",
self:get_table_name(), where_clause, self._top_limit)
end
local q_res = interface.alert_store_query(q) or {}
return q_res
end
-- ##############################################
--@brief Performs a query for the top server hosts by alert count
function flow_alert_store:top_srv_ip_historical()
-- Preserve all the filters currently set
local where_clause = self:build_where_clause()
local q
if ntop.isClickHouseEnabled() then
q = string.format("SELECT srv_ip, vlan_id, srv_name, count(*) count FROM %s WHERE %s GROUP BY srv_ip, vlan_id, srv_name ORDER BY count DESC LIMIT %u",
self:get_table_name(), where_clause, self._top_limit)
else
q = string.format("SELECT srv_ip, vlan_id, srv_name, count(*) count FROM %s WHERE %s GROUP BY srv_ip ORDER BY count DESC LIMIT %u",
self:get_table_name(), where_clause, self._top_limit)
end
local q_res = interface.alert_store_query(q) or {}
return q_res
end
-- ##############################################
--@brief Merge top clients and top servers to build a top hosts
function flow_alert_store:top_ip_merge(top_cli_ip, top_srv_ip)
local all_ip = {}
local top_ip = {}
local ip_names = {}
for _, p in ipairs(top_cli_ip) do
all_ip[p.cli_ip] = tonumber(p.count)
ip_names[p.cli_ip] = {
name = p.cli_name,
vlan_id = p.vlan_id,
}
p.name = p.cli_name
p.ip = p.cli_ip
end
for _, p in ipairs(top_srv_ip) do
all_ip[p.srv_ip] = (all_ip[p.srv_ip] or 0) + tonumber(p.count)
ip_names[p.srv_ip] = {
name = p.srv_name,
vlan_id = p.vlan_id,
}
p.name = p.srv_name
p.ip = p.srv_ip
end
for ip, count in pairsByValues(all_ip, rev) do
top_ip[#top_ip + 1] = {
ip = ip,
count = count,
name = ip_names[ip]["name"],
vlan_id = ip_names[ip]["vlan_id"],
}
if #top_ip >= self._top_limit then break end
end
return top_ip
end
-- ##############################################
--@brief Stats used by the dashboard
function flow_alert_store:_get_additional_stats()
local stats = {}
stats.top = {}
stats.top.cli_ip = self:top_cli_ip_historical()
stats.top.srv_ip = self:top_srv_ip_historical()
stats.top.ip = self:top_ip_merge(stats.top.cli_ip, stats.top.srv_ip)
stats.top.l7_proto = self:top_l7_proto_historical()
return stats
end
-- ##############################################
--@brief Add ip filter
function flow_alert_store:add_ip_filter(ip)
self:add_filter_condition('ip', 'eq', ip);
end
-- ##############################################
--@brief Add ip filter
function flow_alert_store:add_vlan_filter(vlan_id)
self:add_filter_condition('vlan_id', 'eq', vlan_id);
end
-- ##############################################
--@brief Add domain (info) filter
function flow_alert_store:add_domain_filter(domain)
self:add_filter_condition('info', 'in', domain);
end
-- ##############################################
--@brief Add filters according to what is specified inside the REST API
function flow_alert_store:_add_additional_request_filters()
local ip_version = _GET["ip_version"]
local ip = _GET["ip"]
local cli_ip = _GET["cli_ip"]
local srv_ip = _GET["srv_ip"]
local cli_name = _GET["cli_name"]
local srv_name = _GET["srv_name"]
local cli_port = _GET["cli_port"]
local srv_port = _GET["srv_port"]
local vlan_id = _GET["vlan_id"]
local l7proto = _GET["l7proto"]
local role = _GET["role"]
local cli_country = _GET["cli_country"]
local srv_country = _GET["srv_country"]
local probe_ip = _GET["probe_ip"]
local input_snmp = _GET["input_snmp"]
local output_snmp = _GET["output_snmp"]
local snmp_interface = _GET["snmp_interface"]
local cli_host_pool_id = _GET["cli_host_pool_id"]
local srv_host_pool_id = _GET["srv_host_pool_id"]
local cli_network = _GET["cli_network"]
local srv_network = _GET["srv_network"]
local error_code = _GET["l7_error_id"]
local confidence = _GET["confidence"]
self:format_traffic_direction(_GET["traffic_direction"])
-- Filter out flows with no alert
self:add_filter_condition_list('alert_id', "0"..tag_utils.SEPARATOR.."neq", 'number')
self:add_filter_condition_list('vlan_id', vlan_id, 'number')
self:add_filter_condition_list('ip_version', ip_version)
self:add_filter_condition_list('ip', ip)
self:add_filter_condition_list('cli_ip', cli_ip)
self:add_filter_condition_list('srv_ip', srv_ip)
self:add_filter_condition_list('cli_name', cli_name)
self:add_filter_condition_list('srv_name', srv_name)
self:add_filter_condition_list('cli_country', cli_country)
self:add_filter_condition_list('srv_country', srv_country)
self:add_filter_condition_list('cli_port', cli_port, 'number')
self:add_filter_condition_list('srv_port', srv_port, 'number')
self:add_filter_condition_list('flow_role', role)
self:add_filter_condition_list('l7proto', l7proto, 'number')
self:add_filter_condition_list('cli_host_pool_id', cli_host_pool_id, 'number')
self:add_filter_condition_list('srv_host_pool_id', srv_host_pool_id, 'number')
self:add_filter_condition_list('cli_network', cli_network, 'number')
self:add_filter_condition_list('srv_network', srv_network, 'number')
self:add_filter_condition_list('probe_ip', probe_ip)
self:add_filter_condition_list('input_snmp', input_snmp)
self:add_filter_condition_list('output_snmp', output_snmp)
self:add_filter_condition_list('snmp_interface', snmp_interface)
self:add_filter_condition_list(self:format_query_json_value('proto.l7_error_code'), error_code, 'string')
self:add_filter_condition_list(self:format_query_json_value('proto.confidence'), confidence, 'string')
end
-- ##############################################
--@brief Get info about additional available filters
function flow_alert_store:_get_additional_available_filters()
local filters = {
vlan_id = tag_utils.defined_tags.vlan_id,
ip_version = tag_utils.defined_tags.ip_version,
ip = tag_utils.defined_tags.ip,
cli_ip = tag_utils.defined_tags.cli_ip,
srv_ip = tag_utils.defined_tags.srv_ip,
cli_name = tag_utils.defined_tags.cli_name,
srv_name = tag_utils.defined_tags.srv_name,
cli_port = tag_utils.defined_tags.cli_port,
srv_port = tag_utils.defined_tags.srv_port,
cli_country = tag_utils.defined_tags.cli_country,
srv_country = tag_utils.defined_tags.srv_country,
role = tag_utils.defined_tags.role,
l7proto = tag_utils.defined_tags.l7proto,
info = tag_utils.defined_tags.info,
cli_host_pool_id = tag_utils.defined_tags.cli_host_pool_id,
srv_host_pool_id = tag_utils.defined_tags.srv_host_pool_id,
cli_network = tag_utils.defined_tags.cli_network,
srv_network = tag_utils.defined_tags.srv_network,
l7_error_id = tag_utils.defined_tags.l7_error_id,
confidence = tag_utils.defined_tags.confidence,
traffic_direction = tag_utils.defined_tags.traffic_direction,
probe_ip = tag_utils.defined_tags.probe_ip,
input_snmp = tag_utils.defined_tags.input_snmp,
output_snmp = tag_utils.defined_tags.output_snmp,
snmp_interface = tag_utils.defined_tags.snmp_interface,
}
return filters
end
-- ##############################################
local RNAME = {
ADDITIONAL_ALERTS = { name = "additional_alerts", export = true},
ALERT_NAME = { name = "alert_name", export = true},
DESCRIPTION = { name = "description", export = true},
FLOW_RELATED_INFO = { name = "flow_related_info", export = true },
MSG = { name = "msg", export = true, elements = {"name", "value", "description"}},
FLOW = { name = "flow", export = true, elements = {"srv_ip.label", "srv_ip.value", "srv_port", "cli_ip.label", "cli_ip.value", "cli_port"}},
VLAN_ID = { name = "vlan_id", export = true},
PROTO = { name = "proto", export = true},
L7_PROTO = { name = "l7_proto", export = true},
LINK_TO_PAST_FLOWS = { name = "link_to_past_flows", export = false},
CLI_HOST_POOL_ID = { name = "cli_host_pool_id", export = false },
SRV_HOST_POOL_ID = { name = "srv_host_pool_id", export = false },
CLI_NETWORK = { name = "cli_network", export = false },
SRV_NETWORK = { name = "srv_network", export = false },
PROBE_IP = { name = "probe_ip", export = true},
INFO = { name = "info", export = true },
}
-- ##############################################
function flow_alert_store:get_rnames()
return RNAME
end
-- ##############################################
--@brief Convert an alert coming from the DB (value) to an host_info table, either for the client or for the server
--@param value The alert as read from the database
--@param as_client A boolean indicating whether the hostinfo should be build for the client or for the server
function flow_alert_store:_alert2hostinfo(value, as_client)
if as_client then
return {ip = value["cli_ip"], name = value["cli_name"]}
else
return {ip = value["srv_ip"], name = value["srv_name"]}
end
end
-- ##############################################
--@brief Convert an alert coming from the DB (value) to a record returned by the REST API
function flow_alert_store:format_record(value, no_html)
local record = self:format_json_record_common(value, alert_entities.flow.entity_id, no_html)
local alert_info = alert_utils.getAlertInfo(value)
local alert_name = alert_consts.alertTypeLabel(tonumber(value["alert_id"]), true --[[ no_html --]], alert_entities.flow.entity_id)
local alert_risk = ntop.getFlowAlertRisk(tonumber(value.alert_id))
local l4_protocol = l4_proto_to_string(value["proto"])
local l7_protocol = interface.getnDPIFullProtoName(tonumber(value["l7_master_proto"]), tonumber(value["l7_proto"]))
local show_cli_port = (value["cli_port"] ~= '' and value["cli_port"] ~= '0')
local show_srv_port = (value["srv_port"] ~= '' and value["srv_port"] ~= '0')
local msg = alert_utils.formatFlowAlertMessage(interface.getId(), value, alert_info)
local active_url = ""
local attacker = ""
local victim = ""
-- Add link to active flow
local alert_json = json.decode(value.json)
local flow_related_info = addExtraFlowInfo(alert_json, value)
-- TLS IssuerDN
local flow_tls_issuerdn = nil
if alert_risk and alert_risk > 0 and
--record.script_key == 'tls_certificate_selfsigned'
tonumber(value.alert_id) == flow_alert_keys.flow_alert_tls_certificate_selfsigned
then
flow_tls_issuerdn = alert_utils.get_flow_risk_info(alert_risk, alert_info)
end
if isEmptyString(flow_tls_issuerdn) then
flow_tls_issuerdn = getExtraFlowInfoTLSIssuerDN(alert_json)
end
if not no_html and alert_json and (alert_json["ntopng.key"]) and (alert_json["hash_entry_id"]) then
local active_flow = interface.findFlowByKeyAndHashId(alert_json["ntopng.key"], alert_json["hash_entry_id"])
if active_flow and active_flow["seen.first"] < tonumber(value["tstamp_end"]) then
local href = string.format("%s/lua/flow_details.lua?flow_key=%u&flow_hash_id=%u",
ntop.getHttpPrefix(), active_flow["ntopng.key"], active_flow["hash_entry_id"])
active_url = href
end
end
local other_alerts_by_score = {} -- Table used to keep messages ordered by score
local additional_alerts = {}
other_alerts_by_score, additional_alerts = alert_utils.format_other_alerts(value.alerts_map, value['alert_id'])
-- Print additional issues, sorted by score
record[RNAME.ADDITIONAL_ALERTS.name] = ''
local cur_additional_alert = 0
for _, messages in pairsByKeys(other_alerts_by_score, rev) do
for _, message in pairsByValues(messages, asc) do
local cur_msg = ''
if cur_additional_alert > 0 then
-- Every 4 issues print a newline
cur_msg = cur_additional_alert and "<br>"
end
cur_additional_alert = cur_additional_alert + 1
cur_msg = cur_msg..message
record[RNAME.ADDITIONAL_ALERTS.name] = record[RNAME.ADDITIONAL_ALERTS.name] ..cur_msg
end
end
-- Handle VLAN as a separate field
local cli_ip = value["cli_ip"]
local srv_ip = value["srv_ip"]
local shorten_msg
record[RNAME.ADDITIONAL_ALERTS.name] = {
descr = record[RNAME.ADDITIONAL_ALERTS.name],
}
if no_html then
msg = noHtml(msg)
flow_related_info = noHtml(flow_related_info)
else
record[RNAME.DESCRIPTION.name] = {
descr = msg,
shorten_descr = shorten_msg,
}
end
local proto = string.lower(interface.getnDPIProtoName(tonumber(value["l7_master_proto"])))
local flow_server_name = getExtraFlowInfoServerName(alert_json)
local flow_domain
if hostnameIsDomain(flow_server_name) then
flow_domain = flow_server_name
end
record[RNAME.INFO.name] = {
descr = format_external_link(value["info"], value["info"], no_html, proto),
value = flow_domain, -- Domain name used for alert exclusion
issuerdn = flow_tls_issuerdn, -- IssuerDN used for alert exclusion
}
record[RNAME.FLOW_RELATED_INFO.name] = {
descr = flow_related_info,
}
record[RNAME.ALERT_NAME.name] = alert_name
local cli_host_pool_id = RNAME.CLI_HOST_POOL_ID.name
record[cli_host_pool_id] = {
value = value['cli_host_pool_id'],
label = getPoolName(value['cli_host_pool_id']),
}
local srv_host_pool_id = RNAME.SRV_HOST_POOL_ID.name
record[srv_host_pool_id] = {
value = value['srv_host_pool_id'],
label = getPoolName(value['srv_host_pool_id']),
}
local cli_network = RNAME.CLI_NETWORK.name
record[cli_network] = {
value = value['cli_network'],
label = getLocalNetworkAliasById(value['cli_network']),
}
local srv_network = RNAME.SRV_NETWORK.name
record[srv_network] = {
value = value['srv_network'],
label = getLocalNetworkAliasById(value['srv_network']),
}
-- Removing the server network if the host has no network
if value['srv_network'] == '65535' then
record[srv_network]['label'] = ''
record[srv_network]['value'] = ''
end
if value['cli_network'] == '65535' then
record[cli_network]['label'] = ''
record[cli_network]['value'] = ''
end
if string.lower(noHtml(msg)) == string.lower(noHtml(alert_name)) then
msg = ""
end
record[RNAME.MSG.name] = {
name = noHtml(alert_name),
fullname = alert_name,
value = tonumber(value["alert_id"]),
description = msg,
configset_ref = alert_utils.getConfigsetAlertLink(alert_info)
}
-- Format Client
local reference_html = ""
if not no_html then
reference_html = hostinfo2detailshref({ip = value["cli_ip"], value["vlan_id"]}, nil, href_icon, "", true, nil, false)
if reference_html == href_icon then
reference_html = ""
end
end
-- In case no country is found, let's check if the host is in memory and retrieve country info
local country = value["cli_country"]
if isEmptyString(country) or country == "nil" then
local host_info = interface.getHostMinInfo(cli_ip)
if host_info then
country = host_info["country"] or ""
end
end
local flow_cli_ip = {
value = cli_ip,
label = cli_ip,
reference = reference_html,
country = country,
blacklisted = value["cli_blacklisted"]
}
if no_html then
flow_cli_ip["label"] = cli_name_long
else
if not isEmptyString(value["cli_name"]) and value["cli_name"] ~= flow_cli_ip["value"] then
flow_cli_ip["name"] = value["cli_name"]
end
-- Shortened label if necessary for UI purposes
flow_cli_ip["label"] = hostinfo2label(self:_alert2hostinfo(value, true --[[ As client --]]), false --[[ Show VLAN --]], false --[[ Shorten --]])
flow_cli_ip["label_long"] = hostinfo2label(self:_alert2hostinfo(value, true --[[ As client --]]), false --[[ Show VLAN --]], false)
end
-- Format Server
reference_html = ""
if not no_html then
reference_html = hostinfo2detailshref({ip = value["srv_ip"], vlan = value["vlan_id"]}, nil, href_icon, "", true)
if reference_html == href_icon then
reference_html = ""
end
end
-- In case no country is found, let's check if the host is in memory and retrieve country info
country = value["srv_country"]
if isEmptyString(country) or country == "nil" then
local host_info = interface.getHostMinInfo(srv_ip)
if host_info then
country = host_info["country"] or ""
end
end
local flow_srv_ip = {
value = srv_ip,
label = srv_ip,
reference = reference_html,
country = country,
blacklisted = value["srv_blacklisted"]
}
if no_html then
flow_srv_ip["label"] = srv_name_long
else
if not isEmptyString(value["srv_name"]) and value["srv_name"] ~= flow_srv_ip["value"] then
flow_srv_ip["name"] = value["srv_name"]
end
-- Shortened label if necessary for UI purposes
flow_srv_ip["label"] = hostinfo2label(self:_alert2hostinfo(value, false --[[ As server --]]), false --[[ Show VLAN --]], false --[[ Shorten --]])
flow_srv_ip["label_long"] = hostinfo2label(self:_alert2hostinfo(value, false --[[ As server --]]), false --[[ Show VLAN --]], false)
end
local flow_cli_port = value["cli_port"]
local flow_srv_port = value["srv_port"]
local vlan
if value["vlan_id"] and tonumber(value["vlan_id"]) ~= 0 then
vlan = {
label = value["vlan_id"],
title = value["vlan_id"],
value = tonumber(value["vlan_id"]),
}
end
record[RNAME.FLOW.name] = {
vlan = vlan,
cli_ip = flow_cli_ip,
srv_ip = flow_srv_ip,
cli_port = flow_cli_port,
srv_port = flow_srv_port,
active_url = active_url,
}
record[RNAME.VLAN_ID.name] = value["vlan_id"]
record[RNAME.PROTO.name] = {
value = value["proto"],
label = l4_protocol
}
if value["is_cli_victim"] == "1" then record["cli_role"] = { value = 'victim', label = i18n("victim"), tag_label = i18n("victim") } end
if value["is_cli_attacker"] == "1" then record["cli_role"] = { value = 'attacker', label = i18n("attacker"), tag_label = i18n("attacker") } end
if value["is_srv_victim"] == "1" then record["srv_role"] = { value = 'victim', label = i18n("victim"), tag_label = i18n("victim") } end
if value["is_srv_attacker"] == "1" then record["srv_role"] = { value = 'attacker', label = i18n("attacker"), tag_label = i18n("attacker") } end
-- Check the two labels, otherwise an ICMP:ICMP label could be possible
local proto_label = l7_protocol
if l4_protocol ~= l7_protocol then
proto_label = l4_protocol..":"..l7_protocol
end
record[RNAME.L7_PROTO.name] = {
value = ternary(tonumber(value["l7_proto"]) ~= 0, value["l7_proto"], value["l7_master_proto"]),
l4_label = l4_protocol,
l7_label = l7_protocol,
label = proto_label,
confidence = format_confidence_from_json(value)
}
-- Add link to historical flow
if ntop.isEnterpriseM() and hasClickHouseSupport() and not no_html then
local op_suffix = tag_utils.SEPARATOR .. 'eq'
local href = string.format('%s/lua/pro/db_search.lua?epoch_begin=%u&epoch_end=%u&cli_ip=%s%s&srv_ip=%s%s&cli_port=%s%s&srv_port=%s%s&l4proto=%s%s',
ntop.getHttpPrefix(),
tonumber(value["tstamp"]) - (5*60),
tonumber(value["tstamp_end"]) + (5*60),
value["cli_ip"], op_suffix,
value["srv_ip"], op_suffix,
ternary(show_cli_port, tostring(value["cli_port"]), ''), op_suffix,
ternary(show_srv_port, tostring(value["srv_port"]), ''), op_suffix,
l4_protocol, op_suffix)
record[RNAME.LINK_TO_PAST_FLOWS.name] = href
end
-- Add BPF filter
local rules = {}
rules[#rules+1] = 'host ' .. value["cli_ip"]
rules[#rules+1] = 'host ' .. value["srv_ip"]
if value["cli_port"] and tonumber(value["cli_port"]) > 0 then
rules[#rules+1] = 'port ' .. tostring(value["cli_port"])
rules[#rules+1] = 'port ' .. tostring(value["srv_port"])
end
record['filter'] = {
epoch_begin = tonumber(value["tstamp"]),
epoch_end = tonumber(value["tstamp_end"]) + 1,
bpf = table.concat(rules, " and "),
}
local probe_ip = ''
local probe_label = ''
if value["probe_ip"] and value["probe_ip"] ~= "0.0.0.0" then
probe_ip = value["probe_ip"]
probe_label = getProbeName(probe_ip)
end
record[RNAME.PROBE_IP.name] = {
value = probe_ip,
label = probe_label,
}
return record
end
-- ##############################################
local function get_label_link(label, tag, value, add_hyperlink)
if add_hyperlink then
return "<a href=\"" .. ntop.getHttpPrefix() .. "/lua/alert_stats.lua?status=" .. _GET['status'] .. "&page=" .. _GET['page'] .. "&" ..
tag .. "=" .. value .. tag_utils.SEPARATOR .. "eq\" " .. ">" .. label .. "</a>"
else
return label
end
end
-- ##############################################
local function get_flow_link(fmt, add_hyperlink)
local label = ''
local value = fmt['flow']['cli_ip']['value']
local vlan = ''
local tag = 'cli_ip'
local vlan_id = 0
if fmt['flow']['vlan'] and fmt['flow']['vlan']["value"] ~= 0 then
vlan_id = tonumber(fmt['flow']['vlan']["value"])
vlan = '@' .. get_label_link(fmt['flow']['vlan']['label'], 'vlan_id', fmt['flow']['vlan']["value"], add_hyperlink)
end
local reference = hostinfo2detailshref({ip = fmt['flow']['cli_ip']['value'], vlan = vlan_id}, nil, href_icon, "", true)
local cli_ip = ""
local srv_ip = ""
if fmt['flow']['cli_ip']['label_long'] ~= fmt['flow']['cli_ip']['value'] then
if add_hyperlink then
cli_ip = " [ " .. get_label_link(fmt['flow']['cli_ip']['value'], 'cli_ip', value, add_hyperlink) .. " ]"
end
value = fmt['flow']['cli_ip']['label_long']
tag = 'cli_name'
end
label = label .. get_label_link(fmt['flow']['cli_ip']['label_long'], tag, value, add_hyperlink) .. cli_ip
if fmt['flow']['cli_port'] then
label = label .. vlan .. ':' .. get_label_link(fmt['flow']['cli_port'], 'cli_port', fmt['flow']['cli_port'], add_hyperlink)
end
if add_hyperlink then
label = label .. " " .. reference
end
label = label .. ' <i class="fas fa-exchange-alt fa-lg" aria-hidden="true"></i> '
reference = hostinfo2detailshref({ip = fmt['flow']['srv_ip']['value'], vlan = vlan_id}, nil, href_icon, "", true)
local value = fmt['flow']['srv_ip']['value']
local tag = 'srv_ip'
if fmt['flow']['srv_ip']['label_long'] ~= fmt['flow']['srv_ip']['value'] then
if add_hyperlink then
srv_ip = " [ " .. get_label_link(fmt['flow']['srv_ip']['value'], 'srv_ip', value, add_hyperlink) .. " ]"
end
value = fmt['flow']['srv_ip']['label_long']
tag = 'srv_name'
end
label = label .. get_label_link(fmt['flow']['srv_ip']['label_long'], tag, value, add_hyperlink) .. srv_ip
if fmt['flow']['srv_port'] then
label = label .. vlan .. ':' .. get_label_link(fmt['flow']['srv_port'], 'srv_port', fmt['flow']['srv_port'], add_hyperlink)
end
if add_hyperlink then
label = label .. " " .. reference
end
return label
end
-- ##############################################
--@brief Edit specifica proto info, like converting
-- timestamp to date/time for TLS Certificate Validity
local function editProtoDetails(proto_info)
for key, value in pairs(proto_info) do
if type(value) ~= "table" then
proto_info[key] = nil
end
end
for proto, info in pairs(proto_info) do
if proto == "tls" then
info = format_tls_info(info)
break;
elseif proto == "dns" then
info = format_dns_query_info(info)
break;
elseif proto == "http" then
info = format_http_info(info)
break;
elseif proto == "icmp" then
info = format_icmp_info(info)
break;
end
end
return proto_info
end
-- ##############################################
local function add_historical_link(value, flow_link)
local historical_href = ""
if ntop.isClickHouseEnabled() then
historical_href = "<a href=\"" .. ntop.getHttpPrefix() .. "/lua/pro/db_flow_details.lua?row_id=" .. value["rowid"] .. "&tstamp=" .. value["tstamp_epoch"] .. "\" title='" .. i18n('alert_details.flow_details') .. "' target='_blank'> <i class='fas fa fa-search-plus'></i> </a>"
end
return flow_link .. " " ..historical_href
end
-- ##############################################
--@brief Get a label/title for the alert coming from the DB (value)
function flow_alert_store:get_alert_label(value)
local fmt = self:format_record(value, false)
return fmt['msg']['name'] .. ' | ' .. get_flow_link(fmt, false)
end
-- ##############################################
--@brief Convert an alert coming from the DB (value) to a list of items to be printed in the details page
function flow_alert_store:get_alert_details(value)
local details = {}
local fmt = self:format_record(value, false)
local add_hyperlink = true
local json = json.decode(value["json"]) or {}
local proto_info = json["proto"]
local traffic_info = {}
details[#details + 1] = {
label = i18n("alerts_dashboard.alert"),
content = get_label_link(fmt['alert_id']['label'], 'alert_id', fmt['alert_id']['value'], add_hyperlink)
}
details[#details + 1] = {
label = i18n("flow_details.flow_peers_client_server"),
content = add_historical_link(value, get_flow_link(fmt, add_hyperlink))
}
details[#details + 1] = {
label = i18n("protocol") .. " / " .. i18n("application"),
content = get_label_link(fmt['l7_proto']['l4_label'] .. ':' .. fmt['l7_proto']['l7_label'], 'l7proto', fmt['l7_proto']['value'], add_hyperlink)
}
details[#details + 1] = {
label = i18n("show_alerts.alert_datetime"),
content = fmt['tstamp']['label'],
}
details[#details + 1] = {
label = i18n("score"),
content = '<span style="color: ' .. fmt['score']['color'] .. '">' .. fmt['score']['label'] .. '</span>',
}
details[#details + 1] = {
label = i18n("description"),
content = fmt['msg']['description'],
}
details[#details + 1] = {
label = i18n("flow_details.additional_alert_type"),
content = fmt['additional_alerts']['descr'],
}
if(proto_info and (proto_info.l7_error_code ~= nil) and (proto_info.l7_error_code ~= 0)) then
details[#details + 1] = {
label = i18n("l7_error_code"),
content = proto_info.l7_error_code
}
proto_info.l7_error_code = nil -- Avoid to print it twice in the flow details section
end
proto_info = editProtoDetails(proto_info or {})
traffic_info = format_common_info(value, traffic_info)
details[#details + 1] = {
label = i18n("flow_details.traffic_info"),
content = traffic_info
}
for k, info in pairs(proto_info or {}) do
details[#details + 1] = {
label = i18n("alerts_dashboard.flow_related_info"),
content = info
}
end
--[[
details[#details + 1] = {
label = "Title",
content = {
[1] = "Content 1",
[2] = "Content 2",
}
}
--]]
return details
end
-- ##############################################
return flow_alert_store
| gpl-3.0 |
corbinmunce/domoticz | dzVents/runtime/persistence.lua | 19 | 5741 | -- Internal persistence library
--[[ Provides ]]
-- persistence.store(path, ...): Stores arbitrary items to the file at the given path
-- persistence.load(path): Loads files that were previously stored with store and returns them
--[[ Limitations ]]
-- Does not export userdata, threads or most function values
-- Function export is not portable
--[[ License: MIT (see bottom) ]]
-- Private methods
local write, writeIndent, writers, refCount;
persistence =
{
store = function (path, ...)
local file, e;
if type(path) == "string" then
-- Path, open a file
file, e = io.open(path, "w");
if not file then
return error(e);
end
else
-- Just treat it as file
file = path;
end
local n = select("#", ...);
-- Count references
local objRefCount = {}; -- Stores reference that will be exported
for i = 1, n do
refCount(objRefCount, (select(i,...)));
end;
-- Export Objects with more than one ref and assign name
-- First, create empty tables for each
local objRefNames = {};
local objRefIdx = 0;
file:write("-- Persistent Data\n");
file:write("local multiRefObjects = {\n");
for obj, count in pairs(objRefCount) do
if count > 1 then
objRefIdx = objRefIdx + 1;
objRefNames[obj] = objRefIdx;
file:write("{};"); -- table objRefIdx
end;
end;
file:write("\n} -- multiRefObjects\n");
-- Then fill them (this requires all empty multiRefObjects to exist)
for obj, idx in pairs(objRefNames) do
for k, v in pairs(obj) do
file:write("multiRefObjects["..idx.."][");
write(file, k, 0, objRefNames);
file:write("] = ");
write(file, v, 0, objRefNames);
file:write(";\n");
end;
end;
-- Create the remaining objects
for i = 1, n do
file:write("local ".."obj"..i.." = ");
write(file, (select(i,...)), 0, objRefNames);
file:write("\n");
end
-- Return them
if n > 0 then
file:write("return obj1");
for i = 2, n do
file:write(" ,obj"..i);
end;
file:write("\n");
else
file:write("return\n");
end;
file:close();
end;
load = function (path)
local f, e = loadfile(path);
if f then
return f();
else
return nil, e;
end;
end;
}
-- Private methods
-- write thing (dispatcher)
write = function (file, item, level, objRefNames)
writers[type(item)](file, item, level, objRefNames);
end;
-- write indent
writeIndent = function (file, level)
for i = 1, level do
file:write("\t");
end;
end;
-- recursively count references
refCount = function (objRefCount, item)
-- only count reference types (tables)
if type(item) == "table" then
-- Increase ref count
if objRefCount[item] then
objRefCount[item] = objRefCount[item] + 1;
else
objRefCount[item] = 1;
-- If first encounter, traverse
for k, v in pairs(item) do
refCount(objRefCount, k);
refCount(objRefCount, v);
end;
end;
end;
end;
-- Format items for the purpose of restoring
writers = {
["nil"] = function (file, item)
file:write("nil");
end;
["number"] = function (file, item)
file:write(tostring(item));
end;
["string"] = function (file, item)
file:write(string.format("%q", item));
end;
["boolean"] = function (file, item)
if item then
file:write("true");
else
file:write("false");
end
end;
["table"] = function (file, item, level, objRefNames)
local refIdx = objRefNames[item];
if refIdx then
-- Table with multiple references
file:write("multiRefObjects["..refIdx.."]");
else
-- Single use table
file:write("{\n");
for k, v in pairs(item) do
writeIndent(file, level+1);
file:write("[");
write(file, k, level+1, objRefNames);
file:write("] = ");
write(file, v, level+1, objRefNames);
file:write(";\n");
end
writeIndent(file, level);
file:write("}");
end;
end;
["function"] = function (file, item)
file:write("nil --[[function]]\n");
-- -- Does only work for "normal" functions, not those
-- -- with upvalues or c functions
-- local dInfo = debug.getinfo(item, "uS");
-- if dInfo.nups > 0 then
-- --file:write("nil --[[functions with upvalue not supported]]");
-- elseif dInfo.what ~= "Lua" then
-- --file:write("nil --[[non-lua function not supported]]");
-- else
-- local r, s = pcall(string.dump,item);
-- if r then
-- file:write(string.format("loadstring(%q)", s));
-- else
-- --file:write("nil --[[function could not be dumped]]");
-- end
-- end
end;
["thread"] = function (file, item)
file:write("nil --[[thread]]\n");
end;
["userdata"] = function (file, item)
file:write("nil --[[userdata]]\n");
end;
}
return persistence
--[[
Copyright (c) 2010 Gerhard Roethlin
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.
]]
| gpl-3.0 |
shangjiyu/openwrt-extra | luci/applications/luci-app-vsftpd/luasrc/model/cbi/vsftpd/item.lua | 8 | 1728 | --[[
LuCI - Lua Configuration Interface
Copyright 2016 Weijie Gao <hackpascal@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local sid = arg[1]
local utl = require "luci.util"
m = Map("vsftpd", translate("FTP Server - Virtual User <new>"))
m.redirect = luci.dispatcher.build_url("admin/services/vsftpd/users")
if m.uci:get("vsftpd", sid) ~= "user" then
luci.http.redirect(m.redirect)
return
end
m.uci:foreach("vsftpd", "user",
function(s)
if s['.name'] == sid and s.username then
m.title = translatef("FTP Server - Virtual User %q", s.username)
return false
end
end)
s = m:section(NamedSection, sid, "settings", translate("User Settings"))
s.addremove = false
o = s:option(Value, "username", translate("Username"))
o.rmempty = false
function o.validate(self, value)
if value == "" then
return nil, translate("Username cannot be empty")
end
return value
end
o = s:option(Value, "password", translate("Password"))
o.password = true
o = s:option(Value, "home", translate("Home directory"))
o.default = "/home/ftp"
o = s:option(Value, "umask", translate("File mode umask"))
o.default = "022"
o = s:option(Value, "maxrate", translate("Max transmit rate"), translate("0 means no limitation"))
o.default = "0"
o = s:option(Flag, "writemkdir", translate("Enable write/mkdir"))
o.default = false
o = s:option(Flag, "upload", translate("Enable upload"))
o.default = false
o = s:option(Flag, "others", translate("Enable other rights"), translate("Include rename, deletion ..."))
o.default = false
return m
| gpl-2.0 |
ASantosVal/vlc-extension-trials | share/lua/playlist/canalplus.lua | 8 | 3507 | --[[
$Id: $
Copyright (c) 2007 the VideoLAN team
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, "^www%.canalplus%.fr/.+" )
end
-- Parse function.
function parse()
p = {}
--vlc.msg.dbg( vlc.path )
if string.match( vlc.path, "www.canalplus.fr/.*%?pid=.*" )
then -- This is the HTML page's URL
local _,_,pid = string.find( vlc.path, "pid(%d-)%-" )
local id, name, description, arturl
while true do
-- Try to find the video's title
local line = vlc.readline()
if not line then break end
-- vlc.msg.dbg( line )
if string.match( line, "aVideos" ) then
if string.match( line, "CONTENT_ID.*=" ) then
_,_,id = string.find( line, "\"(.-)\"" )
elseif string.match( line, "CONTENT_VNC_TITRE" ) then
_,_,arturl = string.find( line, "src=\"(.-)\"" )
_,_,name = string.find( line, "title=\"(.-)\"" )
elseif string.match( line, "CONTENT_VNC_DESCRIPTION" ) then
_,_,description = string.find( line, "\"(.-)\"" )
end
if id and string.match( line, "new Array" ) then
add_item( p, id, name, description, arturl )
id = nil
name = nil
arturl = nil
description = nil
end
end
end
if id then
add_item( p, id, name, description, arturl )
end
return p
elseif string.match( vlc.path, "embed%-video%-player" ) then
while true do
local line = vlc.readline()
if not line then break end
--vlc.msg.dbg( line )
if string.match( line, "<hi" ) then
local _,_,path = string.find( line, "%[(http.-)%]" )
return { { path = path } }
end
end
end
end
function get_url_param( url, name )
local _,_,ret = string.find( url, "[&?]"..name.."=([^&]*)" )
return ret
end
function add_item( p, id, name, description, arturl )
--[[vlc.msg.dbg( "id: " .. tostring(id) )
vlc.msg.dbg( "name: " .. tostring(name) )
vlc.msg.dbg( "arturl: " .. tostring(arturl) )
vlc.msg.dbg( "description: " .. tostring(description) )
--]]
--local path = "http://www.canalplus.fr/flash/xml/configuration/configuration-embed-video-player.php?xmlParam="..id.."-"..get_url_param(vlc.path,"pid")
local path = "http://www.canalplus.fr/flash/xml/module/embed-video-player/embed-video-player.php?video_id="..id.."&pid="..get_url_param(vlc.path,"pid")
table.insert( p, { path = path; name = name; description = description; arturl = arturl } )
end
| gpl-2.0 |
Banderi/OpenTomb | scripts/strings/english/generic.lua | 5 | 3151 | -- OPENTOMB GENERIC STRINGS - ENGLISH LANGUAGE
-- by Lwmte, Jan 2015
--------------------------------------------------------------------------------
-- This set of strings is used globally in all engine versions for various
-- menu entries, notify pop-ups, inventory entries etc.
--------------------------------------------------------------------------------
-- Game menu entries
strings[000] = "New Game";
strings[001] = "Select Game";
strings[002] = "Select Level";
strings[003] = "Lara's Home";
strings[004] = "Save Game";
strings[005] = "Load Game";
strings[006] = "Options";
strings[007] = "Quit";
strings[008] = "Restart Level";
strings[009] = "Exit to Title";
-- Dialog components
strings[010] = "Yes";
strings[011] = "No";
strings[012] = "Apply";
strings[013] = "Cancel";
strings[014] = "Previous";
strings[015] = "Next";
strings[016] = "OK";
strings[017] = "Discard";
-- Interface headers
strings[018] = "INVENTORY";
strings[019] = "ITEMS";
strings[020] = "PAUSED";
strings[021] = "OPTIONS";
strings[022] = "STATISTICS";
-- Dialogs
strings[023] = "Exit Game?";
strings[024] = "Select Game to Load";
strings[025] = "Select Game to Save";
strings[026] = "Select Item to Combine";
-- Inventory actions
strings[027] = "Equip";
strings[028] = "Choose Ammo";
strings[029] = "Choose Fire Mode";
strings[030] = "Use";
strings[031] = "Combine";
strings[032] = "Separate";
strings[033] = "Examine";
strings[034] = "Throw Away";
-- Interface hints
strings[035] = " - Accept";
strings[036] = " - Cancel";
strings[037] = "Hold left mouse button and pan to rotate inventory.";
strings[038] = "Scoll mouse wheel to switch inventory menu.";
strings[039] = "Hold right mouse button and pan to examine item.";
-- Statistics bar
strings[040] = "Location: %s";
strings[041] = "Secrets: %d / %d";
strings[042] = "Distance: %d km";
strings[043] = "Ammo used: %d";
strings[044] = "Kills: %d";
strings[045] = "Medipacks used: %d";
-- Notify pop-up tips - FIND A WAY TO USE THEM!
strings[046] = "Press ROLL while crouching in TR3-5 to use crawlspace roll.";
strings[047] = "In OpenTomb, Lara slides from slopes in their exact direction.";
strings[048] = "Did you know that at least ten different programmers worked on OpenTomb?"; -- ;)
strings[049] = "Did you know that Core Design never released any Tomb Raider source code?"; -- Whatever... :]
strings[050] = "Press INVENTORY key to skip.";
-- String masks
strings[090] = "%s (%d)" -- Inventory item header
strings[091] = "%dx %s" -- Ammo header
strings[092] = "%02d:%02d:%02d" -- Timer
strings[093] = "%d days, %02d:%02d" -- Time passed
-- Game names - to use with Select Game menu...
strings[100] = "Tomb Raider I";
strings[101] = "Tomb Raider I Gold: Unfinished Business";
strings[200] = "Tomb Raider II";
strings[201] = "Tomb Raider II Gold: The Golden Mask";
strings[300] = "Tomb Raider III";
strings[301] = "Tomb Raider III Gold: The Lost Artifact";
strings[400] = "Tomb Raider IV: The Last Revelation";
strings[401] = "Tomb Raider IV Bonus: The Times Level";
strings[500] = "Tomb Raider V: Chronicles";
strings[600] = "Custom Levels"; | lgpl-3.0 |
vikas17a/Algorithm-Implementations | Caesar_Cipher/Lua/Yonaba/caesar_cipher_test.lua | 26 | 1202 | -- Tests for caesar_cipher.lua
local caesar = require 'caesar_cipher'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
run('Ciphering test', function()
assert(caesar.cipher('abcd',1) == 'bcde')
assert(caesar.cipher('WXYZ',2) == 'YZAB')
assert(caesar.cipher('abcdefghijklmnopqrstuvwxyz',3) == 'defghijklmnopqrstuvwxyzabc')
assert(caesar.cipher('ABCDEFGHIJKLMNOPQRSTUVWXYZ',4) == 'EFGHIJKLMNOPQRSTUVWXYZABCD')
end)
run('Deciphering test', function()
assert(caesar.decipher('bcde',1) == 'abcd')
assert(caesar.decipher('YZAB',2) == 'WXYZ')
assert(caesar.decipher('defghijklmnopqrstuvwxyzabc',3) == 'abcdefghijklmnopqrstuvwxyz')
assert(caesar.decipher('EFGHIJKLMNOPQRSTUVWXYZABCD',4) == 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
shadowmourne/vicious | widgets/mem.lua | 15 | 1850 | ---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2010, Adrian C. <anrxc@sysphere.org>
-- * (c) 2009, Lucas de Vries <lucas@glacicle.com>
---------------------------------------------------
-- {{{ Grab environment
local io = { lines = io.lines }
local setmetatable = setmetatable
local math = { floor = math.floor }
local string = { gmatch = string.gmatch }
-- }}}
-- Mem: provides RAM and Swap usage statistics
-- vicious.widgets.mem
local mem = {}
-- {{{ Memory widget type
local function worker(format)
local _mem = { buf = {}, swp = {} }
-- Get MEM info
for line in io.lines("/proc/meminfo") do
for k, v in string.gmatch(line, "([%a]+):[%s]+([%d]+).+") do
if k == "MemTotal" then _mem.total = math.floor(v/1024)
elseif k == "MemFree" then _mem.buf.f = math.floor(v/1024)
elseif k == "Buffers" then _mem.buf.b = math.floor(v/1024)
elseif k == "Cached" then _mem.buf.c = math.floor(v/1024)
elseif k == "SwapTotal" then _mem.swp.t = math.floor(v/1024)
elseif k == "SwapFree" then _mem.swp.f = math.floor(v/1024)
end
end
end
-- Calculate memory percentage
_mem.free = _mem.buf.f + _mem.buf.b + _mem.buf.c
_mem.inuse = _mem.total - _mem.free
_mem.bcuse = _mem.total - _mem.buf.f
_mem.usep = math.floor(_mem.inuse / _mem.total * 100)
-- Calculate swap percentage
_mem.swp.inuse = _mem.swp.t - _mem.swp.f
_mem.swp.usep = math.floor(_mem.swp.inuse / _mem.swp.t * 100)
return {_mem.usep, _mem.inuse, _mem.total, _mem.free,
_mem.swp.usep, _mem.swp.inuse, _mem.swp.t, _mem.swp.f,
_mem.bcuse }
end
-- }}}
return setmetatable(mem, { __call = function(_, ...) return worker(...) end })
| gpl-2.0 |
Altenius/cuberite | Server/Plugins/APIDump/Classes/Projectiles.lua | 1 | 8520 | return
{
cArrowEntity =
{
Desc = [[
Represents the arrow when it is shot from the bow. A subclass of the {{cProjectileEntity}}.
]],
Functions =
{
CanPickup =
{
Params =
{
{
Name = "Player",
Type = "cPlayer",
},
},
Returns =
{
{
Type = "boolean",
},
},
Notes = "Returns true if the specified player can pick the arrow when it's on the ground",
},
GetBlockHit =
{
Notes = "Returns the coords of the block into which the arrow is stuck. Undefined if the arrow is still moving.",
Returns =
{
{
Type = "Vector3i",
},
},
},
GetDamageCoeff =
{
Returns =
{
{
Type = "number",
},
},
Notes = "Returns the damage coefficient stored within the arrow. The damage dealt by this arrow is multiplied by this coeff",
},
GetPickupState =
{
Returns =
{
{
Type = "cArrowEntity#ePickupState",
},
},
Notes = "Returns the pickup state (one of the psXXX constants, above)",
},
IsCritical =
{
Returns =
{
{
Type = "boolean",
},
},
Notes = "Returns true if the arrow should deal critical damage. Based on the bow charge when the arrow was shot.",
},
SetDamageCoeff =
{
Params =
{
{
Name = "DamageCoeff",
Type = "number",
},
},
Notes = "Sets the damage coefficient. The damage dealt by this arrow is multiplied by this coeff",
},
SetIsCritical =
{
Params =
{
{
Name = "IsCritical",
Type = "boolean",
},
},
Notes = "Sets the IsCritical flag on the arrow. Critical arrow deal additional damage",
},
SetPickupState =
{
Params =
{
{
Name = "PickupState",
Type = "cArrowEntity#ePickupState",
},
},
Notes = "Sets the pickup state (one of the psXXX constants, above)",
},
},
Constants =
{
psInCreative =
{
Notes = "The arrow can be picked up only by players in creative gamemode",
},
psInSurvivalOrCreative =
{
Notes = "The arrow can be picked up by players in survival or creative gamemode",
},
psNoPickup =
{
Notes = "The arrow cannot be picked up at all",
},
},
ConstantGroups =
{
ePickupState =
{
Include = "ps.*",
TextBefore = [[
The following constants are used to signalize whether the arrow, once it lands, can be picked by
players:
]],
},
},
Inherits = "cProjectileEntity",
},
cExpBottleEntity =
{
Desc = [[
Represents a thrown ExpBottle. A subclass of the {{cProjectileEntity}}.
]],
Functions =
{
},
Inherits = "cProjectileEntity",
},
cFireChargeEntity =
{
Desc = [[
Represents a fire charge that has been shot by a Blaze or a {{cDispenserEntity|Dispenser}}. A subclass
of the {{cProjectileEntity}}.
]],
Functions =
{
},
Inherits = "cProjectileEntity",
},
cFireworkEntity =
{
Desc = [[
Represents a firework rocket.
]],
Functions =
{
GetItem =
{
Returns =
{
{
Type = "cItem",
},
},
Notes = "Returns the item that has been used to create the firework rocket. The item's m_FireworkItem member contains all the firework-related data.",
},
GetTicksToExplosion =
{
Returns =
{
{
Type = "number",
},
},
Notes = "Returns the number of ticks left until the firework explodes.",
},
SetItem =
{
Params =
{
{
Name = "FireworkItem",
Type = "cItem",
},
},
Notes = "Sets a new item to be used for the firework.",
},
SetTicksToExplosion =
{
Params =
{
{
Name = "NumTicks",
Type = "number",
},
},
Notes = "Sets the number of ticks left until the firework explodes.",
},
},
Inherits = "cProjectileEntity",
},
cGhastFireballEntity =
{
Desc = "",
Functions =
{
},
Inherits = "cProjectileEntity",
},
cProjectileEntity =
{
Desc = "Base class for all projectiles, such as arrows and fireballs.",
Functions =
{
GetCreator =
{
Returns =
{
{
Type = "cEntity",
},
},
Notes = "Returns the entity who created this projectile. May return nil.",
},
GetCreatorName =
{
Returns =
{
{
Type = "string",
},
},
Notes = "Returns the name of the player that created the projectile. Will be empty for non-player creators",
},
GetCreatorUniqueID =
{
Returns =
{
{
Type = "number",
},
},
Notes = "Returns the unique ID of the entity who created this projectile, or {{cEntity#INVALID_ID|cEntity.INVALID_ID}} if the projectile wasn't created by an entity.",
},
GetMCAClassName =
{
Returns =
{
{
Type = "string",
},
},
Notes = "Returns the string that identifies the projectile type (class name) in MCA files",
},
GetProjectileKind =
{
Returns =
{
{
Type = "cProjectileEntity#eKind",
},
},
Notes = "Returns the kind of this projectile (pkXXX constant)",
},
IsInGround =
{
Returns =
{
{
Type = "boolean",
},
},
Notes = "Returns true if this projectile has hit the ground.",
},
},
Constants =
{
pkArrow =
{
Notes = "The projectile is an {{cArrowEntity|arrow}}",
},
pkEgg =
{
Notes = "The projectile is a {{cThrownEggEntity|thrown egg}}",
},
pkEnderPearl =
{
Notes = "The projectile is a {{cThrownEnderPearlEntity|thrown enderpearl}}",
},
pkExpBottle =
{
Notes = "The projectile is a {{cExpBottleEntity|thrown exp bottle}}",
},
pkFireCharge =
{
Notes = "The projectile is a {{cFireChargeEntity|fire charge}}",
},
pkFirework =
{
Notes = "The projectile is a (flying) {{cFireworkEntity|firework}}",
},
pkFishingFloat =
{
Notes = "The projectile is a {{cFloater|fishing float}}",
},
pkGhastFireball =
{
Notes = "The projectile is a {{cGhastFireballEntity|ghast fireball}}",
},
pkSnowball =
{
Notes = "The projectile is a {{cThrownSnowballEntity|thrown snowball}}",
},
pkSplashPotion =
{
Notes = "The projectile is a {{cSplashPotionEntity|thrown splash potion}}",
},
pkWitherSkull =
{
Notes = "The projectile is a {{cWitherSkullEntity|wither skull}}",
},
},
ConstantGroups =
{
eKind =
{
Include = "pk.*",
TextBefore = "The following constants are used to distinguish between the different projectile kinds:",
},
},
Inherits = "cEntity",
},
cSplashPotionEntity =
{
Desc = [[
Represents a thrown splash potion.
]],
Functions =
{
GetEntityEffect =
{
Returns =
{
{
Type = "cEntityEffect",
},
},
Notes = "Returns the entity effect in this potion",
},
GetEntityEffectType =
{
Returns =
{
{
Type = "cEntityEffect",
},
},
Notes = "Returns the effect type of this potion",
},
GetItem =
{
Returns =
{
{
Type = "cItem",
},
},
Notes = "Gets the potion item that was thrown.",
},
GetPotionColor =
{
Returns =
{
{
Type = "number",
},
},
Notes = "Returns the color index of the particles emitted by this potion",
},
SetEntityEffect =
{
Params =
{
{
Name = "EntityEffect",
Type = "cEntityEffect",
},
},
Notes = "Sets the entity effect for this potion",
},
SetEntityEffectType =
{
Params =
{
{
Name = "EntityEffectType",
Type = "cEntityEffect#eType",
},
},
Notes = "Sets the effect type of this potion",
},
SetPotionColor =
{
Params =
{
{
Name = "PotionColor",
Type = "number",
},
},
Notes = "Sets the color index of the particles for this potion",
},
},
Inherits = "cProjectileEntity",
},
cThrownEggEntity =
{
Desc = [[
Represents a thrown egg.
]],
Functions =
{
},
Inherits = "cProjectileEntity",
},
cThrownEnderPearlEntity =
{
Desc = "Represents a thrown ender pearl.",
Functions =
{
},
Inherits = "cProjectileEntity",
},
cThrownSnowballEntity =
{
Desc = "Represents a thrown snowball.",
Functions =
{
},
Inherits = "cProjectileEntity",
},
cWitherSkullEntity =
{
Desc = "Represents a wither skull being shot.",
Functions =
{
},
Inherits = "cProjectileEntity",
},
}
| apache-2.0 |
graydon/monotone | tests/_MTN_case-folding_security_patch/__driver__.lua | 1 | 2294 |
mtn_setup()
-- The patch for this security issue is to treat all case-folded
-- versions of _MTN as being bookkeeping files (and thus illegal
-- file_paths). Make sure it's working.
names = {"_mtn", "_mtN", "_mTn", "_Mtn", "_MTn", "_MtN", "_mTN", "_MTN"}
-- bookkeeping files are an error for add
for _,i in pairs(names) do if not exists(i) then writefile(i) end end
for _,i in pairs(names) do
check(mtn("add", i), 1, false, true)
check(qgrep(i, "stderr"))
end
check(mtn("ls", "known"), 0, true, false)
check(grep("-qi", "_mtn", "stdout"), 1)
for _,i in pairs(names) do remove(i) end
-- run setup again, because we've removed our bookkeeping dir.
check(mtn("--branch=testbranch", "setup", "."))
-- files in bookkeeping dirs are also ignored by add
-- (mkdir -p used because the directories already exist on case-folding FSes)
for _,i in pairs(names) do
if not exists(i) then mkdir(i) end
writefile(i.."/foo", "")
end
for _,i in pairs(names) do
check(mtn("add", i), 1, false, true)
check(qgrep(i, "stderr"))
end
check(mtn("ls", "known"), 0, true, false)
check(grep("-qi", "_mtn", "stdout"), 1)
for _,i in pairs(names) do remove(i) end
-- just to make sure, check that it's not only add that fails, if it somehow
-- sneaks into an internal format then that fails too
remove("_MTN")
check(mtn("--branch=testbranch", "setup", "."))
mkdir("_mTn")
writefile("_MTN/revision",
'format_version "1"\n'
.. '\n'
.. 'new_manifest []\n'
.. '\n'
.. 'old_revision []\n'
.. '\n'
.. 'add_dir ""\n'
.. '\n'
.. 'add_dir "_mTn"\n')
check(mtn("status"), 3, false, false)
check(mtn("commit", "-m", "blah"), 3, false, false)
-- assert trips if we have a db that already has a file with this sort
-- of name in it. it would be better to test that checkout or pull fail, but
-- it is too difficult to regenerate this database every time things change,
-- and in fact we know that the same code paths are exercised by this.
for _,i in pairs({"files", "dirs"}) do
get(i..".db.dumped", "stdin")
check(mtn("db", "load", "-d", i..".mtn"), 0, false, false, true)
check(mtn("db", "migrate", "-d", i..".mtn"), 0, false, false)
check(mtn("-d", i..".mtn", "db", "regenerate_caches"), 3, false, false)
end
| gpl-2.0 |
wsantas/gamecode4 | Assets/Scripts/ActorManager.lua | 4 | 10265 | --========================================================================
-- ActorManager.lua : Defines the ActorManager class
--
-- Part of the GameCode4 Application
--
-- GameCode4 is the sample application that encapsulates much of the source code
-- discussed in "Game Coding Complete - 4th Edition" by Mike McShaffry and David
-- "Rez" Graham, published by Charles River Media.
-- ISBN-10: 1133776574 | ISBN-13: 978-1133776574
--
-- If this source code has found it's way to you, and you think it has helped you
-- in any way, do the authors a favor and buy a new copy of the book - there are
-- detailed explanations in it that compliment this code well. Buy a copy at Amazon.com
-- by clicking here:
-- http://www.amazon.com/gp/product/1133776574/ref=olp_product_details?ie=UTF8&me=&seller=
--
-- There's a companion web site at http://www.mcshaffry.com/GameCode/
--
-- The source code is managed and maintained through Google Code:
-- http://code.google.com/p/gamecode4/
--
-- (c) Copyright 2012 Michael L. McShaffry and David Graham
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser GPL v3
-- as published by the Free Software Foundation.
--
-- 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
-- http://www.gnu.org/licenses/lgpl-3.0.txt for more details.
--
-- You should have received a copy of the GNU Lesser GPL v3
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--
--========================================================================
require("scripts\\TeapotAi.lua");
-- brains
require("scripts\\HardCodedBrain.lua");
require("scripts\\DecisionTreeBrain.lua");
require("scripts\\DebugBrain.lua");
-- [rez] Set this constant to change brains for teapots. Note that there's no visual difference between
-- the hard-coded brain and the decision tree brain, they just have different implementations under the
-- covers. This is a good example of how to keep the AI decision making nice and decoupled from the rest
-- of your engine.
TEAPOT_BRAIN = DecisionTreeBrain;
--TEAPOT_BRAIN = HardCodedBrain;
-----------------------------------------------------------------------------------------------------------------------
-- Internal Processes that operate on the ActorManager.
-----------------------------------------------------------------------------------------------------------------------
ActorManagerProcess = class(ScriptProcess,
{
_enemies = nil, -- this points to the same table as ActorManager._enemies
});
--------------------
EnemyHealer = class(ActorManagerProcess,
{
--
});
function EnemyHealer:OnUpdate(deltaMs)
print("Healing all enemies");
for id, actor in pairs(self._enemies) do
actor.hitPoints = actor.maxHitPoints;
end
g_actorMgr:UpdateUi();
end
--------------------
-- Chapter 21, page 744
EnemyThinker = class(ActorManagerProcess,
{
--
});
function EnemyThinker:OnUpdate(deltaMs)
print("Running AI update for enemies");
for id, actor in pairs(self._enemies) do
actor.stateMachine:ChooseBestState();
end
end
--------------------
EnemyUpdater = class(ActorManagerProcess,
{
--
});
function EnemyUpdater:OnUpdate(deltaMs)
for id, actor in pairs(self._enemies) do
actor.stateMachine:Update(deltaMs);
end
end
-----------------------------------------------------------------------------------------------------------------------
-- ActorManager - Chapter 21, page 739
-- This class manages the script representation of all actors in the game.
-----------------------------------------------------------------------------------------------------------------------
ActorManager = class(nil,
{
_player = nil, -- this will be filled automatically when player_teapot.xml is loaded
_enemies = {}, -- a map of enemy teapots; key = actor id
_spheres = {}, -- a map of spheres; key = actor id
-- processes
_enemyProcesses = nil;
_enemyHealer = nil, -- process that periodically heals all enemies
_enemyThinker = nil, -- process that causes enemies to make a new decision
_enemyUpdater = nil, -- process that updates all enemy states
});
function ActorManager:AddPlayer(scriptObject)
if (self._player ~= nil) then
print("Attempting to add player to ActorManager when one already exists; id = " .. self._player:GetActorId());
end
-- add the new player regardless
self._player = scriptObject;
-- tell the human view that this is the controlled actor
QueueEvent(EventType.EvtData_Set_Controlled_Actor, self._player:GetActorId());
end
function ActorManager:RemovePlayer(scriptObject)
self._player = nil;
end
function ActorManager:GetPlayer()
return self._player;
end
function ActorManager:AddEnemy(scriptObject)
print("Adding Enemy");
-- add the enemy to the list of enemies
local actorId = scriptObject:GetActorId();
if (self._enemies[actorId] ~= nil) then
print("Overwriting enemy actor; id = " .. actorId);
end
self._enemies[actorId] = scriptObject;
-- set up some sample game data
scriptObject.maxHitPoints = 3;
scriptObject.hitPoints = scriptObject.maxHitPoints;
-- create the teapot brain
local brain = nil;
if (TEAPOT_BRAIN) then
brain = TEAPOT_BRAIN:Create({_teapot = scriptObject});
if (not brain:Init()) then
print("Failed to initialize brain");
brain = nil;
end
end
-- set up the state machine
scriptObject.stateMachine = TeapotStateMachine:Create({_teapot = scriptObject, _brain = brain});
-- set the initial state
scriptObject.stateMachine:SetState(PatrolState);
-- increment the enemy count and create the enemy processes if necessary
if (self._enemyProcesses == nil) then
self:_CreateEnemyProcesses();
end
-- make sure the UI is up to date
self:UpdateUi();
end
function ActorManager:RemoveEnemy(scriptObject)
-- destroy the state machine
if (scriptObject.stateMachine) then
scriptObject.stateMachine:Destroy();
scriptObject.stateMachine = nil;
end
-- remove the teapot from the enemy list
local actorId = scriptObject:GetActorId();
self._enemies[actorId] = nil;
-- update the UI
self:UpdateUi();
end
function ActorManager:GetEnemy(actorId)
return self._enemies[actorId];
end
function ActorManager:AddSphere(scriptObject)
local actorId = scriptObject:GetActorId();
if (self._spheres[actorId] ~= nil) then
print("Overwriting sphere actor; id = " .. actorId);
end
self._spheres[actorId] = scriptObject;
end
function ActorManager:RemoveSphere(scriptObject)
local actorId = scriptObject:GetActorId();
self._spheres[actorId] = nil;
end
function ActorManager:GetSphere(actorId)
return self._spheres[actorId];
end
function ActorManager:OnFireWeapon(eventData)
local aggressor = self:GetActorById(eventData.id);
if (aggressor == nil) then
print("FireWeapon from noone?");
return;
end;
print("FireWeapon!");
local pos = Vec3:Create(aggressor:GetPos());
local lookAt = Vec3:Create(aggressor:GetLookAt());
lookAt.y = lookAt.y + 1;
local dir = lookAt * 2;
pos = pos + dir;
local ypr = Vec3:Create({x=0, y=0, z=0});
local ball = CreateActor("actors\\sphere.xml", pos, ypr);
if (ball ~= -1) then
dir:Normalize();
ApplyForce(dir, .3, ball);
end
end
function ActorManager:OnPhysicsCollision(eventData)
local actorA = self:GetActorById(eventData.actorA);
local actorB = self:GetActorById(eventData.actorB);
-- one of the actors isn't in the script manager
if (actorA == nil or actorB == nil) then
return;
end
local teapot = nil;
local sphere = nil;
if (actorA.actorType == "Teapot" and actorB.actorType == "Sphere") then
teapot = actorA;
sphere = actorB;
elseif (actorA.actorType == "Sphere" and actorB.actorType == "Teapot") then
teapot = actorB;
sphere = actorA;
end
-- needs to be a teapot and sphere collision for us to care
if (teapot == nil or sphere == nil) then
return;
end
-- If we get here, there was a collision between a teapot and a sphere. Damage the teapot.
self:_DamageTeapot(teapot);
-- destroy the sphere
self:RemoveSphere(sphere);
QueueEvent(EventType.EvtData_Request_Destroy_Actor, sphere:GetActorId());
-- play the hit sound
QueueEvent(EventType.EvtData_PlaySound, "audio\\computerbeep3.wav");
end
function ActorManager:GetActorById(actorId)
local actor = nil;
if (self._player and self._player:GetActorId() == actorId) then
actor = self._player;
end
if (not actor) then
actor = self:GetEnemy(actorId);
end
if (not actor) then
actor = self:GetSphere(actorId);
end
return actor;
end
function ActorManager:_CreateEnemyProcesses()
self._enemyProcesses = {};
-- create all enemy processes
-- [rez] Note: The frequency values probably look a little weird. I chose these number because they are prime
-- numbers, ensuring that these two processes will rarely ever update on the same frame.
self._enemyProcesses[#self._enemyProcesses+1] = EnemyUpdater:Create({_enemies = self._enemies});
self._enemyProcesses[#self._enemyProcesses+1] = EnemyHealer:Create({_enemies = self._enemies, frequency = 15013}); -- ~10 seconds
self._enemyProcesses[#self._enemyProcesses+1] = EnemyThinker:Create({_enemies = self._enemies, frequency = 3499}); -- ~ 3.5 seconds
-- attach all the processes
for i, proc in ipairs(self._enemyProcesses) do
AttachProcess(proc);
end
end
function ActorManager:UpdateUi()
-- Build up the UI text string for the human view
local uiText = "";
if (self._enemies ~= nil) then
for id, teapot in pairs(self._enemies) do
uiText = uiText .. "Teapot " .. id .. " HP: " .. teapot.hitPoints .. "\n";
end
end
QueueEvent(EventType.EvtData_Gameplay_UI_Update, uiText);
end
function ActorManager:_DamageTeapot(teapot)
-- [rez] DEBUG: player is immune for now....
if (teapot == self._player) then
return;
end
-- subtract a hitpoint
teapot.hitPoints = teapot.hitPoints - 1;
-- if the teapot is dead, destroy it, otherwise update the UI
if (teapot.hitPoints <= 0) then
self:RemoveEnemy(teapot);
QueueEvent(EventType.EvtData_Request_Destroy_Actor, teapot:GetActorId());
else
self:UpdateUi();
end
end
| lgpl-3.0 |
Noneatme/MTA-NFS | client/CRenderCursor.lua | 1 | 1340 | -- ###############################
-- ## Project: MTA:Speedrace ##
-- ## Name: RenderCursor ##
-- ## Author: Noneatme ##
-- ## Version: 1.0 ##
-- ## License: See top Folder ##
-- ###############################
-- FUNCTIONS / METHODS --
local cFunc = {}; -- Local Functions
local cSetting = {}; -- Local Settings
RenderCursor = {};
RenderCursor.__index = RenderCursor;
--[[
]]
-- ///////////////////////////////
-- ///// New //////
-- ///////////////////////////////
function RenderCursor:New(...)
local obj = setmetatable({}, {__index = self});
if obj.Constructor then
obj:Constructor(...);
end
return obj;
end
-- ///////////////////////////////
-- ///// Render //////
-- ///////////////////////////////
function RenderCursor:Render(...)
if(isCursorShowing()) then
local x, y = getCursorPosition()
local sx, sy = guiGetScreenSize();
dxDrawImage(sx*x, sy*y, 21, 30, "files/images/cursor.png", 0, 0, 0, tocolor(0, 255, 255, 200), true);
end
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///////////////////////////////
function RenderCursor:Constructor(...)
self.renderFunc = function()
self:Render();
end
addEventHandler("onClientRender", getRootElement(), self.renderFunc)
logger:OutputInfo("[CALLING] RenderCursor: Constructor");
end
-- EVENT HANDLER --
| mit |
dalab/deep-ed | ed/minibatch/data_loader.lua | 1 | 2965 | -- Data loader for training of ED models.
train_file = opt.root_data_dir .. 'generated/test_train_data/aida_train.csv'
it_train, _ = io.open(train_file)
print('==> Loading training data with option ' .. opt.store_train_data)
local function one_doc_to_minibatch(doc_lines)
-- Create empty mini batch:
local num_mentions = #doc_lines
assert(num_mentions > 0)
local inputs = empty_minibatch_with_ids(num_mentions)
local targets = torch.zeros(num_mentions)
-- Fill in each example:
for i = 1, num_mentions do
local target = process_one_line(doc_lines[i], inputs, i, true)
targets[i] = target
assert(target >= 1 and target == targets[i])
end
return inputs, targets
end
if opt.store_train_data == 'RAM' then
all_docs_inputs = tds.Hash()
all_docs_targets = tds.Hash()
doc2id = tds.Hash()
id2doc = tds.Hash()
local cur_doc_lines = tds.Hash()
local prev_doc_id = nil
local line = it_train:read()
while line do
local parts = split(line, '\t')
local doc_name = parts[1]
if not doc2id[doc_name] then
if prev_doc_id then
local inputs, targets = one_doc_to_minibatch(cur_doc_lines)
all_docs_inputs[prev_doc_id] = minibatch_table2tds(inputs)
all_docs_targets[prev_doc_id] = targets
end
local cur_docid = 1 + #doc2id
id2doc[cur_docid] = doc_name
doc2id[doc_name] = cur_docid
cur_doc_lines = tds.Hash()
prev_doc_id = cur_docid
end
cur_doc_lines[1 + #cur_doc_lines] = line
line = it_train:read()
end
if prev_doc_id then
local inputs, targets = one_doc_to_minibatch(cur_doc_lines)
all_docs_inputs[prev_doc_id] = minibatch_table2tds(inputs)
all_docs_targets[prev_doc_id] = targets
end
assert(#doc2id == #all_docs_inputs, #doc2id .. ' ' .. #all_docs_inputs)
else
all_doc_lines = tds.Hash()
doc2id = tds.Hash()
id2doc = tds.Hash()
local line = it_train:read()
while line do
local parts = split(line, '\t')
local doc_name = parts[1]
if not doc2id[doc_name] then
local cur_docid = 1 + #doc2id
id2doc[cur_docid] = doc_name
doc2id[doc_name] = cur_docid
all_doc_lines[cur_docid] = tds.Hash()
end
all_doc_lines[doc2id[doc_name]][1 + #all_doc_lines[doc2id[doc_name]]] = line
line = it_train:read()
end
assert(#doc2id == #all_doc_lines)
end
get_minibatch = function()
-- Create empty mini batch:
local inputs = nil
local targets = nil
if opt.store_train_data == 'RAM' then
local random_docid = math.random(#id2doc)
inputs = minibatch_tds2table(all_docs_inputs[random_docid])
targets = all_docs_targets[random_docid]
else
local doc_lines = all_doc_lines[math.random(#id2doc)]
inputs, targets = one_doc_to_minibatch(doc_lines)
end
-- Move data to GPU:
inputs, targets = minibatch_to_correct_type(inputs, targets, true)
targets = correct_type(targets)
return inputs, targets
end
print(' Done loading training data.')
| apache-2.0 |
xianjiec/nn | MultiMarginCriterion.lua | 11 | 1615 | local THNN = require 'nn.THNN'
local MultiMarginCriterion, parent = torch.class('nn.MultiMarginCriterion', 'nn.Criterion')
function MultiMarginCriterion:__init(p, weights, margin)
assert(p == nil or p == 1 or p == 2, 'only p=1 and p=2 supported')
self.p = p or 1
self.margin = margin or 1.0
parent.__init(self)
self.sizeAverage = true
if weights then
assert(weights:dim() == 1, "weights input should be 1-D Tensor")
self.weights = weights
end
end
function MultiMarginCriterion:updateOutput(input, target)
-- backward compatibility
if not torch.isTensor(target) then
self.target_tensor = self.target_tensor or input.new(1)
self.target_tensor[1] = target
target = self.target_tensor
end
self.p = self.p or 1
self.output_tensor = self.output_tensor or input.new(1)
input.THNN.MultiMarginCriterion_updateOutput(
input:cdata(),
target:cdata(),
self.output_tensor:cdata(),
self.sizeAverage,
self.p,
THNN.optionalTensor(self.weights),
self.margin
)
self.output = self.output_tensor[1]
return self.output
end
function MultiMarginCriterion:updateGradInput(input, target)
if not torch.isTensor(target) then
self.target_tensor = self.target_tensor or input.new(1)
self.target_tensor[1] = target
target = self.target_tensor
end
input.THNN.MultiMarginCriterion_updateGradInput(
input:cdata(),
target:cdata(),
self.gradInput:cdata(),
self.sizeAverage,
self.p,
THNN.optionalTensor(self.weights),
self.margin
)
return self.gradInput
end
| bsd-3-clause |
takahashim/h2o | deps/klib/lua/klib.lua | 42 | 20155 | --[[
The MIT License
Copyright (c) 2011, Attractive Chaos <attractor@live.co.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]--
--[[
This is a Lua library, more exactly a collection of Lua snippets, covering
utilities (e.g. getopt), string operations (e.g. split), statistics (e.g.
Fisher's exact test), special functions (e.g. logarithm gamma) and matrix
operations (e.g. Gauss-Jordan elimination). The routines are designed to be
as independent as possible, such that one can copy-paste relevant pieces of
code without worrying about additional library dependencies.
If you use routines from this library, please include the licensing
information above where appropriate.
]]--
--[[
Library functions and dependencies. "a>b" means "a is required by b"; "b<a"
means "b depends on a".
os.getopt()
string:split()
io.xopen()
table.ksmall()
table.shuffle()
math.lgamma() >math.lbinom() >math.igamma()
math.igamma() <math.lgamma() >matrix.chi2()
math.erfc()
math.lbinom() <math.lgamma() >math.fisher_exact()
math.bernstein_poly() <math.lbinom()
math.fisher_exact() <math.lbinom()
math.jackknife()
math.pearson()
math.spearman()
math.fmin()
matrix
matrix.add()
matrix.T() >matrix.mul()
matrix.mul() <matrix.T()
matrix.tostring()
matrix.chi2() <math.igamma()
matrix.solve()
]]--
-- Description: getopt() translated from the BSD getopt(); compatible with the default Unix getopt()
--[[ Example:
for o, a in os.getopt(arg, 'a:b') do
print(o, a)
end
]]--
function os.getopt(args, ostr)
local arg, place = nil, 0;
return function ()
if place == 0 then -- update scanning pointer
place = 1
if #args == 0 or args[1]:sub(1, 1) ~= '-' then place = 0; return nil end
if #args[1] >= 2 then
place = place + 1
if args[1]:sub(2, 2) == '-' then -- found "--"
place = 0
table.remove(args, 1);
return nil;
end
end
end
local optopt = args[1]:sub(place, place);
place = place + 1;
local oli = ostr:find(optopt);
if optopt == ':' or oli == nil then -- unknown option
if optopt == '-' then return nil end
if place > #args[1] then
table.remove(args, 1);
place = 0;
end
return '?';
end
oli = oli + 1;
if ostr:sub(oli, oli) ~= ':' then -- do not need argument
arg = nil;
if place > #args[1] then
table.remove(args, 1);
place = 0;
end
else -- need an argument
if place <= #args[1] then -- no white space
arg = args[1]:sub(place);
else
table.remove(args, 1);
if #args == 0 then -- an option requiring argument is the last one
place = 0;
if ostr:sub(1, 1) == ':' then return ':' end
return '?';
else arg = args[1] end
end
table.remove(args, 1);
place = 0;
end
return optopt, arg;
end
end
-- Description: string split
function string:split(sep, n)
local a, start = {}, 1;
sep = sep or "%s+";
repeat
local b, e = self:find(sep, start);
if b == nil then
table.insert(a, self:sub(start));
break
end
a[#a+1] = self:sub(start, b - 1);
start = e + 1;
if n and #a == n then
table.insert(a, self:sub(start));
break
end
until start > #self;
return a;
end
-- Description: smart file open
function io.xopen(fn, mode)
mode = mode or 'r';
if fn == nil then return io.stdin;
elseif fn == '-' then return (mode == 'r' and io.stdin) or io.stdout;
elseif fn:sub(-3) == '.gz' then return (mode == 'r' and io.popen('gzip -dc ' .. fn, 'r')) or io.popen('gzip > ' .. fn, 'w');
elseif fn:sub(-4) == '.bz2' then return (mode == 'r' and io.popen('bzip2 -dc ' .. fn, 'r')) or io.popen('bgzip2 > ' .. fn, 'w');
else return io.open(fn, mode) end
end
-- Description: find the k-th smallest element in an array (Ref. http://ndevilla.free.fr/median/)
function table.ksmall(arr, k)
local low, high = 1, #arr;
while true do
if high <= low then return arr[k] end
if high == low + 1 then
if arr[high] < arr[low] then arr[high], arr[low] = arr[low], arr[high] end;
return arr[k];
end
local mid = math.floor((high + low) / 2);
if arr[high] < arr[mid] then arr[mid], arr[high] = arr[high], arr[mid] end
if arr[high] < arr[low] then arr[low], arr[high] = arr[high], arr[low] end
if arr[low] < arr[mid] then arr[low], arr[mid] = arr[mid], arr[low] end
arr[mid], arr[low+1] = arr[low+1], arr[mid];
local ll, hh = low + 1, high;
while true do
repeat ll = ll + 1 until arr[ll] >= arr[low]
repeat hh = hh - 1 until arr[low] >= arr[hh]
if hh < ll then break end
arr[ll], arr[hh] = arr[hh], arr[ll];
end
arr[low], arr[hh] = arr[hh], arr[low];
if hh <= k then low = ll end
if hh >= k then high = hh - 1 end
end
end
-- Description: shuffle/permutate an array
function table.shuffle(a)
for i = #a, 1, -1 do
local j = math.random(i)
a[j], a[i] = a[i], a[j]
end
end
--
-- Mathematics
--
-- Description: log gamma function
-- Required by: math.lbinom()
-- Reference: AS245, 2nd algorithm, http://lib.stat.cmu.edu/apstat/245
function math.lgamma(z)
local x;
x = 0.1659470187408462e-06 / (z+7);
x = x + 0.9934937113930748e-05 / (z+6);
x = x - 0.1385710331296526 / (z+5);
x = x + 12.50734324009056 / (z+4);
x = x - 176.6150291498386 / (z+3);
x = x + 771.3234287757674 / (z+2);
x = x - 1259.139216722289 / (z+1);
x = x + 676.5203681218835 / z;
x = x + 0.9999999999995183;
return math.log(x) - 5.58106146679532777 - z + (z-0.5) * math.log(z+6.5);
end
-- Description: regularized incomplete gamma function
-- Dependent on: math.lgamma()
--[[
Formulas are taken from Wiki, with additional input from Numerical
Recipes in C (for modified Lentz's algorithm) and AS245
(http://lib.stat.cmu.edu/apstat/245).
A good online calculator is available at:
http://www.danielsoper.com/statcalc/calc23.aspx
It calculates upper incomplete gamma function, which equals
math.igamma(s,z,true)*math.exp(math.lgamma(s))
]]--
function math.igamma(s, z, complement)
local function _kf_gammap(s, z)
local sum, x = 1, 1;
for k = 1, 100 do
x = x * z / (s + k);
sum = sum + x;
if x / sum < 1e-14 then break end
end
return math.exp(s * math.log(z) - z - math.lgamma(s + 1.) + math.log(sum));
end
local function _kf_gammaq(s, z)
local C, D, f, TINY;
f = 1. + z - s; C = f; D = 0.; TINY = 1e-290;
-- Modified Lentz's algorithm for computing continued fraction. See Numerical Recipes in C, 2nd edition, section 5.2
for j = 1, 100 do
local d;
local a, b = j * (s - j), j*2 + 1 + z - s;
D = b + a * D;
if D < TINY then D = TINY end
C = b + a / C;
if C < TINY then C = TINY end
D = 1. / D;
d = C * D;
f = f * d;
if math.abs(d - 1) < 1e-14 then break end
end
return math.exp(s * math.log(z) - z - math.lgamma(s) - math.log(f));
end
if complement then
return ((z <= 1 or z < s) and 1 - _kf_gammap(s, z)) or _kf_gammaq(s, z);
else
return ((z <= 1 or z < s) and _kf_gammap(s, z)) or (1 - _kf_gammaq(s, z));
end
end
math.M_SQRT2 = 1.41421356237309504880 -- sqrt(2)
math.M_SQRT1_2 = 0.70710678118654752440 -- 1/sqrt(2)
-- Description: complement error function erfc(x): \Phi(x) = 0.5 * erfc(-x/M_SQRT2)
function math.erfc(x)
local z = math.abs(x) * math.M_SQRT2
if z > 37 then return (x > 0 and 0) or 2 end
local expntl = math.exp(-0.5 * z * z)
local p
if z < 10. / math.M_SQRT2 then -- for small z
p = expntl * ((((((.03526249659989109 * z + .7003830644436881) * z + 6.37396220353165) * z + 33.912866078383)
* z + 112.0792914978709) * z + 221.2135961699311) * z + 220.2068679123761)
/ (((((((.08838834764831844 * z + 1.755667163182642) * z + 16.06417757920695) * z + 86.78073220294608)
* z + 296.5642487796737) * z + 637.3336333788311) * z + 793.8265125199484) * z + 440.4137358247522);
else p = expntl / 2.506628274631001 / (z + 1. / (z + 2. / (z + 3. / (z + 4. / (z + .65))))) end
return (x > 0 and 2 * p) or 2 * (1 - p)
end
-- Description: log binomial coefficient
-- Dependent on: math.lgamma()
-- Required by: math.fisher_exact()
function math.lbinom(n, m)
if m == nil then
local a = {};
a[0], a[n] = 0, 0;
local t = math.lgamma(n+1);
for m = 1, n-1 do a[m] = t - math.lgamma(m+1) - math.lgamma(n-m+1) end
return a;
else return math.lgamma(n+1) - math.lgamma(m+1) - math.lgamma(n-m+1) end
end
-- Description: Berstein polynomials (mainly for Bezier curves)
-- Dependent on: math.lbinom()
-- Note: to compute derivative: let beta_new[i]=beta[i+1]-beta[i]
function math.bernstein_poly(beta)
local n = #beta - 1;
local lbc = math.lbinom(n); -- log binomial coefficients
return function (t)
assert(t >= 0 and t <= 1);
if t == 0 then return beta[1] end
if t == 1 then return beta[n+1] end
local sum, logt, logt1 = 0, math.log(t), math.log(1-t);
for i = 0, n do sum = sum + beta[i+1] * math.exp(lbc[i] + i * logt + (n-i) * logt1) end
return sum;
end
end
-- Description: Fisher's exact test
-- Dependent on: math.lbinom()
-- Return: left-, right- and two-tail P-values
--[[
Fisher's exact test for 2x2 congintency tables:
n11 n12 | n1_
n21 n22 | n2_
-----------+----
n_1 n_2 | n
Reference: http://www.langsrud.com/fisher.htm
]]--
function math.fisher_exact(n11, n12, n21, n22)
local aux; -- keep the states of n* for acceleration
-- Description: hypergeometric function
local function hypergeo(n11, n1_, n_1, n)
return math.exp(math.lbinom(n1_, n11) + math.lbinom(n-n1_, n_1-n11) - math.lbinom(n, n_1));
end
-- Description: incremental hypergeometric function
-- Note: aux = {n11, n1_, n_1, n, p}
local function hypergeo_inc(n11, n1_, n_1, n)
if n1_ ~= 0 or n_1 ~= 0 or n ~= 0 then
aux = {n11, n1_, n_1, n, 1};
else -- then only n11 is changed
local mod;
_, mod = math.modf(n11 / 11);
if mod ~= 0 and n11 + aux[4] - aux[2] - aux[3] ~= 0 then
if n11 == aux[1] + 1 then -- increase by 1
aux[5] = aux[5] * (aux[2] - aux[1]) / n11 * (aux[3] - aux[1]) / (n11 + aux[4] - aux[2] - aux[3]);
aux[1] = n11;
return aux[5];
end
if n11 == aux[1] - 1 then -- descrease by 1
aux[5] = aux[5] * aux[1] / (aux[2] - n11) * (aux[1] + aux[4] - aux[2] - aux[3]) / (aux[3] - n11);
aux[1] = n11;
return aux[5];
end
end
aux[1] = n11;
end
aux[5] = hypergeo(aux[1], aux[2], aux[3], aux[4]);
return aux[5];
end
-- Description: computing the P-value by Fisher's exact test
local max, min, left, right, n1_, n_1, n, two, p, q, i, j;
n1_, n_1, n = n11 + n12, n11 + n21, n11 + n12 + n21 + n22;
max = (n_1 < n1_ and n_1) or n1_; -- max n11, for the right tail
min = n1_ + n_1 - n;
if min < 0 then min = 0 end -- min n11, for the left tail
two, left, right = 1, 1, 1;
if min == max then return 1 end -- no need to do test
q = hypergeo_inc(n11, n1_, n_1, n); -- the probability of the current table
-- left tail
i, left, p = min + 1, 0, hypergeo_inc(min, 0, 0, 0);
while p < 0.99999999 * q do
left, p, i = left + p, hypergeo_inc(i, 0, 0, 0), i + 1;
end
i = i - 1;
if p < 1.00000001 * q then left = left + p;
else i = i - 1 end
-- right tail
j, right, p = max - 1, 0, hypergeo_inc(max, 0, 0, 0);
while p < 0.99999999 * q do
right, p, j = right + p, hypergeo_inc(j, 0, 0, 0), j - 1;
end
j = j + 1;
if p < 1.00000001 * q then right = right + p;
else j = j + 1 end
-- two-tail
two = left + right;
if two > 1 then two = 1 end
-- adjust left and right
if math.abs(i - n11) < math.abs(j - n11) then right = 1 - left + q;
else left = 1 - right + q end
return left, right, two;
end
-- Description: Delete-m Jackknife
--[[
Given g groups of values with a statistics estimated from m[i] samples in
i-th group being t[i], compute the mean and the variance. t0 below is the
estimate from all samples. Reference:
Busing et al. (1999) Delete-m Jackknife for unequal m. Statistics and Computing, 9:3-8.
]]--
function math.jackknife(g, m, t, t0)
local h, n, sum = {}, 0, 0;
for j = 1, g do n = n + m[j] end
if t0 == nil then -- When t0 is absent, estimate it in a naive way
t0 = 0;
for j = 1, g do t0 = t0 + m[j] * t[j] end
t0 = t0 / n;
end
local mean, var = 0, 0;
for j = 1, g do
h[j] = n / m[j];
mean = mean + (1 - m[j] / n) * t[j];
end
mean = g * t0 - mean; -- Eq. (8)
for j = 1, g do
local x = h[j] * t0 - (h[j] - 1) * t[j] - mean;
var = var + 1 / (h[j] - 1) * x * x;
end
var = var / g;
return mean, var;
end
-- Description: Pearson correlation coefficient
-- Input: a is an n*2 table
function math.pearson(a)
-- compute the mean
local x1, y1 = 0, 0
for _, v in pairs(a) do
x1, y1 = x1 + v[1], y1 + v[2]
end
-- compute the coefficient
x1, y1 = x1 / #a, y1 / #a
local x2, y2, xy = 0, 0, 0
for _, v in pairs(a) do
local tx, ty = v[1] - x1, v[2] - y1
xy, x2, y2 = xy + tx * ty, x2 + tx * tx, y2 + ty * ty
end
return xy / math.sqrt(x2) / math.sqrt(y2)
end
-- Description: Spearman correlation coefficient
function math.spearman(a)
local function aux_func(t) -- auxiliary function
return (t == 1 and 0) or (t*t - 1) * t / 12
end
for _, v in pairs(a) do v.r = {} end
local T, S = {}, {}
-- compute the rank
for k = 1, 2 do
table.sort(a, function(u,v) return u[k]<v[k] end)
local same = 1
T[k] = 0
for i = 2, #a + 1 do
if i <= #a and a[i-1][k] == a[i][k] then same = same + 1
else
local rank = (i-1) * 2 - same + 1
for j = i - same, i - 1 do a[j].r[k] = rank end
if same > 1 then T[k], same = T[k] + aux_func(same), 1 end
end
end
S[k] = aux_func(#a) - T[k]
end
-- compute the coefficient
local sum = 0
for _, v in pairs(a) do -- TODO: use nested loops to reduce loss of precision
local t = (v.r[1] - v.r[2]) / 2
sum = sum + t * t
end
return (S[1] + S[2] - sum) / 2 / math.sqrt(S[1] * S[2])
end
-- Description: Hooke-Jeeves derivative-free optimization
function math.fmin(func, x, data, r, eps, max_calls)
local n, n_calls = #x, 0;
r = r or 0.5;
eps = eps or 1e-7;
max_calls = max_calls or 50000
function fmin_aux(x1, data, fx1, dx) -- auxiliary function
local ftmp;
for k = 1, n do
x1[k] = x1[k] + dx[k];
local ftmp = func(x1, data); n_calls = n_calls + 1;
if ftmp < fx1 then fx1 = ftmp;
else -- search the opposite direction
dx[k] = -dx[k];
x1[k] = x1[k] + dx[k] + dx[k];
ftmp = func(x1, data); n_calls = n_calls + 1;
if ftmp < fx1 then fx1 = ftmp
else x1[k] = x1[k] - dx[k] end -- back to the original x[k]
end
end
return fx1; -- here: fx1=f(n,x1)
end
local dx, x1 = {}, {};
for k = 1, n do -- initial directions, based on MGJ
dx[k] = math.abs(x[k]) * r;
if dx[k] == 0 then dx[k] = r end;
end
local radius = r;
local fx1, fx;
fx = func(x, data); fx1 = fx; n_calls = n_calls + 1;
while true do
for i = 1, n do x1[i] = x[i] end; -- x1 = x
fx1 = fmin_aux(x1, data, fx, dx);
while fx1 < fx do
for k = 1, n do
local t = x[k];
dx[k] = (x1[k] > x[k] and math.abs(dx[k])) or -math.abs(dx[k]);
x[k] = x1[k];
x1[k] = x1[k] + x1[k] - t;
end
fx = fx1;
if n_calls >= max_calls then break end
fx1 = func(x1, data); n_calls = n_calls + 1;
fx1 = fmin_aux(x1, data, fx1, dx);
if fx1 >= fx then break end
local kk = n;
for k = 1, n do
if math.abs(x1[k] - x[k]) > .5 * math.abs(dx[k]) then
kk = k;
break;
end
end
if kk == n then break end
end
if radius >= eps then
if n_calls >= max_calls then break end
radius = radius * r;
for k = 1, n do dx[k] = dx[k] * r end
else break end
end
return fx1, n_calls;
end
--
-- Matrix
--
matrix = {}
-- Description: matrix transpose
-- Required by: matrix.mul()
function matrix.T(a)
local m, n, x = #a, #a[1], {};
for i = 1, n do
x[i] = {};
for j = 1, m do x[i][j] = a[j][i] end
end
return x;
end
-- Description: matrix add
function matrix.add(a, b)
assert(#a == #b and #a[1] == #b[1]);
local m, n, x = #a, #a[1], {};
for i = 1, m do
x[i] = {};
local ai, bi, xi = a[i], b[i], x[i];
for j = 1, n do xi[j] = ai[j] + bi[j] end
end
return x;
end
-- Description: matrix mul
-- Dependent on: matrix.T()
-- Note: much slower without transpose
function matrix.mul(a, b)
assert(#a[1] == #b);
local m, n, p, x = #a, #a[1], #b[1], {};
local c = matrix.T(b); -- transpose for efficiency
for i = 1, m do
x[i] = {}
local xi = x[i];
for j = 1, p do
local sum, ai, cj = 0, a[i], c[j];
for k = 1, n do sum = sum + ai[k] * cj[k] end
xi[j] = sum;
end
end
return x;
end
-- Description: matrix print
function matrix.tostring(a)
local z = {};
for i = 1, #a do
z[i] = table.concat(a[i], "\t");
end
return table.concat(z, "\n");
end
-- Description: chi^2 test for contingency tables
-- Dependent on: math.igamma()
function matrix.chi2(a)
if #a == 2 and #a[1] == 2 then -- 2x2 table
local x, z
x = (a[1][1] + a[1][2]) * (a[2][1] + a[2][2]) * (a[1][1] + a[2][1]) * (a[1][2] + a[2][2])
if x == 0 then return 0, 1, false end
z = a[1][1] * a[2][2] - a[1][2] * a[2][1]
z = (a[1][1] + a[1][2] + a[2][1] + a[2][2]) * z * z / x
return z, math.igamma(.5, .5 * z, true), true
else -- generic table
local rs, cs, n, m, N, z = {}, {}, #a, #a[1], 0, 0
for i = 1, n do rs[i] = 0 end
for j = 1, m do cs[j] = 0 end
for i = 1, n do -- compute column sum and row sum
for j = 1, m do cs[j], rs[i] = cs[j] + a[i][j], rs[i] + a[i][j] end
end
for i = 1, n do N = N + rs[i] end
for i = 1, n do -- compute the chi^2 statistics
for j = 1, m do
local E = rs[i] * cs[j] / N;
z = z + (a[i][j] - E) * (a[i][j] - E) / E
end
end
return z, math.igamma(.5 * (n-1) * (m-1), .5 * z, true), true;
end
end
-- Description: Gauss-Jordan elimination (solving equations; computing inverse)
-- Note: on return, a[n][n] is the inverse; b[n][m] is the solution
-- Reference: Section 2.1, Numerical Recipes in C, 2nd edition
function matrix.solve(a, b)
assert(#a == #a[1]);
local n, m = #a, (b and #b[1]) or 0;
local xc, xr, ipiv = {}, {}, {};
local ic, ir;
for j = 1, n do ipiv[j] = 0 end
for i = 1, n do
local big = 0;
for j = 1, n do
local aj = a[j];
if ipiv[j] ~= 1 then
for k = 1, n do
if ipiv[k] == 0 then
if math.abs(aj[k]) >= big then
big = math.abs(aj[k]);
ir, ic = j, k;
end
elseif ipiv[k] > 1 then return -2 end -- singular matrix
end
end
end
ipiv[ic] = ipiv[ic] + 1;
if ir ~= ic then
for l = 1, n do a[ir][l], a[ic][l] = a[ic][l], a[ir][l] end
if b then
for l = 1, m do b[ir][l], b[ic][l] = b[ic][l], b[ir][l] end
end
end
xr[i], xc[i] = ir, ic;
if a[ic][ic] == 0 then return -3 end -- singular matrix
local pivinv = 1 / a[ic][ic];
a[ic][ic] = 1;
for l = 1, n do a[ic][l] = a[ic][l] * pivinv end
if b then
for l = 1, n do b[ic][l] = b[ic][l] * pivinv end
end
for ll = 1, n do
if ll ~= ic then
local tmp = a[ll][ic];
a[ll][ic] = 0;
local all, aic = a[ll], a[ic];
for l = 1, n do all[l] = all[l] - aic[l] * tmp end
if b then
local bll, bic = b[ll], b[ic];
for l = 1, m do bll[l] = bll[l] - bic[l] * tmp end
end
end
end
end
for l = n, 1, -1 do
if xr[l] ~= xc[l] then
for k = 1, n do a[k][xr[l]], a[k][xc[l]] = a[k][xc[l]], a[k][xr[l]] end
end
end
return 0;
end
| mit |
corbinmunce/domoticz | dzVents/runtime/device-adapters/scene_device.lua | 6 | 1104 | local TimedCommand = require('TimedCommand')
return {
baseType = 'scene',
name = 'Scene device adapter',
matches = function(device, adapterManager)
local res = (device.baseType == 'scene')
if (not res) then
adapterManager.addDummyMethod(device, 'switchOn')
adapterManager.addDummyMethod(device, 'switchOff')
end
return res
end,
process = function(scene, data, domoticz, utils, adapterManager)
scene.isScene = true
function scene.setState(newState)
-- generic state update method
return domoticz.setScene(scene.name, newState)
end
function scene.switchOn()
return TimedCommand(domoticz, 'Scene:' .. scene.name, 'On', 'device', scene.state)
end
function scene.switchOff()
return TimedCommand(domoticz, 'Scene:' .. scene.name, 'Off', 'device', scene.state)
end
function scene.devices()
local subData = {}
local ids = data.deviceIDs ~= nil and data.deviceIDs or {}
for i, id in pairs(ids) do
subData[i] = domoticz._getItemFromData('device', id)
end
return domoticz._setIterators({}, true, 'device', false , subData)
end
end
}
| gpl-3.0 |
zhrtz/vicious | contrib/ati.lua | 12 | 2694 | ---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2013, NormalRa <normalrawr gmail com>
---------------------------------------------------
-- {{{ Grab environment
local tonumber = tonumber
local io = { open = io.open }
local setmetatable = setmetatable
local helpers = require("vicious.helpers")
local string = {
sub = string.sub,
match = string.match,
gmatch = string.gmatch
}
-- }}}
-- ATI: provides various info about ATI GPU status
-- vicious.widgets.ati
local ati = {}
-- {{{ Define variables
local _units = { clock = { ["khz"] = 1, ["mhz"] = 1000 },
voltage = { ["v"] = 1, ["mv"] = 1000 } }
local _reps = {
["sclk"] = { name = "engine_clock", units = _units.clock, mul = 10 },
["mclk"] = { name = "memory_clock", units = _units.clock, mul = 10 },
["vddc"] = { name = "voltage", units = _units.voltage },
["voltage"] = { name = "voltage", units = _units.voltage },
["current engine clock"] = { name = "engine_clock", units = _units.clock },
["current memory clock"] = { name = "memory_clock", units = _units.clock }
}
-- }}}
-- {{{ ATI widget type
local function worker(format, warg)
if not warg then return end
local pm = helpers.pathtotable("/sys/class/drm/"..warg.."/device")
local _data = {}
-- Get power info
_data["{method}"] =
pm.power_method and string.sub(pm.power_method, 1, -2) or "N/A"
_data["{dpm_state}"] =
pm.power_dpm_state and string.sub(pm.power_dpm_state, 1, -2) or "N/A"
_data["{dpm_perf_level}"] =
pm.power_dpm_force_performance_level and
string.sub(pm.power_dpm_force_performance_level, 1, -2) or "N/A"
_data["{profile}"] =
pm.power_profile and string.sub(pm.power_profile, 1, -2) or "N/A"
local f = io.open("/sys/kernel/debug/dri/64/radeon_pm_info", "r")
if f then -- Get ATI info from the debug filesystem
for line in f:lines() do
for k, unit in string.gmatch(line, "(%a+[%a%s]*):[%s]+([%d]+)") do
unit = tonumber(unit)
_data["{dpm_power_level}"] = -- DPM active?
tonumber(string.match(line, "power level ([%d])")) or "N/A"
if _reps[k] then
for u, v in pairs(_reps[k].units) do
_data["{".._reps[k].name.." "..u.."}"] =
(unit * (_reps[k].mul or 1)) / v
end
end
end
end
f:close()
end
return _data
end
-- }}}
return setmetatable(ati, { __call = function(_, ...) return worker(...) end })
| gpl-2.0 |
shayanchabok007/antispam_ok_new | plugins/inrealm.lua | 850 | 25085 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "For admins only!"
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
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 mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](createrealm) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (.*)$",
"^[!/](setgpname) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](type)$",
"^[!/](kill) (chat) (%d+)$",
"^[!/](kill) (realm) (%d+)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^[!/](help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
ghoghnousteamHT/ghoghnous_bot | plugins/inrealm.lua | 850 | 25085 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "For admins only!"
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
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 mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](createrealm) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (.*)$",
"^[!/](setgpname) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](type)$",
"^[!/](kill) (chat) (%d+)$",
"^[!/](kill) (realm) (%d+)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^[!/](help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
matinbot/telebot | plugins/inrealm.lua | 850 | 25085 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "For admins only!"
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
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 mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](createrealm) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (.*)$",
"^[!/](setgpname) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](type)$",
"^[!/](kill) (chat) (%d+)$",
"^[!/](kill) (realm) (%d+)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^[!/](help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
caohongtao/quick-cocos-demo | runtime/ios/PrebuiltRuntimeLua.app/src/framework/cocos2dx.lua | 18 | 1999 | --[[
Copyright (c) 2011-2014 chukong-inc.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
--------------------------------
-- @module cocos2dx
--[[--
针对 cocos2d-x 的一些封装和扩展
预定义的节点事件:
- cc.NODE_EVENT - enter, exit 等事件
- cc.NODE_ENTER_FRAME_EVENT - 帧事件
- cc.NODE_TOUCH_EVENT - 触摸事件
- cc.NODE_TOUCH_CAPTURE_EVENT - 捕获触摸事件
预定义的层事件:
- cc.ACCELERATE_EVENT - 重力感应事件
- cc.KEYPAD_EVENT - 硬件按键事件
预定义的触摸模式:
- cc.TOUCH_MODE_ALL_AT_ONCE - 多点触摸
- cc.TOUCH_MODE_ONE_BY_ONE - 单点触摸
]]
local p = cc.PACKAGE_NAME .. ".cocos2dx."
if not cc.p then
-- cc.p exist, so the cocos.init have loaded
require(p .. "Cocos2dConstants")
require(p .. "OpenglConstants")
require(p .. "Cocos2d")
require(p .. "StudioConstants")
end
require(p .. "Event")
require(p .. "ActionEx")
require(p .. "NodeEx")
require(p .. "SceneEx")
require(p .. "SpriteEx")
require(p .. "DrawNodeEx")
| apache-2.0 |
vikas17a/Algorithm-Implementations | Average/Lua/Yonaba/average_test.lua | 26 | 1557 | -- Tests for average.lua
local mean = require 'average'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
local function fuzzyEqual(a, b, eps) return math.abs(a - b) < eps end
local x = {1, 2, 3, 4, 5}
run('Arithmetic mean', function()
assert(mean.arithmetic(x) == 3)
end)
run('Geometric mean', function()
assert(fuzzyEqual(mean.geometric(x), 2.60517108,1e-8))
end)
run('Harmonic mean', function()
assert(fuzzyEqual(mean.harmonic(x), 2.18978102,1e-8))
end)
run('Quadratic mean', function()
assert(fuzzyEqual(mean.quadratic(x), 3.31662479,1e-8))
end)
run('Generalized mean', function()
assert(fuzzyEqual(mean.generalized(x,1), mean.arithmetic(x),1e-8))
assert(fuzzyEqual(mean.generalized(x,2), mean.quadratic(x),1e-8))
assert(fuzzyEqual(mean.generalized(x,-1), mean.harmonic(x),1e-8))
end)
run('Weighted mean', function()
local w = { 0.1, 0.2, 0.2, 0.3, 0.2}
assert(mean.weighted(x, w) == 3.3)
end)
run('Midrange mean', function()
assert(mean.midrange(x) == 3)
end)
run('Energetic mean', function()
assert(fuzzyEqual(mean.energetic(x), 3.22766781,1e-8))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
solid021/TeleBeyond | plugins/media.lua | 376 | 1679 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
ntop/ntopng | scripts/lua/modules/alert_definitions/other/alert_device_connection_disconnection.lua | 1 | 2172 | --
-- (C) 2019-22 - ntop.org
--
-- ##############################################
local other_alert_keys = require "other_alert_keys"
local alert_creators = require "alert_creators"
-- Import the classes library.
local classes = require "classes"
-- Make sure to import the Superclass!
local alert = require "alert"
local alert_entities = require "alert_entities"
-- ##############################################
local alert_device_connection = classes.class(alert)
-- ##############################################
alert_device_connection.meta = {
alert_key = other_alert_keys.alert_device_connection_disconnection,
i18n_title = "alerts_dashboard.device_connection_disconnection",
icon = "fas fa-fw fa-sign-in",
entities = {
alert_entities.mac
},
}
-- ##############################################
-- @brief Prepare an alert table used to generate the alert
-- @param device The a string with the name or ip address of the device that connected the network
-- @return A table with the alert built
function alert_device_connection:init(device, event)
-- Call the parent constructor
self.super:init()
self.alert_type_params = {
device = device,
event = event,
}
end
-- #######################################################
-- @brief Format an alert into a human-readable string
-- @param ifid The integer interface id of the generated alert
-- @param alert The alert description table, including alert data such as the generating entity, timestamp, granularity, type
-- @param alert_type_params Table `alert_type_params` as built in the `:init` method
-- @return A human-readable string
function alert_device_connection.format(ifid, alert, alert_type_params)
return(i18n("alert_messages.device_has_connected", {
event = alert_type_params.event or "connected",
device = alert_type_params.device,
device_url = getMacUrl(alert_type_params.device),
if_name = getInterfaceName(ifid),
if_url = getInterfaceUrl(ifid),
exclusion_url = ntop.getHttpPrefix() .. "/lua/pro/admin/edit_device_exclusions.lua",
}))
end
-- #######################################################
return alert_device_connection
| gpl-3.0 |
caohongtao/quick-cocos-demo | runtime/ios/PrebuiltRuntimeLua.app/src/cocos/cocos2d/DeprecatedOpenglEnum.lua | 148 | 11934 | -- This is the DeprecatedEnum
DeprecatedClass = {} or DeprecatedClass
_G.GL_RENDERBUFFER_INTERNAL_FORMAT = gl.RENDERBUFFER_INTERNAL_FORMAT
_G.GL_LINE_WIDTH = gl.LINE_WIDTH
_G.GL_CONSTANT_ALPHA = gl.CONSTANT_ALPHA
_G.GL_BLEND_SRC_ALPHA = gl.BLEND_SRC_ALPHA
_G.GL_GREEN_BITS = gl.GREEN_BITS
_G.GL_STENCIL_REF = gl.STENCIL_REF
_G.GL_ONE_MINUS_SRC_ALPHA = gl.ONE_MINUS_SRC_ALPHA
_G.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE
_G.GL_CCW = gl.CCW
_G.GL_MAX_TEXTURE_IMAGE_UNITS = gl.MAX_TEXTURE_IMAGE_UNITS
_G.GL_BACK = gl.BACK
_G.GL_ACTIVE_ATTRIBUTES = gl.ACTIVE_ATTRIBUTES
_G.GL_TEXTURE_CUBE_MAP_POSITIVE_X = gl.TEXTURE_CUBE_MAP_POSITIVE_X
_G.GL_STENCIL_BACK_VALUE_MASK = gl.STENCIL_BACK_VALUE_MASK
_G.GL_TEXTURE_CUBE_MAP_POSITIVE_Z = gl.TEXTURE_CUBE_MAP_POSITIVE_Z
_G.GL_ONE = gl.ONE
_G.GL_TRUE = gl.TRUE
_G.GL_TEXTURE12 = gl.TEXTURE12
_G.GL_LINK_STATUS = gl.LINK_STATUS
_G.GL_BLEND = gl.BLEND
_G.GL_LESS = gl.LESS
_G.GL_TEXTURE16 = gl.TEXTURE16
_G.GL_BOOL_VEC2 = gl.BOOL_VEC2
_G.GL_KEEP = gl.KEEP
_G.GL_DST_COLOR = gl.DST_COLOR
_G.GL_VERTEX_ATTRIB_ARRAY_ENABLED = gl.VERTEX_ATTRIB_ARRAY_ENABLED
_G.GL_EXTENSIONS = gl.EXTENSIONS
_G.GL_FRONT = gl.FRONT
_G.GL_DST_ALPHA = gl.DST_ALPHA
_G.GL_ATTACHED_SHADERS = gl.ATTACHED_SHADERS
_G.GL_STENCIL_BACK_FUNC = gl.STENCIL_BACK_FUNC
_G.GL_ONE_MINUS_DST_COLOR = gl.ONE_MINUS_DST_COLOR
_G.GL_BLEND_EQUATION = gl.BLEND_EQUATION
_G.GL_RENDERBUFFER_DEPTH_SIZE = gl.RENDERBUFFER_DEPTH_SIZE
_G.GL_PACK_ALIGNMENT = gl.PACK_ALIGNMENT
_G.GL_VENDOR = gl.VENDOR
_G.GL_NEAREST_MIPMAP_LINEAR = gl.NEAREST_MIPMAP_LINEAR
_G.GL_TEXTURE_CUBE_MAP_POSITIVE_Y = gl.TEXTURE_CUBE_MAP_POSITIVE_Y
_G.GL_NEAREST = gl.NEAREST
_G.GL_RENDERBUFFER_WIDTH = gl.RENDERBUFFER_WIDTH
_G.GL_ARRAY_BUFFER_BINDING = gl.ARRAY_BUFFER_BINDING
_G.GL_ARRAY_BUFFER = gl.ARRAY_BUFFER
_G.GL_LEQUAL = gl.LEQUAL
_G.GL_VERSION = gl.VERSION
_G.GL_COLOR_CLEAR_VALUE = gl.COLOR_CLEAR_VALUE
_G.GL_RENDERER = gl.RENDERER
_G.GL_STENCIL_BACK_PASS_DEPTH_PASS = gl.STENCIL_BACK_PASS_DEPTH_PASS
_G.GL_STENCIL_BACK_PASS_DEPTH_FAIL = gl.STENCIL_BACK_PASS_DEPTH_FAIL
_G.GL_STENCIL_BACK_WRITEMASK = gl.STENCIL_BACK_WRITEMASK
_G.GL_BOOL = gl.BOOL
_G.GL_VIEWPORT = gl.VIEWPORT
_G.GL_FRAGMENT_SHADER = gl.FRAGMENT_SHADER
_G.GL_LUMINANCE = gl.LUMINANCE
_G.GL_DECR_WRAP = gl.DECR_WRAP
_G.GL_FUNC_ADD = gl.FUNC_ADD
_G.GL_ONE_MINUS_DST_ALPHA = gl.ONE_MINUS_DST_ALPHA
_G.GL_OUT_OF_MEMORY = gl.OUT_OF_MEMORY
_G.GL_BOOL_VEC4 = gl.BOOL_VEC4
_G.GL_POLYGON_OFFSET_FACTOR = gl.POLYGON_OFFSET_FACTOR
_G.GL_STATIC_DRAW = gl.STATIC_DRAW
_G.GL_DITHER = gl.DITHER
_G.GL_TEXTURE31 = gl.TEXTURE31
_G.GL_TEXTURE30 = gl.TEXTURE30
_G.GL_UNSIGNED_BYTE = gl.UNSIGNED_BYTE
_G.GL_DEPTH_COMPONENT16 = gl.DEPTH_COMPONENT16
_G.GL_TEXTURE23 = gl.TEXTURE23
_G.GL_DEPTH_TEST = gl.DEPTH_TEST
_G.GL_STENCIL_PASS_DEPTH_FAIL = gl.STENCIL_PASS_DEPTH_FAIL
_G.GL_BOOL_VEC3 = gl.BOOL_VEC3
_G.GL_POLYGON_OFFSET_UNITS = gl.POLYGON_OFFSET_UNITS
_G.GL_TEXTURE_BINDING_2D = gl.TEXTURE_BINDING_2D
_G.GL_TEXTURE21 = gl.TEXTURE21
_G.GL_UNPACK_ALIGNMENT = gl.UNPACK_ALIGNMENT
_G.GL_DONT_CARE = gl.DONT_CARE
_G.GL_BUFFER_SIZE = gl.BUFFER_SIZE
_G.GL_FLOAT_MAT3 = gl.FLOAT_MAT3
_G.GL_UNSIGNED_SHORT_5_6_5 = gl.UNSIGNED_SHORT_5_6_5
_G.GL_INT_VEC2 = gl.INT_VEC2
_G.GL_UNSIGNED_SHORT_4_4_4_4 = gl.UNSIGNED_SHORT_4_4_4_4
_G.GL_NONE = gl.NONE
_G.GL_BLEND_DST_ALPHA = gl.BLEND_DST_ALPHA
_G.GL_VERTEX_ATTRIB_ARRAY_SIZE = gl.VERTEX_ATTRIB_ARRAY_SIZE
_G.GL_SRC_COLOR = gl.SRC_COLOR
_G.GL_COMPRESSED_TEXTURE_FORMATS = gl.COMPRESSED_TEXTURE_FORMATS
_G.GL_STENCIL_ATTACHMENT = gl.STENCIL_ATTACHMENT
_G.GL_MAX_VERTEX_ATTRIBS = gl.MAX_VERTEX_ATTRIBS
_G.GL_NUM_COMPRESSED_TEXTURE_FORMATS = gl.NUM_COMPRESSED_TEXTURE_FORMATS
_G.GL_BLEND_EQUATION_RGB = gl.BLEND_EQUATION_RGB
_G.GL_TEXTURE = gl.TEXTURE
_G.GL_LINEAR_MIPMAP_LINEAR = gl.LINEAR_MIPMAP_LINEAR
_G.GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING
_G.GL_CURRENT_PROGRAM = gl.CURRENT_PROGRAM
_G.GL_COLOR_BUFFER_BIT = gl.COLOR_BUFFER_BIT
_G.GL_TEXTURE20 = gl.TEXTURE20
_G.GL_ACTIVE_ATTRIBUTE_MAX_LENGTH = gl.ACTIVE_ATTRIBUTE_MAX_LENGTH
_G.GL_TEXTURE28 = gl.TEXTURE28
_G.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE
_G.GL_TEXTURE22 = gl.TEXTURE22
_G.GL_ELEMENT_ARRAY_BUFFER_BINDING = gl.ELEMENT_ARRAY_BUFFER_BINDING
_G.GL_STREAM_DRAW = gl.STREAM_DRAW
_G.GL_SCISSOR_BOX = gl.SCISSOR_BOX
_G.GL_TEXTURE26 = gl.TEXTURE26
_G.GL_TEXTURE27 = gl.TEXTURE27
_G.GL_TEXTURE24 = gl.TEXTURE24
_G.GL_TEXTURE25 = gl.TEXTURE25
_G.GL_NO_ERROR = gl.NO_ERROR
_G.GL_TEXTURE29 = gl.TEXTURE29
_G.GL_FLOAT_MAT4 = gl.FLOAT_MAT4
_G.GL_VERTEX_ATTRIB_ARRAY_NORMALIZED = gl.VERTEX_ATTRIB_ARRAY_NORMALIZED
_G.GL_SAMPLE_COVERAGE_INVERT = gl.SAMPLE_COVERAGE_INVERT
_G.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL
_G.GL_FLOAT_VEC3 = gl.FLOAT_VEC3
_G.GL_STENCIL_CLEAR_VALUE = gl.STENCIL_CLEAR_VALUE
_G.GL_UNSIGNED_SHORT_5_5_5_1 = gl.UNSIGNED_SHORT_5_5_5_1
_G.GL_ACTIVE_UNIFORMS = gl.ACTIVE_UNIFORMS
_G.GL_INVALID_OPERATION = gl.INVALID_OPERATION
_G.GL_DEPTH_ATTACHMENT = gl.DEPTH_ATTACHMENT
_G.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS
_G.GL_FRAMEBUFFER_COMPLETE = gl.FRAMEBUFFER_COMPLETE
_G.GL_ONE_MINUS_CONSTANT_COLOR = gl.ONE_MINUS_CONSTANT_COLOR
_G.GL_TEXTURE2 = gl.TEXTURE2
_G.GL_TEXTURE1 = gl.TEXTURE1
_G.GL_GEQUAL = gl.GEQUAL
_G.GL_TEXTURE7 = gl.TEXTURE7
_G.GL_TEXTURE6 = gl.TEXTURE6
_G.GL_TEXTURE5 = gl.TEXTURE5
_G.GL_TEXTURE4 = gl.TEXTURE4
_G.GL_GENERATE_MIPMAP_HINT = gl.GENERATE_MIPMAP_HINT
_G.GL_ONE_MINUS_SRC_COLOR = gl.ONE_MINUS_SRC_COLOR
_G.GL_TEXTURE9 = gl.TEXTURE9
_G.GL_STENCIL_TEST = gl.STENCIL_TEST
_G.GL_COLOR_WRITEMASK = gl.COLOR_WRITEMASK
_G.GL_DEPTH_COMPONENT = gl.DEPTH_COMPONENT
_G.GL_STENCIL_INDEX8 = gl.STENCIL_INDEX8
_G.GL_VERTEX_ATTRIB_ARRAY_TYPE = gl.VERTEX_ATTRIB_ARRAY_TYPE
_G.GL_FLOAT_VEC2 = gl.FLOAT_VEC2
_G.GL_BLUE_BITS = gl.BLUE_BITS
_G.GL_VERTEX_SHADER = gl.VERTEX_SHADER
_G.GL_SUBPIXEL_BITS = gl.SUBPIXEL_BITS
_G.GL_STENCIL_WRITEMASK = gl.STENCIL_WRITEMASK
_G.GL_FLOAT_VEC4 = gl.FLOAT_VEC4
_G.GL_TEXTURE17 = gl.TEXTURE17
_G.GL_ONE_MINUS_CONSTANT_ALPHA = gl.ONE_MINUS_CONSTANT_ALPHA
_G.GL_TEXTURE15 = gl.TEXTURE15
_G.GL_TEXTURE14 = gl.TEXTURE14
_G.GL_TEXTURE13 = gl.TEXTURE13
_G.GL_SAMPLES = gl.SAMPLES
_G.GL_TEXTURE11 = gl.TEXTURE11
_G.GL_TEXTURE10 = gl.TEXTURE10
_G.GL_FUNC_SUBTRACT = gl.FUNC_SUBTRACT
_G.GL_STENCIL_BUFFER_BIT = gl.STENCIL_BUFFER_BIT
_G.GL_TEXTURE19 = gl.TEXTURE19
_G.GL_TEXTURE18 = gl.TEXTURE18
_G.GL_NEAREST_MIPMAP_NEAREST = gl.NEAREST_MIPMAP_NEAREST
_G.GL_SHORT = gl.SHORT
_G.GL_RENDERBUFFER_BINDING = gl.RENDERBUFFER_BINDING
_G.GL_REPEAT = gl.REPEAT
_G.GL_TEXTURE_MIN_FILTER = gl.TEXTURE_MIN_FILTER
_G.GL_RED_BITS = gl.RED_BITS
_G.GL_FRONT_FACE = gl.FRONT_FACE
_G.GL_BLEND_COLOR = gl.BLEND_COLOR
_G.GL_MIRRORED_REPEAT = gl.MIRRORED_REPEAT
_G.GL_INT_VEC4 = gl.INT_VEC4
_G.GL_MAX_CUBE_MAP_TEXTURE_SIZE = gl.MAX_CUBE_MAP_TEXTURE_SIZE
_G.GL_RENDERBUFFER_BLUE_SIZE = gl.RENDERBUFFER_BLUE_SIZE
_G.GL_SAMPLE_COVERAGE = gl.SAMPLE_COVERAGE
_G.GL_SRC_ALPHA = gl.SRC_ALPHA
_G.GL_FUNC_REVERSE_SUBTRACT = gl.FUNC_REVERSE_SUBTRACT
_G.GL_DEPTH_WRITEMASK = gl.DEPTH_WRITEMASK
_G.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT = gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT
_G.GL_POLYGON_OFFSET_FILL = gl.POLYGON_OFFSET_FILL
_G.GL_STENCIL_FUNC = gl.STENCIL_FUNC
_G.GL_REPLACE = gl.REPLACE
_G.GL_LUMINANCE_ALPHA = gl.LUMINANCE_ALPHA
_G.GL_DEPTH_RANGE = gl.DEPTH_RANGE
_G.GL_FASTEST = gl.FASTEST
_G.GL_STENCIL_FAIL = gl.STENCIL_FAIL
_G.GL_UNSIGNED_SHORT = gl.UNSIGNED_SHORT
_G.GL_RENDERBUFFER_HEIGHT = gl.RENDERBUFFER_HEIGHT
_G.GL_STENCIL_BACK_FAIL = gl.STENCIL_BACK_FAIL
_G.GL_BLEND_SRC_RGB = gl.BLEND_SRC_RGB
_G.GL_TEXTURE3 = gl.TEXTURE3
_G.GL_RENDERBUFFER = gl.RENDERBUFFER
_G.GL_RGB5_A1 = gl.RGB5_A1
_G.GL_RENDERBUFFER_ALPHA_SIZE = gl.RENDERBUFFER_ALPHA_SIZE
_G.GL_RENDERBUFFER_STENCIL_SIZE = gl.RENDERBUFFER_STENCIL_SIZE
_G.GL_NOTEQUAL = gl.NOTEQUAL
_G.GL_BLEND_DST_RGB = gl.BLEND_DST_RGB
_G.GL_FRONT_AND_BACK = gl.FRONT_AND_BACK
_G.GL_TEXTURE_BINDING_CUBE_MAP = gl.TEXTURE_BINDING_CUBE_MAP
_G.GL_MAX_RENDERBUFFER_SIZE = gl.MAX_RENDERBUFFER_SIZE
_G.GL_ZERO = gl.ZERO
_G.GL_TEXTURE0 = gl.TEXTURE0
_G.GL_SAMPLE_ALPHA_TO_COVERAGE = gl.SAMPLE_ALPHA_TO_COVERAGE
_G.GL_BUFFER_USAGE = gl.BUFFER_USAGE
_G.GL_ACTIVE_TEXTURE = gl.ACTIVE_TEXTURE
_G.GL_BYTE = gl.BYTE
_G.GL_CW = gl.CW
_G.GL_DYNAMIC_DRAW = gl.DYNAMIC_DRAW
_G.GL_RENDERBUFFER_RED_SIZE = gl.RENDERBUFFER_RED_SIZE
_G.GL_FALSE = gl.FALSE
_G.GL_GREATER = gl.GREATER
_G.GL_RGBA4 = gl.RGBA4
_G.GL_VALIDATE_STATUS = gl.VALIDATE_STATUS
_G.GL_STENCIL_BITS = gl.STENCIL_BITS
_G.GL_RGB = gl.RGB
_G.GL_INT = gl.INT
_G.GL_DEPTH_FUNC = gl.DEPTH_FUNC
_G.GL_SAMPLER_2D = gl.SAMPLER_2D
_G.GL_NICEST = gl.NICEST
_G.GL_MAX_VIEWPORT_DIMS = gl.MAX_VIEWPORT_DIMS
_G.GL_CULL_FACE = gl.CULL_FACE
_G.GL_INT_VEC3 = gl.INT_VEC3
_G.GL_ALIASED_POINT_SIZE_RANGE = gl.ALIASED_POINT_SIZE_RANGE
_G.GL_INVALID_ENUM = gl.INVALID_ENUM
_G.GL_INVERT = gl.INVERT
_G.GL_CULL_FACE_MODE = gl.CULL_FACE_MODE
_G.GL_TEXTURE8 = gl.TEXTURE8
_G.GL_VERTEX_ATTRIB_ARRAY_POINTER = gl.VERTEX_ATTRIB_ARRAY_POINTER
_G.GL_TEXTURE_WRAP_S = gl.TEXTURE_WRAP_S
_G.GL_VERTEX_ATTRIB_ARRAY_STRIDE = gl.VERTEX_ATTRIB_ARRAY_STRIDE
_G.GL_LINES = gl.LINES
_G.GL_EQUAL = gl.EQUAL
_G.GL_LINE_LOOP = gl.LINE_LOOP
_G.GL_TEXTURE_WRAP_T = gl.TEXTURE_WRAP_T
_G.GL_DEPTH_BUFFER_BIT = gl.DEPTH_BUFFER_BIT
_G.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS
_G.GL_SHADER_TYPE = gl.SHADER_TYPE
_G.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = gl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME
_G.GL_TEXTURE_CUBE_MAP_NEGATIVE_X = gl.TEXTURE_CUBE_MAP_NEGATIVE_X
_G.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y = gl.TEXTURE_CUBE_MAP_NEGATIVE_Y
_G.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z = gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
_G.GL_DECR = gl.DECR
_G.GL_DELETE_STATUS = gl.DELETE_STATUS
_G.GL_DEPTH_BITS = gl.DEPTH_BITS
_G.GL_INCR = gl.INCR
_G.GL_SAMPLE_COVERAGE_VALUE = gl.SAMPLE_COVERAGE_VALUE
_G.GL_ALPHA_BITS = gl.ALPHA_BITS
_G.GL_FLOAT_MAT2 = gl.FLOAT_MAT2
_G.GL_LINE_STRIP = gl.LINE_STRIP
_G.GL_SHADER_SOURCE_LENGTH = gl.SHADER_SOURCE_LENGTH
_G.GL_INVALID_VALUE = gl.INVALID_VALUE
_G.GL_NEVER = gl.NEVER
_G.GL_INCR_WRAP = gl.INCR_WRAP
_G.GL_BLEND_EQUATION_ALPHA = gl.BLEND_EQUATION_ALPHA
_G.GL_TEXTURE_MAG_FILTER = gl.TEXTURE_MAG_FILTER
_G.GL_POINTS = gl.POINTS
_G.GL_COLOR_ATTACHMENT0 = gl.COLOR_ATTACHMENT0
_G.GL_RGBA = gl.RGBA
_G.GL_SRC_ALPHA_SATURATE = gl.SRC_ALPHA_SATURATE
_G.GL_SAMPLER_CUBE = gl.SAMPLER_CUBE
_G.GL_FRAMEBUFFER = gl.FRAMEBUFFER
_G.GL_TEXTURE_CUBE_MAP = gl.TEXTURE_CUBE_MAP
_G.GL_SAMPLE_BUFFERS = gl.SAMPLE_BUFFERS
_G.GL_LINEAR = gl.LINEAR
_G.GL_LINEAR_MIPMAP_NEAREST = gl.LINEAR_MIPMAP_NEAREST
_G.GL_ACTIVE_UNIFORM_MAX_LENGTH = gl.ACTIVE_UNIFORM_MAX_LENGTH
_G.GL_STENCIL_BACK_REF = gl.STENCIL_BACK_REF
_G.GL_ELEMENT_ARRAY_BUFFER = gl.ELEMENT_ARRAY_BUFFER
_G.GL_CLAMP_TO_EDGE = gl.CLAMP_TO_EDGE
_G.GL_TRIANGLE_STRIP = gl.TRIANGLE_STRIP
_G.GL_CONSTANT_COLOR = gl.CONSTANT_COLOR
_G.GL_COMPILE_STATUS = gl.COMPILE_STATUS
_G.GL_RENDERBUFFER_GREEN_SIZE = gl.RENDERBUFFER_GREEN_SIZE
_G.GL_UNSIGNED_INT = gl.UNSIGNED_INT
_G.GL_DEPTH_CLEAR_VALUE = gl.DEPTH_CLEAR_VALUE
_G.GL_ALIASED_LINE_WIDTH_RANGE = gl.ALIASED_LINE_WIDTH_RANGE
_G.GL_SHADING_LANGUAGE_VERSION = gl.SHADING_LANGUAGE_VERSION
_G.GL_FRAMEBUFFER_UNSUPPORTED = gl.FRAMEBUFFER_UNSUPPORTED
_G.GL_INFO_LOG_LENGTH = gl.INFO_LOG_LENGTH
_G.GL_STENCIL_PASS_DEPTH_PASS = gl.STENCIL_PASS_DEPTH_PASS
_G.GL_STENCIL_VALUE_MASK = gl.STENCIL_VALUE_MASK
_G.GL_ALWAYS = gl.ALWAYS
_G.GL_MAX_TEXTURE_SIZE = gl.MAX_TEXTURE_SIZE
_G.GL_FLOAT = gl.FLOAT
_G.GL_FRAMEBUFFER_BINDING = gl.FRAMEBUFFER_BINDING
_G.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT
_G.GL_TRIANGLE_FAN = gl.TRIANGLE_FAN
_G.GL_INVALID_FRAMEBUFFER_OPERATION = gl.INVALID_FRAMEBUFFER_OPERATION
_G.GL_TEXTURE_2D = gl.TEXTURE_2D
_G.GL_ALPHA = gl.ALPHA
_G.GL_CURRENT_VERTEX_ATTRIB = gl.CURRENT_VERTEX_ATTRIB
_G.GL_SCISSOR_TEST = gl.SCISSOR_TEST
_G.GL_TRIANGLES = gl.TRIANGLES
| apache-2.0 |
ntop/ntopng | attic/scripts/lua/show_alerts.lua | 2 | 2041 | --
-- (C) 2013-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
local alert_utils = require "alert_utils"
local page_utils = require("page_utils")
local alerts_api = require("alerts_api")
local recording_utils = require "recording_utils"
sendHTTPContentTypeHeader('text/html')
local ifid = interface.getId()
page_utils.set_active_menu_entry(page_utils.menu_entries.detected_alerts)
alert_utils.checkDeleteStoredAlerts()
dofile(dirs.installdir .. "/scripts/lua/inc/menu.lua")
page_utils.print_page_title(i18n('alerts_dashboard.alerts'))
local has_engaged_alerts = alert_utils.hasAlerts("engaged", alert_utils.getTabParameters(_GET, "engaged"))
local has_past_alerts = alert_utils.hasAlerts("historical", alert_utils.getTabParameters(_GET, "historical"))
local has_flow_alerts = alert_utils.hasAlerts("historical-flows", alert_utils.getTabParameters(_GET, "historical-flows"))
if ntop.getPrefs().are_alerts_enabled == false then
print("<div class=\"alert alert alert-warning\"><img src=".. ntop.getHttpPrefix() .. "/img/warning.png>" .. " " .. i18n("show_alerts.alerts_are_disabled_message") .. "</div>")
--return
elseif not has_engaged_alerts and not has_past_alerts and not has_flow_alerts then
print("<div class=\"alert alert alert-info\"><i class=\"fas fa-info-circle fa-lg\" aria-hidden=\"true\"></i>" .. " " .. i18n("show_alerts.no_recorded_alerts_message").."</div>")
else
-- Alerts Tablei
alert_utils.drawAlertTables(has_past_alerts, has_engaged_alerts, has_flow_alerts, false, _GET, nil, nil, {
is_standalone = true
})
-- PCAP modal for alert traffic extraction
local traffic_extraction_available = recording_utils.isActive(ifid) or recording_utils.isExtractionActive(ifid)
if traffic_extraction_available then
alert_utils.drawAlertPCAPDownloadDialog(ifid)
end
end -- closes if ntop.getPrefs().are_alerts_enabled == false then
dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
| gpl-3.0 |
martial69320/mlvuzkgq | src/server/scripts/Custom/GoMove/GOMove/GOMoveFunctions.lua | 8 | 9890 | GOMove = {Frames = {}, Inputs = {}}
function GOMove:Update()
for k, Frame in ipairs(GOMove.Frames) do
if(Frame.Update) then
Frame:Update()
end
end
end
function GOMove:Tonumber(val) -- returns nil if the value is not a number or 0x starting hex
if(type(val) == "string") then
if(val:find("0x") == 1) then
return tonumber(val, 16), true
end
end
return tonumber(val), false
end
function GOMove:CreateFrame(name, width, height, DataTable, both)
local Frame = CreateFrame("Frame", name, UIParent)
Frame:SetMovable(true)
Frame:EnableMouse(true)
Frame:RegisterForDrag("LeftButton")
Frame:SetScript("OnDragStart", Frame.StartMoving)
Frame:SetScript("OnDragStop", Frame.StopMovingOrSizing)
Frame:SetScript("OnHide", Frame.StopMovingOrSizing)
Frame:SetSize(width, height)
Frame:SetPoint("CENTER")
Frame.ButtonCount = math.floor((height-32)/16)
Frame:SetBackdrop({
bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background", tile = true, tileSize = 16,
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", edgeSize = 16,
insets = { left = 4, right = 4, top = 4, bottom = 4 },
})
local NameFrame = CreateFrame("Frame", name.."_Name", Frame)
NameFrame:SetHeight(16)
NameFrame:SetWidth(width-16)
NameFrame.text = NameFrame:CreateFontString()
NameFrame.text:SetFont("Fonts\\MORPHEUS.ttf", 14)
NameFrame.text:SetTextColor(0.8, 0.2, 0.2)
NameFrame.text:SetJustifyH("LEFT")
NameFrame.text:SetAllPoints()
NameFrame.text:SetText(name:gsub("_", " "))
NameFrame:SetPoint("TOPLEFT", Frame, "TOPLEFT", 8, -8)
NameFrame:Show()
Frame.NameFrame = NameFrame
local CloseButton = CreateFrame("Button", name.."_CloseButton", Frame)
CloseButton:SetSize(25, 25)
CloseButton:SetNormalTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Up")
CloseButton:SetPushedTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Down")
CloseButton:SetHighlightTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Highlight")
CloseButton:SetPoint("TOPRIGHT", Frame, "TOPRIGHT", 0, 0)
CloseButton:SetScript("OnClick", function() Frame:Hide() end)
if(DataTable) then
Frame.DataTable = DataTable
function Frame:Update()
local maxValue = #DataTable
FauxScrollFrame_Update(self.ScrollBar, maxValue, self.ButtonCount, 16, nil, nil, nil, nil, nil, nil, true)
local offset = FauxScrollFrame_GetOffset(self.ScrollBar)
for Button = 1, self.ButtonCount do
local value = Button + offset
if value <= maxValue then
local Button = self.Buttons[Button]
local Label = DataTable[value][1]
if(DataTable.NameWidth and strlen(DataTable[value][1]) > DataTable.NameWidth) then
Label = DataTable[value][1]:sub(0, DataTable.NameWidth-2)..".."
end
if(not both) then
Button:SetText(Label)
else
Button:SetText(DataTable[value][2].." "..Label)
end
Button.MiscButton:Show()
Button:Show()
else
self.Buttons[Button]:Hide()
self.Buttons[Button].MiscButton:Hide()
end
if(Frame.UpdateScript) then
Frame:UpdateScript(Button)
end
end
end
local ScrollBar = CreateFrame("ScrollFrame", "$parent_ScrollBar", Frame, "FauxScrollFrameTemplate")
ScrollBar:SetPoint("TOPLEFT", 0, -24) -- -8
ScrollBar:SetPoint("BOTTOMRIGHT", -30, 8)
ScrollBar:SetScript("OnVerticalScroll", function(self, offset)
self.offset = math.floor(offset / 16 + 0.5)
Frame:Update()
end)
ScrollBar:SetScript("OnShow", function()
Frame:Update()
end)
Frame.ScrollBar = ScrollBar
local Buttons = setmetatable({}, { __index = function(t, i)
local Button = CreateFrame("Button", "$parent_Button"..i, Frame)
Button:SetSize(width-55, 16)
Button:SetNormalFontObject(GameFontHighlightLeft)
if i == 1 then
Button:SetPoint("TOPLEFT", ScrollBar, 8, 0)
else
Button:SetPoint("TOPLEFT", Frame.Buttons[i-1], "BOTTOMLEFT")
end
Button:SetScript("OnClick", function(self) if(Frame.ButtonOnClick) then Frame:ButtonOnClick(i) end end)
local MiscButton = CreateFrame("Button", "$parent_Button"..i.."_Misc", Frame)
MiscButton:SetSize(16, 16)
MiscButton:SetNormalTexture("Interface\\Buttons\\UI-MinusButton-Disabled")
MiscButton:SetPushedTexture("Interface\\Buttons\\UI-MinusButton-Down")
MiscButton:SetHighlightTexture("Interface\\Buttons\\UI-MinusButton-Up")
MiscButton:SetNormalFontObject(GameFontHighlightLeft)
MiscButton:SetPoint("TOPLEFT", Button, "TOPRIGHT", 0, 0)
MiscButton:SetScript("OnClick", function(self) if(Frame.MiscOnClick) then Frame:MiscOnClick(i) end end)
Button.MiscButton = MiscButton
rawset(t, i, Button)
return Button
end })
Frame.Buttons = Buttons
Frame:Update()
end
function Frame:Position(FramePoint, Parent, ParentPoint, Ox, Oy)
Frame.Default = {FramePoint, Parent, ParentPoint, Ox, Oy}
Frame:SetPoint(FramePoint, Parent, ParentPoint, Ox, Oy)
end
table.insert(GOMove.Frames, Frame)
return Frame
end
function GOMove:CreateButton(Frame, name, width, height, Ox, Oy)
local Button = CreateFrame("Button", Frame:GetName().."_"..name, Frame, "UIPanelButtonTemplate")
Button:SetSize(width, height)
Button:SetText(name)
Button:SetPoint("TOP", Frame, "TOP", Ox, Oy-10)
Button:SetScript("OnClick", function(self) if(self.OnClick) then self:OnClick(Frame) end end)
return Button
end
function GOMove:CreateInput(Frame, name, width, height, Ox, Oy, letters, default)
local Input = CreateFrame("EditBox", Frame:GetName().."_"..name, Frame, "InputBoxTemplate")
Input:SetSize(width, height)
Input:SetPoint("TOP", Frame, "TOP", Ox+2.5, Oy-10)
Input:SetAutoFocus(false)
Input:SetNumeric(true)
Input:SetMaxLetters(letters)
Input:SetScript("OnEnterPressed", function() Input:ClearFocus() end)
Input:SetScript("OnEscapePressed", function() Input:ClearFocus() end)
if(default) then
Input:SetNumber(default)
end
table.insert(GOMove.Inputs, Input)
return Input
end
local trinityID = {}
local TIDs = 0
local function TID(name, reqguid, onetime)
trinityID[name] = {TIDs, reqguid, onetime}
TIDs = TIDs+1
end
-- NEED to be in order(same as core)
TID("TEST" , false , true ) -- unused
TID("SELECTNEAR" , false , true )
TID("DELETE" , true , true )
TID("X" , true , false )
TID("Y" , true , false )
TID("Z" , true , false )
TID("O" , true , false )
TID("GROUND" , true , false )
TID("RESPAWN" , true , true )
TID("GOTO" , true , true )
TID("FACE" , false , true )
TID("SAVE" , true , true )
TID("SPAWN" , false , true )
TID("NORTH" , true , false )
TID("EAST" , true , false )
TID("SOUTH" , true , false )
TID("WEST" , true , false )
TID("NORTHEAST" , true , false )
TID("NORTHWEST" , true , false )
TID("SOUTHEAST" , true , false )
TID("SOUTHWEST" , true , false )
TID("UP" , true , false )
TID("DOWN" , true , false )
TID("LEFT" , true , false )
TID("RIGHT" , true , false )
TID("PHASE" , true , false )
TID("SELECTALLNEAR" , false , true )
TID("SPAWNSPELL" , false , true )
--TID("COPYSEL" , false , false )
--TID("COPY" , false , false )
--TID("BIG" , false , false )
--TID("SMALL" , false , false )
function GOMove:Move(ID, input)
if(UnitIsDeadOrGhost("player")) then
NotWhileDeadError()
return
end
for k, inputfield in ipairs(GOMove.Inputs) do
inputfield:ClearFocus()
end
local ARG = 0
if(input) then
ARG = input
end
-- SendAddonMessage("$GOMOVE$,"..ID, ARG, "WHISPER", UnitName("player"))
if(not trinityID[ID] or not tonumber(trinityID[ID][1])) then
return
end
if(not trinityID[ID][2]) then
SendAddonMessage(".gomove "..trinityID[ID][1].." "..(0).." "..ARG, "", "WHISPER", UnitName("player"))
elseif(trinityID[ID][3] and GOMove:Tonumber(ARG) and GOMove:Tonumber(ARG) > 0) then
SendAddonMessage(".gomove "..trinityID[ID][1].." "..ARG.." "..(0), "", "WHISPER", UnitName("player"))
else
local did = false
for GUID, NAME in pairs(GOMove.Selected) do
if(GOMove:Tonumber(GUID)) then -- HAD TONUMBER
SendAddonMessage(".gomove "..trinityID[ID][1].." "..GUID.." "..ARG, "", "WHISPER", UnitName("player"))
if(ID == "GOTO") then
return
end
did = true
end
end
if(not did) then
UIErrorsFrame:AddMessage("No objects selected", 1.0, 0.0, 0.0, 53, 2)
return
end
end
end | gpl-2.0 |
cis542/VR_Wall | PongGame2/glsdk/glload/codegen/_util.lua | 5 | 2771 |
--Works like the regular pairs, but returns the key/value pairs in a key-sorted order.
--sortFunc is the function used to compare them.
function sortPairs(theTable, sortFunc)
local keyTable = {};
for key, value in pairs(theTable) do
table.insert(keyTable, key);
end
table.sort(keyTable, sortFunc);
local currIndex = 1;
local lenTable = #keyTable;
return function()
local currKey = keyTable[currIndex];
currIndex = currIndex + 1;
return currKey, theTable[currKey];
end
end
--Works like ipairs, but returns the list as through it were in a sorted order.
--It even returns the "wrong" indices.
--sortFunc is the function used to compare them.
function isortPairs(theTable, sortFunc)
local tempTable = {};
for i, value in ipairs(theTable) do
table.insert(tempTable, value);
end
table.sort(tempTable, sortFunc);
local currIndex = 1;
local lenTable = #tempTable;
return function()
local tempIndex = currIndex;
currIndex = currIndex + 1;
return tempIndex, theTable[tempIndex];
end
end
--ipairs in reverse order.
function ripairs(theTable)
local currIndex = #theTable;
return function()
local tempIndex = currIndex;
currIndex = currIndex - 1;
if(currIndex < 0) then return nil, nil; end;
return tempIndex, theTable[tempIndex];
end
end
--Standard lessthan compare function. For use with the above.
function CompLess(key1, key2)
return key1 < key2;
end
--A combined printf and hFile:write.
function WriteFormatted(hFile, strFormat, ...)
hFile:write(string.format(strFormat, ...));
end
function WriteForm(hFile, strFormat, ...)
hFile:write(string.format(strFormat, ...));
end
function GetIncludePath()
return "../include/glload/";
end
function GetSourcePath()
return "../source/";
end
function GetSpecFilePath()
return "glspecs/";
end
function GetDataFilePath()
return "data/";
end
--This returns the starting part of a header's includeguard. Takes the name of the define.
function GetFileIncludeGuardStart(defineName)
return string.format([[
#ifndef %s
#define %s
]], defineName, defineName);
end
--This returns the ending part of a header's includeguard. Takes the name of the define.
function GetFileIncludeGuardEnd(defineName)
return string.format([[
#endif //%s
]], defineName);
end
--Retrieves the beginning of the extern C block
function GetExternCStart()
return [[
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
]]
end
--Retrieves the end of the extern C block.
function GetExternCEnd()
return [[
#ifdef __cplusplus
}
#endif //__cplusplus
]]
end
--Retrieves a string for a C-style heading. Takes the name of the heading.
function GetSectionHeading(headingName)
return string.format(
[[/******************************
* %s
******************************/
]], headingName);
end
| epl-1.0 |
icetoggle/skynet | test/testrediscluster.lua | 19 | 3400 | local skynet = require "skynet"
local rediscluster = require "skynet.db.redis.cluster"
local test_more = ...
-- subscribe mode's callback
local function onmessage(data,channel,pchannel)
print("onmessage",data,channel,pchannel)
end
skynet.start(function ()
local db = rediscluster.new({
{host="127.0.0.1",port=7000},
{host="127.0.0.1",port=7001},},
{read_slave=true,auth=nil,db=0,},
onmessage
)
db:del("list")
db:del("map")
db:rpush("list",1,2,3)
local list = db:lrange("list",0,-1)
for i,v in ipairs(list) do
print(v)
end
db:hmset("map","key1",1,"key2",2)
local map = db:hgetall("map")
for i=1,#map,2 do
local key = map[i]
local val = map[i+1]
print(key,val)
end
-- test MOVED
db:flush_slots_cache()
print(db:set("A",1))
print(db:get("A"))
-- reconnect
local cnt = 0
for name,conn in pairs(db.connections) do
print(name,conn)
cnt = cnt + 1
end
print("cnt:",cnt)
db:close_all_connection()
print(db:set("A",1))
print(db:del("A"))
local slot = db:keyslot("{foo}")
local conn = db:get_connection_by_slot(slot)
-- You must ensure keys at one slot: use same key or hash tags
local ret = conn:pipeline({
{"hincrby", "{foo}hello", 1, 1},
{"del", "{foo}hello"},
{"hmset", "{foo}hello", 1, 1, 2, 2, 3, 3},
{"hgetall", "{foo}hello"},
},{})
print(ret[1].ok,ret[1].out)
print(ret[2].ok,ret[2].out)
print(ret[3].ok,ret[3].out)
print(ret[4].ok)
if ret[4].ok then
for i,v in ipairs(ret[4].out) do
print(v)
end
else
print(ret[4].out)
end
-- dbsize/info/keys
local conn = db:get_random_connection()
print("dbsize:",conn:dbsize())
print("info:",conn:info())
local keys = conn:keys("list*")
for i,key in ipairs(keys) do
print(key)
end
print("cluster nodes")
local nodes = db:cluster("nodes")
print(nodes)
print("cluster slots")
local slots = db:cluster("slots")
for i,slot_map in ipairs(slots) do
local start_slot = slot_map[1]
local end_slot = slot_map[2]
local master_node = slot_map[3]
print(start_slot,end_slot)
for i,v in ipairs(master_node) do
print(v)
end
for i=4,#slot_map do
local slave_node = slot_map[i]
for i,v in ipairs(slave_node) do
print(v)
end
end
end
-- test subscribe/publish
db:subscribe("world")
db:subscribe("myteam")
db:publish("world","hello,world")
db:publish("myteam","hello,my team")
-- low-version(such as 3.0.2) redis-server psubscribe is locally
-- if publish and psubscribe not map to same node,
-- we may lost message. so upgrade your redis or use tag to resolved!
db:psubscribe("{tag}*team")
db:publish("{tag}1team","hello,1team")
db:publish("{tag}2team","hello,2team")
-- i test in redis-4.0.9, it's ok
db:psubscribe("*team")
db:publish("1team","hello,1team")
db:publish("2team","hello,2team")
-- test eval
db:set("A",1)
local script = [[
if redis.call("get",KEYS[1]) == ARGV[1] then
return "ok"
else
return "fail"
end]]
print("eval#get",db:eval(script,1,"A",1))
db:del("A")
if not test_more then
skynet.exit()
return
end
local last = false
while not last do
last = db:get("__last__")
if last == nil then
last = 0
end
last = tonumber(last)
end
for val=last,1000000000 do
local ok,errmsg = pcall(function ()
local key = string.format("foo%s",val)
db:set(key,val)
print(key,db:get(key))
db:set("__last__",val)
end)
if not ok then
print("error:",errmsg)
end
end
skynet.exit()
end)
| mit |
graydon/monotone | tests/update_to_off-branch_rev/__driver__.lua | 1 | 1797 |
mtn_setup()
revs = {}
addfile("testfile", "blah blah")
commit()
revs.t = base_revision()
writefile("testfile", "other other")
commit("otherbranch")
revs.o = base_revision()
writefile("testfile", "third third")
commit("somebranch")
revs.s = base_revision()
check(mtn("cert", revs.s, "branch", "otherbranch"), 0, false, false)
writefile("testfile", "double double")
commit("nobranch")
revs.n = base_revision()
check(mtn("db", "kill_branch_certs_locally", "nobranch"))
check(mtn("checkout", "--branch=testbranch", "--revision", revs.t, "codir"), 0, false, false)
check(grep('^ *branch "testbranch"', "codir/_MTN/options"), 0, false, false)
-- make sure that updating to a rev in one other branch puts us in that branch
check(indir("codir", mtn("update", "--revision", revs.o)), 0, false, false)
check(grep('^ *branch "otherbranch"', "codir/_MTN/options"), 0, false, false)
-- updating to a rev in multiple branches, including current branch, leaves branch alone
check(indir("codir", mtn("update", "-r", revs.s)), 0, false, false)
check(grep('^ *branch "otherbranch"', "codir/_MTN/options"), 0, false, false)
-- but updating to a rev in multiple branches that _don't_ include the current one, fails
-- first go back out to TR
check(indir("codir", mtn("update", "-r", revs.t)), 0, false, false)
check(grep('^ *branch "testbranch"', "codir/_MTN/options"), 0, false, false)
-- and now jumping to SR directly should fail
check(indir("codir", mtn("update", "-r", revs.s)), 1, false, false)
check(grep('^ *branch "testbranch"', "codir/_MTN/options"), 0, false, false)
-- updating to a rev in no branches at all succeeds, and leaves current branch alone
check(indir("codir", mtn("update", "-r", revs.n)), 0, false, false)
check(grep('^ *branch "testbranch"', "codir/_MTN/options"), 0, false, false)
| gpl-2.0 |
Star2Billing/newfies-dialer | lua/libs/fsm_callflow.lua | 2 | 37408 | --
-- Newfies-Dialer License
-- http://www.newfies-dialer.org
--
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this file,
-- You can obtain one at http://mozilla.org/MPL/2.0/.
--
-- Copyright (C) 2011-2015 Star2Billing S.L.
--
-- The primary maintainer of this project is
-- Arezqui Belaid <info@star2billing.com>
--
package.path = package.path .. ";/usr/share/newfies-lua/?.lua";
package.path = package.path .. ";/usr/share/newfies-lua/libs/?.lua";
local Database = require "database"
require "tag_replace"
require "texttospeech"
require "constant"
local FSMCall = {
session = nil,
debug_mode = nil,
debugger = nil,
db = nil,
-- default field values
call_ended = false,
extension_list = nil,
caller_id_name = nil,
caller_id_number = nil,
destination_number = nil,
uuid = nil,
marked_completed = false,
survey_id = nil,
call_duration = 0,
hangup_trigger = false,
current_node_id = false,
record_filename = false,
actionresult = false,
lastaction_start = false,
last_node = nil,
ended = false,
}
function FSMCall:new (o)
o = o or {} -- create object if user does not provide one
setmetatable(o, self)
self.__index = self
return o
end
function FSMCall:init()
-- Set db
self.db = Database:new{
debug_mode=self.debug_mode,
debugger=self.debugger
}
self.db:init()
-- Initialization
self.debugger:msg("DEBUG", "FSMCall:init")
self.call_start = os.time()
self.caller_id_name = self.session:getVariable("caller_id_name")
self.caller_id_number = self.session:getVariable("caller_id_number")
self.destination_number = self.session:getVariable("destination_number")
self.uuid = self.session:getVariable("uuid")
self.campaign_id = self.session:getVariable("campaign_id")
self.subscriber_id = self.session:getVariable("subscriber_id")
self.contact_id = self.session:getVariable("contact_id")
self.callrequest_id = self.session:getVariable("callrequest_id")
self.used_gateway_id = self.session:getVariable("used_gateway_id")
self.alarm_request_id = self.session:getVariable("alarm_request_id")
self.dialout_phone_number = self.session:getVariable("dialout_phone_number")
--This is needed for Inbound test
if not self.campaign_id or self.campaign_id == 0 or not self.contact_id then
local nofs_type = 'alarm'
if nofs_type == 'campaign' then
-- Campaign Test
self.campaign_id = 46
self.subscriber_id = 39
self.contact_id = 39
self.callrequest_id = 215
self.db.DG_SURVEY_ID = 41
self.alarm_request_id = nil
else
-- Alarm Test
self.campaign_id = 'None'
self.subscriber_id = 'None'
self.contact_id = 'None'
self.callrequest_id = 15390
self.db.DG_SURVEY_ID = 74
self.alarm_request_id = 43
end
end
call_id = self.uuid..'_'..self.callrequest_id
self.debugger:set_call_id(call_id)
-- This is the first connect
if not self.db:connect() then
self.debugger:msg("ERROR", "Error Connecting to database")
self:hangupcall()
return false
end
--Load All data
self.survey_id = self.db:load_all(self.campaign_id, self.contact_id, self.alarm_request_id)
if not self.survey_id then
self.debugger:msg("ERROR", "Error Survey loading data")
self:hangupcall()
return false
end
self.db:check_data()
if not self.db.valid_data then
self.debugger:msg("ERROR", "Error invalid data")
self:hangupcall()
return false
end
self.debugger:msg("INFO", "Start_node : "..self.db.start_node)
self.current_node_id = self.db.start_node
return true
end
function FSMCall:end_call()
if self.ended then
return true
end
self.ended = true
self.debugger:msg("INFO", "FSMCall:end_call")
--Check if we need to save the last recording
if self.record_filename and string.len(self.record_filename) > 0 then
local digits = ''
local record_dur = audio_lenght(FS_RECORDING_PATH..self.record_filename)
self.debugger:msg("INFO", "End_call -> Save missing recording")
self.db:save_section_result(self.callrequest_id, self.last_node, digits, self.record_filename, record_dur)
end
--Check if we need to save the last action
if self.actionresult and string.len(self.actionresult) > 0 then
self.actionresult = self.actionresult
self.db:save_section_result(self.callrequest_id, self.last_node, self.actionresult, '', 0)
self.actionresult = false
end
--Save all the result to the Database
self.db:commit_result_mem(self.survey_id)
-- We need to keep this disconnect as it's End of Call
self.db:disconnect()
-- NOTE: Don't use this call time for Billing / Use CDRs
if not self.call_ended then
self.call_ended = true
--Estimate the call Duration
self.call_duration = os.time() - self.call_start
self.debugger:msg("DEBUG", "Estimated Call Duration : "..self.call_duration)
self:hangupcall()
end
end
function FSMCall:hangupcall()
-- This will interrupt lua script
self.debugger:msg("INFO", "FSMCall:hangupcall")
self.hangup_trigger = true
if self.session then
self.session:hangup()
end
end
function FSMCall:start_call()
self.debugger:msg("INFO", "FSMCall:start_call...")
self:next_node()
end
function FSMCall:playnode(current_node)
--play the audiofile or play the audio TTS
local filetoplay = self:get_playnode_audiofile(current_node)
if filetoplay and string.len(filetoplay) > 1 then
self.debugger:msg("INFO", "StreamFile : "..filetoplay)
self.session:streamFile(filetoplay)
end
end
function FSMCall:get_playnode_audiofile(current_node)
--get the audiofile or play the audio TTS
if current_node.audiofile_id then
--Get audio path
local current_audio = self.db.list_audio[tonumber(current_node.audiofile_id)]
local filetoplay = UPLOAD_DIR..current_audio.audio_file
self.debugger:msg("DEBUG", "Prepare StreamFile : "..filetoplay)
return filetoplay
else
--Use TTS
local mscript = tag_replace(current_node.script, self.db.contact)
self.debugger:msg("INFO", "Speak TTS : "..mscript)
if mscript and mscript ~= '' then
local tts_file = tts(mscript, TTS_DIR)
self.debugger:msg("DEBUG", "Prepare Speak TTS : "..tostring(tts_file))
return tts_file
end
end
return false
end
function FSMCall:get_confirm_ttsfile(current_node)
-- This function is going to be used by transfer
local mscript = tag_replace(current_node.confirm_script, self.db.contact)
self.debugger:msg("INFO", "Prepare Speak : "..mscript)
if mscript and mscript ~= '' then
local tts_file = tts(mscript, TTS_DIR)
self.debugger:msg("DEBUG", "Prepare File for TTS : "..tostring(tts_file))
-- if tts_file then
-- self.session:streamFile(tts_file)
-- end
return tts_file
end
return false
end
--local digits = session:playAndGetDigits(1, 1, 2,4000, "#", "phrase:voicemail_record_file_check:1:2:3", invalid,"\\d{1}")
function FSMCall:build_dtmf_mask(current_node)
-- Build the dtmf filter to capture digits
local mask = ''
if current_node.key_0 and string.len(current_node.key_0) > 0 then
mask = mask..'0'
end
if current_node.key_1 and string.len(current_node.key_1) > 0 then
mask = mask..'1'
end
if current_node.key_2 and string.len(current_node.key_2) > 0 then
mask = mask..'2'
end
if current_node.key_3 and string.len(current_node.key_3) > 0 then
mask = mask..'3'
end
if current_node.key_4 and string.len(current_node.key_4) > 0 then
mask = mask..'4'
end
if current_node.key_5 and string.len(current_node.key_5) > 0 then
mask = mask..'5'
end
if current_node.key_6 and string.len(current_node.key_6) > 0 then
mask = mask..'6'
end
if current_node.key_7 and string.len(current_node.key_7) > 0 then
mask = mask..'7'
end
if current_node.key_8 and string.len(current_node.key_8) > 0 then
mask = mask..'8'
end
if current_node.key_9 and string.len(current_node.key_9) > 0 then
mask = mask..'9'
end
return mask
end
function FSMCall:getdigitnode(current_node)
-- Get the node type and start playing it
self.debugger:msg("DEBUG", "*** getdigitnode ***")
local number_digits = 1
local dtmf_mask = '0123456789'
local invalid_audiofile = ''
local timeout = tonumber(current_node.timeout)
local retries = tonumber(current_node.retries)
--Validate timeout
if timeout <= 0 then
timeout = 1 -- GetDigits 'timeout' must be a positive integer
end
--Validate retries
if not retries then
retries = 1
elseif retries <= 0 then
retries = 1
else
retries = retries + 1
end
--Get Invalid Audio
if current_node.invalid_audiofile_id then
invalid_audiofile = UPLOAD_DIR..
self.db.list_audio[tonumber(current_node.invalid_audiofile_id)].audio_file
end
--Get DTMF Filter
if current_node.type == MULTI_CHOICE then
dtmf_mask = self:build_dtmf_mask(current_node)
end
--Retrieve number_digits
if current_node.type == RATING_SECTION then
number_digits = string.len(tostring(current_node.rating_laps))
elseif current_node.type == CAPTURE_DIGITS then
number_digits = current_node.number_digits
end
-- Function definition for playAndGetDigits
-- digits = session:playAndGetDigits (
-- min_digits, max_digits, max_attempts, timeout, terminators,
-- prompt_audio_files, input_error_audio_files,
-- digit_regex, variable_name, digit_timeout,
-- transfer_on_failure)
self.debugger:msg("DEBUG", "Play TTS (timeout="..tostring(timeout)..
",number_digits="..number_digits..", retries="..retries..
",invalid_audiofile="..tostring(invalid_audiofile)..
", dtmf_mask="..tostring(dtmf_mask)..")")
local i = 0
while i < retries do
i = i + 1
self.debugger:msg("DEBUG", ">> Retries counter = "..i.." - Max Retries = "..retries)
invalid = invalid_audiofile
digits = ''
if current_node.type == RATING_SECTION or current_node.type == CAPTURE_DIGITS then
-- for those 2 types we don't need invalid audio as we will handle this manually
invalid = ''
end
--play the audiofile or play the audio TTS
if current_node.audiofile_id then
--Get audio path
self.debugger:msg("DEBUG", "Play Audio GetDigits")
current_audio = self.db.list_audio[tonumber(current_node.audiofile_id)]
filetoplay = UPLOAD_DIR..current_audio.audio_file
self.debugger:msg("INFO", "Play Audiofile : "..filetoplay)
digits = self.session:playAndGetDigits(1, number_digits, retries,
timeout*1000, '#', filetoplay, invalid, '['..dtmf_mask..']|#')
else
--Use TTS
self.debugger:msg("DEBUG", "Play TTS GetDigits")
mscript = tag_replace(current_node.script, self.db.contact)
tts_file = tts(mscript, TTS_DIR)
self.debugger:msg("INFO", "Play TTS : "..tostring(tts_file))
if tts_file then
digits = self.session:playAndGetDigits(1, number_digits, retries,
timeout*1000, '#', tts_file, invalid, '['..dtmf_mask..']|#')
end
end
self.debugger:msg("INFO", "RESULT playAndGetDigits : "..digits)
if current_node.type == RATING_SECTION then
--break if digits is accepted
if digits ~= '' and tonumber(digits) >= 0 and tonumber(digits) <= tonumber(current_node.rating_laps) then
--Correct entrie, quit the loop
break
end
elseif current_node.type == MULTI_CHOICE then
--We already managed invalid on the playAndGetDigits
break
elseif current_node.type == CAPTURE_DIGITS
and (current_node.validate_number == '1' or current_node.validate_number == 't')
and digits ~= '' then
--CAPTURE_DIGITS / Check Validity
local int_dtmf = tonumber(digits)
local int_max = 0 -- init
if int_dtmf and int_dtmf >= 0 then
int_min = tonumber(current_node.min_number)
int_max = tonumber(current_node.max_number)
if not int_min then
int_min = 0
end
if not int_max then
int_max = 999999999999999
end
if int_dtmf >= int_min and int_dtmf <= int_max then
break
end
end
elseif current_node.type == CAPTURE_DIGITS
and not (current_node.validate_number == '1' or current_node.validate_number == 't')
and digits ~= '' then
self.debugger:msg("INFO", "CAPTURE_DIGITS / No Check Validity")
break
end
if invalid_audiofile ~= '' and i < retries then
--Play invalid audiofile
self.debugger:msg("INFO", "StreamFile Invalid : "..invalid_audiofile)
self.session:streamFile(invalid_audiofile)
end
end
return digits
end
--Used for AMD / Version of next_node only for PLAY_MESSAGE
--Review if this code is really needed, maybe can replace by next_node
function FSMCall:next_node_light()
self.debugger:msg("INFO", "FSMCall:next_node_light (current_node="..tonumber(self.current_node_id)..")")
local current_node = self.db.list_section[tonumber(self.current_node_id)]
self.last_node = current_node
self.debugger:msg_inspect("DEBUG", current_node)
current_branching = self.db.list_branching[tonumber(self.current_node_id)]
self:marked_node_completed(current_node)
self.debugger:msg("DEBUG", "-------------------------------------------")
self.debugger:msg("DEBUG", "TITLE :: ("..current_node.id..") "..current_node.question)
self.debugger:msg("DEBUG", "NODE TYPE ==> "..SECTION_TYPE[current_node.type])
--
--Run Action
--
if current_node.type == PLAY_MESSAGE then
self:playnode(current_node)
else
self.debugger:msg("ERROR", "next_node_light need to be a PLAY_MESSAGE : "..current_node.type)
self:end_call()
return false
end
--
--Check Branching / Find the next node
--
self.debugger:msg_inspect("DEBUG", current_branching)
if current_node.type == PLAY_MESSAGE then
--Check for timeout
if (not current_branching["0"] or not current_branching["0"].goto_id) and
(not current_branching["timeout"] or not current_branching["timeout"].goto_id) then
--Go to hangup
self.debugger:msg("DEBUG", "PLAY_MESSAGE : No more branching -> Goto Hangup")
self:end_call()
else
if current_branching["0"] and current_branching["0"].goto_id then
self.current_node_id = tonumber(current_branching["0"].goto_id)
elseif current_branching["timeout"] and current_branching["timeout"].goto_id then
self.current_node_id = tonumber(current_branching["timeout"].goto_id)
end
end
end
return true
end
function FSMCall:marked_node_completed(current_node)
if (current_node.completed == 't' and not self.marked_completed) then
--Mark the subscriber as completed and increment campaign completed field
self.db:update_subscriber(self.subscriber_id, SUBSCRIBER_COMPLETED)
--Flag Callrequest
self.db:update_callrequest_cpt(self.callrequest_id)
end
end
function FSMCall:next_node()
local digits = false
local recording_filename = false
local actionduration = 0
self.debugger:msg("DEBUG", "FSMCall:next_node (current_node="..tonumber(self.current_node_id)..")")
local current_node = self.db.list_section[tonumber(self.current_node_id)]
self.last_node = current_node
local current_branching = self.db.list_branching[tonumber(self.current_node_id)]
if not current_node then
self.debugger:msg("ERROR", "Not current_node : "..type(current_node))
self.debugger:msg_inspect("ERROR", self.db.list_section[tonumber(self.current_node_id)])
return false
end
self:marked_node_completed(current_node)
self.debugger:msg("DEBUG", "-------------------------------------------")
self.debugger:msg("DEBUG", "TITLE :: ("..current_node.id..") "..current_node.question)
self.debugger:msg("DEBUG", "NODE TYPE ==> "..SECTION_TYPE[current_node.type])
--
--Run Action
--
if current_node.type == PLAY_MESSAGE then
self:playnode(current_node)
elseif current_node.type == HANGUP_SECTION then
self:playnode(current_node)
self:end_call()
elseif current_node.type == CALL_TRANSFER then
-- Removed and replaced by Smooth-Transfer
-- self:playnode(current_node)
self.debugger:msg("INFO", "STARTING CALL_TRANSFER : "..current_node.phonenumber)
if current_node.phonenumber == '' then
self:end_call()
else
-- Flush the insert for the survey results when node is a Transfer
self.db:commit_result_mem()
self.lastaction_start = os.time()
-- Allow to hang up transfer call detecting DMTF ( *0 ) in LEG A
session:execute("bind_meta_app","0 a o hangup::normal_clearing")
session:setAutoHangup(false)
-- callerid = self.db.campaign_info.callerid
-- CallerID display at transfer will be the contact's phonenumber
callerid = self.dialout_phone_number
caller_id_name = self.dialout_phone_number
-- originate_timeout = self.db.campaign_info.calltimeout
-- leg_timeout = self.db.campaign_info.calltimeout
originate_timeout = 300
leg_timeout = 300
mcontact = mtable_jsoncontact(self.db.contact)
local dialstr = ''
local confirm_string = ''
local smooth_transfer = ''
-- check if we got a json phonenumber for transfer
if mcontact.transfer_phonenumber then
transfer_phonenumber = mcontact.transfer_phonenumber
else
transfer_phonenumber = current_node.phonenumber
end
new_dialout_phone_number = transfer_phonenumber
--dialstr = 'sofia/default/'..current_node.phonenumber..'@'..self.outbound_gateway;
if string.find(transfer_phonenumber, "/") then
--SIP URI call
dialstr = transfer_phonenumber
else
--Use Gateway call
dialstr = self.db.campaign_info.gateways..transfer_phonenumber
end
-- Set SIP HEADER P-CallRequest-ID & P-Contact-ID
-- http://wiki.freeswitch.org/wiki/Sofia-SIP#Adding_Request_Headers
session:execute("set", "sip_h_P-CallRequest-ID="..self.callrequest_id)
session:execute("set", "sip_h_P-Contact-ID="..self.contact_id)
-- Set SIP HEADER P-Contact-Transfer-Ref provisioned by Contact.additional_vars.transfer_ref Json setting
if mcontact.transfer_ref then
session:execute("set", "sip_h_P-Contact-Transfer-Ref="..mcontact.transfer_ref)
end
-- Smooth-Transfer - Play audio to user while bridging the call
transfer_audio = self:get_playnode_audiofile(current_node)
if transfer_audio then
-- Test audio
-- transfer_audio = "/usr/local/freeswitch/sounds/en/us/callie/ivr/8000/ivr-congratulations_you_pressed_star.wav"
-- idea: try api_on_originate or api_on_pre_originate? https://wiki.freeswitch.org/wiki/Channel_Variables
-- uuid_broadcast don't work cause the audio keep playing when the agent accept the call
-- api = freeswitch.API()
-- cmd = "bgapi uuid_broadcast "..self.uuid.." "..transfer_audio.." aleg"
-- result = api:executeString(cmd)
-- api_on_answer don't work as expect
-- smooth_transfer = ",api_on_answer=uuid_break"..self.uuid..","
-- Custom music on hold - Doesn't seem to work
-- session:execute("set", "hold_music=/usr/local/freeswitch/sounds/music/8000/suite-espanola-op-47-leyenda.wav")
-- smooth_transfer = ',api_on_pre_originate=playback'
-- session:execute("set", "hold_music="..transfer_audio)
-- bridge_pre_execute_aleg_app Seems broken
-- smooth_transfer = ',bridge_pre_execute_bleg_app=playback,bridge_pre_execute_bleg_data='..transfer_audio
-- session:execute("set", "campon=true")
-- session:execute("set", "campon_hold_music="..transfer_audio)
-- session:execute("set", "campon_retries=1")
-- session:execute("set", "campon_sleep=30")
-- session:execute("set", "campon_timeout=20")
-- Use ringback
-- <action application="set" data="ringback=file_string://${xxsounds}hi-long.wav!${sayname}!tone_stream://${us-ring};loops=-1"/>
session:execute("set", "ringback=file_string://"..transfer_audio.."!tone_stream://${us-ring};loops=-1")
session:execute("set", "transfer_ringback=file_string://"..transfer_audio.."!tone_stream://${us-ring};loops=-1")
end
-- Sending Ringback
-- session:execute("set", "ringback=${us-ring}")
-- session:execute("set", "transfer_ringback=${us-ring}")
-- Confirm Key
if string.len(current_node.confirm_key) == 1 and string.len(current_node.confirm_script) > 1 then
-- Great TTS file
confirm_file = self:get_confirm_ttsfile(current_node)
if confirm_file and string.len(confirm_file) > 1 then
-- <action application="bridge" data="{group_confirm_file=playback /path/to/prompt.wav,group_confirm_key=exec,call_timeout=60} iax/guest@somebox/1234,sofia/test-int/1000@somehost"/>
-- confirm_file = "/usr/local/freeswitch/sounds/en/us/callie/ivr/8000/ivr-congratulations_you_pressed_star.wav"
confirm_string = ',group_confirm_file='..confirm_file..',group_confirm_key='..current_node.confirm_key..',group_confirm_cancel_timeout=1'
-- group_confirm_read_timeout: Time in milliseconds to wait for the confirmation input (default: 5000 ms)
end
elseif string.len(current_node.confirm_script) > 1 then
-- No confirm key so we want to just playback an audio to the callee before bridging the call
-- Great TTS file
confirm_file = self:get_confirm_ttsfile(current_node)
if confirm_file and string.len(confirm_file) > 1 then
-- confirm_file = "/usr/local/freeswitch/sounds/en/us/callie/ivr/8000/ivr-congratulations_you_pressed_star.wav"
-- <action application="bridge" data="{group_confirm_file=playback /path/to/prompt.wav,group_confirm_key=exec,call_timeout=60} iax/guest@somebox/1234,sofia/test-int/1000@somehost"/>
confirm_string = ',group_confirm_file=playback '..confirm_file..',group_confirm_key=exec,group_confirm_cancel_timeout=1'
end
end
self.actionresult = 'phonenumber: '..current_node.phonenumber
dialstr = "{ignore_early_media=true,instant_ringback=true,hangup_after_bridge=false,origination_caller_id_number="..callerid..
",origination_caller_id_name="..caller_id_name..",originate_timeout="..originate_timeout..
",leg_timeout="..leg_timeout..",legtype=bleg,callrequest_id="..self.callrequest_id..
",dialout_phone_number="..new_dialout_phone_number..
",used_gateway_id="..self.used_gateway_id..confirm_string..smooth_transfer.."}"..dialstr
-- originate the call
self.debugger:msg("INFO", "dialstr:"..dialstr)
session:execute("bridge", dialstr)
actionduration = os.time() - self.lastaction_start
-- get disposition status
originate_disposition = session:getVariable("originate_disposition") or ''
if originate_disposition ~= 'SUCCESS' then
actionduration = 0
end
self.debugger:msg("INFO", "END CALL_TRANSFER callduration:"..actionduration.." - originate_disposition:"..originate_disposition)
self.actionresult = 'phonenumber: '..current_node.phonenumber
--.." duration: "..actionduration
self.db:save_section_result(self.callrequest_id, current_node, self.actionresult, '', 0)
self.actionresult = false
end
elseif current_node.type == DNC then
-- Add this phonenumber to the DNC campaign list
if self.db.campaign_info.dnc_id then
self.db:add_dnc(self.db.campaign_info.dnc_id, self.destination_number)
end
-- Save result
self.actionresult = 'DNC: '..self.destination_number
self.db:save_section_result(self.callrequest_id, current_node, self.actionresult, '', 0)
self.actionresult = false
-- Play Node
self:playnode(current_node)
self:end_call()
elseif current_node.type == CONFERENCE then
self:playnode(current_node)
conference = current_node.conference
self.debugger:msg("INFO", "STARTING CONFERENCE : "..conference)
if conference == '' then
conference = self.campaign_id
end
self.lastaction_start = os.time()
self.session:execute("conference", conference..'@default')
actionduration = os.time() - self.lastaction_start
self.debugger:msg("INFO", "END CONFERENCE : duration "..actionduration)
-- Save result
self.actionresult = 'conf: '..conference
self.db:save_section_result(self.callrequest_id, current_node, self.actionresult, '', 0)
self.actionresult = false
elseif current_node.type == SMS then
--Send an SMS
if current_node.sms_text and current_node.sms_text ~= '' then
mcontact = mtable_jsoncontact(self.db.contact)
if mcontact.sms_phonenumber then
destination_number = mcontact.sms_phonenumber
else
destination_number = self.destination_number
end
-- Use Event to decide to whom send the SMS
if self.db.event_data then
dec_eventdata = decodejson(self.db.event_data)
if dec_eventdata.sms_phonenumber then
destination_number = dec_eventdata.sms_phonenumber
end
end
local sms_text = tag_replace(current_node.sms_text, self.db.contact)
self.debugger:msg("INFO", "Prepare Send SMS : "..sms_text)
self.db:send_sms(sms_text, self.survey_id, destination_number)
-- Save result
self.actionresult = 'SMS: '..destination_number
self.db:save_section_result(self.callrequest_id, current_node, self.actionresult, '', 0)
self.actionresult = false
end
--Play Node
self:playnode(current_node)
elseif current_node.type == MULTI_CHOICE then
digits = self:getdigitnode(current_node)
self.debugger:msg("INFO", "result digit => "..digits)
elseif current_node.type == CAPTURE_DIGITS then
digits = self:getdigitnode(current_node)
self.debugger:msg("INFO", "result digit => "..digits)
elseif current_node.type == RATING_SECTION then
digits = self:getdigitnode(current_node)
self.debugger:msg("INFO", "result digit => "..digits)
-- Save the result to Alarm model
if self.db.event_alarm and self.db.event_alarm.alarm_id then
self.db:save_alarm_result(self.db.event_alarm.alarm_id, digits)
end
elseif current_node.type == RECORD_MSG then
self:playnode(current_node)
--timeout : Seconds of silence before considering the recording complete
--syntax is session:recordFile(file_name, max_len_secs, silence_threshold, silence_secs)
max_len_secs = 120
silence_threshold = 30
silence_secs = 5
id_recordfile = math.random(10000000, 99999999)
self.record_filename = "recording-"..current_node.id.."-"..id_recordfile..".wav"
record_filepath = FS_RECORDING_PATH..self.record_filename
self.debugger:msg("INFO", "STARTING RECORDING : "..record_filepath)
-- <action application="set" data="playback_terminators=#"/>
--session:setVariable("playback_terminators", "#")
session:execute("set", "playback_terminators=#")
result_rec = self.session:recordFile(record_filepath, max_len_secs, silence_threshold, silence_secs)
record_dur = audio_lenght(record_filepath)
self.debugger:msg("DEBUG", "RECORDING DONE DURATION: "..record_dur)
else
self.debugger:msg("DEBUG", "EXCEPTION -> HANGUP")
self:end_call()
end
--
--3. Record result and Aggregate result
--
if digits or self.record_filename then
self.db:save_section_result(self.callrequest_id, current_node, digits, self.record_filename, record_dur)
--reinit record_filename
self.record_filename = false
record_dur = false
end
--
--Check Branching / Find the next node
--
self.debugger:msg_inspect("DEBUG", current_branching)
if current_node.type == PLAY_MESSAGE
or current_node.type == RECORD_MSG
or current_node.type == CALL_TRANSFER
or current_node.type == CONFERENCE
or current_node.type == SMS then
--Check when no branching has been created
if (not current_branching) then
self.debugger:msg("ERROR", "No existing branching -> Goto Hangup - nodetype:"..current_node.type)
self:end_call()
--Check for timeout
elseif (not current_branching["0"] or not current_branching["0"].goto_id) and
(not current_branching["timeout"] or not current_branching["timeout"].goto_id) then
--Go to hangup
self.debugger:msg("DEBUG", "Check Branching : No more branching -> Goto Hangup")
self:end_call()
else
if current_branching["0"] and current_branching["0"].goto_id then
self.current_node_id = tonumber(current_branching["0"].goto_id)
elseif current_branching["timeout"] and current_branching["timeout"].goto_id then
self.current_node_id = tonumber(current_branching["timeout"].goto_id)
end
end
elseif current_node.type == MULTI_CHOICE
or current_node.type == RATING_SECTION
or current_node.type == CAPTURE_DIGITS then
--Flag for invalid input
local invalid_input = false
self.debugger:msg("DEBUG", "Check Validity")
--Check Validity
if current_node.type == RATING_SECTION then
--Break if digits is accepted
if digits == '' or tonumber(digits) < 1 or tonumber(digits) > tonumber(current_node.rating_laps) then
self.debugger:msg("DEBUG", "RATING_SECTION invalid_input")
invalid_input = true
end
elseif current_node.type == MULTI_CHOICE then
--Break if digits is accepted
if digits == '' then
self.debugger:msg("DEBUG", "MULTI_CHOICE invalid_input or maybe timeout")
invalid_input = true
-- in case of MULTI_CHOICE if digits is empty we might want to branch to the timeout first
if current_branching["timeout"] and current_branching["timeout"].goto_id then
--We got an "timeout branching"
self.debugger:msg("DEBUG", "Got 'timeout' Branching : "..current_branching["timeout"].goto_id)
self.current_node_id = tonumber(current_branching["timeout"].goto_id)
return true
elseif current_branching["timeout"] then
--There is no goto_id -> then we got to hangup
self.debugger:msg("DEBUG", "Got 'timeout' Branching but no goto_id -> then we got to hangup")
self:end_call()
return true
end
end
elseif current_node.type == CAPTURE_DIGITS
and (current_node.validate_number == '1' or current_node.validate_number == 't')
and digits ~= '' then
self.debugger:msg("DEBUG", "We have DTMF now we check validity")
local int_dtmf = tonumber(digits)
local int_min = tonumber(current_node.min_number)
local int_max = tonumber(current_node.max_number)
if not int_min then
int_min = 0
end
if not int_max then
int_max = 999999999999999
end
if not int_dtmf or int_dtmf < int_min or int_dtmf > int_max then
self.debugger:msg("DEBUG", "CAPTURE_DIGITS invalid_input")
invalid_input = true
end
end
if invalid_input then
--Invalid input
if current_branching["invalid"] and current_branching["invalid"].goto_id then
--We got an "invalid branching" and as we got a DTMF we shall go there
self.debugger:msg("DEBUG", "Got 'invalid' Branching : "..current_branching["invalid"].goto_id)
self.current_node_id = tonumber(current_branching["invalid"].goto_id)
return true
elseif current_branching["invalid"] then
--There is no goto_id -> then we got to hangup
self.debugger:msg("DEBUG", "Got 'invalid' Branching but no goto_id -> then we got to hangup")
self:end_call()
return true
end
end
self.debugger:msg("INFO", "Got valid digit(s) : "..digits)
--Check if we got a branching for this capture
if digits and string.len(digits) > 0 then
if current_branching[digits] and current_branching[digits].goto_id then
--We got a branching for this DTMF and a goto_id
self.current_node_id = tonumber(current_branching[digits].goto_id)
return true
elseif current_branching[digits] then
--We got a branching for this DTMF but no goto_id
self.debugger:msg("DEBUG", "We got a branching for this DTMF but no goto_id -> then we got to hangup")
self:end_call()
return true
elseif current_branching["any"] and current_branching["any"].goto_id then
--We got an "any branching" and as we got a DTMF we shall go there
self.debugger:msg("DEBUG", "Got 'any' Branching : "..current_branching["any"].goto_id)
self.current_node_id = tonumber(current_branching["any"].goto_id)
return true
elseif current_branching["any"] then
--There is no goto_id -> then we got to hangup
self.debugger:msg("DEBUG", "Got 'any' Branching but no goto_id -> then we got to hangup")
self:end_call()
return true
else
--Got digits but nothing accepted for this, let's stay on the same node
self.debugger:msg("DEBUG", "Got digits but nothing accepted for this, let's stay on the same node")
--If Rating and it's value
if current_node.type == RATING_SECTION and not invalid_input then
self.debugger:msg("DEBUG", "It's a valid input but there is no branching for it, so we hangup")
self:end_call()
end
return true
end
end
--Check if we got a branching for this capture
if not digits or string.len(digits) == 0 then
--Check if there is a timeout / you should
if not current_branching["timeout"] or not current_branching["timeout"].goto_id then
--Go to hangup
self.debugger:msg("DEBUG", "Check capture : No more branching -> Goto Hangup")
self:end_call()
else
self.current_node_id = tonumber(current_branching["timeout"].goto_id)
end
end
end
return true
end
return FSMCall
| mpl-2.0 |
pgl/prat | modules/OriginalButtons.lua | 2 | 16648 | ---------------------------------------------------------------------------------
--
-- Prat - A framework for World of Warcraft chat mods
--
-- Copyright (C) 2006-2007 Prat Development Team
--
-- 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:
--
-- Free Software Foundation, Inc.,
-- 51 Franklin Street, Fifth Floor,
-- Boston, MA 02110-1301, USA.
--
--
-------------------------------------------------------------------------------
--[[
Name: OriginalButtons (was PratChatButtons)
Revision: $Revision: 80138 $
Author(s): Curney (asml8ed@gmail.com)
Krtek (krtek4@gmail.com)
Sylvanaar (sylvanaar@mindspring.com)
Inspired by: idChat2_Buttons by Industrial
Website: http://www.wowace.com/files/index.php?path=Prat/
Documentation: http://www.wowace.com/wiki/Prat/Integrated_Modules#Buttons
Subversion: http://svn.wowace.com/wowace/trunk/Prat/
Discussions: http://groups.google.com/group/wow-prat
Issues and feature requests: http://code.google.com/p/prat/issues/list
Description: Module for Prat that adds chat menu and button options.
Dependencies: Prat
]]
Prat:AddModuleToLoad(function()
local PRAT_MODULE = Prat:RequestModuleName("OriginalButtons")
if PRAT_MODULE == nil then
return
end
-- define localized strings
local L = Prat:GetLocalizer({})
--@debug@
L:AddLocale("enUS", {
["ChannelNames"] = true,
["Original Buttons"] = true,
["Chat window button options."] = true,
["chatmenu_name"] = "Show Chat Menu",
["chatmenu_desc"] = "Toggles chat menu on and off.",
["Show Arrows"] = true,
["Toggle showing chat arrows for each chat window."] = true,
["Show Chat%d Arrows"] = true,
["Toggles navigation arrows on and off."] = true,
["reminder_name"] = "Show ScrollDown Reminder",
["reminder_desc"] = "Show reminder button when not at the bottom of a chat window.",
["Set Position"] = true,
["Sets position of chat menu and arrows for all chat windows."] = true,
["Default"] = true,
["Right, Inside Frame"] = true,
["Right, Outside Frame"] = true,
["alpha_name"] = "Set Alpha",
["alpha_desc"] = "Sets alpha of chat menu and arrows for all chat windows.",
["reflow_name"] = "Text Flows Around",
["reflow_desc"] = "Chatframe text should flow around the buttons not under them.",
})
--@end-debug@
-- These Localizations are auto-generated. To help with localization
-- please go to http://www.wowace.com/projects/prat-3-0/localization/
--[===[@non-debug@
L:AddLocale("enUS",
--@localization(locale="enUS", format="lua_table", same-key-is-true=true, namespace="OriginalButtons")@
)
L:AddLocale("frFR",
--@localization(locale="frFR", format="lua_table", same-key-is-true=true, namespace="OriginalButtons")@
)
L:AddLocale("deDE",
--@localization(locale="deDE", format="lua_table", same-key-is-true=true, namespace="OriginalButtons")@
)
L:AddLocale("koKR",
--@localization(locale="koKR", format="lua_table", same-key-is-true=true, namespace="OriginalButtons")@
)
L:AddLocale("esMX",
--@localization(locale="esMX", format="lua_table", same-key-is-true=true, namespace="OriginalButtons")@
)
L:AddLocale("ruRU",
--@localization(locale="ruRU", format="lua_table", same-key-is-true=true, namespace="OriginalButtons")@
)
L:AddLocale("zhCN",
--@localization(locale="zhCN", format="lua_table", same-key-is-true=true, namespace="OriginalButtons")@
)
L:AddLocale("esES",
--@localization(locale="esES", format="lua_table", same-key-is-true=true, namespace="OriginalButtons")@
)
L:AddLocale("zhTW",
--@localization(locale="zhTW", format="lua_table", same-key-is-true=true, namespace="OriginalButtons")@
)
--@end-non-debug@]===]
local module = Prat:NewModule(PRAT_MODULE, "AceHook-3.0")
--module.moduleName = L["Buttons"]
--module.moduleDesc = L["Chat window button options."]
--module.consoleName = "buttons"
--module.guiName = L["Buttons"]
--module.Categories = { cat.BUTTON, cat.FRAME }
-- define the default db values
--module.defaultDB = {
-- on = true,
-- chatmenu = false,
-- chatbutton = {false, false, false, false, false, false, false},
-- position = "DEFAULT",
-- reminder = false,
-- alpha = 1.0,
--}
Prat:SetModuleDefaults(module.name, {
profile = {
on = false,
chatmenu = false,
chatarrows = { ["*"] = true },
position = "RIGHTINSIDE",
reminder = true,
reflow = false,
alpha = 1.0,
}
})
Prat:SetModuleOptions(module.name, {
name = L["Original Buttons"],
desc = L["Chat window button options."],
type = "group",
args = {
chatarrows = {
name = L["Show Arrows"],
desc = L["Toggle showing chat arrows for each chat window."],
order = 120,
get = "GetSubValue",
set = "SetSubValue",
type = "multiselect",
values = Prat.FrameList,
},
chatmenu = {
type = "toggle",
order = 110,
name = L["chatmenu_name"],
desc = L["chatmenu_desc"],
get = function(info) return module.db.profile.chatmenu end,
set = function(info, v) module.db.profile.chatmenu = v module:ChatMenu(v) end,
},
reminder = {
type = "toggle",
name = L["reminder_name"],
desc = L["reminder_desc"],
get = function(info) return module.db.profile.reminder end,
set = function(info, v) module.db.profile.reminder = v end,
},
reflow = {
type = "toggle",
name = L["reflow_name"],
desc = L["reflow_desc"],
get = function(info) return module.db.profile.reflow end,
set = function(info, v) module.db.profile.reflow = v if v then Prat.Addon:GetModule("SMFHax", true):Enable() end end,
hidden = function(info) return Prat.Addon:GetModule("SMFHax", true) == nil end,
},
alpha = {
name = L["alpha_name"],
desc = L["alpha_desc"],
type = "range",
set = function(info, v) module.db.profile.alpha = v; module:ConfigureAllFrames() end,
min = 0.1,
max = 1,
step = 0.1,
order = 150,
get = function(info) return module.db.profile.alpha end,
},
position = {
name = L["Set Position"],
desc = L["Sets position of chat menu and arrows for all chat windows."],
type = "select",
order = 140,
get = function(info) return module.db.profile.position end,
set = function(info, v) module.db.profile.position = v; module:ConfigureAllFrames() end,
values = {["DEFAULT"] = L["Default"], ["RIGHTINSIDE"] = L["Right, Inside Frame"], ["RIGHTOUTSIDE"] = L["Right, Outside Frame"]}
}
}
})
function module:OnSubValueChanged(info, val, b)
self:chatbutton(_G[val]:GetID(), b)
end
--[[------------------------------------------------
Module Event Functions
------------------------------------------------]]--
-- things to do when the module is enabled
function module:OnModuleEnable()
local buttons3 = Prat.Addon:GetModule("Buttons", true)
if buttons3 and buttons3:IsEnabled() then
self.disabledB3 = true
buttons3.db.profile.on = false
buttons3:Disable()
LibStub("AceConfigRegistry-3.0"):NotifyChange("Prat")
end
-- stub variables for frame handling
self.frames = {}
self.reminders = {}
for i = 1,NUM_CHAT_WINDOWS do
table.insert(self.reminders, self:MakeReminder(i))
self:chatbutton(i,self.db.profile.chatarrows["ChatFrame"..i])
end
self:ChatMenu(self.db.profile.chatmenu)
-- set OnUpdateInterval, if they are profiling, update less
-- if GetCVar("scriptProfile") == "1" then
-- self.OnUpdateInterval = 0.5
-- else
-- self.OnUpdateInterval = 0.05
-- end
self.OnUpdateInterval = 0.05
self.lastupdate = 0
-- hook functions
self:SecureHook("ChatFrame_OnUpdate", "ChatFrame_OnUpdateHook")
end
-- things to do when the module is disabled
function module:OnModuleDisable()
-- show chatmenu
self:ChatMenu(true)
-- show all the chatbuttons
for i = 1,NUM_CHAT_WINDOWS do
self:chatbutton(i,true)
end
-- unhook functions
self:UnhookAll()
end
--[[------------------------------------------------
Core Functions
------------------------------------------------]]--
function module:ConfigureAllFrames()
for i = 1,NUM_CHAT_WINDOWS do
self:chatbutton(i,self.db.profile.chatarrows["ChatFrame"..i])
end
self:ChatMenu(self.db.profile.chatmenu)
end
function module:ChatFrame_OnUpdateHook(this, elapsed)
if not this:IsVisible() and not this:IsShown() then return end
self.lastupdate = self.lastupdate + elapsed
while (self.lastupdate > self.OnUpdateInterval) do
self:ChatFrame_OnUpdate(this, elapsed)
self.lastupdate = self.lastupdate - self.OnUpdateInterval;
end
end
function module:ChatFrame_OnUpdate(this, elapsed)
if ( not this:IsShown() ) then
return;
end
local id = this:GetID()
local prof = self.db.profile
local show = prof.chatarrows[this:GetName()]
self:chatbutton(id, show)
--self:ChatFrame_OnUpdateTextFlow(this, elapsed)
-- This is all code for the 'reminder' from here on
if show then
return
end
if not prof.reminder then
return
end
local remind = getglobal(this:GetName().."ScrollDownReminder");
local flash = getglobal(this:GetName().."ScrollDownReminderFlash");
if ( not flash ) then
return
end
if ( this:AtBottom() ) then
if ( remind:IsShown() ) then
remind:Hide();
UIFrameFlashRemoveFrame(flash)
end
return;
else
if ( remind:IsShown() ) then
return
end
remind:Show()
UIFrameFlash(flash, 0, 0, -1, false, CHAT_BUTTON_FLASH_TIME, CHAT_BUTTON_FLASH_TIME)
end
end
-- manipulate chatframe menu button
function module:ChatMenu(visible)
-- define variables used
local f = self.frames[1]
if not f then
self.frames[1] = {}
f = self.frames[1]
end
f.cfScrl = f.cfScrl or {}
f.cfScrl.up = getglobal("ChatFrame1UpButton")
-- chatmenu position:
-- position chatmenu under the UpButton for chatframe1 if button position is set to "RIGHTINSIDE"
-- otherwise position chatmenu above the UpButton for chatframe1
ChatFrameMenuButton:ClearAllPoints()
if self.db.profile.position == "RIGHTINSIDE" then
ChatFrameMenuButton:SetPoint("TOP", f.cfScrl.up, "BOTTOM")
else
ChatFrameMenuButton:SetPoint("BOTTOM", f.cfScrl.up, "TOP")
end
-- chatmenu alpha:
-- set alpha of the chatmenu based on the alpha setting
ChatFrameMenuButton:SetAlpha(self.db.profile.alpha)
-- chatmenu visibility
-- show buttons based on show settings
if visible then
ChatFrameMenuButton:Show()
else
ChatFrameMenuButton:Hide()
end
end
-- manipulate chatframe scrolling and reminder buttons
function module:chatbutton(id,visible)
-- define variables used
local f = self.frames[id]
local id = this:GetID()
if not f then
self.frames[id] = {}
f = self.frames[id]
end
f.cfScrl = f.cfScrl or {}
f.cf = f.cf or getglobal("ChatFrame"..id)
f.cfScrl.up = f.cfScrl.up or getglobal("ChatFrame"..id.."UpButton")
f.cfScrl.down = f.cfScrl.down or getglobal("ChatFrame"..id.."DownButton")
f.cfScrl.bottom = f.cfScrl.bottom or getglobal("ChatFrame"..id.."BottomButton")
f.cfScrlheight = (f.cfScrlheight and f.cfScrlheight > 0) and f.cfScrlheight or ((f.cfScrl.up and f.cfScrl.down and f.cfScrl.bottom) and
(f.cfScrl.up:GetHeight() + f.cfScrl.down:GetHeight() + f.cfScrl.bottom:GetHeight()) or 0)
f.cfreminder = f.cfreminder or self:MakeReminder(id)
f.cfreminderflash = f.cfreminderflash or getglobal("ChatFrame"..id.."ScrollDownReminderFlash")
-- chatbuttons position:
-- position of the chatbuttons based on position setting
if f.cfScrl.bottom and f.cfScrl.up then
f.cfScrl.bottom:ClearAllPoints()
f.cfScrl.up:ClearAllPoints()
if self.db.profile.position == "RIGHTINSIDE" then
f.cfScrl.bottom:SetPoint("BOTTOMRIGHT", f.cf, "BOTTOMRIGHT", 0, -4)
f.cfScrl.up:SetPoint("TOPRIGHT", f.cf, "TOPRIGHT", 0, -4)
elseif self.db.profile.position == "RIGHTOUTSIDE" then
f.cfScrl.bottom:SetPoint("BOTTOMLEFT", f.cf, "BOTTOMRIGHT", 0, -4)
f.cfScrl.up:SetPoint("BOTTOM", f.cfScrl.down, "TOP", 0, -2)
else
f.cfScrl.bottom:SetPoint("BOTTOMLEFT", f.cf, "BOTTOMLEFT", -32, -4)
f.cfScrl.up:SetPoint("BOTTOM", f.cfScrl.down, "TOP", 0, -2)
end
end
-- chatbuttons alpha:
-- set alpha of the chatbuttons based on the alpha setting
for _,v in pairs(f.cfScrl) do
v:SetAlpha(self.db.profile.alpha)
end
-- chatbuttons visibility:
-- show buttons based on visible value passed to function
if f.cf then
if visible and (f.cf:GetHeight() > f.cfScrlheight) then
for k, v in pairs(f.cfScrl) do
f.cfScrl[k]:Show()
end
else
for k, v in pairs(f.cfScrl) do
f.cfScrl[k]:Hide()
end
-- reminder visibility:
-- show the reminder button (if enabled) when not at the bottom of the chatframe
if (not f.cf:AtBottom()) and self.db.profile.reminder and (f.cf:GetHeight() > f.cfreminder:GetHeight()) then
local b = f.cfreminder
b:ClearAllPoints()
if f.cf:GetJustifyH() == "RIGHT" then
b:SetPoint("LEFT", f.cf, "LEFT", 0, 0)
b:SetPoint("RIGHT", f.cf, "LEFT", 32, 0)
b:SetPoint("TOP", f.cf, "BOTTOM", 0, 28)
b:SetPoint("BOTTOM", f.cf, "BOTTOM", 0, 0)
elseif f.cf:GetJustifyH() == "LEFT" then
b:SetPoint("RIGHT", f.cf, "RIGHT", 0, 0)
b:SetPoint("LEFT", f.cf, "RIGHT", -32, 0)
b:SetPoint("TOP", f.cf, "BOTTOM", 0, 28)
b:SetPoint("BOTTOM", f.cf, "BOTTOM", 0, 0)
end
f.cfreminder:Show()
f.cfreminderflash:Show()
else
f.cfreminder:Hide()
f.cfreminderflash:Hide()
end
end
end
end
-- create a "reminder" button
function module:MakeReminder(id)
-- define variables used
local cf = getglobal("ChatFrame"..id)
local b = getglobal("ChatFrame"..id.."ScrollDownReminder")
if b then return b end
b = CreateFrame("Button","ChatFrame"..id.."ScrollDownReminder",cf )
-- define the parameters for the button
b:SetFrameStrata("BACKGROUND")
b:SetWidth(24)
b:SetHeight(24)
b:SetNormalTexture("Interface\\ChatFrame\\UI-ChatIcon-ScrollEnd-Up")
b:SetPushedTexture("Interface\\ChatFrame\\UI-ChatIcon-ScrollEnd-Down")
b:SetHighlightTexture("Interface\\Buttons\\UI-Common-MouseHilight")
b:SetPoint("RIGHT", cf, "RIGHT", 0, 0)
b:SetPoint("LEFT", cf, "RIGHT", -32, 0)
b:SetPoint("TOP", cf, "BOTTOM", 0, 28)
b:SetPoint("BOTTOM", cf, "BOTTOM", 0, 0)
b:SetScript("OnClick", function() PlaySound("igChatBottom"); this:GetParent():ScrollToBottom() end)
-- hide the button by default
b:Hide()
-- add a flash texture for the reminder button
self:AddFlashTexture(b)
return b
end
-- create a "flash" texture
function module:AddFlashTexture(frame)
-- define variables used
local t = frame:CreateTexture(frame:GetName().."Flash", "OVERLAY")
-- define the parameters for the texture
t:SetTexture("Interface\\ChatFrame\\UI-ChatIcon-BlinkHilight")
t:SetPoint("CENTER", frame, "CENTER", 0, 1)
t:SetBlendMode("ADD")
t:SetAlpha(0.5)
-- hide the texture by default
t:Hide()
end
return
end ) -- Prat:AddModuleToLoad | gpl-3.0 |
mespinozas/si | t7/xapian/xapian-bindings/lua/docs/examples/simpleexpand.lua | 2 | 2939 | #!/usr/bin/env lua
--
-- Simple example script demonstrating query expansion.
--
-- Copyright (C) 2011 Xiaona Han
--
-- 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 St, Fifth Floor, Boston, MA 02110-1301
-- USA
require("xapian")
-- Require at least two command line arguments.
if #arg < 2 then
io.stderr:write("Usage:" .. arg[0] .. " PATH_TO_DATABASE QUERY [-- [DOCID...]]\n")
os.exit()
end
-- Open the database for searching.
database = xapian.Database(arg[1])
-- Start an enquire session.
enquire = xapian.Enquire(database)
-- Combine command line arguments up to "--" with spaces between
-- them, so that simple queries don't have to be quoted at the shell level.
query_string = arg[2]
local index = 3
while index <= #arg do
local para = arg[index]
index = index + 1;
if para == '--' then
break
end
query_string = query_string .. ' ' .. para
end
-- Create an RSet with the listed docids in.
reldocs = xapian.RSet()
--for index in range(index, #arg) do
for i = index, #arg do
reldocs:add_document(tonumber(arg[index]))
index = index + 1
end
-- Parse the query string to produce a Xapian::Query object.
qp = xapian.QueryParser()
stemmer = xapian.Stem("english")
qp:set_stemmer(stemmer)
qp:set_database(database)
qp:set_stemming_strategy(xapian.QueryParser_STEM_SOME)
query = qp:parse_query(query_string)
if not query:empty() then
print("Parsed query is: " .. tostring(query))
-- Find the top 10 results for the query.
enquire:set_query(query)
matches = enquire:get_mset(0, 10)
-- Display the size of the results.
print(string.format("%i results found.", matches:get_matches_estimated()))
print(string.format("Results 1-%i:", matches:size()))
-- Display the results
for m in matches:items() do
print(m:get_rank() + 1, m:get_percent() .. "%", m:get_docid(), m:get_document():get_data())
end
-- Put the top 5 (at most) docs into the rset if rset is empty
if reldocs:empty() then
local c = 5
for m in matches:items() do
reldocs:add_document(m:get_docid())
print (c)
c = c - 1
if c == 0 then
break
end
end
end
-- Get the suggested expand terms
eterms = enquire:get_eset(10, reldocs)
print (string.format("%i suggested additional terms", eterms:size()))
for m in eterms:terms() do
print(string.format("%s: %f", m:get_term(), m:get_weight()))
end
end
| gpl-2.0 |
FelixMaxwell/ReDead | entities/weapons/rad_base/shared.lua | 1 | 21107 | if SERVER then
AddCSLuaFile( "shared.lua" )
SWEP.Weight = 1
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
end
if CLIENT then
SWEP.DrawAmmo = true
SWEP.DrawCrosshair = false
SWEP.CSMuzzleFlashes = true
SWEP.ViewModelFOV = 75
SWEP.ViewModelFlip = true
SWEP.PrintName = "BASE WEAPON"
SWEP.IconLetter = "c"
SWEP.Slot = 0
SWEP.Slotpos = 0
SWEP.IconFont = "CSSelectIcons"
function SWEP:DrawWeaponSelection( x, y, wide, tall, alpha )
//draw.SimpleText( self.IconLetter, self.IconFont, x + wide/2, y + tall/2.5, Color( 15, 20, 200, 255 ), TEXT_ALIGN_CENTER )
end
end
SWEP.HoldType = "pistol"
SWEP.ViewModel = "models/weapons/v_pistol.mdl"
SWEP.WorldModel = "models/weapons/w_pistol.mdl"
SWEP.SprintPos = Vector(0,0,0)
SWEP.SprintAng = Vector(0,0,0)
SWEP.ZoomModes = { 0, 50, 10 }
SWEP.ZoomSpeeds = { 5, 5, 5 }
SWEP.IsSniper = false
SWEP.AmmoType = "SMG"
SWEP.Primary.Empty = Sound( "weapons/clipempty_rifle.wav" )
SWEP.Primary.Sound = Sound( "Weapon_USP.Single" )
SWEP.Primary.Recoil = 3.5
SWEP.Primary.Damage = 10
SWEP.Primary.NumShots = 1
SWEP.Primary.Cone = 0.025
SWEP.Primary.SniperCone = 0.025
SWEP.Primary.Delay = 0.150
SWEP.Primary.Ammo = "Pistol"
SWEP.Primary.ClipSize = 50
SWEP.Primary.DefaultClip = 200
SWEP.Primary.Automatic = false
SWEP.Secondary.Sound = Sound( "weapons/zoom.wav" )
SWEP.Secondary.Laser = Sound( "weapons/ar2/ar2_empty.wav" )
SWEP.Secondary.Delay = 0.5
SWEP.Secondary.Ammo = "none"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.LaserOffset = Vector(0,0,0)
SWEP.HolsterMode = false
SWEP.HolsterTime = 0
SWEP.LastRunFrame = 0
SWEP.MinShellDelay = 0.3
SWEP.MaxShellDelay = 0.6
SWEP.FalloffDistances = {}
SWEP.FalloffDistances[ "Sniper" ] = { Range = 3500, Falloff = 8000 }
SWEP.FalloffDistances[ "Rifle" ] = { Range = 2000, Falloff = 2000 }
SWEP.FalloffDistances[ "SMG" ] = { Range = 1500, Falloff = 1500 }
SWEP.FalloffDistances[ "Pistol" ] = { Range = 1000, Falloff = 500 }
SWEP.FalloffDistances[ "Buckshot" ] = { Range = 300, Falloff = 500 }
SWEP.UseShellSounds = true
SWEP.ShellSounds = { "player/pl_shell1.wav", "player/pl_shell2.wav", "player/pl_shell3.wav" }
SWEP.BuckshotShellSounds = { "weapons/fx/tink/shotgun_shell1.wav", "weapons/fx/tink/shotgun_shell2.wav", "weapons/fx/tink/shotgun_shell3.wav" }
SWEP.Pitches = {}
SWEP.Pitches[ "Pistol" ] = 100
SWEP.Pitches[ "SMG" ] = 90
SWEP.Pitches[ "Rifle" ] = 80
SWEP.Pitches[ "Sniper" ] = 70
SWEP.Pitches[ "Buckshot" ] = 100
function SWEP:GetViewModelPosition( pos, ang )
local newpos = nil
local newang = nil
local movetime = 0.25
local duration = 0//self.Weapon:GetNWInt( "ViewTime", 0 )
local pang = self.Owner:EyeAngles()
local vel = self.Owner:GetVelocity()
//if not newpos or not newang then
// newpos = pos
// newang = ang
//end
local mul = 0
self.SwayScale = 1.0
self.BobScale = 1.0
if ( self.Owner:KeyDown( IN_SPEED ) and self.Owner:GetVelocity():Length() > 0 ) or GAMEMODE:ElementsVisible() or self.HolsterMode then
self.SwayScale = 1.25
self.BobScale = 1.25
if not self.SprintStart then
self.SprintStart = CurTime()
end
mul = math.Clamp( ( CurTime() - self.SprintStart ) / movetime, 0, 1 )
mul = -( mul - 1 ) ^ 2 + 1
newang = self.SprintAng
newpos = self.SprintPos
else
if self.SprintStart then
self.SprintEnd = CurTime()
self.SprintStart = nil
end
if self.SprintEnd then
mul = math.Clamp( ( CurTime() - self.SprintEnd ) / movetime, 0, 1 )
mul = ( mul - 1 ) ^ 2
newang = self.SprintAng
newpos = self.SprintPos
if mul == 0 then
self.SprintEnd = nil
end
else
mul = self:GetMoveScale( movetime, duration, mul )
end
end
return self:MoveViewModelTo( newpos, newang, pos, ang, mul )
end
function SWEP:GetMoveScale( movetime, duration, mul )
mul = 1
if CurTime() - movetime < duration then
mul = math.Clamp( ( CurTime() - duration ) / movetime, 0, 1 )
end
if self.Weapon:GetNWBool( "ReverseAnim", false ) then
return -( mul - 1 ) ^ 3
end
return ( mul - 1 ) ^ 3 + 1
end
function SWEP:AngApproach( newang, ang, mul )
if not newang then return ang end
ang:RotateAroundAxis( ang:Right(), newang.x * mul )
ang:RotateAroundAxis( ang:Up(), newang.y * mul )
ang:RotateAroundAxis( ang:Forward(), newang.z * mul )
return ang
end
function SWEP:PosApproach( newpos, pos, ang, mul )
local right = ang:Right()
local up = ang:Up()
local forward = ang:Forward()
if not newpos then return pos end
pos = pos + newpos.x * right * mul
pos = pos + newpos.y * forward * mul
pos = pos + newpos.z * up * mul
return pos
end
function SWEP:MoveViewModelTo( newpos, newang, pos, ang, mul )
ang = self:AngApproach( newang, ang, mul )
pos = self:PosApproach( newpos, pos, ang, mul )
return pos, ang
end
function SWEP:Initialize()
self.Weapon:SetWeaponHoldType( self.HoldType )
end
function SWEP:Deploy()
if SERVER then
self.Weapon:SetZoomMode( 1 )
self.Owner:DrawViewModel( true )
end
self.Weapon:SendWeaponAnim( ACT_VM_DRAW )
return true
end
function SWEP:Holster()
return true
end
function SWEP:Think()
self.Weapon:ReloadThink()
if self.Owner:GetVelocity():Length() > 0 and self.Owner:KeyDown( IN_SPEED ) then
self.LastRunFrame = CurTime() + 0.3
self.Weapon:UnZoom()
end
end
function SWEP:SetZoomMode( num )
if num > #self.ZoomModes then
num = 1
self.Weapon:UnZoom()
end
self.Weapon:SetNWInt( "Mode", num )
if self.Owner:GetFOV() != self.ZoomModes[num] then
self.Owner:SetFOV( self.ZoomModes[num], self.ZoomSpeeds[num] )
end
end
function SWEP:GetZoomMode()
return self.Weapon:GetNWInt( "Mode", 1 )
end
function SWEP:UnZoom()
if CLIENT then return end
self.Weapon:SetZoomMode( 1 )
self.Weapon:SetNWBool( "ReverseAnim", true )
self.Owner:DrawViewModel( true )
end
function SWEP:Reload()
if self.Weapon:Clip1() == self.Primary.ClipSize or self.Weapon:Clip1() > self.Owner:GetNWInt( "Ammo" .. self.AmmoType, 0 ) or self.HolsterMode or self.ReloadTime then return end
if self.Owner:GetNWInt( "Ammo" .. self.AmmoType, 0 ) < 1 then
self.Weapon:SetClip1( self.Primary.ClipSize )
return
end
if self.Weapon:GetZoomMode() != 1 then
self.Weapon:UnZoom()
end
self.Weapon:DoReload()
end
function SWEP:StartWeaponAnim( anim )
if IsValid( self.Owner ) then
local vm = self.Owner:GetViewModel()
local idealSequence = self:SelectWeightedSequence( anim )
local nextSequence = self:FindTransitionSequence( self.Weapon:GetSequence(), idealSequence )
//vm:RemoveEffects( EF_NODRAW )
//vm:SetPlaybackRate( pbr )
if nextSequence > 0 then
vm:SendViewModelMatchingSequence( nextSequence )
else
vm:SendViewModelMatchingSequence( idealSequence )
end
return vm:SequenceDuration( vm:GetSequence() )
end
end
function SWEP:DoReload()
local time = self.Weapon:StartWeaponAnim( ACT_VM_RELOAD )
self.Weapon:SetNextPrimaryFire( CurTime() + time + 0.080 )
self.ReloadTime = CurTime() + time
end
function SWEP:ReloadThink()
if self.ReloadTime and self.ReloadTime <= CurTime() then
self.ReloadTime = nil
self.Weapon:SetClip1( self.Primary.ClipSize )
end
end
function SWEP:CanSecondaryAttack()
if self.HolsterMode or self.Owner:KeyDown( IN_SPEED ) or self.LastRunFrame > CurTime() then return false end
if self.Weapon:Clip1() <= 0 and self.IsSniper then
if self.Weapon:GetZoomMode() != 1 then
self.Weapon:UnZoom()
end
return false
end
return true
end
function SWEP:CanPrimaryAttack()
if self.HolsterMode or self.ReloadTime or self.LastRunFrame > CurTime() then return false end
if self.Owner:GetNWInt( "Ammo" .. self.AmmoType, 0 ) < 1 then
self.Weapon:EmitSound( self.Primary.Empty )
return false
end
if self.Weapon:Clip1() <= 0 then
self.Weapon:SetNextPrimaryFire( CurTime() + 0.5 )
self.Weapon:DoReload()
if self.Weapon:GetZoomMode() != 1 then
self.Weapon:UnZoom()
end
return false
end
return true
end
function SWEP:ShootEffects()
if IsFirstTimePredicted() then
self.Owner:ViewPunch( Angle( math.Rand( -0.2, -0.1 ) * self.Primary.Recoil, math.Rand( -0.05, 0.05 ) * self.Primary.Recoil, 0 ) )
end
self.Owner:MuzzleFlash()
self.Owner:SetAnimation( PLAYER_ATTACK1 )
self.Weapon:SendWeaponAnim( ACT_VM_PRIMARYATTACK )
if CLIENT then return end
if self.UseShellSounds then
local pitch = self.Pitches[ self.AmmoType ] + math.random( -3, 3 )
local tbl = self.ShellSounds
local pos = self.Owner:GetPos()
if self.AmmoType == "Buckshot" then
tbl = self.BuckshotShellSounds
end
timer.Simple( math.Rand( self.MinShellDelay, self.MaxShellDelay ), function() sound.Play( table.Random( tbl ), pos, 50, pitch ) end )
end
end
function SWEP:PrimaryAttack()
if not self.Weapon:CanPrimaryAttack() then
self.Weapon:SetNextPrimaryFire( CurTime() + 0.25 )
return
end
self.Weapon:SetNextPrimaryFire( CurTime() + self.Primary.Delay )
self.Weapon:EmitSound( self.Primary.Sound, 100, math.random(95,105) )
self.Weapon:SetClip1( self.Weapon:Clip1() - self.Primary.NumShots )
self.Weapon:ShootEffects()
if self.IsSniper and self.Weapon:GetZoomMode() == 1 then
self.Weapon:ShootBullets( self.Primary.Damage, self.Primary.NumShots, self.Primary.SniperCone, 1 )
else
self.Weapon:ShootBullets( self.Primary.Damage, self.Primary.NumShots, self.Primary.Cone, self.Weapon:GetZoomMode() )
end
if self.Weapon:GetZoomMode() > 1 then
self.Weapon:UnZoom()
end
if SERVER then
self.Owner:AddAmmo( self.AmmoType, self.Primary.NumShots * -1 )
end
end
function SWEP:SecondaryAttack()
if not self.Weapon:CanSecondaryAttack() then return end
self.Weapon:SetNextSecondaryFire( CurTime() + 0.25 )
if not self.IsSniper then
self.Weapon:ToggleLaser()
return
end
if SERVER then
if self.Weapon:GetZoomMode() == 1 then
self.Owner:DrawViewModel( false )
end
self.Weapon:SetZoomMode( self.Weapon:GetZoomMode() + 1 )
end
self.Weapon:EmitSound( self.Secondary.Sound )
end
function SWEP:ToggleLaser()
self.Weapon:EmitSound( self.Secondary.Laser )
self.Weapon:SetNWBool( "Laser", !self.Weapon:GetNWBool( "Laser", false ) )
end
function SWEP:AdjustMouseSensitivity()
local num = self.Weapon:GetNWInt( "Mode", 1 )
local scale = ( self.ZoomModes[ num ] or 0 ) / 100
if scale == 0 then
return nil
end
return scale
end
function SWEP:GetDamageFalloffScale( distance )
local scale = 1
if distance > self.FalloffDistances[ self.AmmoType ].Range then
scale = ( 1 - ( ( distance - self.FalloffDistances[ self.AmmoType ].Range ) / self.FalloffDistances[ self.AmmoType ].Falloff ) )
end
return math.Clamp( scale, 0.1, 1.0 )
end
function SWEP:ShootBullets( damage, numbullets, aimcone, zoommode )
if SERVER then
self.Owner:AddStat( "Bullets", numbullets )
end
local scale = aimcone
if self.Owner:KeyDown( IN_FORWARD ) or self.Owner:KeyDown( IN_BACK ) or self.Owner:KeyDown( IN_MOVELEFT ) or self.Owner:KeyDown( IN_MOVERIGHT ) then
scale = aimcone * 1.75
elseif self.Owner:KeyDown( IN_DUCK ) or self.Owner:KeyDown( IN_WALK ) then
scale = math.Clamp( aimcone / 1.75, 0, 10 )
end
local bullet = {}
bullet.Num = numbullets
bullet.Src = self.Owner:GetShootPos()
bullet.Dir = self.Owner:GetAimVector()
bullet.Spread = Vector( scale, scale, 0 )
bullet.Tracer = 0
bullet.Force = damage * 2
bullet.Damage = damage
bullet.AmmoType = "Pistol"
//if self.IsSniper and self.AmmoType == "Sniper" then
//bullet.TracerName = "sniper_tracer"
//end
bullet.Callback = function( attacker, tr, dmginfo )
dmginfo:ScaleDamage( self:GetDamageFalloffScale( tr.HitPos:Distance( self.Owner:GetShootPos() ) ) )
if tr.Entity.NextBot then
tr.Entity:OnLimbHit( tr.HitGroup, dmginfo )
end
if ( IsValid( tr.Entity ) and tr.Entity:IsPlayer() ) or math.random(1,5) != 1 then return end
self.Weapon:BulletPenetration( attacker, tr, dmginfo, 0 )
end
self.Owner:LagCompensation( true )
self.Owner:FireBullets( bullet )
self.Owner:LagCompensation( false )
end
function SWEP:GetPenetrationDistance( mat_type )
if ( mat_type == MAT_PLASTIC || mat_type == MAT_WOOD || mat_type == MAT_ALIENFLESH || mat_type == MAT_FLESH || mat_type == MAT_GLASS ) then
return 64
end
return 32
end
function SWEP:GetPenetrationDamageLoss( mat_type, distance, damage )
if ( mat_type == MAT_GLASS || mat_type == MAT_ALIENFLESH || mat_type == MAT_FLESH ) then
return damage
elseif ( mat_type == MAT_PLASTIC || mat_type == MAT_WOOD ) then
return damage - distance
elseif( mat_type == MAT_TILE || mat_type == MAT_SAND || mat_type == MAT_DIRT ) then
return damage - ( distance * 1.2 )
end
return damage - ( distance * 1.8 )
end
--[[function SWEP:BulletPenetration( attacker, tr, dmginfo, bounce )
if ( !self or !IsValid( self.Weapon ) ) then return end
if IsValid( tr.Entity ) and string.find( tr.Entity:GetClass(), "npc" ) then
local effectdata = EffectData()
effectdata:SetOrigin( tr.HitPos )
util.Effect( "BloodImpact", effectdata )
end
// Don't go through more than 3 times
if ( bounce > 3 ) then return false end
// Direction (and length) that we are gonna penetrate
local PeneDir = tr.Normal * self:GetPenetrationDistance( tr.MatType )
local PeneTrace = {}
PeneTrace.endpos = tr.HitPos
PeneTrace.start = tr.HitPos + PeneDir
PeneTrace.mask = MASK_SHOT
PeneTrace.filter = { self.Owner }
local PeneTrace = util.TraceLine( PeneTrace )
// Bullet didn't penetrate.
if ( PeneTrace.StartSolid or PeneTrace.Fraction >= 1.0 or tr.Fraction <= 0.0 ) then return false end
local distance = ( PeneTrace.HitPos - tr.HitPos ):Length()
local new_damage = self:GetPenetrationDamageLoss( tr.MatType, distance, dmginfo:GetDamage() )
if new_damage > 0 then
local bullet =
{
Num = 1,
Src = PeneTrace.HitPos,
Dir = tr.Normal,
Spread = Vector( 0, 0, 0 ),
Tracer = 0,
Force = 5,
Damage = new_damage,
AmmoType = "Pistol",
}
bullet.Callback = function ( attacker, tr, dmginfo )
if IsValid( self ) and IsValid( self.Weapon ) then
self.Weapon:BulletPenetration( attacker, tr, dmginfo, bounce + 1 )
end
end
local effectdata = EffectData()
effectdata:SetOrigin( PeneTrace.HitPos )
effectdata:SetNormal( PeneTrace.Normal )
util.Effect( "Impact", effectdata )
local func = function( attacker, bullet )
if IsValid( attacker ) then
attacker.FireBullets( attacker, bullet, true )
end
end
timer.Simple( 0.05, function() func( attacker, bullet ) end )
if SERVER and tr.MatType != MAT_FLESH then
sound.Play( table.Random( GAMEMODE.Ricochet ), tr.HitPos, 100, math.random(90,120) )
end
end
end]]
function SWEP:BulletPenetration( attacker, tr, dmginfo, bounce )
if ( !self or not IsValid( self.Weapon ) ) then return end
if IsValid( tr.Entity ) and string.find( tr.Entity:GetClass(), "npc" ) then
local effectdata = EffectData()
effectdata:SetOrigin( tr.HitPos )
util.Effect( "BloodImpact", effectdata )
end
if ( bounce > 3 ) then return false end
local PeneDir = tr.Normal * self:GetPenetrationDistance( tr.MatType )
local PeneTrace = {}
PeneTrace.endpos = tr.HitPos
PeneTrace.start = tr.HitPos + PeneDir
PeneTrace.mask = MASK_SHOT
PeneTrace.filter = { self.Owner }
local PeneTrace = util.TraceLine( PeneTrace )
if ( PeneTrace.StartSolid || PeneTrace.Fraction >= 1.0 || tr.Fraction <= 0.0 ) then return false end
local distance = ( PeneTrace.HitPos - tr.HitPos ):Length()
local new_damage = self:GetPenetrationDamageLoss( tr.MatType, distance, dmginfo:GetDamage() )
if new_damage > 0 then
local bullet =
{
Num = 1,
Src = PeneTrace.HitPos,
Dir = tr.Normal,
Spread = Vector( 0, 0, 0 ),
Tracer = 0,
Force = 5,
Damage = new_damage,
AmmoType = "Pistol",
}
bullet.Callback = function( a, b, c )
if IsValid( self ) and IsValid( self.Weapon ) then
self.Weapon:BulletPenetration( attacker, tr, dmginfo, bounce + 1 )
end
end
local effectdata = EffectData()
effectdata:SetOrigin( PeneTrace.HitPos );
effectdata:SetNormal( PeneTrace.Normal );
util.Effect( "Impact", effectdata )
timer.Simple( 0.01, function() attacker:FireBullets( bullet, true ) end )
if SERVER and tr.MatType != MAT_FLESH and bounce == 0 then
sound.Play( table.Random( GAMEMODE.Ricochet ), tr.HitPos, 100, math.random(90,120) )
end
end
end
function SWEP:ShouldNotDraw()
return self.Weapon:GetNWBool( "Laser", false )
end
if CLIENT then
SWEP.CrossRed = CreateClientConVar( "cl_redead_crosshair_r", 255, true, false )
SWEP.CrossGreen = CreateClientConVar( "cl_redead_crosshair_g", 255, true, false )
SWEP.CrossBlue = CreateClientConVar( "cl_redead_crosshair_b", 255, true, false )
SWEP.CrossAlpha = CreateClientConVar( "cl_redead_crosshair_a", 255, true, false )
SWEP.CrossLength = CreateClientConVar( "cl_redead_crosshair_length", 10, true, false )
SWEP.DotMat = Material( "Sprites/light_glow02_add_noz" )
SWEP.LasMat = Material( "sprites/bluelaser1" )
end
SWEP.CrosshairScale = 1
function SWEP:LaserDraw()
local vm = self.Owner:GetViewModel()
if IsValid( vm ) then
local idx = vm:LookupAttachment( "1" )
if idx == 0 then idx = vm:LookupAttachment( "muzzle" ) end
local trace = util.GetPlayerTrace( ply )
local tr = util.TraceLine( trace )
local tbl = vm:GetAttachment( idx )
local pos = tr.HitPos
if vm:GetSequence() != ACT_VM_IDLE then
self.AngDiff = ( tbl.Ang - self.LastGoodAng ):Forward()
trace = {}
trace.start = tbl.Pos or Vector(0,0,0)
trace.endpos = trace.start + ( ( EyeAngles() + self.AngDiff ):Forward() * 99999 )
trace.filter = { self.Owner, self.Weapon }
local tr2 = util.TraceLine( trace )
pos = tr2.HitPos
else
self.LastGoodAng = tbl.Ang
end
cam.Start3D( EyePos(), EyeAngles() )
local dir = ( tbl.Ang ):Forward()
local start = tbl.Pos
render.SetMaterial( self.LasMat )
for i=0,254 do
render.DrawBeam( start, start + dir * 5, 2, 0, 12, Color( 255, 0, 0, 255 - i ) )
start = start + dir * 5
end
local dist = tr.HitPos:Distance( EyePos() )
local size = math.Rand( 6, 7 )
local dotsize = dist / size ^ 2
render.SetMaterial( self.DotMat )
render.DrawQuadEasy( pos, ( EyePos() - tr.HitPos ):GetNormal(), dotsize, dotsize, Color( 255, 0, 0, 255 ), 0 )
cam.End3D()
end
end
function SWEP:DrawHUD()
if self.Weapon:ShouldNotDraw() then return end
if self.Weapon:GetNWBool( "Laser", false ) then return end
local mode = self.Weapon:GetZoomMode()
if not self.IsSniper or mode == 1 then
local cone = self.Primary.Cone
local scale = cone
if self.IsSniper then
cone = self.Primary.SniperCone
scale = cone
end
local x = ScrW() * 0.5
local y = ScrH() * 0.5
local scalebywidth = ( ScrW() / 1024 ) * 10
if self.Owner:KeyDown( IN_FORWARD ) or self.Owner:KeyDown( IN_BACK ) or self.Owner:KeyDown( IN_MOVELEFT ) or self.Owner:KeyDown( IN_MOVERIGHT ) then
scale = cone * 1.75
elseif self.Owner:KeyDown( IN_DUCK ) or self.Owner:KeyDown( IN_WALK ) then
scale = math.Clamp( cone / 1.75, 0, 10 )
end
scale = scale * scalebywidth
local dist = math.abs( self.CrosshairScale - scale )
self.CrosshairScale = math.Approach( self.CrosshairScale, scale, FrameTime() * 2 + dist * 0.05 )
local gap = 40 * self.CrosshairScale
local length = gap + self.CrossLength:GetInt() //20 * self.CrosshairScale
surface.SetDrawColor( self.CrossRed:GetInt(), self.CrossGreen:GetInt(), self.CrossBlue:GetInt(), self.CrossAlpha:GetInt() )
surface.DrawLine( x - length, y, x - gap, y )
surface.DrawLine( x + length, y, x + gap, y )
surface.DrawLine( x, y - length, x, y - gap )
surface.DrawLine( x, y + length, x, y + gap )
return
end
if mode != 1 then
local w = ScrW()
local h = ScrH()
local wr = ( h / 3 ) * 4
surface.SetTexture( surface.GetTextureID( "gmod/scope" ) )
surface.SetDrawColor( 0, 0, 0, 255 )
surface.DrawTexturedRect( ( w / 2 ) - wr / 2, 0, wr, h )
surface.SetDrawColor( 0, 0, 0, 255 )
surface.DrawRect( 0, 0, ( w / 2 ) - wr / 2, h )
surface.DrawRect( ( w / 2 ) + wr / 2, 0, w - ( ( w / 2 ) + wr / 2 ), h )
surface.DrawLine( 0, h * 0.50, w, h * 0.50 )
surface.DrawLine( w * 0.50, 0, w * 0.50, h )
end
end
| mit |
turbogus/fluideMP | fluide/init.lua | 1 | 10465 | -- Sève
--
-- code licence gpl v2 ou superieur
-- graphisme sous licence CC-BY-NC-SA
--
-- Par Jat et Turbogus
--
--*********************
--
--Génère de la sève pour la creation d'arbres géants
--La sève regénère la vie quand on se place en dessous
--Elle à les mêmes propriétés que l'eau
--
--Disponible uniquement pour le(s) administrateur(s) : utiliser /giveme seve:seve_source
--pour obtenir de la sève
minetest.register_craft ({
output = "fluide:seve_source",
recipe = {
{"","default:mese",""},
{"","default:mese",""},
{"","bucket:bucket_water",""},
}
})
--*********************
--Parametres du liquide
--*********************
WATER_ALPHA = 160
WATER_VISC = 1
LIGHT_MAX = 14
--**********************************************
--Gestion écoulement de la seve ( seve_flowing )
--**********************************************
minetest.register_node("fluide:seve_flowing", { -- on enregistre le nom de l'item
description = "Flowing Seve", -- description dans le menu
inventory_image = minetest.inventorycube("seve.png"), -- on charge la skin du bloc dans l'inventaire du joueur
drawtype = "flowingliquid", -- type de bloc : ecoulement de liquide
tiles = {"seve.png"}, -- on charge la skin du bloc dans le jeu
special_tiles = {
{name="seve.png", backface_culling=false}, -- parametres speciaux
{name="seve.png", backface_culling=true}, -- //
},
alpha = WATER_ALPHA, -- paramètre du liquide
paramtype = "light",
light_source = LIGHT_MAX - 3, -- //
walkable = false, -- //
pointable = false, -- //
diggable = false, -- //
buildable_to = true, -- //
liquidtype = "flowing", -- //
liquid_alternative_flowing = "fluide:seve_flowing", -- //
liquid_alternative_source = "fluide:seve_source", -- //
liquid_viscosity = WATER_VISC, -- //
post_effect_color = {a=64, r=255, g=114, b=0}, -- //
groups = {water=3, liquid=3, puts_out_fire=1}, -- //
})
--*******************************************
--Gestion et cretion d'un bloc source de sève
--*******************************************
minetest.register_node("fluide:seve_source", { -- Declaration du nom de l'item
description = "Seve Source", -- description dans l'inventaire
inventory_image = minetest.inventorycube("seve.png"), -- chargement de la skin pour l'inventaire
drawtype = "liquid", -- type de bloc : liquide
tiles = {"seve.png"}, -- chargement skin pour jeu
special_tiles = {
-- New-style water source material (mostly unused)
{name="seve.png", backface_culling=false},
},
alpha = WATER_ALPHA, -- parametres du bloc
paramtype = "light",
light_source = LIGHT_MAX - 3, -- //
walkable = false, -- //
pointable = false, -- //
diggable = false, -- //
buildable_to = true, -- //
liquidtype = "source",
liquid_alternative_flowing = "fluide:seve_flowing", -- //
liquid_alternative_source = "fluide:seve_source", -- //
liquid_viscosity = WATER_VISC, -- //
post_effect_color = {a=64, r=255, g=114, b=0}, -- //
groups = {water=3, liquid=3, puts_out_fire=1}, -- //
})
--*****************************************
-- On gagne de la vie si on va dans la seve
--*****************************************
minetest.register_abm( -- fonction permettant d'assigner une action à un bloc
{nodenames = {"fluide:seve_flowing","fluide:seve_source"}, -- nom du bloc
interval = 1.0, -- ???
chance = 1, -- ???
action = function(pos, node, active_object_count, active_object_count_wider) -- fonction associée au bloc
local objs = minetest.env:get_objects_inside_radius(pos, 1) -- variable d'environnement : quand le joueur est dans le bloc
for k, obj in pairs(objs) do -- boucle "for" :
obj:set_hp(obj:get_hp()+1) -- give 1HP -- augmenter la vie HP du joueur de +1
end
end,
})
--=========================================================================================================================================================
--=========================================================================================================================================================
-- OR
-- Fluide qui vous tue en un seul coup si vous le touchez
minetest.register_craft ({
output = "fluide:or_source",
recipe = {
{"","default:mese",""},
{"","default:mese",""},
{"","bucket:bucket_lava",""},
}
})
--**********************************************
--Gestion écoulement du liquide ( or_flowing )
--**********************************************
minetest.register_node("fluide:or_flowing", { -- on enregistre le nom de l'item
description = "Flowing Or", -- description dans le menu
inventory_image = minetest.inventorycube("or.png"), -- on charge la skin du bloc dans l'inventaire du joueur
drawtype = "flowingliquid", -- type de bloc : ecoulement de liquide
tiles = {"or.png"}, -- on charge la skin du bloc dans le jeu
special_tiles = {
{name="or.png", backface_culling=false}, -- parametres speciaux
{name="or.png", backface_culling=true}, -- //
},
alpha = WATER_ALPHA, -- paramètre du liquide
paramtype = "light",
light_source = LIGHT_MAX - 1, -- //
walkable = false, -- //
pointable = false, -- //
diggable = false, -- //
buildable_to = true, -- //
liquidtype = "flowing", -- //
liquid_alternative_flowing = "fluide:or_flowing", -- //
liquid_alternative_source = "fluide:or_source", -- //
liquid_viscosity = WATER_VISC,
damage_per_second = 20*2,
post_effect_color = {a=64, r=100, g=100, b=200}, -- //
groups = {water=3, liquid=3, puts_out_fire=1}, -- //
})
--***********************************************
--Gestion et cretion d'un bloc source de liquide
--***********************************************
minetest.register_node("fluide:or_source", { -- Declaration du nom de l'item
description = "Or Source", -- description dans l'inventaire
inventory_image = minetest.inventorycube("or.png"), -- chargement de la skin pour l'inventaire
drawtype = "liquid", -- type de bloc : liquide
tiles = {"or.png"}, -- chargement skin pour jeu
special_tiles = {
-- New-style water source material (mostly unused)
{name="or.png", backface_culling=false},
},
alpha = WATER_ALPHA, -- parametres du bloc
paramtype = "light",
light_source = LIGHT_MAX - 1, -- Le fluide Or emet de la lumiere
walkable = false, -- //
pointable = false, -- //
diggable = false, -- //
buildable_to = true, -- //
liquidtype = "source",
liquid_alternative_flowing = "fluide:or_flowing", -- //
liquid_alternative_source = "fluide:or_source", -- //
liquid_viscosity = WATER_VISC,
damage_per_second = 20*2,
post_effect_color = {a=64, r=255, g=255, b=0}, -- //
groups = {water=3, liquid=3, puts_out_fire=1}, -- //
})
--=========================================================================================================================================================
--=========================================================================================================================================================
--gazole
-- Liquide extremement inflammable utilise en combustible dans les fours
minetest.register_node("fluide:gazole_flowing", { -- on enregistre le nom de l'item
description = "Flowing gazole", -- description dans le menu
inventory_image = minetest.inventorycube("gazole.png"), -- on charge la skin du bloc dans l'inventaire du joueur
drawtype = "flowingliquid", -- type de bloc : ecoulement de liquide
tiles = {"gazole.png"}, -- on charge la skin du bloc dans le jeu
special_tiles = {
{name="gazole.png", backface_culling=false}, -- parametres speciaux
{name="gazole.png", backface_culling=true}, -- //
},
alpha = WATER_ALPHA, -- paramètre du liquide
paramtype = "light",
light_source = LIGHT_MAX - 1, -- //
walkable = false, -- //
pointable = true, -- //
diggable = false, -- //
buildable_to = true, -- //
liquidtype = "flowing", -- //
liquid_alternative_flowing = "fluide:gazole_flowing", -- //
liquid_alternative_source = "fluide:gazole_source", -- //
liquid_viscosity = WATER_VISC, -- //
post_effect_color = {a=64, r=255, g=255, b=0}, -- //
groups = {water=3, liquid=3, flammable=1}, -- //
})
--***********************************************
--Gestion et cretion d'un bloc source de liquide
--***********************************************
minetest.register_node("fluide:gazole_source", { -- Declaration du nom de l'item
description = "gazole Source", -- description dans l'inventaire
inventory_image = minetest.inventorycube("gazole.png"), -- chargement de la skin pour l'inventaire
drawtype = "liquid", -- type de bloc : liquide
tiles = {"gazole.png"}, -- chargement skin pour jeu
special_tiles = {
-- New-style water source material (mostly unused)
{name="gazole.png", backface_culling=false},
},
alpha = WATER_ALPHA, -- parametres du bloc
paramtype = "light",
light_source = LIGHT_MAX - 1, -- Le fluide Or emet de la lumiere
walkable = false, -- //
pointable = true, -- //
diggable = false, -- //
buildable_to = true, -- //
liquidtype = "source",
liquid_alternative_flowing = "fluide:gazole_flowing", -- //
liquid_alternative_source = "fluide:gazole_source", -- //
liquid_viscosity = WATER_VISC, -- //
post_effect_color = {a=64, r=100, g=100, b=200}, -- //
groups = {water=3, liquid=3, flammable=1}, -- //
})
--minetest.register_abm( -- fonction permettant d'assigner une action à un bloc
-- {nodenames = {"fluide:gazole_flowing"}, -- nom du bloc
-- interval = 1.0, -- ???
-- chance = 1, -- ???
-- action = function(pos, node, active_object_count, active_object_count_wider) -- fonction associée au bloc
-- local objs = minetest.env:get_objects_inside_radius(pos, 1) -- variable d'environnement : quand le joueur est dans le bloc
-- for k, obj in pairs(objs) do -- boucle "for" :
-- obj:set_hp(obj:get_hp()-0.5)
-- end
-- end,
--})
-------------------
-- test pour bucket
-------------------
bucket.register_liquid(
"fluide:gazole_source",
"fluide:gazole_flowing",
"fluide:bucket_gazole",
"bucket_gazole.png",
"Gazole Bucket"
)
bucket.register_liquid(
"fluide:seve_source",
"fluide:seve_flowing",
"fluide:bucket_seve",
"bucket_seve.png",
"Seve Bucket"
)
| gpl-2.0 |
maikerumine/aftermath | mods/fire/init.lua | 6 | 8613 | -- Global namespace for functions
fire = {}
--
-- Items
--
-- Flame nodes
minetest.register_node("fire:basic_flame", {
drawtype = "firelike",
tiles = {
{
name = "fire_basic_flame_animated.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1
},
},
},
inventory_image = "fire_basic_flame.png",
paramtype = "light",
light_source = 13,
walkable = false,
buildable_to = true,
sunlight_propagates = true,
damage_per_second = 4,
groups = {igniter = 2, dig_immediate = 3, not_in_creative_inventory = 1},
on_timer = function(pos)
local f = minetest.find_node_near(pos, 1, {"group:flammable"})
if not f then
minetest.remove_node(pos)
return
end
-- Restart timer
return true
end,
drop = "",
on_construct = function(pos)
minetest.get_node_timer(pos):start(math.random(30, 60))
end,
})
minetest.register_node("fire:permanent_flame", {
description = "Permanent Flame",
drawtype = "firelike",
tiles = {
{
name = "fire_basic_flame_animated.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1
},
},
},
inventory_image = "fire_basic_flame.png",
paramtype = "light",
light_source = 13,
walkable = false,
buildable_to = true,
sunlight_propagates = true,
damage_per_second = 4,
groups = {igniter = 2, dig_immediate = 3},
drop = "",
})
-- Flint and steel
minetest.register_tool("fire:flint_and_steel", {
description = "Flint and Steel",
inventory_image = "fire_flint_steel.png",
sound = {breaks = "default_tool_breaks"},
on_use = function(itemstack, user, pointed_thing)
local pt = pointed_thing
minetest.sound_play(
"fire_flint_and_steel",
{pos = pt.above, gain = 0.5, max_hear_distance = 8}
)
if pt.type == "node" then
local node_under = minetest.get_node(pt.under).name
local nodedef = minetest.registered_nodes[node_under]
if not nodedef then
return
end
local player_name = user:get_player_name()
if minetest.is_protected(pt.under, player_name) then
minetest.chat_send_player(player_name, "This area is protected")
return
end
if nodedef.on_ignite then
nodedef.on_ignite(pt.under, user)
elseif minetest.get_item_group(node_under, "flammable") >= 1
and minetest.get_node(pt.above).name == "air" then
minetest.set_node(pt.above, {name = "fire:basic_flame"})
end
end
if not minetest.setting_getbool("creative_mode") then
-- Wear tool
local wdef = itemstack:get_definition()
itemstack:add_wear(1000)
-- Tool break sound
if itemstack:get_count() == 0 and wdef.sound and wdef.sound.breaks then
minetest.sound_play(wdef.sound.breaks, {pos = pt.above, gain = 0.5})
end
return itemstack
end
end
})
minetest.register_craft({
output = "fire:flint_and_steel",
recipe = {
{"default:flint", "default:steel_ingot"}
}
})
-- Override coalblock to enable permanent flame above
-- Coalblock is non-flammable to avoid unwanted basic_flame nodes
minetest.override_item("default:coalblock", {
after_destruct = function(pos, oldnode)
pos.y = pos.y + 1
if minetest.get_node(pos).name == "fire:permanent_flame" then
minetest.remove_node(pos)
end
end,
on_ignite = function(pos, igniter)
local flame_pos = {x = pos.x, y = pos.y + 1, z = pos.z}
if minetest.get_node(flame_pos).name == "air" then
minetest.set_node(flame_pos, {name = "fire:permanent_flame"})
end
end,
})
--
-- Sound
--
local flame_sound = minetest.setting_getbool("flame_sound")
if flame_sound == nil then
-- Enable if no setting present
flame_sound = true
end
if flame_sound then
local handles = {}
local timer = 0
-- Parameters
local radius = 8 -- Flame node search radius around player
local cycle = 3 -- Cycle time for sound updates
-- Update sound for player
function fire.update_player_sound(player)
local player_name = player:get_player_name()
-- Search for flame nodes in radius around player
local ppos = player:getpos()
local areamin = vector.subtract(ppos, radius)
local areamax = vector.add(ppos, radius)
local fpos, num = minetest.find_nodes_in_area(
areamin,
areamax,
{"fire:basic_flame", "fire:permanent_flame"}
)
-- Total number of flames in radius
local flames = (num["fire:basic_flame"] or 0) +
(num["fire:permanent_flame"] or 0)
-- Stop previous sound
if handles[player_name] then
minetest.sound_stop(handles[player_name])
handles[player_name] = nil
end
-- If flames
if flames > 0 then
-- Find centre of flame positions
local fposmid = fpos[1]
-- If more than 1 flame
if #fpos > 1 then
local fposmin = areamax
local fposmax = areamin
for i = 1, #fpos do
local fposi = fpos[i]
if fposi.x > fposmax.x then
fposmax.x = fposi.x
end
if fposi.y > fposmax.y then
fposmax.y = fposi.y
end
if fposi.z > fposmax.z then
fposmax.z = fposi.z
end
if fposi.x < fposmin.x then
fposmin.x = fposi.x
end
if fposi.y < fposmin.y then
fposmin.y = fposi.y
end
if fposi.z < fposmin.z then
fposmin.z = fposi.z
end
end
fposmid = vector.divide(vector.add(fposmin, fposmax), 2)
end
-- Play sound
local handle = minetest.sound_play(
"fire_fire",
{
pos = fposmid,
to_player = player_name,
gain = math.min(0.06 * (1 + flames * 0.125), 0.18),
max_hear_distance = 32,
loop = true, -- In case of lag
}
)
-- Store sound handle for this player
if handle then
handles[player_name] = handle
end
end
end
-- Cycle for updating players sounds
minetest.register_globalstep(function(dtime)
timer = timer + dtime
if timer < cycle then
return
end
timer = 0
local players = minetest.get_connected_players()
for n = 1, #players do
fire.update_player_sound(players[n])
end
end)
-- Stop sound and clear handle on player leave
minetest.register_on_leaveplayer(function(player)
local player_name = player:get_player_name()
if handles[player_name] then
minetest.sound_stop(handles[player_name])
handles[player_name] = nil
end
end)
end
-- Deprecated function kept temporarily to avoid crashes if mod fire nodes call it
function fire.update_sounds_around(pos)
end
--
-- ABMs
--
-- Extinguish all flames quickly with water, snow, ice
minetest.register_abm({
label = "Extinguish flame",
nodenames = {"fire:basic_flame", "fire:permanent_flame"},
neighbors = {"group:puts_out_fire"},
interval = 3,
chance = 1,
catch_up = false,
action = function(pos, node, active_object_count, active_object_count_wider)
minetest.remove_node(pos)
minetest.sound_play("fire_extinguish_flame",
{pos = pos, max_hear_distance = 16, gain = 0.15})
end,
})
-- Enable the following ABMs according to 'enable fire' setting
local fire_enabled = minetest.setting_getbool("enable_fire")
if fire_enabled == nil then
-- New setting not specified, check for old setting.
-- If old setting is also not specified, 'not nil' is true.
fire_enabled = not minetest.setting_getbool("disable_fire")
end
if not fire_enabled then
-- Remove basic flames only if fire disabled
minetest.register_abm({
label = "Remove disabled fire",
nodenames = {"fire:basic_flame"},
interval = 7,
chance = 1,
catch_up = false,
action = minetest.remove_node,
})
else -- Fire enabled
-- Ignite neighboring nodes, add basic flames
minetest.register_abm({
label = "Ignite flame",
nodenames = {"group:flammable"},
neighbors = {"group:igniter"},
interval = 7,
chance = 12,
catch_up = false,
action = function(pos, node, active_object_count, active_object_count_wider)
-- If there is water or stuff like that around node, don't ignite
if minetest.find_node_near(pos, 1, {"group:puts_out_fire"}) then
return
end
local p = minetest.find_node_near(pos, 1, {"air"})
if p then
minetest.set_node(p, {name = "fire:basic_flame"})
end
end,
})
-- Remove flammable nodes around basic flame
minetest.register_abm({
label = "Remove flammable nodes",
nodenames = {"fire:basic_flame"},
neighbors = "group:flammable",
interval = 5,
chance = 18,
catch_up = false,
action = function(pos, node, active_object_count, active_object_count_wider)
local p = minetest.find_node_near(pos, 1, {"group:flammable"})
if p then
local flammable_node = minetest.get_node(p)
local def = minetest.registered_nodes[flammable_node.name]
if def.on_burn then
def.on_burn(p)
else
minetest.remove_node(p)
minetest.check_for_falling(p)
end
end
end,
})
end
| lgpl-2.1 |
Planimeter/lgameframework | lib/opengl.lua | 1 | 89662 | --=========== Copyright © 2020, Planimeter, All rights reserved. ===========--
--
-- Purpose:
--
--==========================================================================--
local ffi = require( "ffi" )
local SDL = require( "sdl" )
io.input( framework.execdir .. "include/glcorearb.h" )
ffi.cdef( io.read( "*all" ) )
local _M = {
__glcorearb_h_ = 1,
WIN32_LEAN_AND_MEAN = 1,
GL_VERSION_1_0 = 1,
GL_VERSION_1_1 = 1,
GL_DEPTH_BUFFER_BIT = 0x00000100,
GL_STENCIL_BUFFER_BIT = 0x00000400,
GL_COLOR_BUFFER_BIT = 0x00004000,
GL_FALSE = 0,
GL_TRUE = 1,
GL_POINTS = 0x0000,
GL_LINES = 0x0001,
GL_LINE_LOOP = 0x0002,
GL_LINE_STRIP = 0x0003,
GL_TRIANGLES = 0x0004,
GL_TRIANGLE_STRIP = 0x0005,
GL_TRIANGLE_FAN = 0x0006,
GL_QUADS = 0x0007,
GL_NEVER = 0x0200,
GL_LESS = 0x0201,
GL_EQUAL = 0x0202,
GL_LEQUAL = 0x0203,
GL_GREATER = 0x0204,
GL_NOTEQUAL = 0x0205,
GL_GEQUAL = 0x0206,
GL_ALWAYS = 0x0207,
GL_ZERO = 0,
GL_ONE = 1,
GL_SRC_COLOR = 0x0300,
GL_ONE_MINUS_SRC_COLOR = 0x0301,
GL_SRC_ALPHA = 0x0302,
GL_ONE_MINUS_SRC_ALPHA = 0x0303,
GL_DST_ALPHA = 0x0304,
GL_ONE_MINUS_DST_ALPHA = 0x0305,
GL_DST_COLOR = 0x0306,
GL_ONE_MINUS_DST_COLOR = 0x0307,
GL_SRC_ALPHA_SATURATE = 0x0308,
GL_NONE = 0,
GL_FRONT_LEFT = 0x0400,
GL_FRONT_RIGHT = 0x0401,
GL_BACK_LEFT = 0x0402,
GL_BACK_RIGHT = 0x0403,
GL_FRONT = 0x0404,
GL_BACK = 0x0405,
GL_LEFT = 0x0406,
GL_RIGHT = 0x0407,
GL_FRONT_AND_BACK = 0x0408,
GL_NO_ERROR = 0,
GL_INVALID_ENUM = 0x0500,
GL_INVALID_VALUE = 0x0501,
GL_INVALID_OPERATION = 0x0502,
GL_OUT_OF_MEMORY = 0x0505,
GL_CW = 0x0900,
GL_CCW = 0x0901,
GL_POINT_SIZE = 0x0B11,
GL_POINT_SIZE_RANGE = 0x0B12,
GL_POINT_SIZE_GRANULARITY = 0x0B13,
GL_LINE_SMOOTH = 0x0B20,
GL_LINE_WIDTH = 0x0B21,
GL_LINE_WIDTH_RANGE = 0x0B22,
GL_LINE_WIDTH_GRANULARITY = 0x0B23,
GL_POLYGON_MODE = 0x0B40,
GL_POLYGON_SMOOTH = 0x0B41,
GL_CULL_FACE = 0x0B44,
GL_CULL_FACE_MODE = 0x0B45,
GL_FRONT_FACE = 0x0B46,
GL_DEPTH_RANGE = 0x0B70,
GL_DEPTH_TEST = 0x0B71,
GL_DEPTH_WRITEMASK = 0x0B72,
GL_DEPTH_CLEAR_VALUE = 0x0B73,
GL_DEPTH_FUNC = 0x0B74,
GL_STENCIL_TEST = 0x0B90,
GL_STENCIL_CLEAR_VALUE = 0x0B91,
GL_STENCIL_FUNC = 0x0B92,
GL_STENCIL_VALUE_MASK = 0x0B93,
GL_STENCIL_FAIL = 0x0B94,
GL_STENCIL_PASS_DEPTH_FAIL = 0x0B95,
GL_STENCIL_PASS_DEPTH_PASS = 0x0B96,
GL_STENCIL_REF = 0x0B97,
GL_STENCIL_WRITEMASK = 0x0B98,
GL_VIEWPORT = 0x0BA2,
GL_DITHER = 0x0BD0,
GL_BLEND_DST = 0x0BE0,
GL_BLEND_SRC = 0x0BE1,
GL_BLEND = 0x0BE2,
GL_LOGIC_OP_MODE = 0x0BF0,
GL_COLOR_LOGIC_OP = 0x0BF2,
GL_DRAW_BUFFER = 0x0C01,
GL_READ_BUFFER = 0x0C02,
GL_SCISSOR_BOX = 0x0C10,
GL_SCISSOR_TEST = 0x0C11,
GL_COLOR_CLEAR_VALUE = 0x0C22,
GL_COLOR_WRITEMASK = 0x0C23,
GL_DOUBLEBUFFER = 0x0C32,
GL_STEREO = 0x0C33,
GL_LINE_SMOOTH_HINT = 0x0C52,
GL_POLYGON_SMOOTH_HINT = 0x0C53,
GL_UNPACK_SWAP_BYTES = 0x0CF0,
GL_UNPACK_LSB_FIRST = 0x0CF1,
GL_UNPACK_ROW_LENGTH = 0x0CF2,
GL_UNPACK_SKIP_ROWS = 0x0CF3,
GL_UNPACK_SKIP_PIXELS = 0x0CF4,
GL_UNPACK_ALIGNMENT = 0x0CF5,
GL_PACK_SWAP_BYTES = 0x0D00,
GL_PACK_LSB_FIRST = 0x0D01,
GL_PACK_ROW_LENGTH = 0x0D02,
GL_PACK_SKIP_ROWS = 0x0D03,
GL_PACK_SKIP_PIXELS = 0x0D04,
GL_PACK_ALIGNMENT = 0x0D05,
GL_MAX_TEXTURE_SIZE = 0x0D33,
GL_MAX_VIEWPORT_DIMS = 0x0D3A,
GL_SUBPIXEL_BITS = 0x0D50,
GL_TEXTURE_1D = 0x0DE0,
GL_TEXTURE_2D = 0x0DE1,
GL_POLYGON_OFFSET_UNITS = 0x2A00,
GL_POLYGON_OFFSET_POINT = 0x2A01,
GL_POLYGON_OFFSET_LINE = 0x2A02,
GL_POLYGON_OFFSET_FILL = 0x8037,
GL_POLYGON_OFFSET_FACTOR = 0x8038,
GL_TEXTURE_BINDING_1D = 0x8068,
GL_TEXTURE_BINDING_2D = 0x8069,
GL_TEXTURE_WIDTH = 0x1000,
GL_TEXTURE_HEIGHT = 0x1001,
GL_TEXTURE_INTERNAL_FORMAT = 0x1003,
GL_TEXTURE_BORDER_COLOR = 0x1004,
GL_TEXTURE_RED_SIZE = 0x805C,
GL_TEXTURE_GREEN_SIZE = 0x805D,
GL_TEXTURE_BLUE_SIZE = 0x805E,
GL_TEXTURE_ALPHA_SIZE = 0x805F,
GL_DONT_CARE = 0x1100,
GL_FASTEST = 0x1101,
GL_NICEST = 0x1102,
GL_BYTE = 0x1400,
GL_UNSIGNED_BYTE = 0x1401,
GL_SHORT = 0x1402,
GL_UNSIGNED_SHORT = 0x1403,
GL_INT = 0x1404,
GL_UNSIGNED_INT = 0x1405,
GL_FLOAT = 0x1406,
GL_DOUBLE = 0x140A,
GL_STACK_OVERFLOW = 0x0503,
GL_STACK_UNDERFLOW = 0x0504,
GL_CLEAR = 0x1500,
GL_AND = 0x1501,
GL_AND_REVERSE = 0x1502,
GL_COPY = 0x1503,
GL_AND_INVERTED = 0x1504,
GL_NOOP = 0x1505,
GL_XOR = 0x1506,
GL_OR = 0x1507,
GL_NOR = 0x1508,
GL_EQUIV = 0x1509,
GL_INVERT = 0x150A,
GL_OR_REVERSE = 0x150B,
GL_COPY_INVERTED = 0x150C,
GL_OR_INVERTED = 0x150D,
GL_NAND = 0x150E,
GL_SET = 0x150F,
GL_TEXTURE = 0x1702,
GL_COLOR = 0x1800,
GL_DEPTH = 0x1801,
GL_STENCIL = 0x1802,
GL_STENCIL_INDEX = 0x1901,
GL_DEPTH_COMPONENT = 0x1902,
GL_RED = 0x1903,
GL_GREEN = 0x1904,
GL_BLUE = 0x1905,
GL_ALPHA = 0x1906,
GL_RGB = 0x1907,
GL_RGBA = 0x1908,
GL_POINT = 0x1B00,
GL_LINE = 0x1B01,
GL_FILL = 0x1B02,
GL_KEEP = 0x1E00,
GL_REPLACE = 0x1E01,
GL_INCR = 0x1E02,
GL_DECR = 0x1E03,
GL_VENDOR = 0x1F00,
GL_RENDERER = 0x1F01,
GL_VERSION = 0x1F02,
GL_EXTENSIONS = 0x1F03,
GL_NEAREST = 0x2600,
GL_LINEAR = 0x2601,
GL_NEAREST_MIPMAP_NEAREST = 0x2700,
GL_LINEAR_MIPMAP_NEAREST = 0x2701,
GL_NEAREST_MIPMAP_LINEAR = 0x2702,
GL_LINEAR_MIPMAP_LINEAR = 0x2703,
GL_TEXTURE_MAG_FILTER = 0x2800,
GL_TEXTURE_MIN_FILTER = 0x2801,
GL_TEXTURE_WRAP_S = 0x2802,
GL_TEXTURE_WRAP_T = 0x2803,
GL_PROXY_TEXTURE_1D = 0x8063,
GL_PROXY_TEXTURE_2D = 0x8064,
GL_REPEAT = 0x2901,
GL_R3_G3_B2 = 0x2A10,
GL_RGB4 = 0x804F,
GL_RGB5 = 0x8050,
GL_RGB8 = 0x8051,
GL_RGB10 = 0x8052,
GL_RGB12 = 0x8053,
GL_RGB16 = 0x8054,
GL_RGBA2 = 0x8055,
GL_RGBA4 = 0x8056,
GL_RGB5_A1 = 0x8057,
GL_RGBA8 = 0x8058,
GL_RGB10_A2 = 0x8059,
GL_RGBA12 = 0x805A,
GL_RGBA16 = 0x805B,
GL_VERTEX_ARRAY = 0x8074,
GL_VERSION_1_2 = 1,
GL_UNSIGNED_BYTE_3_3_2 = 0x8032,
GL_UNSIGNED_SHORT_4_4_4_4 = 0x8033,
GL_UNSIGNED_SHORT_5_5_5_1 = 0x8034,
GL_UNSIGNED_INT_8_8_8_8 = 0x8035,
GL_UNSIGNED_INT_10_10_10_2 = 0x8036,
GL_TEXTURE_BINDING_3D = 0x806A,
GL_PACK_SKIP_IMAGES = 0x806B,
GL_PACK_IMAGE_HEIGHT = 0x806C,
GL_UNPACK_SKIP_IMAGES = 0x806D,
GL_UNPACK_IMAGE_HEIGHT = 0x806E,
GL_TEXTURE_3D = 0x806F,
GL_PROXY_TEXTURE_3D = 0x8070,
GL_TEXTURE_DEPTH = 0x8071,
GL_TEXTURE_WRAP_R = 0x8072,
GL_MAX_3D_TEXTURE_SIZE = 0x8073,
GL_UNSIGNED_BYTE_2_3_3_REV = 0x8362,
GL_UNSIGNED_SHORT_5_6_5 = 0x8363,
GL_UNSIGNED_SHORT_5_6_5_REV = 0x8364,
GL_UNSIGNED_SHORT_4_4_4_4_REV = 0x8365,
GL_UNSIGNED_SHORT_1_5_5_5_REV = 0x8366,
GL_UNSIGNED_INT_8_8_8_8_REV = 0x8367,
GL_UNSIGNED_INT_2_10_10_10_REV = 0x8368,
GL_BGR = 0x80E0,
GL_BGRA = 0x80E1,
GL_MAX_ELEMENTS_VERTICES = 0x80E8,
GL_MAX_ELEMENTS_INDICES = 0x80E9,
GL_CLAMP_TO_EDGE = 0x812F,
GL_TEXTURE_MIN_LOD = 0x813A,
GL_TEXTURE_MAX_LOD = 0x813B,
GL_TEXTURE_BASE_LEVEL = 0x813C,
GL_TEXTURE_MAX_LEVEL = 0x813D,
GL_SMOOTH_POINT_SIZE_RANGE = 0x0B12,
GL_SMOOTH_POINT_SIZE_GRANULARITY = 0x0B13,
GL_SMOOTH_LINE_WIDTH_RANGE = 0x0B22,
GL_SMOOTH_LINE_WIDTH_GRANULARITY = 0x0B23,
GL_ALIASED_LINE_WIDTH_RANGE = 0x846E,
GL_VERSION_1_3 = 1,
GL_TEXTURE0 = 0x84C0,
GL_TEXTURE1 = 0x84C1,
GL_TEXTURE2 = 0x84C2,
GL_TEXTURE3 = 0x84C3,
GL_TEXTURE4 = 0x84C4,
GL_TEXTURE5 = 0x84C5,
GL_TEXTURE6 = 0x84C6,
GL_TEXTURE7 = 0x84C7,
GL_TEXTURE8 = 0x84C8,
GL_TEXTURE9 = 0x84C9,
GL_TEXTURE10 = 0x84CA,
GL_TEXTURE11 = 0x84CB,
GL_TEXTURE12 = 0x84CC,
GL_TEXTURE13 = 0x84CD,
GL_TEXTURE14 = 0x84CE,
GL_TEXTURE15 = 0x84CF,
GL_TEXTURE16 = 0x84D0,
GL_TEXTURE17 = 0x84D1,
GL_TEXTURE18 = 0x84D2,
GL_TEXTURE19 = 0x84D3,
GL_TEXTURE20 = 0x84D4,
GL_TEXTURE21 = 0x84D5,
GL_TEXTURE22 = 0x84D6,
GL_TEXTURE23 = 0x84D7,
GL_TEXTURE24 = 0x84D8,
GL_TEXTURE25 = 0x84D9,
GL_TEXTURE26 = 0x84DA,
GL_TEXTURE27 = 0x84DB,
GL_TEXTURE28 = 0x84DC,
GL_TEXTURE29 = 0x84DD,
GL_TEXTURE30 = 0x84DE,
GL_TEXTURE31 = 0x84DF,
GL_ACTIVE_TEXTURE = 0x84E0,
GL_MULTISAMPLE = 0x809D,
GL_SAMPLE_ALPHA_TO_COVERAGE = 0x809E,
GL_SAMPLE_ALPHA_TO_ONE = 0x809F,
GL_SAMPLE_COVERAGE = 0x80A0,
GL_SAMPLE_BUFFERS = 0x80A8,
GL_SAMPLES = 0x80A9,
GL_SAMPLE_COVERAGE_VALUE = 0x80AA,
GL_SAMPLE_COVERAGE_INVERT = 0x80AB,
GL_TEXTURE_CUBE_MAP = 0x8513,
GL_TEXTURE_BINDING_CUBE_MAP = 0x8514,
GL_TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515,
GL_TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516,
GL_TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517,
GL_TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518,
GL_TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519,
GL_TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A,
GL_PROXY_TEXTURE_CUBE_MAP = 0x851B,
GL_MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C,
GL_COMPRESSED_RGB = 0x84ED,
GL_COMPRESSED_RGBA = 0x84EE,
GL_TEXTURE_COMPRESSION_HINT = 0x84EF,
GL_TEXTURE_COMPRESSED_IMAGE_SIZE = 0x86A0,
GL_TEXTURE_COMPRESSED = 0x86A1,
GL_NUM_COMPRESSED_TEXTURE_FORMATS = 0x86A2,
GL_COMPRESSED_TEXTURE_FORMATS = 0x86A3,
GL_CLAMP_TO_BORDER = 0x812D,
GL_VERSION_1_4 = 1,
GL_BLEND_DST_RGB = 0x80C8,
GL_BLEND_SRC_RGB = 0x80C9,
GL_BLEND_DST_ALPHA = 0x80CA,
GL_BLEND_SRC_ALPHA = 0x80CB,
GL_POINT_FADE_THRESHOLD_SIZE = 0x8128,
GL_DEPTH_COMPONENT16 = 0x81A5,
GL_DEPTH_COMPONENT24 = 0x81A6,
GL_DEPTH_COMPONENT32 = 0x81A7,
GL_MIRRORED_REPEAT = 0x8370,
GL_MAX_TEXTURE_LOD_BIAS = 0x84FD,
GL_TEXTURE_LOD_BIAS = 0x8501,
GL_INCR_WRAP = 0x8507,
GL_DECR_WRAP = 0x8508,
GL_TEXTURE_DEPTH_SIZE = 0x884A,
GL_TEXTURE_COMPARE_MODE = 0x884C,
GL_TEXTURE_COMPARE_FUNC = 0x884D,
GL_FUNC_ADD = 0x8006,
GL_FUNC_SUBTRACT = 0x800A,
GL_FUNC_REVERSE_SUBTRACT = 0x800B,
GL_MIN = 0x8007,
GL_MAX = 0x8008,
GL_CONSTANT_COLOR = 0x8001,
GL_ONE_MINUS_CONSTANT_COLOR = 0x8002,
GL_CONSTANT_ALPHA = 0x8003,
GL_ONE_MINUS_CONSTANT_ALPHA = 0x8004,
GL_VERSION_1_5 = 1,
GL_BUFFER_SIZE = 0x8764,
GL_BUFFER_USAGE = 0x8765,
GL_QUERY_COUNTER_BITS = 0x8864,
GL_CURRENT_QUERY = 0x8865,
GL_QUERY_RESULT = 0x8866,
GL_QUERY_RESULT_AVAILABLE = 0x8867,
GL_ARRAY_BUFFER = 0x8892,
GL_ELEMENT_ARRAY_BUFFER = 0x8893,
GL_ARRAY_BUFFER_BINDING = 0x8894,
GL_ELEMENT_ARRAY_BUFFER_BINDING = 0x8895,
GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F,
GL_READ_ONLY = 0x88B8,
GL_WRITE_ONLY = 0x88B9,
GL_READ_WRITE = 0x88BA,
GL_BUFFER_ACCESS = 0x88BB,
GL_BUFFER_MAPPED = 0x88BC,
GL_BUFFER_MAP_POINTER = 0x88BD,
GL_STREAM_DRAW = 0x88E0,
GL_STREAM_READ = 0x88E1,
GL_STREAM_COPY = 0x88E2,
GL_STATIC_DRAW = 0x88E4,
GL_STATIC_READ = 0x88E5,
GL_STATIC_COPY = 0x88E6,
GL_DYNAMIC_DRAW = 0x88E8,
GL_DYNAMIC_READ = 0x88E9,
GL_DYNAMIC_COPY = 0x88EA,
GL_SAMPLES_PASSED = 0x8914,
GL_SRC1_ALPHA = 0x8589,
GL_VERSION_2_0 = 1,
GL_BLEND_EQUATION_RGB = 0x8009,
GL_VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622,
GL_VERTEX_ATTRIB_ARRAY_SIZE = 0x8623,
GL_VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624,
GL_VERTEX_ATTRIB_ARRAY_TYPE = 0x8625,
GL_CURRENT_VERTEX_ATTRIB = 0x8626,
GL_VERTEX_PROGRAM_POINT_SIZE = 0x8642,
GL_VERTEX_ATTRIB_ARRAY_POINTER = 0x8645,
GL_STENCIL_BACK_FUNC = 0x8800,
GL_STENCIL_BACK_FAIL = 0x8801,
GL_STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802,
GL_STENCIL_BACK_PASS_DEPTH_PASS = 0x8803,
GL_MAX_DRAW_BUFFERS = 0x8824,
GL_DRAW_BUFFER0 = 0x8825,
GL_DRAW_BUFFER1 = 0x8826,
GL_DRAW_BUFFER2 = 0x8827,
GL_DRAW_BUFFER3 = 0x8828,
GL_DRAW_BUFFER4 = 0x8829,
GL_DRAW_BUFFER5 = 0x882A,
GL_DRAW_BUFFER6 = 0x882B,
GL_DRAW_BUFFER7 = 0x882C,
GL_DRAW_BUFFER8 = 0x882D,
GL_DRAW_BUFFER9 = 0x882E,
GL_DRAW_BUFFER10 = 0x882F,
GL_DRAW_BUFFER11 = 0x8830,
GL_DRAW_BUFFER12 = 0x8831,
GL_DRAW_BUFFER13 = 0x8832,
GL_DRAW_BUFFER14 = 0x8833,
GL_DRAW_BUFFER15 = 0x8834,
GL_BLEND_EQUATION_ALPHA = 0x883D,
GL_MAX_VERTEX_ATTRIBS = 0x8869,
GL_VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A,
GL_MAX_TEXTURE_IMAGE_UNITS = 0x8872,
GL_FRAGMENT_SHADER = 0x8B30,
GL_VERTEX_SHADER = 0x8B31,
GL_MAX_FRAGMENT_UNIFORM_COMPONENTS = 0x8B49,
GL_MAX_VERTEX_UNIFORM_COMPONENTS = 0x8B4A,
GL_MAX_VARYING_FLOATS = 0x8B4B,
GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C,
GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D,
GL_SHADER_TYPE = 0x8B4F,
GL_FLOAT_VEC2 = 0x8B50,
GL_FLOAT_VEC3 = 0x8B51,
GL_FLOAT_VEC4 = 0x8B52,
GL_INT_VEC2 = 0x8B53,
GL_INT_VEC3 = 0x8B54,
GL_INT_VEC4 = 0x8B55,
GL_BOOL = 0x8B56,
GL_BOOL_VEC2 = 0x8B57,
GL_BOOL_VEC3 = 0x8B58,
GL_BOOL_VEC4 = 0x8B59,
GL_FLOAT_MAT2 = 0x8B5A,
GL_FLOAT_MAT3 = 0x8B5B,
GL_FLOAT_MAT4 = 0x8B5C,
GL_SAMPLER_1D = 0x8B5D,
GL_SAMPLER_2D = 0x8B5E,
GL_SAMPLER_3D = 0x8B5F,
GL_SAMPLER_CUBE = 0x8B60,
GL_SAMPLER_1D_SHADOW = 0x8B61,
GL_SAMPLER_2D_SHADOW = 0x8B62,
GL_DELETE_STATUS = 0x8B80,
GL_COMPILE_STATUS = 0x8B81,
GL_LINK_STATUS = 0x8B82,
GL_VALIDATE_STATUS = 0x8B83,
GL_INFO_LOG_LENGTH = 0x8B84,
GL_ATTACHED_SHADERS = 0x8B85,
GL_ACTIVE_UNIFORMS = 0x8B86,
GL_ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87,
GL_SHADER_SOURCE_LENGTH = 0x8B88,
GL_ACTIVE_ATTRIBUTES = 0x8B89,
GL_ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A,
GL_FRAGMENT_SHADER_DERIVATIVE_HINT = 0x8B8B,
GL_SHADING_LANGUAGE_VERSION = 0x8B8C,
GL_CURRENT_PROGRAM = 0x8B8D,
GL_POINT_SPRITE_COORD_ORIGIN = 0x8CA0,
GL_LOWER_LEFT = 0x8CA1,
GL_UPPER_LEFT = 0x8CA2,
GL_STENCIL_BACK_REF = 0x8CA3,
GL_STENCIL_BACK_VALUE_MASK = 0x8CA4,
GL_STENCIL_BACK_WRITEMASK = 0x8CA5,
GL_VERSION_2_1 = 1,
GL_PIXEL_PACK_BUFFER = 0x88EB,
GL_PIXEL_UNPACK_BUFFER = 0x88EC,
GL_PIXEL_PACK_BUFFER_BINDING = 0x88ED,
GL_PIXEL_UNPACK_BUFFER_BINDING = 0x88EF,
GL_FLOAT_MAT2x3 = 0x8B65,
GL_FLOAT_MAT2x4 = 0x8B66,
GL_FLOAT_MAT3x2 = 0x8B67,
GL_FLOAT_MAT3x4 = 0x8B68,
GL_FLOAT_MAT4x2 = 0x8B69,
GL_FLOAT_MAT4x3 = 0x8B6A,
GL_SRGB = 0x8C40,
GL_SRGB8 = 0x8C41,
GL_SRGB_ALPHA = 0x8C42,
GL_SRGB8_ALPHA8 = 0x8C43,
GL_COMPRESSED_SRGB = 0x8C48,
GL_COMPRESSED_SRGB_ALPHA = 0x8C49,
GL_VERSION_3_0 = 1,
GL_COMPARE_REF_TO_TEXTURE = 0x884E,
GL_CLIP_DISTANCE0 = 0x3000,
GL_CLIP_DISTANCE1 = 0x3001,
GL_CLIP_DISTANCE2 = 0x3002,
GL_CLIP_DISTANCE3 = 0x3003,
GL_CLIP_DISTANCE4 = 0x3004,
GL_CLIP_DISTANCE5 = 0x3005,
GL_CLIP_DISTANCE6 = 0x3006,
GL_CLIP_DISTANCE7 = 0x3007,
GL_MAX_CLIP_DISTANCES = 0x0D32,
GL_MAJOR_VERSION = 0x821B,
GL_MINOR_VERSION = 0x821C,
GL_NUM_EXTENSIONS = 0x821D,
GL_CONTEXT_FLAGS = 0x821E,
GL_COMPRESSED_RED = 0x8225,
GL_COMPRESSED_RG = 0x8226,
GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT = 0x00000001,
GL_RGBA32F = 0x8814,
GL_RGB32F = 0x8815,
GL_RGBA16F = 0x881A,
GL_RGB16F = 0x881B,
GL_VERTEX_ATTRIB_ARRAY_INTEGER = 0x88FD,
GL_MAX_ARRAY_TEXTURE_LAYERS = 0x88FF,
GL_MIN_PROGRAM_TEXEL_OFFSET = 0x8904,
GL_MAX_PROGRAM_TEXEL_OFFSET = 0x8905,
GL_CLAMP_READ_COLOR = 0x891C,
GL_FIXED_ONLY = 0x891D,
GL_MAX_VARYING_COMPONENTS = 0x8B4B,
GL_TEXTURE_1D_ARRAY = 0x8C18,
GL_PROXY_TEXTURE_1D_ARRAY = 0x8C19,
GL_TEXTURE_2D_ARRAY = 0x8C1A,
GL_PROXY_TEXTURE_2D_ARRAY = 0x8C1B,
GL_TEXTURE_BINDING_1D_ARRAY = 0x8C1C,
GL_TEXTURE_BINDING_2D_ARRAY = 0x8C1D,
GL_R11F_G11F_B10F = 0x8C3A,
GL_UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B,
GL_RGB9_E5 = 0x8C3D,
GL_UNSIGNED_INT_5_9_9_9_REV = 0x8C3E,
GL_TEXTURE_SHARED_SIZE = 0x8C3F,
GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH = 0x8C76,
GL_TRANSFORM_FEEDBACK_BUFFER_MODE = 0x8C7F,
GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = 0x8C80,
GL_TRANSFORM_FEEDBACK_VARYINGS = 0x8C83,
GL_TRANSFORM_FEEDBACK_BUFFER_START = 0x8C84,
GL_TRANSFORM_FEEDBACK_BUFFER_SIZE = 0x8C85,
GL_PRIMITIVES_GENERATED = 0x8C87,
GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = 0x8C88,
GL_RASTERIZER_DISCARD = 0x8C89,
GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = 0x8C8A,
GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = 0x8C8B,
GL_INTERLEAVED_ATTRIBS = 0x8C8C,
GL_SEPARATE_ATTRIBS = 0x8C8D,
GL_TRANSFORM_FEEDBACK_BUFFER = 0x8C8E,
GL_TRANSFORM_FEEDBACK_BUFFER_BINDING = 0x8C8F,
GL_RGBA32UI = 0x8D70,
GL_RGB32UI = 0x8D71,
GL_RGBA16UI = 0x8D76,
GL_RGB16UI = 0x8D77,
GL_RGBA8UI = 0x8D7C,
GL_RGB8UI = 0x8D7D,
GL_RGBA32I = 0x8D82,
GL_RGB32I = 0x8D83,
GL_RGBA16I = 0x8D88,
GL_RGB16I = 0x8D89,
GL_RGBA8I = 0x8D8E,
GL_RGB8I = 0x8D8F,
GL_RED_INTEGER = 0x8D94,
GL_GREEN_INTEGER = 0x8D95,
GL_BLUE_INTEGER = 0x8D96,
GL_RGB_INTEGER = 0x8D98,
GL_RGBA_INTEGER = 0x8D99,
GL_BGR_INTEGER = 0x8D9A,
GL_BGRA_INTEGER = 0x8D9B,
GL_SAMPLER_1D_ARRAY = 0x8DC0,
GL_SAMPLER_2D_ARRAY = 0x8DC1,
GL_SAMPLER_1D_ARRAY_SHADOW = 0x8DC3,
GL_SAMPLER_2D_ARRAY_SHADOW = 0x8DC4,
GL_SAMPLER_CUBE_SHADOW = 0x8DC5,
GL_UNSIGNED_INT_VEC2 = 0x8DC6,
GL_UNSIGNED_INT_VEC3 = 0x8DC7,
GL_UNSIGNED_INT_VEC4 = 0x8DC8,
GL_INT_SAMPLER_1D = 0x8DC9,
GL_INT_SAMPLER_2D = 0x8DCA,
GL_INT_SAMPLER_3D = 0x8DCB,
GL_INT_SAMPLER_CUBE = 0x8DCC,
GL_INT_SAMPLER_1D_ARRAY = 0x8DCE,
GL_INT_SAMPLER_2D_ARRAY = 0x8DCF,
GL_UNSIGNED_INT_SAMPLER_1D = 0x8DD1,
GL_UNSIGNED_INT_SAMPLER_2D = 0x8DD2,
GL_UNSIGNED_INT_SAMPLER_3D = 0x8DD3,
GL_UNSIGNED_INT_SAMPLER_CUBE = 0x8DD4,
GL_UNSIGNED_INT_SAMPLER_1D_ARRAY = 0x8DD6,
GL_UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8DD7,
GL_QUERY_WAIT = 0x8E13,
GL_QUERY_NO_WAIT = 0x8E14,
GL_QUERY_BY_REGION_WAIT = 0x8E15,
GL_QUERY_BY_REGION_NO_WAIT = 0x8E16,
GL_BUFFER_ACCESS_FLAGS = 0x911F,
GL_BUFFER_MAP_LENGTH = 0x9120,
GL_BUFFER_MAP_OFFSET = 0x9121,
GL_DEPTH_COMPONENT32F = 0x8CAC,
GL_DEPTH32F_STENCIL8 = 0x8CAD,
GL_FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8DAD,
GL_INVALID_FRAMEBUFFER_OPERATION = 0x0506,
GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = 0x8210,
GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE = 0x8211,
GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE = 0x8212,
GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE = 0x8213,
GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE = 0x8214,
GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE = 0x8215,
GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE = 0x8216,
GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE = 0x8217,
GL_FRAMEBUFFER_DEFAULT = 0x8218,
GL_FRAMEBUFFER_UNDEFINED = 0x8219,
GL_DEPTH_STENCIL_ATTACHMENT = 0x821A,
GL_MAX_RENDERBUFFER_SIZE = 0x84E8,
GL_DEPTH_STENCIL = 0x84F9,
GL_UNSIGNED_INT_24_8 = 0x84FA,
GL_DEPTH24_STENCIL8 = 0x88F0,
GL_TEXTURE_STENCIL_SIZE = 0x88F1,
GL_TEXTURE_RED_TYPE = 0x8C10,
GL_TEXTURE_GREEN_TYPE = 0x8C11,
GL_TEXTURE_BLUE_TYPE = 0x8C12,
GL_TEXTURE_ALPHA_TYPE = 0x8C13,
GL_TEXTURE_DEPTH_TYPE = 0x8C16,
GL_UNSIGNED_NORMALIZED = 0x8C17,
GL_FRAMEBUFFER_BINDING = 0x8CA6,
GL_DRAW_FRAMEBUFFER_BINDING = 0x8CA6,
GL_RENDERBUFFER_BINDING = 0x8CA7,
GL_READ_FRAMEBUFFER = 0x8CA8,
GL_DRAW_FRAMEBUFFER = 0x8CA9,
GL_READ_FRAMEBUFFER_BINDING = 0x8CAA,
GL_RENDERBUFFER_SAMPLES = 0x8CAB,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1,
GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2,
GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3,
GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER = 0x8CD4,
GL_FRAMEBUFFER_COMPLETE = 0x8CD5,
GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6,
GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7,
GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER = 0x8CDB,
GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER = 0x8CDC,
GL_FRAMEBUFFER_UNSUPPORTED = 0x8CDD,
GL_MAX_COLOR_ATTACHMENTS = 0x8CDF,
GL_COLOR_ATTACHMENT0 = 0x8CE0,
GL_COLOR_ATTACHMENT1 = 0x8CE1,
GL_COLOR_ATTACHMENT2 = 0x8CE2,
GL_COLOR_ATTACHMENT3 = 0x8CE3,
GL_COLOR_ATTACHMENT4 = 0x8CE4,
GL_COLOR_ATTACHMENT5 = 0x8CE5,
GL_COLOR_ATTACHMENT6 = 0x8CE6,
GL_COLOR_ATTACHMENT7 = 0x8CE7,
GL_COLOR_ATTACHMENT8 = 0x8CE8,
GL_COLOR_ATTACHMENT9 = 0x8CE9,
GL_COLOR_ATTACHMENT10 = 0x8CEA,
GL_COLOR_ATTACHMENT11 = 0x8CEB,
GL_COLOR_ATTACHMENT12 = 0x8CEC,
GL_COLOR_ATTACHMENT13 = 0x8CED,
GL_COLOR_ATTACHMENT14 = 0x8CEE,
GL_COLOR_ATTACHMENT15 = 0x8CEF,
GL_COLOR_ATTACHMENT16 = 0x8CF0,
GL_COLOR_ATTACHMENT17 = 0x8CF1,
GL_COLOR_ATTACHMENT18 = 0x8CF2,
GL_COLOR_ATTACHMENT19 = 0x8CF3,
GL_COLOR_ATTACHMENT20 = 0x8CF4,
GL_COLOR_ATTACHMENT21 = 0x8CF5,
GL_COLOR_ATTACHMENT22 = 0x8CF6,
GL_COLOR_ATTACHMENT23 = 0x8CF7,
GL_COLOR_ATTACHMENT24 = 0x8CF8,
GL_COLOR_ATTACHMENT25 = 0x8CF9,
GL_COLOR_ATTACHMENT26 = 0x8CFA,
GL_COLOR_ATTACHMENT27 = 0x8CFB,
GL_COLOR_ATTACHMENT28 = 0x8CFC,
GL_COLOR_ATTACHMENT29 = 0x8CFD,
GL_COLOR_ATTACHMENT30 = 0x8CFE,
GL_COLOR_ATTACHMENT31 = 0x8CFF,
GL_DEPTH_ATTACHMENT = 0x8D00,
GL_STENCIL_ATTACHMENT = 0x8D20,
GL_FRAMEBUFFER = 0x8D40,
GL_RENDERBUFFER = 0x8D41,
GL_RENDERBUFFER_WIDTH = 0x8D42,
GL_RENDERBUFFER_HEIGHT = 0x8D43,
GL_RENDERBUFFER_INTERNAL_FORMAT = 0x8D44,
GL_STENCIL_INDEX1 = 0x8D46,
GL_STENCIL_INDEX4 = 0x8D47,
GL_STENCIL_INDEX8 = 0x8D48,
GL_STENCIL_INDEX16 = 0x8D49,
GL_RENDERBUFFER_RED_SIZE = 0x8D50,
GL_RENDERBUFFER_GREEN_SIZE = 0x8D51,
GL_RENDERBUFFER_BLUE_SIZE = 0x8D52,
GL_RENDERBUFFER_ALPHA_SIZE = 0x8D53,
GL_RENDERBUFFER_DEPTH_SIZE = 0x8D54,
GL_RENDERBUFFER_STENCIL_SIZE = 0x8D55,
GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = 0x8D56,
GL_MAX_SAMPLES = 0x8D57,
GL_FRAMEBUFFER_SRGB = 0x8DB9,
GL_HALF_FLOAT = 0x140B,
GL_MAP_READ_BIT = 0x0001,
GL_MAP_WRITE_BIT = 0x0002,
GL_MAP_INVALIDATE_RANGE_BIT = 0x0004,
GL_MAP_INVALIDATE_BUFFER_BIT = 0x0008,
GL_MAP_FLUSH_EXPLICIT_BIT = 0x0010,
GL_MAP_UNSYNCHRONIZED_BIT = 0x0020,
GL_COMPRESSED_RED_RGTC1 = 0x8DBB,
GL_COMPRESSED_SIGNED_RED_RGTC1 = 0x8DBC,
GL_COMPRESSED_RG_RGTC2 = 0x8DBD,
GL_COMPRESSED_SIGNED_RG_RGTC2 = 0x8DBE,
GL_RG = 0x8227,
GL_RG_INTEGER = 0x8228,
GL_R8 = 0x8229,
GL_R16 = 0x822A,
GL_RG8 = 0x822B,
GL_RG16 = 0x822C,
GL_R16F = 0x822D,
GL_R32F = 0x822E,
GL_RG16F = 0x822F,
GL_RG32F = 0x8230,
GL_R8I = 0x8231,
GL_R8UI = 0x8232,
GL_R16I = 0x8233,
GL_R16UI = 0x8234,
GL_R32I = 0x8235,
GL_R32UI = 0x8236,
GL_RG8I = 0x8237,
GL_RG8UI = 0x8238,
GL_RG16I = 0x8239,
GL_RG16UI = 0x823A,
GL_RG32I = 0x823B,
GL_RG32UI = 0x823C,
GL_VERTEX_ARRAY_BINDING = 0x85B5,
GL_VERSION_3_1 = 1,
GL_SAMPLER_2D_RECT = 0x8B63,
GL_SAMPLER_2D_RECT_SHADOW = 0x8B64,
GL_SAMPLER_BUFFER = 0x8DC2,
GL_INT_SAMPLER_2D_RECT = 0x8DCD,
GL_INT_SAMPLER_BUFFER = 0x8DD0,
GL_UNSIGNED_INT_SAMPLER_2D_RECT = 0x8DD5,
GL_UNSIGNED_INT_SAMPLER_BUFFER = 0x8DD8,
GL_TEXTURE_BUFFER = 0x8C2A,
GL_MAX_TEXTURE_BUFFER_SIZE = 0x8C2B,
GL_TEXTURE_BINDING_BUFFER = 0x8C2C,
GL_TEXTURE_BUFFER_DATA_STORE_BINDING = 0x8C2D,
GL_TEXTURE_RECTANGLE = 0x84F5,
GL_TEXTURE_BINDING_RECTANGLE = 0x84F6,
GL_PROXY_TEXTURE_RECTANGLE = 0x84F7,
GL_MAX_RECTANGLE_TEXTURE_SIZE = 0x84F8,
GL_R8_SNORM = 0x8F94,
GL_RG8_SNORM = 0x8F95,
GL_RGB8_SNORM = 0x8F96,
GL_RGBA8_SNORM = 0x8F97,
GL_R16_SNORM = 0x8F98,
GL_RG16_SNORM = 0x8F99,
GL_RGB16_SNORM = 0x8F9A,
GL_RGBA16_SNORM = 0x8F9B,
GL_SIGNED_NORMALIZED = 0x8F9C,
GL_PRIMITIVE_RESTART = 0x8F9D,
GL_PRIMITIVE_RESTART_INDEX = 0x8F9E,
GL_COPY_READ_BUFFER = 0x8F36,
GL_COPY_WRITE_BUFFER = 0x8F37,
GL_UNIFORM_BUFFER = 0x8A11,
GL_UNIFORM_BUFFER_BINDING = 0x8A28,
GL_UNIFORM_BUFFER_START = 0x8A29,
GL_UNIFORM_BUFFER_SIZE = 0x8A2A,
GL_MAX_VERTEX_UNIFORM_BLOCKS = 0x8A2B,
GL_MAX_GEOMETRY_UNIFORM_BLOCKS = 0x8A2C,
GL_MAX_FRAGMENT_UNIFORM_BLOCKS = 0x8A2D,
GL_MAX_COMBINED_UNIFORM_BLOCKS = 0x8A2E,
GL_MAX_UNIFORM_BUFFER_BINDINGS = 0x8A2F,
GL_MAX_UNIFORM_BLOCK_SIZE = 0x8A30,
GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS = 0x8A31,
GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS = 0x8A32,
GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS = 0x8A33,
GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT = 0x8A34,
GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH = 0x8A35,
GL_ACTIVE_UNIFORM_BLOCKS = 0x8A36,
GL_UNIFORM_TYPE = 0x8A37,
GL_UNIFORM_SIZE = 0x8A38,
GL_UNIFORM_NAME_LENGTH = 0x8A39,
GL_UNIFORM_BLOCK_INDEX = 0x8A3A,
GL_UNIFORM_OFFSET = 0x8A3B,
GL_UNIFORM_ARRAY_STRIDE = 0x8A3C,
GL_UNIFORM_MATRIX_STRIDE = 0x8A3D,
GL_UNIFORM_IS_ROW_MAJOR = 0x8A3E,
GL_UNIFORM_BLOCK_BINDING = 0x8A3F,
GL_UNIFORM_BLOCK_DATA_SIZE = 0x8A40,
GL_UNIFORM_BLOCK_NAME_LENGTH = 0x8A41,
GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS = 0x8A42,
GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = 0x8A43,
GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = 0x8A44,
GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER = 0x8A45,
GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = 0x8A46,
GL_INVALID_INDEX = 0xFFFFFFFF,
GL_VERSION_3_2 = 1,
GL_CONTEXT_CORE_PROFILE_BIT = 0x00000001,
GL_CONTEXT_COMPATIBILITY_PROFILE_BIT = 0x00000002,
GL_LINES_ADJACENCY = 0x000A,
GL_LINE_STRIP_ADJACENCY = 0x000B,
GL_TRIANGLES_ADJACENCY = 0x000C,
GL_TRIANGLE_STRIP_ADJACENCY = 0x000D,
GL_PROGRAM_POINT_SIZE = 0x8642,
GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS = 0x8C29,
GL_FRAMEBUFFER_ATTACHMENT_LAYERED = 0x8DA7,
GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS = 0x8DA8,
GL_GEOMETRY_SHADER = 0x8DD9,
GL_GEOMETRY_VERTICES_OUT = 0x8916,
GL_GEOMETRY_INPUT_TYPE = 0x8917,
GL_GEOMETRY_OUTPUT_TYPE = 0x8918,
GL_MAX_GEOMETRY_UNIFORM_COMPONENTS = 0x8DDF,
GL_MAX_GEOMETRY_OUTPUT_VERTICES = 0x8DE0,
GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS = 0x8DE1,
GL_MAX_VERTEX_OUTPUT_COMPONENTS = 0x9122,
GL_MAX_GEOMETRY_INPUT_COMPONENTS = 0x9123,
GL_MAX_GEOMETRY_OUTPUT_COMPONENTS = 0x9124,
GL_MAX_FRAGMENT_INPUT_COMPONENTS = 0x9125,
GL_CONTEXT_PROFILE_MASK = 0x9126,
GL_DEPTH_CLAMP = 0x864F,
GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION = 0x8E4C,
GL_FIRST_VERTEX_CONVENTION = 0x8E4D,
GL_LAST_VERTEX_CONVENTION = 0x8E4E,
GL_PROVOKING_VERTEX = 0x8E4F,
GL_TEXTURE_CUBE_MAP_SEAMLESS = 0x884F,
GL_MAX_SERVER_WAIT_TIMEOUT = 0x9111,
GL_OBJECT_TYPE = 0x9112,
GL_SYNC_CONDITION = 0x9113,
GL_SYNC_STATUS = 0x9114,
GL_SYNC_FLAGS = 0x9115,
GL_SYNC_FENCE = 0x9116,
GL_SYNC_GPU_COMMANDS_COMPLETE = 0x9117,
GL_UNSIGNALED = 0x9118,
GL_SIGNALED = 0x9119,
GL_ALREADY_SIGNALED = 0x911A,
GL_TIMEOUT_EXPIRED = 0x911B,
GL_CONDITION_SATISFIED = 0x911C,
GL_WAIT_FAILED = 0x911D,
GL_TIMEOUT_IGNORED = 0xFFFFFFFFFFFFFFFFull,
GL_SYNC_FLUSH_COMMANDS_BIT = 0x00000001,
GL_SAMPLE_POSITION = 0x8E50,
GL_SAMPLE_MASK = 0x8E51,
GL_SAMPLE_MASK_VALUE = 0x8E52,
GL_MAX_SAMPLE_MASK_WORDS = 0x8E59,
GL_TEXTURE_2D_MULTISAMPLE = 0x9100,
GL_PROXY_TEXTURE_2D_MULTISAMPLE = 0x9101,
GL_TEXTURE_2D_MULTISAMPLE_ARRAY = 0x9102,
GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY = 0x9103,
GL_TEXTURE_BINDING_2D_MULTISAMPLE = 0x9104,
GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY = 0x9105,
GL_TEXTURE_SAMPLES = 0x9106,
GL_TEXTURE_FIXED_SAMPLE_LOCATIONS = 0x9107,
GL_SAMPLER_2D_MULTISAMPLE = 0x9108,
GL_INT_SAMPLER_2D_MULTISAMPLE = 0x9109,
GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE = 0x910A,
GL_SAMPLER_2D_MULTISAMPLE_ARRAY = 0x910B,
GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY = 0x910C,
GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY = 0x910D,
GL_MAX_COLOR_TEXTURE_SAMPLES = 0x910E,
GL_MAX_DEPTH_TEXTURE_SAMPLES = 0x910F,
GL_MAX_INTEGER_SAMPLES = 0x9110,
GL_VERSION_3_3 = 1,
GL_VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88FE,
GL_SRC1_COLOR = 0x88F9,
GL_ONE_MINUS_SRC1_COLOR = 0x88FA,
GL_ONE_MINUS_SRC1_ALPHA = 0x88FB,
GL_MAX_DUAL_SOURCE_DRAW_BUFFERS = 0x88FC,
GL_ANY_SAMPLES_PASSED = 0x8C2F,
GL_SAMPLER_BINDING = 0x8919,
GL_RGB10_A2UI = 0x906F,
GL_TEXTURE_SWIZZLE_R = 0x8E42,
GL_TEXTURE_SWIZZLE_G = 0x8E43,
GL_TEXTURE_SWIZZLE_B = 0x8E44,
GL_TEXTURE_SWIZZLE_A = 0x8E45,
GL_TEXTURE_SWIZZLE_RGBA = 0x8E46,
GL_TIME_ELAPSED = 0x88BF,
GL_TIMESTAMP = 0x8E28,
GL_INT_2_10_10_10_REV = 0x8D9F,
GL_VERSION_4_0 = 1,
GL_SAMPLE_SHADING = 0x8C36,
GL_MIN_SAMPLE_SHADING_VALUE = 0x8C37,
GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET = 0x8E5E,
GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET = 0x8E5F,
GL_TEXTURE_CUBE_MAP_ARRAY = 0x9009,
GL_TEXTURE_BINDING_CUBE_MAP_ARRAY = 0x900A,
GL_PROXY_TEXTURE_CUBE_MAP_ARRAY = 0x900B,
GL_SAMPLER_CUBE_MAP_ARRAY = 0x900C,
GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW = 0x900D,
GL_INT_SAMPLER_CUBE_MAP_ARRAY = 0x900E,
GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY = 0x900F,
GL_DRAW_INDIRECT_BUFFER = 0x8F3F,
GL_DRAW_INDIRECT_BUFFER_BINDING = 0x8F43,
GL_GEOMETRY_SHADER_INVOCATIONS = 0x887F,
GL_MAX_GEOMETRY_SHADER_INVOCATIONS = 0x8E5A,
GL_MIN_FRAGMENT_INTERPOLATION_OFFSET = 0x8E5B,
GL_MAX_FRAGMENT_INTERPOLATION_OFFSET = 0x8E5C,
GL_FRAGMENT_INTERPOLATION_OFFSET_BITS = 0x8E5D,
GL_MAX_VERTEX_STREAMS = 0x8E71,
GL_DOUBLE_VEC2 = 0x8FFC,
GL_DOUBLE_VEC3 = 0x8FFD,
GL_DOUBLE_VEC4 = 0x8FFE,
GL_DOUBLE_MAT2 = 0x8F46,
GL_DOUBLE_MAT3 = 0x8F47,
GL_DOUBLE_MAT4 = 0x8F48,
GL_DOUBLE_MAT2x3 = 0x8F49,
GL_DOUBLE_MAT2x4 = 0x8F4A,
GL_DOUBLE_MAT3x2 = 0x8F4B,
GL_DOUBLE_MAT3x4 = 0x8F4C,
GL_DOUBLE_MAT4x2 = 0x8F4D,
GL_DOUBLE_MAT4x3 = 0x8F4E,
GL_ACTIVE_SUBROUTINES = 0x8DE5,
GL_ACTIVE_SUBROUTINE_UNIFORMS = 0x8DE6,
GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS = 0x8E47,
GL_ACTIVE_SUBROUTINE_MAX_LENGTH = 0x8E48,
GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH = 0x8E49,
GL_MAX_SUBROUTINES = 0x8DE7,
GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS = 0x8DE8,
GL_NUM_COMPATIBLE_SUBROUTINES = 0x8E4A,
GL_COMPATIBLE_SUBROUTINES = 0x8E4B,
GL_PATCHES = 0x000E,
GL_PATCH_VERTICES = 0x8E72,
GL_PATCH_DEFAULT_INNER_LEVEL = 0x8E73,
GL_PATCH_DEFAULT_OUTER_LEVEL = 0x8E74,
GL_TESS_CONTROL_OUTPUT_VERTICES = 0x8E75,
GL_TESS_GEN_MODE = 0x8E76,
GL_TESS_GEN_SPACING = 0x8E77,
GL_TESS_GEN_VERTEX_ORDER = 0x8E78,
GL_TESS_GEN_POINT_MODE = 0x8E79,
GL_ISOLINES = 0x8E7A,
GL_FRACTIONAL_ODD = 0x8E7B,
GL_FRACTIONAL_EVEN = 0x8E7C,
GL_MAX_PATCH_VERTICES = 0x8E7D,
GL_MAX_TESS_GEN_LEVEL = 0x8E7E,
GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS = 0x8E7F,
GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS = 0x8E80,
GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS = 0x8E81,
GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS = 0x8E82,
GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS = 0x8E83,
GL_MAX_TESS_PATCH_COMPONENTS = 0x8E84,
GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS = 0x8E85,
GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS = 0x8E86,
GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS = 0x8E89,
GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS = 0x8E8A,
GL_MAX_TESS_CONTROL_INPUT_COMPONENTS = 0x886C,
GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS = 0x886D,
GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS = 0x8E1E,
GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS = 0x8E1F,
GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER = 0x84F0,
GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER = 0x84F1,
GL_TESS_EVALUATION_SHADER = 0x8E87,
GL_TESS_CONTROL_SHADER = 0x8E88,
GL_TRANSFORM_FEEDBACK = 0x8E22,
GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED = 0x8E23,
GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE = 0x8E24,
GL_TRANSFORM_FEEDBACK_BINDING = 0x8E25,
GL_MAX_TRANSFORM_FEEDBACK_BUFFERS = 0x8E70,
GL_VERSION_4_1 = 1,
GL_FIXED = 0x140C,
GL_IMPLEMENTATION_COLOR_READ_TYPE = 0x8B9A,
GL_IMPLEMENTATION_COLOR_READ_FORMAT = 0x8B9B,
GL_LOW_FLOAT = 0x8DF0,
GL_MEDIUM_FLOAT = 0x8DF1,
GL_HIGH_FLOAT = 0x8DF2,
GL_LOW_INT = 0x8DF3,
GL_MEDIUM_INT = 0x8DF4,
GL_HIGH_INT = 0x8DF5,
GL_SHADER_COMPILER = 0x8DFA,
GL_SHADER_BINARY_FORMATS = 0x8DF8,
GL_NUM_SHADER_BINARY_FORMATS = 0x8DF9,
GL_MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB,
GL_MAX_VARYING_VECTORS = 0x8DFC,
GL_MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD,
GL_RGB565 = 0x8D62,
GL_PROGRAM_BINARY_RETRIEVABLE_HINT = 0x8257,
GL_PROGRAM_BINARY_LENGTH = 0x8741,
GL_NUM_PROGRAM_BINARY_FORMATS = 0x87FE,
GL_PROGRAM_BINARY_FORMATS = 0x87FF,
GL_VERTEX_SHADER_BIT = 0x00000001,
GL_FRAGMENT_SHADER_BIT = 0x00000002,
GL_GEOMETRY_SHADER_BIT = 0x00000004,
GL_TESS_CONTROL_SHADER_BIT = 0x00000008,
GL_TESS_EVALUATION_SHADER_BIT = 0x00000010,
GL_ALL_SHADER_BITS = 0xFFFFFFFF,
GL_PROGRAM_SEPARABLE = 0x8258,
GL_ACTIVE_PROGRAM = 0x8259,
GL_PROGRAM_PIPELINE_BINDING = 0x825A,
GL_MAX_VIEWPORTS = 0x825B,
GL_VIEWPORT_SUBPIXEL_BITS = 0x825C,
GL_VIEWPORT_BOUNDS_RANGE = 0x825D,
GL_LAYER_PROVOKING_VERTEX = 0x825E,
GL_VIEWPORT_INDEX_PROVOKING_VERTEX = 0x825F,
GL_UNDEFINED_VERTEX = 0x8260,
GL_VERSION_4_2 = 1,
GL_COPY_READ_BUFFER_BINDING = 0x8F36,
GL_COPY_WRITE_BUFFER_BINDING = 0x8F37,
GL_TRANSFORM_FEEDBACK_ACTIVE = 0x8E24,
GL_TRANSFORM_FEEDBACK_PAUSED = 0x8E23,
GL_UNPACK_COMPRESSED_BLOCK_WIDTH = 0x9127,
GL_UNPACK_COMPRESSED_BLOCK_HEIGHT = 0x9128,
GL_UNPACK_COMPRESSED_BLOCK_DEPTH = 0x9129,
GL_UNPACK_COMPRESSED_BLOCK_SIZE = 0x912A,
GL_PACK_COMPRESSED_BLOCK_WIDTH = 0x912B,
GL_PACK_COMPRESSED_BLOCK_HEIGHT = 0x912C,
GL_PACK_COMPRESSED_BLOCK_DEPTH = 0x912D,
GL_PACK_COMPRESSED_BLOCK_SIZE = 0x912E,
GL_NUM_SAMPLE_COUNTS = 0x9380,
GL_MIN_MAP_BUFFER_ALIGNMENT = 0x90BC,
GL_ATOMIC_COUNTER_BUFFER = 0x92C0,
GL_ATOMIC_COUNTER_BUFFER_BINDING = 0x92C1,
GL_ATOMIC_COUNTER_BUFFER_START = 0x92C2,
GL_ATOMIC_COUNTER_BUFFER_SIZE = 0x92C3,
GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE = 0x92C4,
GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS = 0x92C5,
GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES = 0x92C6,
GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER = 0x92C7,
GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER = 0x92C8,
GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER = 0x92C9,
GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER = 0x92CA,
GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER = 0x92CB,
GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS = 0x92CC,
GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS = 0x92CD,
GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS = 0x92CE,
GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS = 0x92CF,
GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS = 0x92D0,
GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS = 0x92D1,
GL_MAX_VERTEX_ATOMIC_COUNTERS = 0x92D2,
GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS = 0x92D3,
GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS = 0x92D4,
GL_MAX_GEOMETRY_ATOMIC_COUNTERS = 0x92D5,
GL_MAX_FRAGMENT_ATOMIC_COUNTERS = 0x92D6,
GL_MAX_COMBINED_ATOMIC_COUNTERS = 0x92D7,
GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE = 0x92D8,
GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS = 0x92DC,
GL_ACTIVE_ATOMIC_COUNTER_BUFFERS = 0x92D9,
GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX = 0x92DA,
GL_UNSIGNED_INT_ATOMIC_COUNTER = 0x92DB,
GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT = 0x00000001,
GL_ELEMENT_ARRAY_BARRIER_BIT = 0x00000002,
GL_UNIFORM_BARRIER_BIT = 0x00000004,
GL_TEXTURE_FETCH_BARRIER_BIT = 0x00000008,
GL_SHADER_IMAGE_ACCESS_BARRIER_BIT = 0x00000020,
GL_COMMAND_BARRIER_BIT = 0x00000040,
GL_PIXEL_BUFFER_BARRIER_BIT = 0x00000080,
GL_TEXTURE_UPDATE_BARRIER_BIT = 0x00000100,
GL_BUFFER_UPDATE_BARRIER_BIT = 0x00000200,
GL_FRAMEBUFFER_BARRIER_BIT = 0x00000400,
GL_TRANSFORM_FEEDBACK_BARRIER_BIT = 0x00000800,
GL_ATOMIC_COUNTER_BARRIER_BIT = 0x00001000,
GL_ALL_BARRIER_BITS = 0xFFFFFFFF,
GL_MAX_IMAGE_UNITS = 0x8F38,
GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS = 0x8F39,
GL_IMAGE_BINDING_NAME = 0x8F3A,
GL_IMAGE_BINDING_LEVEL = 0x8F3B,
GL_IMAGE_BINDING_LAYERED = 0x8F3C,
GL_IMAGE_BINDING_LAYER = 0x8F3D,
GL_IMAGE_BINDING_ACCESS = 0x8F3E,
GL_IMAGE_1D = 0x904C,
GL_IMAGE_2D = 0x904D,
GL_IMAGE_3D = 0x904E,
GL_IMAGE_2D_RECT = 0x904F,
GL_IMAGE_CUBE = 0x9050,
GL_IMAGE_BUFFER = 0x9051,
GL_IMAGE_1D_ARRAY = 0x9052,
GL_IMAGE_2D_ARRAY = 0x9053,
GL_IMAGE_CUBE_MAP_ARRAY = 0x9054,
GL_IMAGE_2D_MULTISAMPLE = 0x9055,
GL_IMAGE_2D_MULTISAMPLE_ARRAY = 0x9056,
GL_INT_IMAGE_1D = 0x9057,
GL_INT_IMAGE_2D = 0x9058,
GL_INT_IMAGE_3D = 0x9059,
GL_INT_IMAGE_2D_RECT = 0x905A,
GL_INT_IMAGE_CUBE = 0x905B,
GL_INT_IMAGE_BUFFER = 0x905C,
GL_INT_IMAGE_1D_ARRAY = 0x905D,
GL_INT_IMAGE_2D_ARRAY = 0x905E,
GL_INT_IMAGE_CUBE_MAP_ARRAY = 0x905F,
GL_INT_IMAGE_2D_MULTISAMPLE = 0x9060,
GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY = 0x9061,
GL_UNSIGNED_INT_IMAGE_1D = 0x9062,
GL_UNSIGNED_INT_IMAGE_2D = 0x9063,
GL_UNSIGNED_INT_IMAGE_3D = 0x9064,
GL_UNSIGNED_INT_IMAGE_2D_RECT = 0x9065,
GL_UNSIGNED_INT_IMAGE_CUBE = 0x9066,
GL_UNSIGNED_INT_IMAGE_BUFFER = 0x9067,
GL_UNSIGNED_INT_IMAGE_1D_ARRAY = 0x9068,
GL_UNSIGNED_INT_IMAGE_2D_ARRAY = 0x9069,
GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY = 0x906A,
GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE = 0x906B,
GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY = 0x906C,
GL_MAX_IMAGE_SAMPLES = 0x906D,
GL_IMAGE_BINDING_FORMAT = 0x906E,
GL_IMAGE_FORMAT_COMPATIBILITY_TYPE = 0x90C7,
GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE = 0x90C8,
GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS = 0x90C9,
GL_MAX_VERTEX_IMAGE_UNIFORMS = 0x90CA,
GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS = 0x90CB,
GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS = 0x90CC,
GL_MAX_GEOMETRY_IMAGE_UNIFORMS = 0x90CD,
GL_MAX_FRAGMENT_IMAGE_UNIFORMS = 0x90CE,
GL_MAX_COMBINED_IMAGE_UNIFORMS = 0x90CF,
GL_COMPRESSED_RGBA_BPTC_UNORM = 0x8E8C,
GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM = 0x8E8D,
GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT = 0x8E8E,
GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT = 0x8E8F,
GL_TEXTURE_IMMUTABLE_FORMAT = 0x912F,
GL_VERSION_4_3 = 1,
GL_NUM_SHADING_LANGUAGE_VERSIONS = 0x82E9,
GL_VERTEX_ATTRIB_ARRAY_LONG = 0x874E,
GL_COMPRESSED_RGB8_ETC2 = 0x9274,
GL_COMPRESSED_SRGB8_ETC2 = 0x9275,
GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276,
GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277,
GL_COMPRESSED_RGBA8_ETC2_EAC = 0x9278,
GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279,
GL_COMPRESSED_R11_EAC = 0x9270,
GL_COMPRESSED_SIGNED_R11_EAC = 0x9271,
GL_COMPRESSED_RG11_EAC = 0x9272,
GL_COMPRESSED_SIGNED_RG11_EAC = 0x9273,
GL_PRIMITIVE_RESTART_FIXED_INDEX = 0x8D69,
GL_ANY_SAMPLES_PASSED_CONSERVATIVE = 0x8D6A,
GL_MAX_ELEMENT_INDEX = 0x8D6B,
GL_COMPUTE_SHADER = 0x91B9,
GL_MAX_COMPUTE_UNIFORM_BLOCKS = 0x91BB,
GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS = 0x91BC,
GL_MAX_COMPUTE_IMAGE_UNIFORMS = 0x91BD,
GL_MAX_COMPUTE_SHARED_MEMORY_SIZE = 0x8262,
GL_MAX_COMPUTE_UNIFORM_COMPONENTS = 0x8263,
GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS = 0x8264,
GL_MAX_COMPUTE_ATOMIC_COUNTERS = 0x8265,
GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS = 0x8266,
GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS = 0x90EB,
GL_MAX_COMPUTE_WORK_GROUP_COUNT = 0x91BE,
GL_MAX_COMPUTE_WORK_GROUP_SIZE = 0x91BF,
GL_COMPUTE_WORK_GROUP_SIZE = 0x8267,
GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER = 0x90EC,
GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER = 0x90ED,
GL_DISPATCH_INDIRECT_BUFFER = 0x90EE,
GL_DISPATCH_INDIRECT_BUFFER_BINDING = 0x90EF,
GL_COMPUTE_SHADER_BIT = 0x00000020,
GL_DEBUG_OUTPUT_SYNCHRONOUS = 0x8242,
GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH = 0x8243,
GL_DEBUG_CALLBACK_FUNCTION = 0x8244,
GL_DEBUG_CALLBACK_USER_PARAM = 0x8245,
GL_DEBUG_SOURCE_API = 0x8246,
GL_DEBUG_SOURCE_WINDOW_SYSTEM = 0x8247,
GL_DEBUG_SOURCE_SHADER_COMPILER = 0x8248,
GL_DEBUG_SOURCE_THIRD_PARTY = 0x8249,
GL_DEBUG_SOURCE_APPLICATION = 0x824A,
GL_DEBUG_SOURCE_OTHER = 0x824B,
GL_DEBUG_TYPE_ERROR = 0x824C,
GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR = 0x824D,
GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR = 0x824E,
GL_DEBUG_TYPE_PORTABILITY = 0x824F,
GL_DEBUG_TYPE_PERFORMANCE = 0x8250,
GL_DEBUG_TYPE_OTHER = 0x8251,
GL_MAX_DEBUG_MESSAGE_LENGTH = 0x9143,
GL_MAX_DEBUG_LOGGED_MESSAGES = 0x9144,
GL_DEBUG_LOGGED_MESSAGES = 0x9145,
GL_DEBUG_SEVERITY_HIGH = 0x9146,
GL_DEBUG_SEVERITY_MEDIUM = 0x9147,
GL_DEBUG_SEVERITY_LOW = 0x9148,
GL_DEBUG_TYPE_MARKER = 0x8268,
GL_DEBUG_TYPE_PUSH_GROUP = 0x8269,
GL_DEBUG_TYPE_POP_GROUP = 0x826A,
GL_DEBUG_SEVERITY_NOTIFICATION = 0x826B,
GL_MAX_DEBUG_GROUP_STACK_DEPTH = 0x826C,
GL_DEBUG_GROUP_STACK_DEPTH = 0x826D,
GL_BUFFER = 0x82E0,
GL_SHADER = 0x82E1,
GL_PROGRAM = 0x82E2,
GL_QUERY = 0x82E3,
GL_PROGRAM_PIPELINE = 0x82E4,
GL_SAMPLER = 0x82E6,
GL_MAX_LABEL_LENGTH = 0x82E8,
GL_DEBUG_OUTPUT = 0x92E0,
GL_CONTEXT_FLAG_DEBUG_BIT = 0x00000002,
GL_MAX_UNIFORM_LOCATIONS = 0x826E,
GL_FRAMEBUFFER_DEFAULT_WIDTH = 0x9310,
GL_FRAMEBUFFER_DEFAULT_HEIGHT = 0x9311,
GL_FRAMEBUFFER_DEFAULT_LAYERS = 0x9312,
GL_FRAMEBUFFER_DEFAULT_SAMPLES = 0x9313,
GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS = 0x9314,
GL_MAX_FRAMEBUFFER_WIDTH = 0x9315,
GL_MAX_FRAMEBUFFER_HEIGHT = 0x9316,
GL_MAX_FRAMEBUFFER_LAYERS = 0x9317,
GL_MAX_FRAMEBUFFER_SAMPLES = 0x9318,
GL_INTERNALFORMAT_SUPPORTED = 0x826F,
GL_INTERNALFORMAT_PREFERRED = 0x8270,
GL_INTERNALFORMAT_RED_SIZE = 0x8271,
GL_INTERNALFORMAT_GREEN_SIZE = 0x8272,
GL_INTERNALFORMAT_BLUE_SIZE = 0x8273,
GL_INTERNALFORMAT_ALPHA_SIZE = 0x8274,
GL_INTERNALFORMAT_DEPTH_SIZE = 0x8275,
GL_INTERNALFORMAT_STENCIL_SIZE = 0x8276,
GL_INTERNALFORMAT_SHARED_SIZE = 0x8277,
GL_INTERNALFORMAT_RED_TYPE = 0x8278,
GL_INTERNALFORMAT_GREEN_TYPE = 0x8279,
GL_INTERNALFORMAT_BLUE_TYPE = 0x827A,
GL_INTERNALFORMAT_ALPHA_TYPE = 0x827B,
GL_INTERNALFORMAT_DEPTH_TYPE = 0x827C,
GL_INTERNALFORMAT_STENCIL_TYPE = 0x827D,
GL_MAX_WIDTH = 0x827E,
GL_MAX_HEIGHT = 0x827F,
GL_MAX_DEPTH = 0x8280,
GL_MAX_LAYERS = 0x8281,
GL_MAX_COMBINED_DIMENSIONS = 0x8282,
GL_COLOR_COMPONENTS = 0x8283,
GL_DEPTH_COMPONENTS = 0x8284,
GL_STENCIL_COMPONENTS = 0x8285,
GL_COLOR_RENDERABLE = 0x8286,
GL_DEPTH_RENDERABLE = 0x8287,
GL_STENCIL_RENDERABLE = 0x8288,
GL_FRAMEBUFFER_RENDERABLE = 0x8289,
GL_FRAMEBUFFER_RENDERABLE_LAYERED = 0x828A,
GL_FRAMEBUFFER_BLEND = 0x828B,
GL_READ_PIXELS = 0x828C,
GL_READ_PIXELS_FORMAT = 0x828D,
GL_READ_PIXELS_TYPE = 0x828E,
GL_TEXTURE_IMAGE_FORMAT = 0x828F,
GL_TEXTURE_IMAGE_TYPE = 0x8290,
GL_GET_TEXTURE_IMAGE_FORMAT = 0x8291,
GL_GET_TEXTURE_IMAGE_TYPE = 0x8292,
GL_MIPMAP = 0x8293,
GL_MANUAL_GENERATE_MIPMAP = 0x8294,
GL_AUTO_GENERATE_MIPMAP = 0x8295,
GL_COLOR_ENCODING = 0x8296,
GL_SRGB_READ = 0x8297,
GL_SRGB_WRITE = 0x8298,
GL_FILTER = 0x829A,
GL_VERTEX_TEXTURE = 0x829B,
GL_TESS_CONTROL_TEXTURE = 0x829C,
GL_TESS_EVALUATION_TEXTURE = 0x829D,
GL_GEOMETRY_TEXTURE = 0x829E,
GL_FRAGMENT_TEXTURE = 0x829F,
GL_COMPUTE_TEXTURE = 0x82A0,
GL_TEXTURE_SHADOW = 0x82A1,
GL_TEXTURE_GATHER = 0x82A2,
GL_TEXTURE_GATHER_SHADOW = 0x82A3,
GL_SHADER_IMAGE_LOAD = 0x82A4,
GL_SHADER_IMAGE_STORE = 0x82A5,
GL_SHADER_IMAGE_ATOMIC = 0x82A6,
GL_IMAGE_TEXEL_SIZE = 0x82A7,
GL_IMAGE_COMPATIBILITY_CLASS = 0x82A8,
GL_IMAGE_PIXEL_FORMAT = 0x82A9,
GL_IMAGE_PIXEL_TYPE = 0x82AA,
GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST = 0x82AC,
GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST = 0x82AD,
GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE = 0x82AE,
GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE = 0x82AF,
GL_TEXTURE_COMPRESSED_BLOCK_WIDTH = 0x82B1,
GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT = 0x82B2,
GL_TEXTURE_COMPRESSED_BLOCK_SIZE = 0x82B3,
GL_CLEAR_BUFFER = 0x82B4,
GL_TEXTURE_VIEW = 0x82B5,
GL_VIEW_COMPATIBILITY_CLASS = 0x82B6,
GL_FULL_SUPPORT = 0x82B7,
GL_CAVEAT_SUPPORT = 0x82B8,
GL_IMAGE_CLASS_4_X_32 = 0x82B9,
GL_IMAGE_CLASS_2_X_32 = 0x82BA,
GL_IMAGE_CLASS_1_X_32 = 0x82BB,
GL_IMAGE_CLASS_4_X_16 = 0x82BC,
GL_IMAGE_CLASS_2_X_16 = 0x82BD,
GL_IMAGE_CLASS_1_X_16 = 0x82BE,
GL_IMAGE_CLASS_4_X_8 = 0x82BF,
GL_IMAGE_CLASS_2_X_8 = 0x82C0,
GL_IMAGE_CLASS_1_X_8 = 0x82C1,
GL_IMAGE_CLASS_11_11_10 = 0x82C2,
GL_IMAGE_CLASS_10_10_10_2 = 0x82C3,
GL_VIEW_CLASS_128_BITS = 0x82C4,
GL_VIEW_CLASS_96_BITS = 0x82C5,
GL_VIEW_CLASS_64_BITS = 0x82C6,
GL_VIEW_CLASS_48_BITS = 0x82C7,
GL_VIEW_CLASS_32_BITS = 0x82C8,
GL_VIEW_CLASS_24_BITS = 0x82C9,
GL_VIEW_CLASS_16_BITS = 0x82CA,
GL_VIEW_CLASS_8_BITS = 0x82CB,
GL_VIEW_CLASS_S3TC_DXT1_RGB = 0x82CC,
GL_VIEW_CLASS_S3TC_DXT1_RGBA = 0x82CD,
GL_VIEW_CLASS_S3TC_DXT3_RGBA = 0x82CE,
GL_VIEW_CLASS_S3TC_DXT5_RGBA = 0x82CF,
GL_VIEW_CLASS_RGTC1_RED = 0x82D0,
GL_VIEW_CLASS_RGTC2_RG = 0x82D1,
GL_VIEW_CLASS_BPTC_UNORM = 0x82D2,
GL_VIEW_CLASS_BPTC_FLOAT = 0x82D3,
GL_UNIFORM = 0x92E1,
GL_UNIFORM_BLOCK = 0x92E2,
GL_PROGRAM_INPUT = 0x92E3,
GL_PROGRAM_OUTPUT = 0x92E4,
GL_BUFFER_VARIABLE = 0x92E5,
GL_SHADER_STORAGE_BLOCK = 0x92E6,
GL_VERTEX_SUBROUTINE = 0x92E8,
GL_TESS_CONTROL_SUBROUTINE = 0x92E9,
GL_TESS_EVALUATION_SUBROUTINE = 0x92EA,
GL_GEOMETRY_SUBROUTINE = 0x92EB,
GL_FRAGMENT_SUBROUTINE = 0x92EC,
GL_COMPUTE_SUBROUTINE = 0x92ED,
GL_VERTEX_SUBROUTINE_UNIFORM = 0x92EE,
GL_TESS_CONTROL_SUBROUTINE_UNIFORM = 0x92EF,
GL_TESS_EVALUATION_SUBROUTINE_UNIFORM = 0x92F0,
GL_GEOMETRY_SUBROUTINE_UNIFORM = 0x92F1,
GL_FRAGMENT_SUBROUTINE_UNIFORM = 0x92F2,
GL_COMPUTE_SUBROUTINE_UNIFORM = 0x92F3,
GL_TRANSFORM_FEEDBACK_VARYING = 0x92F4,
GL_ACTIVE_RESOURCES = 0x92F5,
GL_MAX_NAME_LENGTH = 0x92F6,
GL_MAX_NUM_ACTIVE_VARIABLES = 0x92F7,
GL_MAX_NUM_COMPATIBLE_SUBROUTINES = 0x92F8,
GL_NAME_LENGTH = 0x92F9,
GL_TYPE = 0x92FA,
GL_ARRAY_SIZE = 0x92FB,
GL_OFFSET = 0x92FC,
GL_BLOCK_INDEX = 0x92FD,
GL_ARRAY_STRIDE = 0x92FE,
GL_MATRIX_STRIDE = 0x92FF,
GL_IS_ROW_MAJOR = 0x9300,
GL_ATOMIC_COUNTER_BUFFER_INDEX = 0x9301,
GL_BUFFER_BINDING = 0x9302,
GL_BUFFER_DATA_SIZE = 0x9303,
GL_NUM_ACTIVE_VARIABLES = 0x9304,
GL_ACTIVE_VARIABLES = 0x9305,
GL_REFERENCED_BY_VERTEX_SHADER = 0x9306,
GL_REFERENCED_BY_TESS_CONTROL_SHADER = 0x9307,
GL_REFERENCED_BY_TESS_EVALUATION_SHADER = 0x9308,
GL_REFERENCED_BY_GEOMETRY_SHADER = 0x9309,
GL_REFERENCED_BY_FRAGMENT_SHADER = 0x930A,
GL_REFERENCED_BY_COMPUTE_SHADER = 0x930B,
GL_TOP_LEVEL_ARRAY_SIZE = 0x930C,
GL_TOP_LEVEL_ARRAY_STRIDE = 0x930D,
GL_LOCATION = 0x930E,
GL_LOCATION_INDEX = 0x930F,
GL_IS_PER_PATCH = 0x92E7,
GL_SHADER_STORAGE_BUFFER = 0x90D2,
GL_SHADER_STORAGE_BUFFER_BINDING = 0x90D3,
GL_SHADER_STORAGE_BUFFER_START = 0x90D4,
GL_SHADER_STORAGE_BUFFER_SIZE = 0x90D5,
GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS = 0x90D6,
GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS = 0x90D7,
GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS = 0x90D8,
GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS = 0x90D9,
GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS = 0x90DA,
GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS = 0x90DB,
GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS = 0x90DC,
GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS = 0x90DD,
GL_MAX_SHADER_STORAGE_BLOCK_SIZE = 0x90DE,
GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT = 0x90DF,
GL_SHADER_STORAGE_BARRIER_BIT = 0x00002000,
GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES = 0x8F39,
GL_DEPTH_STENCIL_TEXTURE_MODE = 0x90EA,
GL_TEXTURE_BUFFER_OFFSET = 0x919D,
GL_TEXTURE_BUFFER_SIZE = 0x919E,
GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT = 0x919F,
GL_TEXTURE_VIEW_MIN_LEVEL = 0x82DB,
GL_TEXTURE_VIEW_NUM_LEVELS = 0x82DC,
GL_TEXTURE_VIEW_MIN_LAYER = 0x82DD,
GL_TEXTURE_VIEW_NUM_LAYERS = 0x82DE,
GL_TEXTURE_IMMUTABLE_LEVELS = 0x82DF,
GL_VERTEX_ATTRIB_BINDING = 0x82D4,
GL_VERTEX_ATTRIB_RELATIVE_OFFSET = 0x82D5,
GL_VERTEX_BINDING_DIVISOR = 0x82D6,
GL_VERTEX_BINDING_OFFSET = 0x82D7,
GL_VERTEX_BINDING_STRIDE = 0x82D8,
GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET = 0x82D9,
GL_MAX_VERTEX_ATTRIB_BINDINGS = 0x82DA,
GL_VERTEX_BINDING_BUFFER = 0x8F4F,
GL_VERSION_4_4 = 1,
GL_MAX_VERTEX_ATTRIB_STRIDE = 0x82E5,
GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED = 0x8221,
GL_TEXTURE_BUFFER_BINDING = 0x8C2A,
GL_MAP_PERSISTENT_BIT = 0x0040,
GL_MAP_COHERENT_BIT = 0x0080,
GL_DYNAMIC_STORAGE_BIT = 0x0100,
GL_CLIENT_STORAGE_BIT = 0x0200,
GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT = 0x00004000,
GL_BUFFER_IMMUTABLE_STORAGE = 0x821F,
GL_BUFFER_STORAGE_FLAGS = 0x8220,
GL_CLEAR_TEXTURE = 0x9365,
GL_LOCATION_COMPONENT = 0x934A,
GL_TRANSFORM_FEEDBACK_BUFFER_INDEX = 0x934B,
GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE = 0x934C,
GL_QUERY_BUFFER = 0x9192,
GL_QUERY_BUFFER_BARRIER_BIT = 0x00008000,
GL_QUERY_BUFFER_BINDING = 0x9193,
GL_QUERY_RESULT_NO_WAIT = 0x9194,
GL_MIRROR_CLAMP_TO_EDGE = 0x8743,
GL_VERSION_4_5 = 1,
GL_CONTEXT_LOST = 0x0507,
GL_NEGATIVE_ONE_TO_ONE = 0x935E,
GL_ZERO_TO_ONE = 0x935F,
GL_CLIP_ORIGIN = 0x935C,
GL_CLIP_DEPTH_MODE = 0x935D,
GL_QUERY_WAIT_INVERTED = 0x8E17,
GL_QUERY_NO_WAIT_INVERTED = 0x8E18,
GL_QUERY_BY_REGION_WAIT_INVERTED = 0x8E19,
GL_QUERY_BY_REGION_NO_WAIT_INVERTED = 0x8E1A,
GL_MAX_CULL_DISTANCES = 0x82F9,
GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES = 0x82FA,
GL_TEXTURE_TARGET = 0x1006,
GL_QUERY_TARGET = 0x82EA,
GL_GUILTY_CONTEXT_RESET = 0x8253,
GL_INNOCENT_CONTEXT_RESET = 0x8254,
GL_UNKNOWN_CONTEXT_RESET = 0x8255,
GL_RESET_NOTIFICATION_STRATEGY = 0x8256,
GL_LOSE_CONTEXT_ON_RESET = 0x8252,
GL_NO_RESET_NOTIFICATION = 0x8261,
GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT = 0x00000004,
GL_CONTEXT_RELEASE_BEHAVIOR = 0x82FB,
GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH = 0x82FC,
GL_ARB_ES2_compatibility = 1,
GL_ARB_ES3_1_compatibility = 1,
GL_ARB_ES3_compatibility = 1,
GL_ARB_arrays_of_arrays = 1,
GL_ARB_base_instance = 1,
GL_ARB_bindless_texture = 1,
GL_UNSIGNED_INT64_ARB = 0x140F,
GL_ARB_blend_func_extended = 1,
GL_ARB_buffer_storage = 1,
GL_ARB_cl_event = 1,
GL_SYNC_CL_EVENT_ARB = 0x8240,
GL_SYNC_CL_EVENT_COMPLETE_ARB = 0x8241,
GL_ARB_clear_buffer_object = 1,
GL_ARB_clear_texture = 1,
GL_ARB_clip_control = 1,
GL_ARB_compressed_texture_pixel_storage = 1,
GL_ARB_compute_shader = 1,
GL_ARB_compute_variable_group_size = 1,
GL_MAX_COMPUTE_VARIABLE_GROUP_INVOCATIONS_ARB = 0x9344,
GL_MAX_COMPUTE_FIXED_GROUP_INVOCATIONS_ARB = 0x90EB,
GL_MAX_COMPUTE_VARIABLE_GROUP_SIZE_ARB = 0x9345,
GL_MAX_COMPUTE_FIXED_GROUP_SIZE_ARB = 0x91BF,
GL_ARB_conditional_render_inverted = 1,
GL_ARB_conservative_depth = 1,
GL_ARB_copy_buffer = 1,
GL_ARB_copy_image = 1,
GL_ARB_cull_distance = 1,
GL_ARB_debug_output = 1,
GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB = 0x8242,
GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB = 0x8243,
GL_DEBUG_CALLBACK_FUNCTION_ARB = 0x8244,
GL_DEBUG_CALLBACK_USER_PARAM_ARB = 0x8245,
GL_DEBUG_SOURCE_API_ARB = 0x8246,
GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB = 0x8247,
GL_DEBUG_SOURCE_SHADER_COMPILER_ARB = 0x8248,
GL_DEBUG_SOURCE_THIRD_PARTY_ARB = 0x8249,
GL_DEBUG_SOURCE_APPLICATION_ARB = 0x824A,
GL_DEBUG_SOURCE_OTHER_ARB = 0x824B,
GL_DEBUG_TYPE_ERROR_ARB = 0x824C,
GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB = 0x824D,
GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB = 0x824E,
GL_DEBUG_TYPE_PORTABILITY_ARB = 0x824F,
GL_DEBUG_TYPE_PERFORMANCE_ARB = 0x8250,
GL_DEBUG_TYPE_OTHER_ARB = 0x8251,
GL_MAX_DEBUG_MESSAGE_LENGTH_ARB = 0x9143,
GL_MAX_DEBUG_LOGGED_MESSAGES_ARB = 0x9144,
GL_DEBUG_LOGGED_MESSAGES_ARB = 0x9145,
GL_DEBUG_SEVERITY_HIGH_ARB = 0x9146,
GL_DEBUG_SEVERITY_MEDIUM_ARB = 0x9147,
GL_DEBUG_SEVERITY_LOW_ARB = 0x9148,
GL_ARB_depth_buffer_float = 1,
GL_ARB_depth_clamp = 1,
GL_ARB_derivative_control = 1,
GL_ARB_direct_state_access = 1,
GL_ARB_draw_buffers_blend = 1,
GL_ARB_draw_elements_base_vertex = 1,
GL_ARB_draw_indirect = 1,
GL_ARB_enhanced_layouts = 1,
GL_ARB_explicit_attrib_location = 1,
GL_ARB_explicit_uniform_location = 1,
GL_ARB_fragment_coord_conventions = 1,
GL_ARB_fragment_layer_viewport = 1,
GL_ARB_framebuffer_no_attachments = 1,
GL_ARB_framebuffer_object = 1,
GL_ARB_framebuffer_sRGB = 1,
GL_ARB_get_program_binary = 1,
GL_ARB_get_texture_sub_image = 1,
GL_ARB_gpu_shader5 = 1,
GL_ARB_gpu_shader_fp64 = 1,
GL_ARB_half_float_vertex = 1,
GL_ARB_imaging = 1,
GL_BLEND_COLOR = 0x8005,
GL_BLEND_EQUATION = 0x8009,
GL_ARB_indirect_parameters = 1,
GL_PARAMETER_BUFFER_ARB = 0x80EE,
GL_PARAMETER_BUFFER_BINDING_ARB = 0x80EF,
GL_ARB_internalformat_query = 1,
GL_ARB_internalformat_query2 = 1,
GL_SRGB_DECODE_ARB = 0x8299,
GL_ARB_invalidate_subdata = 1,
GL_ARB_map_buffer_alignment = 1,
GL_ARB_map_buffer_range = 1,
GL_ARB_multi_bind = 1,
GL_ARB_multi_draw_indirect = 1,
GL_ARB_occlusion_query2 = 1,
GL_ARB_pipeline_statistics_query = 1,
GL_VERTICES_SUBMITTED_ARB = 0x82EE,
GL_PRIMITIVES_SUBMITTED_ARB = 0x82EF,
GL_VERTEX_SHADER_INVOCATIONS_ARB = 0x82F0,
GL_TESS_CONTROL_SHADER_PATCHES_ARB = 0x82F1,
GL_TESS_EVALUATION_SHADER_INVOCATIONS_ARB = 0x82F2,
GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED_ARB = 0x82F3,
GL_FRAGMENT_SHADER_INVOCATIONS_ARB = 0x82F4,
GL_COMPUTE_SHADER_INVOCATIONS_ARB = 0x82F5,
GL_CLIPPING_INPUT_PRIMITIVES_ARB = 0x82F6,
GL_CLIPPING_OUTPUT_PRIMITIVES_ARB = 0x82F7,
GL_ARB_program_interface_query = 1,
GL_ARB_provoking_vertex = 1,
GL_ARB_query_buffer_object = 1,
GL_ARB_robust_buffer_access_behavior = 1,
GL_ARB_robustness = 1,
GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB = 0x00000004,
GL_LOSE_CONTEXT_ON_RESET_ARB = 0x8252,
GL_GUILTY_CONTEXT_RESET_ARB = 0x8253,
GL_INNOCENT_CONTEXT_RESET_ARB = 0x8254,
GL_UNKNOWN_CONTEXT_RESET_ARB = 0x8255,
GL_RESET_NOTIFICATION_STRATEGY_ARB = 0x8256,
GL_NO_RESET_NOTIFICATION_ARB = 0x8261,
GL_ARB_robustness_isolation = 1,
GL_ARB_sample_shading = 1,
GL_SAMPLE_SHADING_ARB = 0x8C36,
GL_MIN_SAMPLE_SHADING_VALUE_ARB = 0x8C37,
GL_ARB_sampler_objects = 1,
GL_ARB_seamless_cube_map = 1,
GL_ARB_seamless_cubemap_per_texture = 1,
GL_ARB_separate_shader_objects = 1,
GL_ARB_shader_atomic_counters = 1,
GL_ARB_shader_bit_encoding = 1,
GL_ARB_shader_draw_parameters = 1,
GL_ARB_shader_group_vote = 1,
GL_ARB_shader_image_load_store = 1,
GL_ARB_shader_image_size = 1,
GL_ARB_shader_precision = 1,
GL_ARB_shader_stencil_export = 1,
GL_ARB_shader_storage_buffer_object = 1,
GL_ARB_shader_subroutine = 1,
GL_ARB_shader_texture_image_samples = 1,
GL_ARB_shading_language_420pack = 1,
GL_ARB_shading_language_include = 1,
GL_SHADER_INCLUDE_ARB = 0x8DAE,
GL_NAMED_STRING_LENGTH_ARB = 0x8DE9,
GL_NAMED_STRING_TYPE_ARB = 0x8DEA,
GL_ARB_shading_language_packing = 1,
GL_ARB_sparse_buffer = 1,
GL_SPARSE_STORAGE_BIT_ARB = 0x0400,
GL_SPARSE_BUFFER_PAGE_SIZE_ARB = 0x82F8,
GL_ARB_sparse_texture = 1,
GL_TEXTURE_SPARSE_ARB = 0x91A6,
GL_VIRTUAL_PAGE_SIZE_INDEX_ARB = 0x91A7,
GL_NUM_SPARSE_LEVELS_ARB = 0x91AA,
GL_NUM_VIRTUAL_PAGE_SIZES_ARB = 0x91A8,
GL_VIRTUAL_PAGE_SIZE_X_ARB = 0x9195,
GL_VIRTUAL_PAGE_SIZE_Y_ARB = 0x9196,
GL_VIRTUAL_PAGE_SIZE_Z_ARB = 0x9197,
GL_MAX_SPARSE_TEXTURE_SIZE_ARB = 0x9198,
GL_MAX_SPARSE_3D_TEXTURE_SIZE_ARB = 0x9199,
GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_ARB = 0x919A,
GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_ARB = 0x91A9,
GL_ARB_sparse_texture2 = 1,
GL_ARB_stencil_texturing = 1,
GL_ARB_sync = 1,
GL_ARB_tessellation_shader = 1,
GL_ARB_texture_barrier = 1,
GL_ARB_texture_buffer_object_rgb32 = 1,
GL_ARB_texture_buffer_range = 1,
GL_ARB_texture_compression_bptc = 1,
GL_COMPRESSED_RGBA_BPTC_UNORM_ARB = 0x8E8C,
GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB = 0x8E8D,
GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB = 0x8E8E,
GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB = 0x8E8F,
GL_ARB_texture_compression_rgtc = 1,
GL_ARB_texture_cube_map_array = 1,
GL_TEXTURE_CUBE_MAP_ARRAY_ARB = 0x9009,
GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB = 0x900A,
GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB = 0x900B,
GL_SAMPLER_CUBE_MAP_ARRAY_ARB = 0x900C,
GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB = 0x900D,
GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB = 0x900E,
GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB = 0x900F,
GL_ARB_texture_gather = 1,
GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB = 0x8E5E,
GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB = 0x8E5F,
GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS_ARB = 0x8F9F,
GL_ARB_texture_mirror_clamp_to_edge = 1,
GL_ARB_texture_multisample = 1,
GL_ARB_texture_query_levels = 1,
GL_ARB_texture_query_lod = 1,
GL_ARB_texture_rg = 1,
GL_ARB_texture_rgb10_a2ui = 1,
GL_ARB_texture_stencil8 = 1,
GL_ARB_texture_storage = 1,
GL_ARB_texture_storage_multisample = 1,
GL_ARB_texture_swizzle = 1,
GL_ARB_texture_view = 1,
GL_ARB_timer_query = 1,
GL_ARB_transform_feedback2 = 1,
GL_ARB_transform_feedback3 = 1,
GL_ARB_transform_feedback_instanced = 1,
GL_ARB_transform_feedback_overflow_query = 1,
GL_TRANSFORM_FEEDBACK_OVERFLOW_ARB = 0x82EC,
GL_TRANSFORM_FEEDBACK_STREAM_OVERFLOW_ARB = 0x82ED,
GL_ARB_uniform_buffer_object = 1,
GL_ARB_vertex_array_bgra = 1,
GL_ARB_vertex_array_object = 1,
GL_ARB_vertex_attrib_64bit = 1,
GL_ARB_vertex_attrib_binding = 1,
GL_ARB_vertex_type_10f_11f_11f_rev = 1,
GL_ARB_vertex_type_2_10_10_10_rev = 1,
GL_ARB_viewport_array = 1,
GL_KHR_blend_equation_advanced = 1,
GL_MULTIPLY_KHR = 0x9294,
GL_SCREEN_KHR = 0x9295,
GL_OVERLAY_KHR = 0x9296,
GL_DARKEN_KHR = 0x9297,
GL_LIGHTEN_KHR = 0x9298,
GL_COLORDODGE_KHR = 0x9299,
GL_COLORBURN_KHR = 0x929A,
GL_HARDLIGHT_KHR = 0x929B,
GL_SOFTLIGHT_KHR = 0x929C,
GL_DIFFERENCE_KHR = 0x929E,
GL_EXCLUSION_KHR = 0x92A0,
GL_HSL_HUE_KHR = 0x92AD,
GL_HSL_SATURATION_KHR = 0x92AE,
GL_HSL_COLOR_KHR = 0x92AF,
GL_HSL_LUMINOSITY_KHR = 0x92B0,
GL_KHR_blend_equation_advanced_coherent = 1,
GL_BLEND_ADVANCED_COHERENT_KHR = 0x9285,
GL_KHR_context_flush_control = 1,
GL_KHR_debug = 1,
GL_KHR_no_error = 1,
GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR = 0x00000008,
GL_KHR_robust_buffer_access_behavior = 1,
GL_KHR_robustness = 1,
GL_CONTEXT_ROBUST_ACCESS = 0x90F3,
GL_KHR_texture_compression_astc_hdr = 1,
GL_COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93B0,
GL_COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93B1,
GL_COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93B2,
GL_COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93B3,
GL_COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93B4,
GL_COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93B5,
GL_COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93B6,
GL_COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93B7,
GL_COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93B8,
GL_COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93B9,
GL_COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93BA,
GL_COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93BB,
GL_COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93BC,
GL_COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93BD,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93D0,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93D1,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93D2,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93D3,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93D4,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93D5,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93D6,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93D7,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93D8,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93D9,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93DA,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93DB,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93DC,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93DD,
GL_KHR_texture_compression_astc_ldr = 1,
GL_KHR_texture_compression_astc_sliced_3d = 1,
GL_AMD_performance_monitor = 1,
GL_COUNTER_TYPE_AMD = 0x8BC0,
GL_COUNTER_RANGE_AMD = 0x8BC1,
GL_UNSIGNED_INT64_AMD = 0x8BC2,
GL_PERCENTAGE_AMD = 0x8BC3,
GL_PERFMON_RESULT_AVAILABLE_AMD = 0x8BC4,
GL_PERFMON_RESULT_SIZE_AMD = 0x8BC5,
GL_PERFMON_RESULT_AMD = 0x8BC6,
GL_APPLE_rgb_422 = 1,
GL_RGB_422_APPLE = 0x8A1F,
GL_UNSIGNED_SHORT_8_8_APPLE = 0x85BA,
GL_UNSIGNED_SHORT_8_8_REV_APPLE = 0x85BB,
GL_RGB_RAW_422_APPLE = 0x8A51,
GL_EXT_debug_label = 1,
GL_PROGRAM_PIPELINE_OBJECT_EXT = 0x8A4F,
GL_PROGRAM_OBJECT_EXT = 0x8B40,
GL_SHADER_OBJECT_EXT = 0x8B48,
GL_BUFFER_OBJECT_EXT = 0x9151,
GL_QUERY_OBJECT_EXT = 0x9153,
GL_VERTEX_ARRAY_OBJECT_EXT = 0x9154,
GL_EXT_debug_marker = 1,
GL_EXT_draw_instanced = 1,
GL_EXT_polygon_offset_clamp = 1,
GL_POLYGON_OFFSET_CLAMP_EXT = 0x8E1B,
GL_EXT_post_depth_coverage = 1,
GL_EXT_raster_multisample = 1,
GL_RASTER_MULTISAMPLE_EXT = 0x9327,
GL_RASTER_SAMPLES_EXT = 0x9328,
GL_MAX_RASTER_SAMPLES_EXT = 0x9329,
GL_RASTER_FIXED_SAMPLE_LOCATIONS_EXT = 0x932A,
GL_MULTISAMPLE_RASTERIZATION_ALLOWED_EXT = 0x932B,
GL_EFFECTIVE_RASTER_SAMPLES_EXT = 0x932C,
GL_EXT_separate_shader_objects = 1,
GL_ACTIVE_PROGRAM_EXT = 0x8B8D,
GL_EXT_shader_integer_mix = 1,
GL_EXT_texture_compression_s3tc = 1,
GL_COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0,
GL_COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1,
GL_COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2,
GL_COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3,
GL_EXT_texture_filter_minmax = 1,
GL_EXT_texture_sRGB_decode = 1,
GL_TEXTURE_SRGB_DECODE_EXT = 0x8A48,
GL_DECODE_EXT = 0x8A49,
GL_SKIP_DECODE_EXT = 0x8A4A,
GL_EXT_window_rectangles = 1,
GL_INCLUSIVE_EXT = 0x8F10,
GL_EXCLUSIVE_EXT = 0x8F11,
GL_WINDOW_RECTANGLE_EXT = 0x8F12,
GL_WINDOW_RECTANGLE_MODE_EXT = 0x8F13,
GL_MAX_WINDOW_RECTANGLES_EXT = 0x8F14,
GL_NUM_WINDOW_RECTANGLES_EXT = 0x8F15,
GL_INTEL_conservative_rasterization = 1,
GL_CONSERVATIVE_RASTERIZATION_INTEL = 0x83FE,
GL_INTEL_framebuffer_CMAA = 1,
GL_INTEL_performance_query = 1,
GL_PERFQUERY_SINGLE_CONTEXT_INTEL = 0x00000000,
GL_PERFQUERY_GLOBAL_CONTEXT_INTEL = 0x00000001,
GL_PERFQUERY_WAIT_INTEL = 0x83FB,
GL_PERFQUERY_FLUSH_INTEL = 0x83FA,
GL_PERFQUERY_DONOT_FLUSH_INTEL = 0x83F9,
GL_PERFQUERY_COUNTER_EVENT_INTEL = 0x94F0,
GL_PERFQUERY_COUNTER_DURATION_NORM_INTEL = 0x94F1,
GL_PERFQUERY_COUNTER_DURATION_RAW_INTEL = 0x94F2,
GL_PERFQUERY_COUNTER_THROUGHPUT_INTEL = 0x94F3,
GL_PERFQUERY_COUNTER_RAW_INTEL = 0x94F4,
GL_PERFQUERY_COUNTER_TIMESTAMP_INTEL = 0x94F5,
GL_PERFQUERY_COUNTER_DATA_UINT32_INTEL = 0x94F8,
GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL = 0x94F9,
GL_PERFQUERY_COUNTER_DATA_FLOAT_INTEL = 0x94FA,
GL_PERFQUERY_COUNTER_DATA_DOUBLE_INTEL = 0x94FB,
GL_PERFQUERY_COUNTER_DATA_BOOL32_INTEL = 0x94FC,
GL_PERFQUERY_QUERY_NAME_LENGTH_MAX_INTEL = 0x94FD,
GL_PERFQUERY_COUNTER_NAME_LENGTH_MAX_INTEL = 0x94FE,
GL_PERFQUERY_COUNTER_DESC_LENGTH_MAX_INTEL = 0x94FF,
GL_PERFQUERY_GPA_EXTENDED_COUNTERS_INTEL = 0x9500,
GL_NV_bindless_texture = 1,
GL_NV_blend_equation_advanced = 1,
GL_BLEND_OVERLAP_NV = 0x9281,
GL_BLEND_PREMULTIPLIED_SRC_NV = 0x9280,
GL_BLUE_NV = 0x1905,
GL_COLORBURN_NV = 0x929A,
GL_COLORDODGE_NV = 0x9299,
GL_CONJOINT_NV = 0x9284,
GL_CONTRAST_NV = 0x92A1,
GL_DARKEN_NV = 0x9297,
GL_DIFFERENCE_NV = 0x929E,
GL_DISJOINT_NV = 0x9283,
GL_DST_ATOP_NV = 0x928F,
GL_DST_IN_NV = 0x928B,
GL_DST_NV = 0x9287,
GL_DST_OUT_NV = 0x928D,
GL_DST_OVER_NV = 0x9289,
GL_EXCLUSION_NV = 0x92A0,
GL_GREEN_NV = 0x1904,
GL_HARDLIGHT_NV = 0x929B,
GL_HARDMIX_NV = 0x92A9,
GL_HSL_COLOR_NV = 0x92AF,
GL_HSL_HUE_NV = 0x92AD,
GL_HSL_LUMINOSITY_NV = 0x92B0,
GL_HSL_SATURATION_NV = 0x92AE,
GL_INVERT_OVG_NV = 0x92B4,
GL_INVERT_RGB_NV = 0x92A3,
GL_LIGHTEN_NV = 0x9298,
GL_LINEARBURN_NV = 0x92A5,
GL_LINEARDODGE_NV = 0x92A4,
GL_LINEARLIGHT_NV = 0x92A7,
GL_MINUS_CLAMPED_NV = 0x92B3,
GL_MINUS_NV = 0x929F,
GL_MULTIPLY_NV = 0x9294,
GL_OVERLAY_NV = 0x9296,
GL_PINLIGHT_NV = 0x92A8,
GL_PLUS_CLAMPED_ALPHA_NV = 0x92B2,
GL_PLUS_CLAMPED_NV = 0x92B1,
GL_PLUS_DARKER_NV = 0x9292,
GL_PLUS_NV = 0x9291,
GL_RED_NV = 0x1903,
GL_SCREEN_NV = 0x9295,
GL_SOFTLIGHT_NV = 0x929C,
GL_SRC_ATOP_NV = 0x928E,
GL_SRC_IN_NV = 0x928A,
GL_SRC_NV = 0x9286,
GL_SRC_OUT_NV = 0x928C,
GL_SRC_OVER_NV = 0x9288,
GL_UNCORRELATED_NV = 0x9282,
GL_VIVIDLIGHT_NV = 0x92A6,
GL_XOR_NV = 0x1506,
GL_NV_blend_equation_advanced_coherent = 1,
GL_BLEND_ADVANCED_COHERENT_NV = 0x9285,
GL_NV_conditional_render = 1,
GL_QUERY_WAIT_NV = 0x8E13,
GL_QUERY_NO_WAIT_NV = 0x8E14,
GL_QUERY_BY_REGION_WAIT_NV = 0x8E15,
GL_QUERY_BY_REGION_NO_WAIT_NV = 0x8E16,
GL_NV_conservative_raster = 1,
GL_CONSERVATIVE_RASTERIZATION_NV = 0x9346,
GL_SUBPIXEL_PRECISION_BIAS_X_BITS_NV = 0x9347,
GL_SUBPIXEL_PRECISION_BIAS_Y_BITS_NV = 0x9348,
GL_MAX_SUBPIXEL_PRECISION_BIAS_BITS_NV = 0x9349,
GL_NV_conservative_raster_pre_snap_triangles = 1,
GL_CONSERVATIVE_RASTER_MODE_NV = 0x954D,
GL_CONSERVATIVE_RASTER_MODE_POST_SNAP_NV = 0x954E,
GL_CONSERVATIVE_RASTER_MODE_PRE_SNAP_TRIANGLES_NV = 0x954F,
GL_NV_fill_rectangle = 1,
GL_FILL_RECTANGLE_NV = 0x933C,
GL_NV_fragment_coverage_to_color = 1,
GL_FRAGMENT_COVERAGE_TO_COLOR_NV = 0x92DD,
GL_FRAGMENT_COVERAGE_COLOR_NV = 0x92DE,
GL_NV_fragment_shader_interlock = 1,
GL_NV_framebuffer_mixed_samples = 1,
GL_COVERAGE_MODULATION_TABLE_NV = 0x9331,
GL_COLOR_SAMPLES_NV = 0x8E20,
GL_DEPTH_SAMPLES_NV = 0x932D,
GL_STENCIL_SAMPLES_NV = 0x932E,
GL_MIXED_DEPTH_SAMPLES_SUPPORTED_NV = 0x932F,
GL_MIXED_STENCIL_SAMPLES_SUPPORTED_NV = 0x9330,
GL_COVERAGE_MODULATION_NV = 0x9332,
GL_COVERAGE_MODULATION_TABLE_SIZE_NV = 0x9333,
GL_NV_geometry_shader_passthrough = 1,
GL_NV_gpu_shader5 = 1,
GL_INT64_NV = 0x140E,
GL_UNSIGNED_INT64_NV = 0x140F,
GL_INT8_NV = 0x8FE0,
GL_INT8_VEC2_NV = 0x8FE1,
GL_INT8_VEC3_NV = 0x8FE2,
GL_INT8_VEC4_NV = 0x8FE3,
GL_INT16_NV = 0x8FE4,
GL_INT16_VEC2_NV = 0x8FE5,
GL_INT16_VEC3_NV = 0x8FE6,
GL_INT16_VEC4_NV = 0x8FE7,
GL_INT64_VEC2_NV = 0x8FE9,
GL_INT64_VEC3_NV = 0x8FEA,
GL_INT64_VEC4_NV = 0x8FEB,
GL_UNSIGNED_INT8_NV = 0x8FEC,
GL_UNSIGNED_INT8_VEC2_NV = 0x8FED,
GL_UNSIGNED_INT8_VEC3_NV = 0x8FEE,
GL_UNSIGNED_INT8_VEC4_NV = 0x8FEF,
GL_UNSIGNED_INT16_NV = 0x8FF0,
GL_UNSIGNED_INT16_VEC2_NV = 0x8FF1,
GL_UNSIGNED_INT16_VEC3_NV = 0x8FF2,
GL_UNSIGNED_INT16_VEC4_NV = 0x8FF3,
GL_UNSIGNED_INT64_VEC2_NV = 0x8FF5,
GL_UNSIGNED_INT64_VEC3_NV = 0x8FF6,
GL_UNSIGNED_INT64_VEC4_NV = 0x8FF7,
GL_FLOAT16_NV = 0x8FF8,
GL_FLOAT16_VEC2_NV = 0x8FF9,
GL_FLOAT16_VEC3_NV = 0x8FFA,
GL_FLOAT16_VEC4_NV = 0x8FFB,
GL_NV_internalformat_sample_query = 1,
GL_MULTISAMPLES_NV = 0x9371,
GL_SUPERSAMPLE_SCALE_X_NV = 0x9372,
GL_SUPERSAMPLE_SCALE_Y_NV = 0x9373,
GL_CONFORMANT_NV = 0x9374,
GL_NV_path_rendering = 1,
GL_PATH_FORMAT_SVG_NV = 0x9070,
GL_PATH_FORMAT_PS_NV = 0x9071,
GL_STANDARD_FONT_NAME_NV = 0x9072,
GL_SYSTEM_FONT_NAME_NV = 0x9073,
GL_FILE_NAME_NV = 0x9074,
GL_PATH_STROKE_WIDTH_NV = 0x9075,
GL_PATH_END_CAPS_NV = 0x9076,
GL_PATH_INITIAL_END_CAP_NV = 0x9077,
GL_PATH_TERMINAL_END_CAP_NV = 0x9078,
GL_PATH_JOIN_STYLE_NV = 0x9079,
GL_PATH_MITER_LIMIT_NV = 0x907A,
GL_PATH_DASH_CAPS_NV = 0x907B,
GL_PATH_INITIAL_DASH_CAP_NV = 0x907C,
GL_PATH_TERMINAL_DASH_CAP_NV = 0x907D,
GL_PATH_DASH_OFFSET_NV = 0x907E,
GL_PATH_CLIENT_LENGTH_NV = 0x907F,
GL_PATH_FILL_MODE_NV = 0x9080,
GL_PATH_FILL_MASK_NV = 0x9081,
GL_PATH_FILL_COVER_MODE_NV = 0x9082,
GL_PATH_STROKE_COVER_MODE_NV = 0x9083,
GL_PATH_STROKE_MASK_NV = 0x9084,
GL_COUNT_UP_NV = 0x9088,
GL_COUNT_DOWN_NV = 0x9089,
GL_PATH_OBJECT_BOUNDING_BOX_NV = 0x908A,
GL_CONVEX_HULL_NV = 0x908B,
GL_BOUNDING_BOX_NV = 0x908D,
GL_TRANSLATE_X_NV = 0x908E,
GL_TRANSLATE_Y_NV = 0x908F,
GL_TRANSLATE_2D_NV = 0x9090,
GL_TRANSLATE_3D_NV = 0x9091,
GL_AFFINE_2D_NV = 0x9092,
GL_AFFINE_3D_NV = 0x9094,
GL_TRANSPOSE_AFFINE_2D_NV = 0x9096,
GL_TRANSPOSE_AFFINE_3D_NV = 0x9098,
GL_UTF8_NV = 0x909A,
GL_UTF16_NV = 0x909B,
GL_BOUNDING_BOX_OF_BOUNDING_BOXES_NV = 0x909C,
GL_PATH_COMMAND_COUNT_NV = 0x909D,
GL_PATH_COORD_COUNT_NV = 0x909E,
GL_PATH_DASH_ARRAY_COUNT_NV = 0x909F,
GL_PATH_COMPUTED_LENGTH_NV = 0x90A0,
GL_PATH_FILL_BOUNDING_BOX_NV = 0x90A1,
GL_PATH_STROKE_BOUNDING_BOX_NV = 0x90A2,
GL_SQUARE_NV = 0x90A3,
GL_ROUND_NV = 0x90A4,
GL_TRIANGULAR_NV = 0x90A5,
GL_BEVEL_NV = 0x90A6,
GL_MITER_REVERT_NV = 0x90A7,
GL_MITER_TRUNCATE_NV = 0x90A8,
GL_SKIP_MISSING_GLYPH_NV = 0x90A9,
GL_USE_MISSING_GLYPH_NV = 0x90AA,
GL_PATH_ERROR_POSITION_NV = 0x90AB,
GL_ACCUM_ADJACENT_PAIRS_NV = 0x90AD,
GL_ADJACENT_PAIRS_NV = 0x90AE,
GL_FIRST_TO_REST_NV = 0x90AF,
GL_PATH_GEN_MODE_NV = 0x90B0,
GL_PATH_GEN_COEFF_NV = 0x90B1,
GL_PATH_GEN_COMPONENTS_NV = 0x90B3,
GL_PATH_STENCIL_FUNC_NV = 0x90B7,
GL_PATH_STENCIL_REF_NV = 0x90B8,
GL_PATH_STENCIL_VALUE_MASK_NV = 0x90B9,
GL_PATH_STENCIL_DEPTH_OFFSET_FACTOR_NV = 0x90BD,
GL_PATH_STENCIL_DEPTH_OFFSET_UNITS_NV = 0x90BE,
GL_PATH_COVER_DEPTH_FUNC_NV = 0x90BF,
GL_PATH_DASH_OFFSET_RESET_NV = 0x90B4,
GL_MOVE_TO_RESETS_NV = 0x90B5,
GL_MOVE_TO_CONTINUES_NV = 0x90B6,
GL_CLOSE_PATH_NV = 0x00,
GL_MOVE_TO_NV = 0x02,
GL_RELATIVE_MOVE_TO_NV = 0x03,
GL_LINE_TO_NV = 0x04,
GL_RELATIVE_LINE_TO_NV = 0x05,
GL_HORIZONTAL_LINE_TO_NV = 0x06,
GL_RELATIVE_HORIZONTAL_LINE_TO_NV = 0x07,
GL_VERTICAL_LINE_TO_NV = 0x08,
GL_RELATIVE_VERTICAL_LINE_TO_NV = 0x09,
GL_QUADRATIC_CURVE_TO_NV = 0x0A,
GL_RELATIVE_QUADRATIC_CURVE_TO_NV = 0x0B,
GL_CUBIC_CURVE_TO_NV = 0x0C,
GL_RELATIVE_CUBIC_CURVE_TO_NV = 0x0D,
GL_SMOOTH_QUADRATIC_CURVE_TO_NV = 0x0E,
GL_RELATIVE_SMOOTH_QUADRATIC_CURVE_TO_NV = 0x0F,
GL_SMOOTH_CUBIC_CURVE_TO_NV = 0x10,
GL_RELATIVE_SMOOTH_CUBIC_CURVE_TO_NV = 0x11,
GL_SMALL_CCW_ARC_TO_NV = 0x12,
GL_RELATIVE_SMALL_CCW_ARC_TO_NV = 0x13,
GL_SMALL_CW_ARC_TO_NV = 0x14,
GL_RELATIVE_SMALL_CW_ARC_TO_NV = 0x15,
GL_LARGE_CCW_ARC_TO_NV = 0x16,
GL_RELATIVE_LARGE_CCW_ARC_TO_NV = 0x17,
GL_LARGE_CW_ARC_TO_NV = 0x18,
GL_RELATIVE_LARGE_CW_ARC_TO_NV = 0x19,
GL_RESTART_PATH_NV = 0xF0,
GL_DUP_FIRST_CUBIC_CURVE_TO_NV = 0xF2,
GL_DUP_LAST_CUBIC_CURVE_TO_NV = 0xF4,
GL_RECT_NV = 0xF6,
GL_CIRCULAR_CCW_ARC_TO_NV = 0xF8,
GL_CIRCULAR_CW_ARC_TO_NV = 0xFA,
GL_CIRCULAR_TANGENT_ARC_TO_NV = 0xFC,
GL_ARC_TO_NV = 0xFE,
GL_RELATIVE_ARC_TO_NV = 0xFF,
GL_BOLD_BIT_NV = 0x01,
GL_ITALIC_BIT_NV = 0x02,
GL_GLYPH_WIDTH_BIT_NV = 0x01,
GL_GLYPH_HEIGHT_BIT_NV = 0x02,
GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV = 0x04,
GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV = 0x08,
GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV = 0x10,
GL_GLYPH_VERTICAL_BEARING_X_BIT_NV = 0x20,
GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV = 0x40,
GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV = 0x80,
GL_GLYPH_HAS_KERNING_BIT_NV = 0x100,
GL_FONT_X_MIN_BOUNDS_BIT_NV = 0x00010000,
GL_FONT_Y_MIN_BOUNDS_BIT_NV = 0x00020000,
GL_FONT_X_MAX_BOUNDS_BIT_NV = 0x00040000,
GL_FONT_Y_MAX_BOUNDS_BIT_NV = 0x00080000,
GL_FONT_UNITS_PER_EM_BIT_NV = 0x00100000,
GL_FONT_ASCENDER_BIT_NV = 0x00200000,
GL_FONT_DESCENDER_BIT_NV = 0x00400000,
GL_FONT_HEIGHT_BIT_NV = 0x00800000,
GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV = 0x01000000,
GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV = 0x02000000,
GL_FONT_UNDERLINE_POSITION_BIT_NV = 0x04000000,
GL_FONT_UNDERLINE_THICKNESS_BIT_NV = 0x08000000,
GL_FONT_HAS_KERNING_BIT_NV = 0x10000000,
GL_ROUNDED_RECT_NV = 0xE8,
GL_RELATIVE_ROUNDED_RECT_NV = 0xE9,
GL_ROUNDED_RECT2_NV = 0xEA,
GL_RELATIVE_ROUNDED_RECT2_NV = 0xEB,
GL_ROUNDED_RECT4_NV = 0xEC,
GL_RELATIVE_ROUNDED_RECT4_NV = 0xED,
GL_ROUNDED_RECT8_NV = 0xEE,
GL_RELATIVE_ROUNDED_RECT8_NV = 0xEF,
GL_RELATIVE_RECT_NV = 0xF7,
GL_FONT_GLYPHS_AVAILABLE_NV = 0x9368,
GL_FONT_TARGET_UNAVAILABLE_NV = 0x9369,
GL_FONT_UNAVAILABLE_NV = 0x936A,
GL_FONT_UNINTELLIGIBLE_NV = 0x936B,
GL_CONIC_CURVE_TO_NV = 0x1A,
GL_RELATIVE_CONIC_CURVE_TO_NV = 0x1B,
GL_FONT_NUM_GLYPH_INDICES_BIT_NV = 0x20000000,
GL_STANDARD_FONT_FORMAT_NV = 0x936C,
GL_PATH_PROJECTION_NV = 0x1701,
GL_PATH_MODELVIEW_NV = 0x1700,
GL_PATH_MODELVIEW_STACK_DEPTH_NV = 0x0BA3,
GL_PATH_MODELVIEW_MATRIX_NV = 0x0BA6,
GL_PATH_MAX_MODELVIEW_STACK_DEPTH_NV = 0x0D36,
GL_PATH_TRANSPOSE_MODELVIEW_MATRIX_NV = 0x84E3,
GL_PATH_PROJECTION_STACK_DEPTH_NV = 0x0BA4,
GL_PATH_PROJECTION_MATRIX_NV = 0x0BA7,
GL_PATH_MAX_PROJECTION_STACK_DEPTH_NV = 0x0D38,
GL_PATH_TRANSPOSE_PROJECTION_MATRIX_NV = 0x84E4,
GL_FRAGMENT_INPUT_NV = 0x936D,
GL_NV_path_rendering_shared_edge = 1,
GL_SHARED_EDGE_NV = 0xC0,
GL_NV_sample_locations = 1,
GL_SAMPLE_LOCATION_SUBPIXEL_BITS_NV = 0x933D,
GL_SAMPLE_LOCATION_PIXEL_GRID_WIDTH_NV = 0x933E,
GL_SAMPLE_LOCATION_PIXEL_GRID_HEIGHT_NV = 0x933F,
GL_PROGRAMMABLE_SAMPLE_LOCATION_TABLE_SIZE_NV = 0x9340,
GL_SAMPLE_LOCATION_NV = 0x8E50,
GL_PROGRAMMABLE_SAMPLE_LOCATION_NV = 0x9341,
GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_NV = 0x9342,
GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_NV = 0x9343,
GL_NV_sample_mask_override_coverage = 1,
GL_NV_shader_atomic_fp16_vector = 1,
GL_NV_viewport_array2 = 1,
GL_NV_viewport_swizzle = 1,
GL_VIEWPORT_SWIZZLE_POSITIVE_X_NV = 0x9350,
GL_VIEWPORT_SWIZZLE_NEGATIVE_X_NV = 0x9351,
GL_VIEWPORT_SWIZZLE_POSITIVE_Y_NV = 0x9352,
GL_VIEWPORT_SWIZZLE_NEGATIVE_Y_NV = 0x9353,
GL_VIEWPORT_SWIZZLE_POSITIVE_Z_NV = 0x9354,
GL_VIEWPORT_SWIZZLE_NEGATIVE_Z_NV = 0x9355,
GL_VIEWPORT_SWIZZLE_POSITIVE_W_NV = 0x9356,
GL_VIEWPORT_SWIZZLE_NEGATIVE_W_NV = 0x9357,
GL_VIEWPORT_SWIZZLE_X_NV = 0x9358,
GL_VIEWPORT_SWIZZLE_Y_NV = 0x9359,
GL_VIEWPORT_SWIZZLE_Z_NV = 0x935A,
GL_VIEWPORT_SWIZZLE_W_NV = 0x935B,
GL_OVR_multiview = 1,
GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR = 0x9630,
GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR = 0x9632,
GL_MAX_VIEWS_OVR = 0x9631,
GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR = 0x9633,
GL_OVR_multiview2 = 1
}
return setmetatable( _M, {
__index = function( table, key )
local ct = "PFN" .. string.upper( key ) .. "PROC"
local pointer = SDL.SDL_GL_GetProcAddress( key )
if ( pointer ~= nil ) then
local cdata = ffi.cast( ct, pointer )
_M[ key ] = cdata
return cdata
end
end
} )
| mit |
tcmug/kello | misc/configuration.lua | 1 | 1185 |
local json = require("json")
module = {}
function module:get(key, default)
if not self.configuration then
local base = system.pathForFile("kello-config.json", system.DocumentsDirectory)
local configuration = {}
local file = io.open( base, "r" )
if file then
local jsoncontents = file:read( "*a" )
print(jsoncontents)
self.configuration = json.decode(jsoncontents)
io.close( file )
end
if self.configuration == nil then
self.configuration = {}
end
end
if self.configuration[key] ~= nil then
return self.configuration[key]
end
return default
end
function module:set(key, value)
if self.configuration then
self.configuration[key] = value
else
self.configuration = {
key = value
}
end
local base = system.pathForFile("kello-config.json", system.DocumentsDirectory)
local file = io.open(base, "w")
if file then
local contents = json.encode(self.configuration)
print(contents)
file:write( contents )
io.close( file )
end
end
return module
| gpl-3.0 |
dalab/deep-ed | ed/args.lua | 1 | 5119 | -- We add params abbreviations to the abbv map if they are important hyperparameters
-- used to differentiate between different methods.
abbv = {}
cmd = torch.CmdLine()
cmd:text()
cmd:text('Deep Joint Entity Disambiguation w/ Local Neural Attention')
cmd:text('Command line options:')
---------------- runtime options:
cmd:option('-root_data_dir', '', 'Root path of the data, $DATA_PATH.')
cmd:option('-unit_tests', false, 'Run unit tests or not')
---------------- CUDA:
cmd:option('-type', 'cudacudnn', 'Type: cuda | float | cudacudnn')
---------------- train data:
cmd:option('-store_train_data', 'RAM', 'Where to read the training data from: RAM (tensors) | DISK (text, parsed all the time)')
---------------- loss:
cmd:option('-loss', 'max-margin', 'Loss: nll | max-margin')
abbv['-loss'] = ''
---------------- optimization:
cmd:option('-opt', 'ADAM', 'Optimization method: SGD | ADADELTA | ADAGRAD | ADAM')
abbv['-opt'] = ''
cmd:option('-lr', 1e-4, 'Learning rate. Will be divided by 10 after validation F1 >= 90%.')
abbv['-lr'] = 'lr'
cmd:option('-batch_size', 1, 'Batch size in terms of number of documents.')
abbv['-batch_size'] = 'bs'
---------------- word vectors
cmd:option('-word_vecs', 'w2v', 'Word vectors type: glove | w2v (Word2Vec)')
abbv['-word_vecs'] = ''
---------------- entity vectors
cmd:option('-entities', 'RLTD', 'Which entity vectors to use, either just those that appear as candidates in all datasets, or all. All is impractical when storing on GPU. RLTD | ALL')
cmd:option('-ent_vecs_filename', 'ent_vecs__ep_228.t7', 'File name containing entity vectors generated with entities/learn_e2v/learn_a.lua.')
---------------- context
cmd:option('-ctxt_window', 100, 'Number of context words at the left plus right of each mention')
abbv['-ctxt_window'] = 'ctxtW'
cmd:option('-R', 25, 'Hard attention threshold: top R context words are kept, the rest are discarded.')
abbv['-R'] = 'R'
---------------- model
cmd:option('-model', 'global', 'ED model: local | global')
cmd:option('-nn_pem_interm_size', 100, 'Number of hidden units in the f function described in Section 4 - Local score combination.')
abbv['-nn_pem_interm_size'] = 'nnPEMintermS'
-------------- model regularization:
cmd:option('-mat_reg_norm', 1, 'Maximum norm of columns of matrices of the f network.')
abbv['-mat_reg_norm'] = 'matRegNorm'
---------------- global model parameters
cmd:option('-lbp_iter', 10, 'Number iterations of LBP hard-coded in a NN. Referred as T in the paper.')
abbv['-lbp_iter'] = 'lbpIt'
cmd:option('-lbp_damp', 0.5, 'Damping factor for LBP')
abbv['-lbp_damp'] = 'lbpDamp'
----------------- reranking of candidates
cmd:option('-num_cand_before_rerank', 30, '')
abbv['-num_cand_before_rerank'] = 'numERerank'
cmd:option('-keep_p_e_m', 4, '')
abbv['-keep_p_e_m'] = 'keepPEM'
cmd:option('-keep_e_ctxt', 3, '')
abbv['-keep_e_ctxt'] = 'keepEC'
----------------- coreference:
cmd:option('-coref', true, 'Coreference heuristic to match persons names.')
abbv['-coref'] = 'coref'
------------------ test one model with saved pretrained parameters
cmd:option('-test_one_model_file', '', 'Saved pretrained model filename from folder $DATA_PATH/generated/ed_models/.')
------------------ banner:
cmd:option('-banner_header', '', ' Banner header to be used for plotting')
cmd:text()
opt = cmd:parse(arg or {})
-- Whether to save the current ED model or not during training.
-- It will become true after the model gets > 90% F1 score on validation set (see test.lua).
opt.save = false
-- Creates a nice banner from the command line arguments
function get_banner(arg, abbv)
local num_args = table_len(arg)
local banner = opt.banner_header
if opt.model == 'global' then
banner = banner .. 'GLB'
else
banner = banner .. 'LCL'
end
for i = 1,num_args do
if abbv[arg[i]] then
banner = banner .. '|' .. abbv[arg[i]] .. '=' .. tostring(opt[arg[i]:sub(2)])
end
end
return banner
end
function serialize_params(arg)
local num_args = table_len(arg)
local str = opt.banner_header
if opt.banner_header:len() > 0 then
str = str .. '|'
end
str = str .. 'model=' .. opt.model
for i = 1,num_args do
if abbv[arg[i]] then
str = str .. '|' .. arg[i]:sub(2) .. '=' .. tostring(opt[arg[i]:sub(2)])
end
end
return str
end
banner = get_banner(arg, abbv)
params_serialized = serialize_params(arg)
print('PARAMS SERIALIZED: ' .. params_serialized)
print('BANNER : ' .. banner .. '\n')
assert(params_serialized:len() < 255, 'Parameters string length should be < 255.')
function extract_args_from_model_title(title)
local x,y = title:find('model=')
local parts = split(title:sub(x), '|')
for _,part in pairs(parts) do
if string.find(part, '=') then
local components = split(part, '=')
opt[components[1]] = components[2]
if tonumber(components[2]) then
opt[components[1]] = tonumber(components[2])
end
if components[2] == 'true' then
opt[components[1]] = true
end
if components[2] == 'false' then
opt[components[1]] = false
end
end
end
end
| apache-2.0 |
Altenius/cuberite | Server/Plugins/APIDump/Hooks/OnBlockToPickups.lua | 36 | 2438 | return
{
HOOK_BLOCK_TO_PICKUPS =
{
CalledWhen = "A block is about to be dug ({{cPlayer|player}}, {{cEntity|entity}} or natural reason), plugins may override what pickups that will produce.",
DefaultFnName = "OnBlockToPickups", -- also used as pagename
Desc = [[
This callback gets called whenever a block is about to be dug. This includes {{cPlayer|players}}
digging blocks, entities causing blocks to disappear ({{cTNTEntity|TNT}}, Endermen) and natural
causes (water washing away a block). Plugins may override the amount and kinds of pickups this
action produces.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world in which the block resides" },
{ Name = "Digger", Type = "{{cEntity}} descendant", Notes = "The entity causing the digging. May be a {{cPlayer}}, {{cTNTEntity}} or even nil (natural causes)" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
{ Name = "BlockType", Type = "BLOCKTYPE", Notes = "Block type of the block" },
{ Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "Block meta of the block" },
{ Name = "Pickups", Type = "{{cItems}}", Notes = "Items that will be spawned as pickups" },
},
Returns = [[
If the function returns false or no value, the next callback in the hook chain will be called. If
the function returns true, no other callbacks in the chain will be called.</p>
<p>
Either way, the server will then spawn pickups specified in the Pickups parameter, so to disable
pickups, you need to Clear the object first, then return true.
]],
CodeExamples =
{
{
Title = "Modify pickups",
Desc = "This example callback function makes tall grass drop diamonds when digged by natural causes (washed away by water).",
Code = [[
function OnBlockToPickups(a_World, a_Digger, a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, a_Pickups)
if (a_Digger ~= nil) then
-- Not a natural cause
return false;
end
if (a_BlockType ~= E_BLOCK_TALL_GRASS) then
-- Not a tall grass being washed away
return false;
end
-- Remove all pickups suggested by Cuberite:
a_Pickups:Clear();
-- Drop a diamond:
a_Pickups:Add(cItem(E_ITEM_DIAMOND));
return true;
end;
]],
},
} , -- CodeExamples
}, -- HOOK_BLOCK_TO_PICKUPS
}
| apache-2.0 |
gajop/chiliui | luaui/chili/chili/controls/image.lua | 1 | 3956 | --// =============================================================================
--- Image module
--- Image fields.
-- Inherits from Control.
-- @see button.Button
-- @table Image
-- @tparam {r, g, b, a} color color, (default {1, 1, 1, 1})
-- @string[opt = nil] file path
-- @bool[opt = true] keepAspect aspect should be kept
-- @tparam {func1, func2} OnClick function listeners to be invoked on click (default {})
Image = Button:Inherit{
classname = "image",
defaultWidth = 64,
defaultHeight = 64,
padding = {0, 0, 0, 0},
color = {1, 1, 1, 1},
color2 = nil,
file = nil,
file2 = nil,
flip = true;
flip2 = true;
keepAspect = true;
checkFileExists = false;
fallbackFile = false;
imageLoadTime = 3.5; -- Seconds
useRTT = false;
OnClick = {},
__nofont = true,
}
local this = Image
local inherited = this.inherited
--// =============================================================================
local function _DrawTextureAspect(x, y, w, h , tw, th, flipy)
local twa = w/tw
local tha = h/th
local aspect = 1
if (twa < tha) then
aspect = twa
y = y + h*0.5 - th*aspect*0.5
h = th*aspect
else
aspect = tha
x = x + w*0.5 - tw*aspect*0.5
w = tw*aspect
end
local right = math.ceil(x + w)
local bottom = math.ceil(y + h)
x = math.ceil(x)
y = math.ceil(y)
gl.TexRect(x, y, right, bottom, false, flipy)
end
function Image:DrawControl()
local file = self.file
local file2 = self.file2
if (not (file or file2)) then
return
end
-- HACK: Chobby hack
if self.checkFileExists then
if self._loadTimer then
if Spring.DiffTimers(Spring.GetTimer(), self._loadTimer) > self.imageLoadTime then
self.checkFileExists = false
end
elseif ((not file) or VFS.FileExists(file)) and ((not file2) or VFS.FileExists(file2)) then
self._loadTimer = Spring.GetTimer()
end
if self.fallbackFile then
file = self.fallbackFile
file2 = nil
else
return
end
end
if (self.keepAspect) then
if (file2) then
gl.Color(self.color2 or self.color)
TextureHandler.LoadTexture(0, file2, self)
local texInfo = gl.TextureInfo(file2) or {xsize = 1, ysize = 1}
local tw, th = texInfo.xsize, texInfo.ysize
_DrawTextureAspect(0, 0, self.width, self.height, tw, th, self.flip2)
end
if (file) then
gl.Color(self.color)
TextureHandler.LoadTexture(0, file, self)
local texInfo = gl.TextureInfo(file) or {xsize = 1, ysize = 1}
local tw, th = texInfo.xsize, texInfo.ysize
_DrawTextureAspect(0, 0, self.width, self.height, tw, th, self.flip)
end
else
if (file2) then
gl.Color(self.color2 or self.color)
TextureHandler.LoadTexture(0, file2, self)
gl.TexRect(0, 0, self.width, self.height, false, self.flip2)
end
if (file) then
gl.Color(self.color)
TextureHandler.LoadTexture(0, file, self)
gl.TexRect(0, 0, self.width, self.height, false, self.flip)
end
end
gl.Texture(0, false)
end
--// =============================================================================
function Image:IsActive()
local onclick = self.OnClick
if (onclick and onclick[1]) then
return true
end
end
function Image:HitTest()
--FIXME check if there are any eventhandlers linked (OnClick, OnMouseUp, ...)
return self:IsActive() and self
end
function Image:MouseDown(...)
--// we don't use `this` here because it would call the eventhandler of the button class,
--// which always returns true, but we just want to do so if a calllistener handled the event
return Control.MouseDown(self, ...) or self:IsActive() and self
end
function Image:MouseUp(...)
return Control.MouseUp(self, ...) or self:IsActive() and self
end
function Image:MouseClick(...)
return Control.MouseClick(self, ...) or self:IsActive() and self
end
--// =============================================================================
| gpl-2.0 |
lizh06/premake-4.x | src/actions/vstudio/vs200x_vcproj.lua | 4 | 21224 | --
-- vs200x_vcproj.lua
-- Generate a Visual Studio 2002-2008 C/C++ project.
-- Copyright (c) 2009-2013 Jason Perkins and the Premake project
--
--
-- Set up a namespace for this file
--
premake.vstudio.vc200x = { }
local vc200x = premake.vstudio.vc200x
local tree = premake.tree
--
-- Return the version-specific text for a boolean value.
--
local function bool(value)
if (_ACTION < "vs2005") then
return iif(value, "TRUE", "FALSE")
else
return iif(value, "true", "false")
end
end
--
-- Return the optimization code.
--
function vc200x.optimization(cfg)
local result = 0
for _, value in ipairs(cfg.flags) do
if (value == "Optimize") then
result = 3
elseif (value == "OptimizeSize") then
result = 1
elseif (value == "OptimizeSpeed") then
result = 2
end
end
return result
end
--
-- Write the project file header
--
function vc200x.header(element)
io.eol = "\r\n"
_p('<?xml version="1.0" encoding="Windows-1252"?>')
_p('<%s', element)
_p(1,'ProjectType="Visual C++"')
if _ACTION == "vs2002" then
_p(1,'Version="7.00"')
elseif _ACTION == "vs2003" then
_p(1,'Version="7.10"')
elseif _ACTION == "vs2005" then
_p(1,'Version="8.00"')
elseif _ACTION == "vs2008" then
_p(1,'Version="9.00"')
end
end
--
-- Write out the <Configuration> element.
--
function vc200x.Configuration(name, cfg)
_p(2,'<Configuration')
_p(3,'Name="%s"', premake.esc(name))
_p(3,'OutputDirectory="%s"', premake.esc(cfg.buildtarget.directory))
_p(3,'IntermediateDirectory="%s"', premake.esc(cfg.objectsdir))
local cfgtype
if (cfg.kind == "SharedLib") then
cfgtype = 2
elseif (cfg.kind == "StaticLib") then
cfgtype = 4
else
cfgtype = 1
end
_p(3,'ConfigurationType="%s"', cfgtype)
if (cfg.flags.MFC) then
_p(3, 'UseOfMFC="%d"', iif(cfg.flags.StaticRuntime, 1, 2))
end
if (cfg.flags.ATL or cfg.flags.StaticATL) then
_p(3, 'UseOfATL="%d"', iif(cfg.flags.StaticATL, 1, 2))
end
_p(3,'CharacterSet="%s"', iif(cfg.flags.Unicode, 1, 2))
if cfg.flags.Managed then
_p(3,'ManagedExtensions="1"')
end
_p(3,'>')
end
--
-- Write out the <Files> element.
--
function vc200x.Files(prj)
local tr = premake.project.buildsourcetree(prj)
tree.traverse(tr, {
-- folders are handled at the internal nodes
onbranchenter = function(node, depth)
_p(depth, '<Filter')
_p(depth, '\tName="%s"', node.name)
_p(depth, '\tFilter=""')
_p(depth, '\t>')
end,
onbranchexit = function(node, depth)
_p(depth, '</Filter>')
end,
-- source files are handled at the leaves
onleaf = function(node, depth)
local fname = node.cfg.name
_p(depth, '<File')
_p(depth, '\tRelativePath="%s"', path.translate(fname, "\\"))
_p(depth, '\t>')
depth = depth + 1
-- handle file configuration stuff. This needs to be cleaned up and simplified.
-- configurations are cached, so this isn't as bad as it looks
for _, cfginfo in ipairs(prj.solution.vstudio_configs) do
if cfginfo.isreal then
local cfg = premake.getconfig(prj, cfginfo.src_buildcfg, cfginfo.src_platform)
local usePCH = (not prj.flags.NoPCH and prj.pchsource == node.cfg.name)
local isSourceCode = path.iscppfile(fname)
local needsCompileAs = (path.iscfile(fname) ~= premake.project.iscproject(prj))
if usePCH or (isSourceCode and needsCompileAs) then
_p(depth, '<FileConfiguration')
_p(depth, '\tName="%s"', cfginfo.name)
_p(depth, '\t>')
_p(depth, '\t<Tool')
_p(depth, '\t\tName="%s"', iif(cfg.system == "Xbox360",
"VCCLX360CompilerTool",
"VCCLCompilerTool"))
if needsCompileAs then
_p(depth, '\t\tCompileAs="%s"', iif(path.iscfile(fname), 1, 2))
end
if usePCH then
if cfg.system == "PS3" then
local options = table.join(premake.snc.getcflags(cfg),
premake.snc.getcxxflags(cfg),
cfg.buildoptions)
options = table.concat(options, " ");
options = options .. ' --create_pch="$(IntDir)/$(TargetName).pch"'
_p(depth, '\t\tAdditionalOptions="%s"', premake.esc(options))
else
_p(depth, '\t\tUsePrecompiledHeader="1"')
end
end
_p(depth, '\t/>')
_p(depth, '</FileConfiguration>')
end
end
end
depth = depth - 1
_p(depth, '</File>')
end,
}, false, 2)
end
--
-- Write out the <Platforms> element; ensures that each target platform
-- is listed only once. Skips over .NET's pseudo-platforms (like "Any CPU").
--
function vc200x.Platforms(prj)
local used = { }
_p(1,'<Platforms>')
for _, cfg in ipairs(prj.solution.vstudio_configs) do
if cfg.isreal and not table.contains(used, cfg.platform) then
table.insert(used, cfg.platform)
_p(2,'<Platform')
_p(3,'Name="%s"', cfg.platform)
_p(2,'/>')
end
end
_p(1,'</Platforms>')
end
--
-- Return the debugging symbols level for a configuration.
--
function vc200x.Symbols(cfg)
if (not cfg.flags.Symbols) then
return 0
else
-- Edit-and-continue does't work for some configurations
if cfg.flags.NoEditAndContinue or
vc200x.optimization(cfg) ~= 0 or
cfg.flags.Managed or
cfg.platform == "x64" then
return 3
else
return 4
end
end
end
--
-- Compiler block for Windows and XBox360 platforms.
--
function vc200x.VCCLCompilerTool(cfg)
_p(3,'<Tool')
_p(4,'Name="%s"', iif(cfg.platform ~= "Xbox360", "VCCLCompilerTool", "VCCLX360CompilerTool"))
if #cfg.buildoptions > 0 then
_p(4,'AdditionalOptions="%s"', table.concat(premake.esc(cfg.buildoptions), " "))
end
_p(4,'Optimization="%s"', vc200x.optimization(cfg))
if cfg.flags.NoFramePointer then
_p(4,'OmitFramePointers="%s"', bool(true))
end
if #cfg.includedirs > 0 then
_p(4,'AdditionalIncludeDirectories="%s"', premake.esc(path.translate(table.concat(cfg.includedirs, ";"), '\\')))
end
if #cfg.defines > 0 then
_p(4,'PreprocessorDefinitions="%s"', premake.esc(table.concat(cfg.defines, ";")))
end
if premake.config.isdebugbuild(cfg) and not cfg.flags.NoMinimalRebuild and not cfg.flags.Managed then
_p(4,'MinimalRebuild="%s"', bool(true))
end
if cfg.flags.NoExceptions then
_p(4,'ExceptionHandling="%s"', iif(_ACTION < "vs2005", "FALSE", 0))
elseif cfg.flags.SEH and _ACTION > "vs2003" then
_p(4,'ExceptionHandling="2"')
end
if vc200x.optimization(cfg) == 0 and not cfg.flags.Managed then
_p(4,'BasicRuntimeChecks="3"')
end
if vc200x.optimization(cfg) ~= 0 then
_p(4,'StringPooling="%s"', bool(true))
end
local runtime
if premake.config.isdebugbuild(cfg) then
runtime = iif(cfg.flags.StaticRuntime, 1, 3)
else
runtime = iif(cfg.flags.StaticRuntime, 0, 2)
end
_p(4,'RuntimeLibrary="%s"', runtime)
_p(4,'EnableFunctionLevelLinking="%s"', bool(true))
if _ACTION > "vs2003" and cfg.platform ~= "Xbox360" and cfg.platform ~= "x64" then
if cfg.flags.EnableSSE then
_p(4,'EnableEnhancedInstructionSet="1"')
elseif cfg.flags.EnableSSE2 then
_p(4,'EnableEnhancedInstructionSet="2"')
end
end
if _ACTION < "vs2005" then
if cfg.flags.FloatFast then
_p(4,'ImproveFloatingPointConsistency="%s"', bool(false))
elseif cfg.flags.FloatStrict then
_p(4,'ImproveFloatingPointConsistency="%s"', bool(true))
end
else
if cfg.flags.FloatFast then
_p(4,'FloatingPointModel="2"')
elseif cfg.flags.FloatStrict then
_p(4,'FloatingPointModel="1"')
end
end
if _ACTION < "vs2005" and not cfg.flags.NoRTTI then
_p(4,'RuntimeTypeInfo="%s"', bool(true))
elseif _ACTION > "vs2003" and cfg.flags.NoRTTI and not cfg.flags.Managed then
_p(4,'RuntimeTypeInfo="%s"', bool(false))
end
if cfg.flags.NativeWChar then
_p(4,'TreatWChar_tAsBuiltInType="%s"', bool(true))
elseif cfg.flags.NoNativeWChar then
_p(4,'TreatWChar_tAsBuiltInType="%s"', bool(false))
end
if not cfg.flags.NoPCH and cfg.pchheader then
_p(4,'UsePrecompiledHeader="%s"', iif(_ACTION < "vs2005", 3, 2))
_p(4,'PrecompiledHeaderThrough="%s"', cfg.pchheader)
else
_p(4,'UsePrecompiledHeader="%s"', iif(_ACTION > "vs2003" or cfg.flags.NoPCH, 0, 2))
end
_p(4,'WarningLevel="%s"', iif(cfg.flags.ExtraWarnings, 4, 3))
if cfg.flags.FatalWarnings then
_p(4,'WarnAsError="%s"', bool(true))
end
if _ACTION < "vs2008" and not cfg.flags.Managed then
_p(4,'Detect64BitPortabilityProblems="%s"', bool(not cfg.flags.No64BitChecks))
end
_p(4,'ProgramDataBaseFileName="$(OutDir)\\%s.pdb"', path.getbasename(cfg.buildtarget.name))
_p(4,'DebugInformationFormat="%s"', vc200x.Symbols(cfg))
if cfg.language == "C" then
_p(4, 'CompileAs="1"')
end
_p(3,'/>')
end
--
-- Linker block for Windows and Xbox 360 platforms.
--
function vc200x.VCLinkerTool(cfg)
_p(3,'<Tool')
if cfg.kind ~= "StaticLib" then
_p(4,'Name="%s"', iif(cfg.platform ~= "Xbox360", "VCLinkerTool", "VCX360LinkerTool"))
if cfg.flags.NoImportLib then
_p(4,'IgnoreImportLibrary="%s"', bool(true))
end
if #cfg.linkoptions > 0 then
_p(4,'AdditionalOptions="%s"', table.concat(premake.esc(cfg.linkoptions), " "))
end
if #cfg.links > 0 then
_p(4,'AdditionalDependencies="%s"', table.concat(premake.getlinks(cfg, "all", "fullpath"), " "))
end
_p(4,'OutputFile="$(OutDir)\\%s"', cfg.buildtarget.name)
_p(4,'LinkIncremental="%s"',
iif(premake.config.isincrementallink(cfg) , 2, 1))
_p(4,'AdditionalLibraryDirectories="%s"', table.concat(premake.esc(path.translate(cfg.libdirs, '\\')) , ";"))
local deffile = premake.findfile(cfg, ".def")
if deffile then
_p(4,'ModuleDefinitionFile="%s"', deffile)
end
if cfg.flags.NoManifest then
_p(4,'GenerateManifest="%s"', bool(false))
end
_p(4,'GenerateDebugInformation="%s"', bool(vc200x.Symbols(cfg) ~= 0))
if vc200x.Symbols(cfg) ~= 0 then
_p(4,'ProgramDataBaseFileName="$(OutDir)\\%s.pdb"', path.getbasename(cfg.buildtarget.name))
end
_p(4,'SubSystem="%s"', iif(cfg.kind == "ConsoleApp", 1, 2))
if vc200x.optimization(cfg) ~= 0 then
_p(4,'OptimizeReferences="2"')
_p(4,'EnableCOMDATFolding="2"')
end
if (cfg.kind == "ConsoleApp" or cfg.kind == "WindowedApp") and not cfg.flags.WinMain then
_p(4,'EntryPointSymbol="mainCRTStartup"')
end
if cfg.kind == "SharedLib" then
local implibname = cfg.linktarget.fullpath
_p(4,'ImportLibrary="%s"', iif(cfg.flags.NoImportLib, cfg.objectsdir .. "\\" .. path.getname(implibname), implibname))
end
_p(4,'TargetMachine="%d"', iif(cfg.platform == "x64", 17, 1))
else
_p(4,'Name="VCLibrarianTool"')
if #cfg.links > 0 then
_p(4,'AdditionalDependencies="%s"', table.concat(premake.getlinks(cfg, "all", "fullpath"), " "))
end
_p(4,'OutputFile="$(OutDir)\\%s"', cfg.buildtarget.name)
if #cfg.libdirs > 0 then
_p(4,'AdditionalLibraryDirectories="%s"', premake.esc(path.translate(table.concat(cfg.libdirs , ";"))))
end
local addlOptions = {}
if cfg.platform == "x32" then
table.insert(addlOptions, "/MACHINE:X86")
elseif cfg.platform == "x64" then
table.insert(addlOptions, "/MACHINE:X64")
end
addlOptions = table.join(addlOptions, cfg.linkoptions)
if #addlOptions > 0 then
_p(4,'AdditionalOptions="%s"', table.concat(premake.esc(addlOptions), " "))
end
end
_p(3,'/>')
end
--
-- Compiler and linker blocks for the PS3 platform, which uses Sony's SNC.
--
function vc200x.VCCLCompilerTool_PS3(cfg)
_p(3,'<Tool')
_p(4,'Name="VCCLCompilerTool"')
local buildoptions = table.join(premake.snc.getcflags(cfg), premake.snc.getcxxflags(cfg), cfg.buildoptions)
if not cfg.flags.NoPCH and cfg.pchheader then
_p(4,'UsePrecompiledHeader="%s"', iif(_ACTION < "vs2005", 3, 2))
_p(4,'PrecompiledHeaderThrough="%s"', path.getname(cfg.pchheader))
table.insert(buildoptions, '--use_pch="$(IntDir)/$(TargetName).pch"')
else
_p(4,'UsePrecompiledHeader="%s"', iif(_ACTION > "vs2003" or cfg.flags.NoPCH, 0, 2))
end
_p(4,'AdditionalOptions="%s"', premake.esc(table.concat(buildoptions, " ")))
if #cfg.includedirs > 0 then
_p(4,'AdditionalIncludeDirectories="%s"', premake.esc(path.translate(table.concat(cfg.includedirs, ";"), '\\')))
end
if #cfg.defines > 0 then
_p(4,'PreprocessorDefinitions="%s"', table.concat(premake.esc(cfg.defines), ";"))
end
_p(4,'ProgramDataBaseFileName="$(OutDir)\\%s.pdb"', path.getbasename(cfg.buildtarget.name))
_p(4,'DebugInformationFormat="0"')
_p(4,'CompileAs="0"')
_p(3,'/>')
end
function vc200x.VCLinkerTool_PS3(cfg)
_p(3,'<Tool')
if cfg.kind ~= "StaticLib" then
_p(4,'Name="VCLinkerTool"')
local buildoptions = table.join(premake.snc.getldflags(cfg), cfg.linkoptions)
if #buildoptions > 0 then
_p(4,'AdditionalOptions="%s"', premake.esc(table.concat(buildoptions, " ")))
end
if #cfg.links > 0 then
_p(4,'AdditionalDependencies="%s"', table.concat(premake.getlinks(cfg, "all", "fullpath"), " "))
end
_p(4,'OutputFile="$(OutDir)\\%s"', cfg.buildtarget.name)
_p(4,'LinkIncremental="0"')
_p(4,'AdditionalLibraryDirectories="%s"', table.concat(premake.esc(path.translate(cfg.libdirs, '\\')) , ";"))
_p(4,'GenerateManifest="%s"', bool(false))
_p(4,'ProgramDatabaseFile=""')
_p(4,'RandomizedBaseAddress="1"')
_p(4,'DataExecutionPrevention="0"')
else
_p(4,'Name="VCLibrarianTool"')
local buildoptions = table.join(premake.snc.getldflags(cfg), cfg.linkoptions)
if #buildoptions > 0 then
_p(4,'AdditionalOptions="%s"', premake.esc(table.concat(buildoptions, " ")))
end
if #cfg.links > 0 then
_p(4,'AdditionalDependencies="%s"', table.concat(premake.getlinks(cfg, "all", "fullpath"), " "))
end
_p(4,'OutputFile="$(OutDir)\\%s"', cfg.buildtarget.name)
if #cfg.libdirs > 0 then
_p(4,'AdditionalLibraryDirectories="%s"', premake.esc(path.translate(table.concat(cfg.libdirs , ";"))))
end
end
_p(3,'/>')
end
--
-- Resource compiler block.
--
function vc200x.VCResourceCompilerTool(cfg)
_p(3,'<Tool')
_p(4,'Name="VCResourceCompilerTool"')
if #cfg.resoptions > 0 then
_p(4,'AdditionalOptions="%s"', table.concat(premake.esc(cfg.resoptions), " "))
end
if #cfg.defines > 0 or #cfg.resdefines > 0 then
_p(4,'PreprocessorDefinitions="%s"', table.concat(premake.esc(table.join(cfg.defines, cfg.resdefines)), ";"))
end
if #cfg.includedirs > 0 or #cfg.resincludedirs > 0 then
local dirs = table.join(cfg.includedirs, cfg.resincludedirs)
_p(4,'AdditionalIncludeDirectories="%s"', premake.esc(path.translate(table.concat(dirs, ";"), '\\')))
end
_p(3,'/>')
end
--
-- Manifest block.
--
function vc200x.VCManifestTool(cfg)
-- locate all manifest files
local manifests = { }
for _, fname in ipairs(cfg.files) do
if path.getextension(fname) == ".manifest" then
table.insert(manifests, fname)
end
end
_p(3,'<Tool')
_p(4,'Name="VCManifestTool"')
if #manifests > 0 then
_p(4,'AdditionalManifestFiles="%s"', premake.esc(table.concat(manifests, ";")))
end
_p(3,'/>')
end
--
-- VCMIDLTool block
--
function vc200x.VCMIDLTool(cfg)
_p(3,'<Tool')
_p(4,'Name="VCMIDLTool"')
if cfg.platform == "x64" then
_p(4,'TargetEnvironment="3"')
end
_p(3,'/>')
end
--
-- Write out a custom build steps block.
--
function vc200x.buildstepsblock(name, steps)
_p(3,'<Tool')
_p(4,'Name="%s"', name)
if #steps > 0 then
_p(4,'CommandLine="%s"', premake.esc(table.implode(steps, "", "", "\r\n")))
end
_p(3,'/>')
end
--
-- Map project tool blocks to handler functions. Unmapped blocks will output
-- an empty <Tool> element.
--
vc200x.toolmap =
{
VCCLCompilerTool = vc200x.VCCLCompilerTool,
VCCLCompilerTool_PS3 = vc200x.VCCLCompilerTool_PS3,
VCLinkerTool = vc200x.VCLinkerTool,
VCLinkerTool_PS3 = vc200x.VCLinkerTool_PS3,
VCManifestTool = vc200x.VCManifestTool,
VCMIDLTool = vc200x.VCMIDLTool,
VCResourceCompilerTool = vc200x.VCResourceCompilerTool,
VCPreBuildEventTool = function(cfg) vc200x.buildstepsblock("VCPreBuildEventTool", cfg.prebuildcommands) end,
VCPreLinkEventTool = function(cfg) vc200x.buildstepsblock("VCPreLinkEventTool", cfg.prelinkcommands) end,
VCPostBuildEventTool = function(cfg) vc200x.buildstepsblock("VCPostBuildEventTool", cfg.postbuildcommands) end,
}
--
-- Return a list of sections for a particular Visual Studio version and target platform.
--
local function getsections(version, platform)
if version == "vs2002" then
return {
"VCCLCompilerTool",
"VCCustomBuildTool",
"VCLinkerTool",
"VCMIDLTool",
"VCPostBuildEventTool",
"VCPreBuildEventTool",
"VCPreLinkEventTool",
"VCResourceCompilerTool",
"VCWebServiceProxyGeneratorTool",
"VCWebDeploymentTool"
}
end
if version == "vs2003" then
return {
"VCCLCompilerTool",
"VCCustomBuildTool",
"VCLinkerTool",
"VCMIDLTool",
"VCPostBuildEventTool",
"VCPreBuildEventTool",
"VCPreLinkEventTool",
"VCResourceCompilerTool",
"VCWebServiceProxyGeneratorTool",
"VCXMLDataGeneratorTool",
"VCWebDeploymentTool",
"VCManagedWrapperGeneratorTool",
"VCAuxiliaryManagedWrapperGeneratorTool"
}
end
if platform == "Xbox360" then
return {
"VCPreBuildEventTool",
"VCCustomBuildTool",
"VCXMLDataGeneratorTool",
"VCWebServiceProxyGeneratorTool",
"VCMIDLTool",
"VCCLCompilerTool",
"VCManagedResourceCompilerTool",
"VCResourceCompilerTool",
"VCPreLinkEventTool",
"VCLinkerTool",
"VCALinkTool",
"VCX360ImageTool",
"VCBscMakeTool",
"VCX360DeploymentTool",
"VCPostBuildEventTool",
"DebuggerTool",
}
end
if platform == "PS3" then
return {
"VCPreBuildEventTool",
"VCCustomBuildTool",
"VCXMLDataGeneratorTool",
"VCWebServiceProxyGeneratorTool",
"VCMIDLTool",
"VCCLCompilerTool_PS3",
"VCManagedResourceCompilerTool",
"VCResourceCompilerTool",
"VCPreLinkEventTool",
"VCLinkerTool_PS3",
"VCALinkTool",
"VCManifestTool",
"VCXDCMakeTool",
"VCBscMakeTool",
"VCFxCopTool",
"VCAppVerifierTool",
"VCWebDeploymentTool",
"VCPostBuildEventTool"
}
else
return {
"VCPreBuildEventTool",
"VCCustomBuildTool",
"VCXMLDataGeneratorTool",
"VCWebServiceProxyGeneratorTool",
"VCMIDLTool",
"VCCLCompilerTool",
"VCManagedResourceCompilerTool",
"VCResourceCompilerTool",
"VCPreLinkEventTool",
"VCLinkerTool",
"VCALinkTool",
"VCManifestTool",
"VCXDCMakeTool",
"VCBscMakeTool",
"VCFxCopTool",
"VCAppVerifierTool",
"VCWebDeploymentTool",
"VCPostBuildEventTool"
}
end
end
--
-- The main function: write the project file.
--
function vc200x.generate(prj)
vc200x.header('VisualStudioProject')
_p(1,'Name="%s"', premake.esc(prj.name))
_p(1,'ProjectGUID="{%s}"', prj.uuid)
if _ACTION > "vs2003" then
_p(1,'RootNamespace="%s"', prj.name)
end
_p(1,'Keyword="%s"', iif(prj.flags.Managed, "ManagedCProj", "Win32Proj"))
_p(1,'>')
-- list the target platforms
vc200x.Platforms(prj)
if _ACTION > "vs2003" then
_p(1,'<ToolFiles>')
_p(1,'</ToolFiles>')
end
_p(1,'<Configurations>')
for _, cfginfo in ipairs(prj.solution.vstudio_configs) do
if cfginfo.isreal then
local cfg = premake.getconfig(prj, cfginfo.src_buildcfg, cfginfo.src_platform)
-- Start a configuration
vc200x.Configuration(cfginfo.name, cfg)
for _, block in ipairs(getsections(_ACTION, cfginfo.src_platform)) do
if vc200x.toolmap[block] then
vc200x.toolmap[block](cfg)
-- Xbox 360 custom sections --
elseif block == "VCX360DeploymentTool" then
_p(3,'<Tool')
_p(4,'Name="VCX360DeploymentTool"')
_p(4,'DeploymentType="0"')
if #cfg.deploymentoptions > 0 then
_p(4,'AdditionalOptions="%s"', table.concat(premake.esc(cfg.deploymentoptions), " "))
end
_p(3,'/>')
elseif block == "VCX360ImageTool" then
_p(3,'<Tool')
_p(4,'Name="VCX360ImageTool"')
if #cfg.imageoptions > 0 then
_p(4,'AdditionalOptions="%s"', table.concat(premake.esc(cfg.imageoptions), " "))
end
if cfg.imagepath ~= nil then
_p(4,'OutputFileName="%s"', premake.esc(path.translate(cfg.imagepath)))
end
_p(3,'/>')
elseif block == "DebuggerTool" then
_p(3,'<DebuggerTool')
_p(3,'/>')
-- End Xbox 360 custom sections --
else
_p(3,'<Tool')
_p(4,'Name="%s"', block)
_p(3,'/>')
end
end
_p(2,'</Configuration>')
end
end
_p(1,'</Configurations>')
_p(1,'<References>')
_p(1,'</References>')
_p(1,'<Files>')
vc200x.Files(prj)
_p(1,'</Files>')
_p(1,'<Globals>')
_p(1,'</Globals>')
_p('</VisualStudioProject>')
end
| bsd-3-clause |
LuaDist2/lunamark | lunamark.lua | 7 | 3477 | -- (c) 2009-2011 John MacFarlane. Released under MIT license.
-- See the file LICENSE in the source for details.
--- Copyright © 2009-2011 John MacFarlane.
--
-- Released under the MIT license (see LICENSE in the source for details).
--
-- ## Description
--
-- Lunamark is a lua library for conversion of markdown to
-- other textual formats. Currently HTML, Docbook, ConTeXt,
-- LaTeX, and Groff man are the supported output formats,
-- but lunamark's modular architecture makes it easy to add
-- writers and modify the markdown parser (written with a PEG
-- grammar).
--
-- Lunamark's markdown parser currently supports the following
-- extensions (which can be turned on or off individually):
--
-- - Smart typography (fancy quotes, dashes, ellipses)
-- - Significant start numbers in ordered lists
-- - Footnotes
-- - Definition lists
--
-- More extensions will be supported in later versions.
--
-- The library is as portable as lua and has very good performance.
-- It is about as fast as the author's own C library
-- [peg-markdown](http://github.com/jgm/peg-markdown).
--
-- ## Simple usage example
--
-- local lunamark = require("lunamark")
-- local writer = lunamark.writer.html.new()
-- local parse = lunamark.reader.markdown.new(writer, { smart = true })
-- local result, metadata = parse("Here's 'my *text*'...")
-- print(result)
-- assert(result == 'Here’s ‘my <em>text</em>’…')
--
-- ## Customizing the writer
--
-- Render emphasized text using `<u>` tags rather than `<em>`.
--
-- local unicode = require("unicode")
-- function writer.emphasis(s)
-- return {"<u>",s,"</u>"}
-- end
-- local parse = lunamark.reader.markdown.new(writer, { smart = true })
-- local result, metadata = parse("*Beiß* nicht in die Hand, die dich *füttert*.")
-- print(result)
-- assert(result == '<u>Beiß</u> nicht in die Hand, die dich <u>füttert</u>.')
--
-- Eliminate hyperlinks:
--
-- function writer.link(lab,url,tit)
-- return lab
-- end
-- local parse = lunamark.reader.markdown.new(writer, { smart = true })
-- local result, metadata = parse("[hi](/url) there")
-- print(result)
-- assert(result == 'hi there')
--
-- ## Customizing the parser
--
-- Parse CamelCase words as wikilinks:
--
-- lpeg = require("lpeg")
-- local writer = lunamark.writer.html.new()
-- function add_wikilinks(syntax)
-- local capword = lpeg.R("AZ")^1 * lpeg.R("az")^1
-- local parse_wikilink = lpeg.C(capword^2)
-- / function(wikipage)
-- return writer.link(writer.string(wikipage),
-- "/" .. wikipage,
-- "Go to " .. wikipage)
-- end
-- syntax.Inline = parse_wikilink + syntax.Inline
-- return syntax
-- end
-- local parse = lunamark.reader.markdown.new(writer, { alter_syntax = add_wikilinks })
-- local result, metadata = parse("My text with WikiLinks.\n")
-- print(result)
-- assert(result == 'My text with <a href="/WikiLinks" title="Go to WikiLinks">WikiLinks</a>.')
--
local G = {}
setmetatable(G,{ __index = function(t,name)
local mod = require("lunamark." .. name)
rawset(t,name,mod)
return t[name]
end })
return G
| mit |
dani-sj/extremenod | plugins/inpm.lua | 14 | 3149 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
--
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
caohongtao/quick-cocos-demo | src/framework/luaoc.lua | 20 | 2593 | --[[
Copyright (c) 2011-2014 chukong-inc.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
--------------------------------
-- @module luaoc
--[[--
Lua 与 Objective-C 的交互接口
]]
local luaoc = {}
local callStaticMethod = LuaObjcBridge.callStaticMethod
-- start --
--------------------------------
-- 调用Objective-C类的接口。
-- @function [parent=#luaoc] callStaticMethod
-- @param string className Objective-C类名
-- @param string methodName Objective-C类方法名
-- @param table args Objective-C类方法所需要的各种参数字典,key值为方法的参数名
-- @return boolean#boolean ret (return value: bool) ok, mixed ret ok为是否调用成功, ok为true时,ret为Objective-C方法的返回值,ok为false时,ret为出错原因
-- end --
function luaoc.callStaticMethod(className, methodName, args)
local ok, ret = callStaticMethod(className, methodName, args)
if not ok then
local msg = string.format("luaoc.callStaticMethod(\"%s\", \"%s\", \"%s\") - error: [%s] ",
className, methodName, tostring(args), tostring(ret))
if ret == -1 then
printError(msg .. "INVALID PARAMETERS")
elseif ret == -2 then
printError(msg .. "CLASS NOT FOUND")
elseif ret == -3 then
printError(msg .. "METHOD NOT FOUND")
elseif ret == -4 then
printError(msg .. "EXCEPTION OCCURRED")
elseif ret == -5 then
printError(msg .. "INVALID METHOD SIGNATURE")
else
printError(msg .. "UNKNOWN")
end
end
return ok, ret
end
return luaoc
| apache-2.0 |
cere-bro/telegram-bot | bot/utils.lua | 239 | 13499 | 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")()
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
| gpl-2.0 |
ASantosVal/vlc-extension-trials | share/lua/playlist/bbc_co_uk.lua | 11 | 1514 | --[[
$Id$
Copyright © 2008 the VideoLAN team
Authors: Dominique Leuenberger <dominique-vlc.suse@leuenberger.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
local path = vlc.path:gsub("^www%.", "")
return vlc.access == "http"
and string.match( path, "^bbc%.co%.uk/iplayer/.+" )
end
-- Parse function.
function parse()
p = {}
while true do
-- Try to find the video's title
line = vlc.readline()
if not line then break end
if string.match( line, "title: " ) then
_,_,name = string.find( line, "title: \"(.*)\"" )
end
if string.match( line, "metaFile: \".*%.ram\"" ) then
_,_,video = string.find( line, "metaFile: \"(.-)\"" )
table.insert( p, { path = video; name = name } )
end
end
return p
end
| gpl-2.0 |
mohammadclashclash/mehdi002 | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
WeiNSteiN-Dev/The_New_Satan | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
mtyzaq/extra | packages/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan3/mwan3_ruleconfig.lua | 9 | 3337 | -- ------ extra functions ------ --
function rule_check() -- determine if rule needs a protocol specified
local sport = ut.trim(sys.exec("uci get -p /var/state mwan3." .. arg[1] .. ".src_port"))
local dport = ut.trim(sys.exec("uci get -p /var/state mwan3." .. arg[1] .. ".dest_port"))
if sport ~= "" or dport ~= "" then -- ports configured
local proto = ut.trim(sys.exec("uci get -p /var/state mwan3." .. arg[1] .. ".proto"))
if proto == "" or proto == "all" then -- no or improper protocol
err_proto = 1
end
end
end
function rule_warn() -- display warning message at the top of the page
if err_proto == 1 then
return "<font color=\"ff0000\"><strong>WARNING: this rule is incorrectly configured with no or improper protocol specified! Please configure a specific protocol!</strong></font>"
else
return ""
end
end
function cbi_add_policy(field)
uci.cursor():foreach("mwan3", "policy",
function (section)
field:value(section[".name"])
end
)
end
function cbi_add_protocol(field)
local protos = ut.trim(sys.exec("cat /etc/protocols | grep ' # ' | awk -F' ' '{print $1}' | grep -vw -e 'ip' -e 'tcp' -e 'udp' -e 'icmp' -e 'esp' | grep -v 'ipv6' | sort | tr '\n' ' '"))
for p in string.gmatch(protos, "%S+") do
field:value(p)
end
end
-- ------ rule configuration ------ --
dsp = require "luci.dispatcher"
sys = require "luci.sys"
ut = require "luci.util"
arg[1] = arg[1] or ""
err_proto = 0
rule_check()
m5 = Map("mwan3", translate("MWAN3 Multi-WAN Rule Configuration - ") .. arg[1],
translate(rule_warn()))
m5.redirect = dsp.build_url("admin", "network", "mwan3", "configuration", "rule")
mwan_rule = m5:section(NamedSection, arg[1], "rule", "")
mwan_rule.addremove = false
mwan_rule.dynamic = false
src_ip = mwan_rule:option(Value, "src_ip", translate("Source address"),
translate("Supports CIDR notation (eg \"192.168.100.0/24\") without quotes"))
src_ip.datatype = ipaddr
src_port = mwan_rule:option(Value, "src_port", translate("Source port"),
translate("May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes"))
dest_ip = mwan_rule:option(Value, "dest_ip", translate("Destination address"),
translate("Supports CIDR notation (eg \"192.168.100.0/24\") without quotes"))
dest_ip.datatype = ipaddr
dest_port = mwan_rule:option(Value, "dest_port", translate("Destination port"),
translate("May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes"))
proto = mwan_rule:option(Value, "proto", translate("Protocol"),
translate("View the contents of /etc/protocols for protocol descriptions"))
proto.default = "all"
proto.rmempty = false
proto:value("all")
proto:value("ip")
proto:value("tcp")
proto:value("udp")
proto:value("icmp")
proto:value("esp")
cbi_add_protocol(proto)
use_policy = mwan_rule:option(Value, "use_policy", translate("Policy assigned"))
cbi_add_policy(use_policy)
use_policy:value("unreachable")
use_policy:value("default")
-- ------ currently configured policies ------ --
mwan_policy = m5:section(TypedSection, "policy", translate("Currently Configured Policies"))
mwan_policy.addremove = false
mwan_policy.dynamic = false
mwan_policy.sortable = false
mwan_policy.template = "cbi/tblsection"
return m5
| gpl-2.0 |
caohongtao/quick-cocos-demo | runtime/mac/PrebuiltRuntimeLua.app/Contents/Resources/src/framework/cc/ui/UIButton.lua | 9 | 15243 |
--[[
Copyright (c) 2011-2014 chukong-inc.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
--------------------------------
-- @module UIButton
--[[--
quick Button控件
]]
local UIButton = class("UIButton", function()
return display.newNode()
end)
UIButton.CLICKED_EVENT = "CLICKED_EVENT"
UIButton.PRESSED_EVENT = "PRESSED_EVENT"
UIButton.RELEASE_EVENT = "RELEASE_EVENT"
UIButton.STATE_CHANGED_EVENT = "STATE_CHANGED_EVENT"
UIButton.IMAGE_ZORDER = -100
UIButton.LABEL_ZORDER = 0
-- start --
--------------------------------
-- UIButton构建函数
-- @function [parent=#UIButton] new
-- @param table events 按钮状态表
-- @param string initialState 初始状态
-- @param table options 参数表
-- end --
function UIButton:ctor(events, initialState, options)
self.fsm_ = {}
cc(self.fsm_)
:addComponent("components.behavior.StateMachine")
:exportMethods()
self.fsm_:setupState({
initial = {state = initialState, event = "startup", defer = false},
events = events,
callbacks = {
onchangestate = handler(self, self.onChangeState_),
}
})
makeUIControl_(self)
self:setLayoutSizePolicy(display.FIXED_SIZE, display.FIXED_SIZE)
self:setButtonEnabled(true)
self:addNodeEventListener(cc.NODE_TOUCH_EVENT, handler(self, self.onTouch_))
self.touchInSpriteOnly_ = options and options.touchInSprite
self.currentImage_ = nil
self.images_ = {}
self.sprite_ = {}
self.scale9_ = options and options.scale9
self.flipX_ = options and options.flipX
self.flipY_ = options and options.flipY
self.scale9Size_ = nil
self.labels_ = {}
self.labelOffset_ = {0, 0}
self.labelAlign_ = display.CENTER
self.initialState_ = initialState
display.align(self, display.CENTER)
if "boolean" ~= type(self.flipX_) then
self.flipX_ = false
end
if "boolean" ~= type(self.flipY_) then
self.flipY_ = false
end
self:addNodeEventListener(cc.NODE_EVENT, function(event)
if event.name == "enter" then
self:updateButtonImage_()
end
end)
end
-- start --
--------------------------------
-- 停靠位置
-- @function [parent=#UIButton] align
-- @param number align 锚点位置
-- @param number x
-- @param number y
-- @return UIButton#UIButton
-- end --
function UIButton:align(align, x, y)
display.align(self, align, x, y)
self:updateButtonImage_()
self:updateButtonLable_()
local size = self:getCascadeBoundingBox().size
local ap = self:getAnchorPoint()
-- self:setPosition(x + size.width * (ap.x - 0.5), y + size.height * (0.5 - ap.y))
return self
end
-- start --
--------------------------------
-- 设置按钮特定状态的图片
-- @function [parent=#UIButton] setButtonImage
-- @param string state 状态
-- @param string image 图片路径
-- @param boolean ignoreEmpty 是否忽略空的图片路径
-- @return UIButton#UIButton
-- end --
function UIButton:setButtonImage(state, image, ignoreEmpty)
if ignoreEmpty and image == nil then return end
self.images_[state] = image
if state == self.fsm_:getState() then
self:updateButtonImage_()
end
return self
end
-- start --
--------------------------------
-- 设置按钮特定状态的文字node
-- @function [parent=#UIButton] setButtonLabel
-- @param string state 状态
-- @param node label 文字node
-- @return UIButton#UIButton
-- end --
function UIButton:setButtonLabel(state, label)
if not label then
label = state
state = self:getDefaultState_()
end
assert(label ~= nil, "UIButton:setButtonLabel() - invalid label")
if type(state) == "table" then state = state[1] end
local currentLabel = self.labels_[state]
if currentLabel then currentLabel:removeSelf() end
self.labels_[state] = label
self:addChild(label, UIButton.LABEL_ZORDER)
self:updateButtonLable_()
return self
end
-- start --
--------------------------------
-- 返回按钮特定状态的文字
-- @function [parent=#UIButton] getButtonLabel
-- @param string state 状态
-- @return node#node 文字label
-- end --
function UIButton:getButtonLabel(state)
if not state then
state = self:getDefaultState_()
end
if type(state) == "table" then state = state[1] end
return self.labels_[state]
end
-- start --
--------------------------------
-- 设置按钮特定状态的文字
-- @function [parent=#UIButton] setButtonLabelString
-- @param string state 状态
-- @param string text 文字
-- @return UIButton#UIButton
-- end --
function UIButton:setButtonLabelString(state, text)
assert(self.labels_ ~= nil, "UIButton:setButtonLabelString() - not add label")
if text == nil then
text = state
for _, label in pairs(self.labels_) do
label:setString(text)
end
else
local label = self.labels_[state]
if label then label:setString(text) end
end
return self
end
-- start --
--------------------------------
-- 返回文字标签的偏移
-- @function [parent=#UIButton] getButtonLabelOffset
-- @return number#number x
-- @return number#number y
-- end --
function UIButton:getButtonLabelOffset()
return self.labelOffset_[1], self.labelOffset_[2]
end
-- start --
--------------------------------
-- 设置文字标签的偏移
-- @function [parent=#UIButton] setButtonLabelOffset
-- @param number x
-- @param number y
-- @return UIButton#UIButton
-- end --
function UIButton:setButtonLabelOffset(ox, oy)
self.labelOffset_ = {ox, oy}
self:updateButtonLable_()
return self
end
-- start --
--------------------------------
-- 得到文字标签的停靠方式
-- @function [parent=#UIButton] getButtonLabelAlignment
-- @return number#number
-- end --
function UIButton:getButtonLabelAlignment()
return self.labelAlign_
end
-- start --
--------------------------------
-- 设置文字标签的停靠方式
-- @function [parent=#UIButton] setButtonLabelAlignment
-- @param number align
-- @return UIButton#UIButton
-- end --
function UIButton:setButtonLabelAlignment(align)
self.labelAlign_ = align
self:updateButtonLable_()
return self
end
-- start --
--------------------------------
-- 设置按钮的大小
-- @function [parent=#UIButton] setButtonSize
-- @param number width
-- @param number height
-- @return UIButton#UIButton
-- end --
function UIButton:setButtonSize(width, height)
-- assert(self.scale9_, "UIButton:setButtonSize() - can't change size for non-scale9 button")
self.scale9Size_ = {width, height}
for i,v in ipairs(self.sprite_) do
if self.scale9_ then
v:setContentSize(cc.size(self.scale9Size_[1], self.scale9Size_[2]))
else
local size = v:getContentSize()
local scaleX = v:getScaleX()
local scaleY = v:getScaleY()
scaleX = scaleX * self.scale9Size_[1]/size.width
scaleY = scaleY * self.scale9Size_[2]/size.height
v:setScaleX(scaleX)
v:setScaleY(scaleY)
end
end
return self
end
-- start --
--------------------------------
-- 设置按钮是否有效
-- @function [parent=#UIButton] setButtonEnabled
-- @param boolean enabled 是否有效
-- @return UIButton#UIButton
-- end --
function UIButton:setButtonEnabled(enabled)
self:setTouchEnabled(enabled)
if enabled and self.fsm_:canDoEvent("enable") then
self.fsm_:doEventForce("enable")
self:dispatchEvent({name = UIButton.STATE_CHANGED_EVENT, state = self.fsm_:getState()})
elseif not enabled and self.fsm_:canDoEvent("disable") then
self.fsm_:doEventForce("disable")
self:dispatchEvent({name = UIButton.STATE_CHANGED_EVENT, state = self.fsm_:getState()})
end
return self
end
-- start --
--------------------------------
-- 返回按钮是否有效
-- @function [parent=#UIButton] isButtonEnabled
-- @return boolean#boolean
-- end --
function UIButton:isButtonEnabled()
return self.fsm_:canDoEvent("disable")
end
function UIButton:addButtonClickedEventListener(callback)
return self:addEventListener(UIButton.CLICKED_EVENT, callback)
end
-- start --
--------------------------------
-- 注册用户点击监听
-- @function [parent=#UIButton] onButtonClicked
-- @param function callback 监听函数
-- @return UIButton#UIButton
-- end --
function UIButton:onButtonClicked(callback)
self:addButtonClickedEventListener(callback)
return self
end
function UIButton:addButtonPressedEventListener(callback)
return self:addEventListener(UIButton.PRESSED_EVENT, callback)
end
-- start --
--------------------------------
-- 注册用户按下监听
-- @function [parent=#UIButton] onButtonPressed
-- @param function callback 监听函数
-- @return UIButton#UIButton
-- end --
function UIButton:onButtonPressed(callback)
self:addButtonPressedEventListener(callback)
return self
end
function UIButton:addButtonReleaseEventListener(callback)
return self:addEventListener(UIButton.RELEASE_EVENT, callback)
end
-- start --
--------------------------------
-- 注册用户释放监听
-- @function [parent=#UIButton] onButtonRelease
-- @param function callback 监听函数
-- @return UIButton#UIButton
-- end --
function UIButton:onButtonRelease(callback)
self:addButtonReleaseEventListener(callback)
return self
end
function UIButton:addButtonStateChangedEventListener(callback)
return self:addEventListener(UIButton.STATE_CHANGED_EVENT, callback)
end
-- start --
--------------------------------
-- 注册按钮状态变化监听
-- @function [parent=#UIButton] onButtonStateChanged
-- @param function callback 监听函数
-- @return UIButton#UIButton
-- end --
function UIButton:onButtonStateChanged(callback)
self:addButtonStateChangedEventListener(callback)
return self
end
function UIButton:onChangeState_(event)
if self:isRunning() then
self:updateButtonImage_()
self:updateButtonLable_()
end
end
function UIButton:onTouch_(event)
printError("UIButton:onTouch_() - must override in inherited class")
end
function UIButton:updateButtonImage_()
local state = self.fsm_:getState()
local image = self.images_[state]
if not image then
for _, s in pairs(self:getDefaultState_()) do
image = self.images_[s]
if image then break end
end
end
if image then
if self.currentImage_ ~= image then
for i,v in ipairs(self.sprite_) do
v:removeFromParent(true)
end
self.sprite_ = {}
self.currentImage_ = image
if "table" == type(image) then
for i,v in ipairs(image) do
if self.scale9_ then
self.sprite_[i] = display.newScale9Sprite(v)
if not self.scale9Size_ then
local size = self.sprite_[i]:getContentSize()
self.scale9Size_ = {size.width, size.height}
else
self.sprite_[i]:setContentSize(cc.size(self.scale9Size_[1], self.scale9Size_[2]))
end
else
self.sprite_[i] = display.newSprite(v)
end
self:addChild(self.sprite_[i], UIButton.IMAGE_ZORDER)
if self.sprite_[i].setFlippedX then
if self.flipX_ then
self.sprite_[i]:setFlippedX(self.flipX_ or false)
end
if self.flipY_ then
self.sprite_[i]:setFlippedY(self.flipY_ or false)
end
end
end
else
if self.scale9_ then
self.sprite_[1] = display.newScale9Sprite(image)
if not self.scale9Size_ then
local size = self.sprite_[1]:getContentSize()
self.scale9Size_ = {size.width, size.height}
else
self.sprite_[1]:setContentSize(cc.size(self.scale9Size_[1], self.scale9Size_[2]))
end
else
self.sprite_[1] = display.newSprite(image)
end
if self.sprite_[1].setFlippedX then
if self.flipX_ then
self.sprite_[1]:setFlippedX(self.flipX_ or false)
end
if self.flipY_ then
self.sprite_[1]:setFlippedY(self.flipY_ or false)
end
end
self:addChild(self.sprite_[1], UIButton.IMAGE_ZORDER)
end
end
for i,v in ipairs(self.sprite_) do
v:setAnchorPoint(self:getAnchorPoint())
v:setPosition(0, 0)
end
elseif not self.labels_ then
printError("UIButton:updateButtonImage_() - not set image for state %s", state)
end
end
function UIButton:updateButtonLable_()
if not self.labels_ then return end
local state = self.fsm_:getState()
local label = self.labels_[state]
if not label then
for _, s in pairs(self:getDefaultState_()) do
label = self.labels_[s]
if label then break end
end
end
local ox, oy = self.labelOffset_[1], self.labelOffset_[2]
if self.sprite_[1] then
local ap = self:getAnchorPoint()
local spriteSize = self.sprite_[1]:getContentSize()
ox = ox + spriteSize.width * (0.5 - ap.x)
oy = oy + spriteSize.height * (0.5 - ap.y)
end
for _, l in pairs(self.labels_) do
l:setVisible(l == label)
l:align(self.labelAlign_, ox, oy)
end
end
function UIButton:getDefaultState_()
return {self.initialState_}
end
function UIButton:checkTouchInSprite_(x, y)
if self.touchInSpriteOnly_ then
return self.sprite_[1] and self.sprite_[1]:getCascadeBoundingBox():containsPoint(cc.p(x, y))
else
return self:getCascadeBoundingBox():containsPoint(cc.p(x, y))
end
end
return UIButton
| apache-2.0 |
vikas17a/Algorithm-Implementations | Ranrot-B-Pseudo_Random_Number_Generator/Lua/Yonaba/numberlua.lua | 115 | 13399 | --[[
LUA MODULE
bit.numberlua - Bitwise operations implemented in pure Lua as numbers,
with Lua 5.2 'bit32' and (LuaJIT) LuaBitOp 'bit' compatibility interfaces.
SYNOPSIS
local bit = require 'bit.numberlua'
print(bit.band(0xff00ff00, 0x00ff00ff)) --> 0xffffffff
-- Interface providing strong Lua 5.2 'bit32' compatibility
local bit32 = require 'bit.numberlua'.bit32
assert(bit32.band(-1) == 0xffffffff)
-- Interface providing strong (LuaJIT) LuaBitOp 'bit' compatibility
local bit = require 'bit.numberlua'.bit
assert(bit.tobit(0xffffffff) == -1)
DESCRIPTION
This library implements bitwise operations entirely in Lua.
This module is typically intended if for some reasons you don't want
to or cannot install a popular C based bit library like BitOp 'bit' [1]
(which comes pre-installed with LuaJIT) or 'bit32' (which comes
pre-installed with Lua 5.2) but want a similar interface.
This modules represents bit arrays as non-negative Lua numbers. [1]
It can represent 32-bit bit arrays when Lua is compiled
with lua_Number as double-precision IEEE 754 floating point.
The module is nearly the most efficient it can be but may be a few times
slower than the C based bit libraries and is orders or magnitude
slower than LuaJIT bit operations, which compile to native code. Therefore,
this library is inferior in performane to the other modules.
The `xor` function in this module is based partly on Roberto Ierusalimschy's
post in http://lua-users.org/lists/lua-l/2002-09/msg00134.html .
The included BIT.bit32 and BIT.bit sublibraries aims to provide 100%
compatibility with the Lua 5.2 "bit32" and (LuaJIT) LuaBitOp "bit" library.
This compatbility is at the cost of some efficiency since inputted
numbers are normalized and more general forms (e.g. multi-argument
bitwise operators) are supported.
STATUS
WARNING: Not all corner cases have been tested and documented.
Some attempt was made to make these similar to the Lua 5.2 [2]
and LuaJit BitOp [3] libraries, but this is not fully tested and there
are currently some differences. Addressing these differences may
be improved in the future but it is not yet fully determined how to
resolve these differences.
The BIT.bit32 library passes the Lua 5.2 test suite (bitwise.lua)
http://www.lua.org/tests/5.2/ . The BIT.bit library passes the LuaBitOp
test suite (bittest.lua). However, these have not been tested on
platforms with Lua compiled with 32-bit integer numbers.
API
BIT.tobit(x) --> z
Similar to function in BitOp.
BIT.tohex(x, n)
Similar to function in BitOp.
BIT.band(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bor(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bxor(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bnot(x) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.lshift(x, disp) --> z
Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift),
BIT.rshift(x, disp) --> z
Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift),
BIT.extract(x, field [, width]) --> z
Similar to function in Lua 5.2.
BIT.replace(x, v, field, width) --> z
Similar to function in Lua 5.2.
BIT.bswap(x) --> z
Similar to function in Lua 5.2.
BIT.rrotate(x, disp) --> z
BIT.ror(x, disp) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.lrotate(x, disp) --> z
BIT.rol(x, disp) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.arshift
Similar to function in Lua 5.2 and BitOp.
BIT.btest
Similar to function in Lua 5.2 with requires two arguments.
BIT.bit32
This table contains functions that aim to provide 100% compatibility
with the Lua 5.2 "bit32" library.
bit32.arshift (x, disp) --> z
bit32.band (...) --> z
bit32.bnot (x) --> z
bit32.bor (...) --> z
bit32.btest (...) --> true | false
bit32.bxor (...) --> z
bit32.extract (x, field [, width]) --> z
bit32.replace (x, v, field [, width]) --> z
bit32.lrotate (x, disp) --> z
bit32.lshift (x, disp) --> z
bit32.rrotate (x, disp) --> z
bit32.rshift (x, disp) --> z
BIT.bit
This table contains functions that aim to provide 100% compatibility
with the LuaBitOp "bit" library (from LuaJIT).
bit.tobit(x) --> y
bit.tohex(x [,n]) --> y
bit.bnot(x) --> y
bit.bor(x1 [,x2...]) --> y
bit.band(x1 [,x2...]) --> y
bit.bxor(x1 [,x2...]) --> y
bit.lshift(x, n) --> y
bit.rshift(x, n) --> y
bit.arshift(x, n) --> y
bit.rol(x, n) --> y
bit.ror(x, n) --> y
bit.bswap(x) --> y
DEPENDENCIES
None (other than Lua 5.1 or 5.2).
DOWNLOAD/INSTALLATION
If using LuaRocks:
luarocks install lua-bit-numberlua
Otherwise, download <https://github.com/davidm/lua-bit-numberlua/zipball/master>.
Alternately, if using git:
git clone git://github.com/davidm/lua-bit-numberlua.git
cd lua-bit-numberlua
Optionally unpack:
./util.mk
or unpack and install in LuaRocks:
./util.mk install
REFERENCES
[1] http://lua-users.org/wiki/FloatingPoint
[2] http://www.lua.org/manual/5.2/
[3] http://bitop.luajit.org/
LICENSE
(c) 2008-2011 David Manura. Licensed under the same terms as Lua (MIT).
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.
(end license)
--]]
local M = {_TYPE='module', _NAME='bit.numberlua', _VERSION='0.3.1.20120131'}
local floor = math.floor
local MOD = 2^32
local MODM = MOD-1
local function memoize(f)
local mt = {}
local t = setmetatable({}, mt)
function mt:__index(k)
local v = f(k); t[k] = v
return v
end
return t
end
local function make_bitop_uncached(t, m)
local function bitop(a, b)
local res,p = 0,1
while a ~= 0 and b ~= 0 do
local am, bm = a%m, b%m
res = res + t[am][bm]*p
a = (a - am) / m
b = (b - bm) / m
p = p*m
end
res = res + (a+b)*p
return res
end
return bitop
end
local function make_bitop(t)
local op1 = make_bitop_uncached(t,2^1)
local op2 = memoize(function(a)
return memoize(function(b)
return op1(a, b)
end)
end)
return make_bitop_uncached(op2, 2^(t.n or 1))
end
-- ok? probably not if running on a 32-bit int Lua number type platform
function M.tobit(x)
return x % 2^32
end
M.bxor = make_bitop {[0]={[0]=0,[1]=1},[1]={[0]=1,[1]=0}, n=4}
local bxor = M.bxor
function M.bnot(a) return MODM - a end
local bnot = M.bnot
function M.band(a,b) return ((a+b) - bxor(a,b))/2 end
local band = M.band
function M.bor(a,b) return MODM - band(MODM - a, MODM - b) end
local bor = M.bor
local lshift, rshift -- forward declare
function M.rshift(a,disp) -- Lua5.2 insipred
if disp < 0 then return lshift(a,-disp) end
return floor(a % 2^32 / 2^disp)
end
rshift = M.rshift
function M.lshift(a,disp) -- Lua5.2 inspired
if disp < 0 then return rshift(a,-disp) end
return (a * 2^disp) % 2^32
end
lshift = M.lshift
function M.tohex(x, n) -- BitOp style
n = n or 8
local up
if n <= 0 then
if n == 0 then return '' end
up = true
n = - n
end
x = band(x, 16^n-1)
return ('%0'..n..(up and 'X' or 'x')):format(x)
end
local tohex = M.tohex
function M.extract(n, field, width) -- Lua5.2 inspired
width = width or 1
return band(rshift(n, field), 2^width-1)
end
local extract = M.extract
function M.replace(n, v, field, width) -- Lua5.2 inspired
width = width or 1
local mask1 = 2^width-1
v = band(v, mask1) -- required by spec?
local mask = bnot(lshift(mask1, field))
return band(n, mask) + lshift(v, field)
end
local replace = M.replace
function M.bswap(x) -- BitOp style
local a = band(x, 0xff); x = rshift(x, 8)
local b = band(x, 0xff); x = rshift(x, 8)
local c = band(x, 0xff); x = rshift(x, 8)
local d = band(x, 0xff)
return lshift(lshift(lshift(a, 8) + b, 8) + c, 8) + d
end
local bswap = M.bswap
function M.rrotate(x, disp) -- Lua5.2 inspired
disp = disp % 32
local low = band(x, 2^disp-1)
return rshift(x, disp) + lshift(low, 32-disp)
end
local rrotate = M.rrotate
function M.lrotate(x, disp) -- Lua5.2 inspired
return rrotate(x, -disp)
end
local lrotate = M.lrotate
M.rol = M.lrotate -- LuaOp inspired
M.ror = M.rrotate -- LuaOp insipred
function M.arshift(x, disp) -- Lua5.2 inspired
local z = rshift(x, disp)
if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end
return z
end
local arshift = M.arshift
function M.btest(x, y) -- Lua5.2 inspired
return band(x, y) ~= 0
end
--
-- Start Lua 5.2 "bit32" compat section.
--
M.bit32 = {} -- Lua 5.2 'bit32' compatibility
local function bit32_bnot(x)
return (-1 - x) % MOD
end
M.bit32.bnot = bit32_bnot
local function bit32_bxor(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = bxor(a, b)
if c then
z = bit32_bxor(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return 0
end
end
M.bit32.bxor = bit32_bxor
local function bit32_band(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = ((a+b) - bxor(a,b)) / 2
if c then
z = bit32_band(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return MODM
end
end
M.bit32.band = bit32_band
local function bit32_bor(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = MODM - band(MODM - a, MODM - b)
if c then
z = bit32_bor(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return 0
end
end
M.bit32.bor = bit32_bor
function M.bit32.btest(...)
return bit32_band(...) ~= 0
end
function M.bit32.lrotate(x, disp)
return lrotate(x % MOD, disp)
end
function M.bit32.rrotate(x, disp)
return rrotate(x % MOD, disp)
end
function M.bit32.lshift(x,disp)
if disp > 31 or disp < -31 then return 0 end
return lshift(x % MOD, disp)
end
function M.bit32.rshift(x,disp)
if disp > 31 or disp < -31 then return 0 end
return rshift(x % MOD, disp)
end
function M.bit32.arshift(x,disp)
x = x % MOD
if disp >= 0 then
if disp > 31 then
return (x >= 0x80000000) and MODM or 0
else
local z = rshift(x, disp)
if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end
return z
end
else
return lshift(x, -disp)
end
end
function M.bit32.extract(x, field, ...)
local width = ... or 1
if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end
x = x % MOD
return extract(x, field, ...)
end
function M.bit32.replace(x, v, field, ...)
local width = ... or 1
if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end
x = x % MOD
v = v % MOD
return replace(x, v, field, ...)
end
--
-- Start LuaBitOp "bit" compat section.
--
M.bit = {} -- LuaBitOp "bit" compatibility
function M.bit.tobit(x)
x = x % MOD
if x >= 0x80000000 then x = x - MOD end
return x
end
local bit_tobit = M.bit.tobit
function M.bit.tohex(x, ...)
return tohex(x % MOD, ...)
end
function M.bit.bnot(x)
return bit_tobit(bnot(x % MOD))
end
local function bit_bor(a, b, c, ...)
if c then
return bit_bor(bit_bor(a, b), c, ...)
elseif b then
return bit_tobit(bor(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.bor = bit_bor
local function bit_band(a, b, c, ...)
if c then
return bit_band(bit_band(a, b), c, ...)
elseif b then
return bit_tobit(band(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.band = bit_band
local function bit_bxor(a, b, c, ...)
if c then
return bit_bxor(bit_bxor(a, b), c, ...)
elseif b then
return bit_tobit(bxor(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.bxor = bit_bxor
function M.bit.lshift(x, n)
return bit_tobit(lshift(x % MOD, n % 32))
end
function M.bit.rshift(x, n)
return bit_tobit(rshift(x % MOD, n % 32))
end
function M.bit.arshift(x, n)
return bit_tobit(arshift(x % MOD, n % 32))
end
function M.bit.rol(x, n)
return bit_tobit(lrotate(x % MOD, n % 32))
end
function M.bit.ror(x, n)
return bit_tobit(rrotate(x % MOD, n % 32))
end
function M.bit.bswap(x)
return bit_tobit(bswap(x % MOD))
end
return M
| mit |
lemones/dotfiles | home/.config/awesome/lain/layout/centerworkd.lua | 4 | 3976 |
--[[
Licensed under GNU General Public License v2
* (c) 2016, Henrik Antonsson
* (c) 2014, projektile
* (c) 2013, Luke Bonham
* (c) 2010-2012, Peter Hofmann
Based on centerwork.lua
--]]
local awful = require("awful")
local beautiful = require("beautiful")
local tonumber = tonumber
local math = { floor = math.floor }
local centerworkd =
{
name = "centerworkd",
}
function centerworkd.arrange(p)
-- A useless gap (like the dwm patch) can be defined with
-- beautiful.useless_gap_width .
local useless_gap = tonumber(beautiful.useless_gap_width) or 0
-- A global border can be defined with
-- beautiful.global_border_width
local global_border = tonumber(beautiful.global_border_width) or 0
if global_border < 0 then global_border = 0 end
-- Screen.
local wa = p.workarea
local cls = p.clients
-- Borders are factored in.
wa.height = wa.height - (global_border * 2)
wa.width = wa.width - (global_border * 2)
wa.x = wa.x + global_border
wa.y = wa.y + global_border
-- Width of main column?
local t = awful.tag.selected(p.screen)
local mwfact = awful.tag.getmwfact(t)
if #cls > 0
then
-- Main column, fixed width and height.
local c = cls[1]
local g = {}
local mainwid = math.floor(wa.width * mwfact)
local slavewid = wa.width - mainwid
local slaveLwid = math.floor(slavewid / 2)
local slaveRwid = slavewid - slaveLwid
local nbrLeftSlaves = math.floor(#cls / 2)
local nbrRightSlaves = math.floor((#cls - 1) / 2)
local slaveLeftHeight = 0
if nbrLeftSlaves > 0 then slaveLeftHeight = math.floor(wa.height / nbrLeftSlaves) end
if nbrRightSlaves > 0 then slaveRightHeight = math.floor(wa.height / nbrRightSlaves) end
g.height = wa.height - 2*useless_gap - 2*c.border_width
g.width = mainwid - 2*c.border_width
g.x = wa.x + slaveLwid
g.y = wa.y + useless_gap
if g.width < 1 then g.width = 1 end
if g.height < 1 then g.height = 1 end
c:geometry(g)
-- Auxiliary windows.
if #cls > 1
then
for i = 2,#cls
do
c = cls[i]
g = {}
local rowIndex = math.floor(i/2)
-- If i is even it should be placed on the left side
if i % 2 == 0
then
-- left slave
g.x = wa.x + useless_gap
g.y = wa.y + useless_gap + (rowIndex-1)*slaveLeftHeight
g.width = slaveLwid - 2*useless_gap - 2*c.border_width
-- if last slave in left row use remaining space for that slave
if rowIndex == nbrLeftSlaves
then
g.height = wa.y + wa.height - g.y - useless_gap - 2*c.border_width
else
g.height = slaveLeftHeight - useless_gap - 2*c.border_width
end
else
-- right slave
g.x = wa.x + slaveLwid + mainwid + useless_gap
g.y = wa.y + useless_gap + (rowIndex-1)*slaveRightHeight
g.width = slaveRwid - 2*useless_gap - 2*c.border_width
-- if last slave in right row use remaining space for that slave
if rowIndex == nbrRightSlaves
then
g.height = wa.y + wa.height - g.y - useless_gap - 2*c.border_width
else
g.height = slaveRightHeight - useless_gap - 2*c.border_width
end
end
if g.width < 1 then g.width = 1 end
if g.height < 1 then g.height = 1 end
c:geometry(g)
end
end
end
end
return centerworkd
| gpl-3.0 |
JosephBywater/ProjectPorcupine | Assets/StreamingAssets/LUA/Furniture.lua | 2 | 25565 | -------------------------------------------------------
-- Project Porcupine Copyright(C) 2016 Team Porcupine
-- This program comes with ABSOLUTELY NO WARRANTY; This is free software,
-- and you are welcome to redistribute it under certain conditions; See
-- file LICENSE, which is part of this source code package, for details.
-------------------------------------------------------
-- TODO: Figure out the nicest way to have unified defines/enums
-- between C# and Lua so we don't have to duplicate anything.
ENTERABILITY_YES = 0
ENTERABILITY_NO = 1
ENTERABILITY_SOON = 2
-- HOWTO Log:
-- ModUtils.ULog("Testing ModUtils.ULogChannel")
-- ModUtils.ULogWarning("Testing ModUtils.ULogWarningChannel")
-- ModUtils.ULogError("Testing ModUtils.ULogErrorChannel") -- Note: pauses the game
-------------------------------- Furniture Actions --------------------------------
function OxygenGenerator_OnUpdate( furniture, deltaTime )
if ( furniture.Tile.Room == nil ) then
return "Furniture's room was null."
end
local keys = furniture.Parameters["gas_gen"].Keys()
for discard, key in pairs(keys) do
if ( furniture.Tile.Room.GetGasPressure(key) < furniture.Parameters["gas_gen"][key]["gas_limit"].ToFloat()) then
furniture.Tile.Room.ChangeGas(key, furniture.Parameters["gas_per_second"].ToFloat() * deltaTime * furniture.Parameters["gas_gen"][key]["gas_limit"].ToFloat())
else
-- Do we go into a standby mode to save power?
end
end
return
furniture.SetAnimationState("running")
end
function OxygenGenerator_OnPowerOff( furniture, deltaTime )
furniture.SetAnimationState("idle")
end
function OnUpdate_Door( furniture, deltaTime )
if (furniture.Parameters["is_opening"].ToFloat() >= 1.0) then
furniture.Parameters["openness"].ChangeFloatValue(deltaTime * 4) -- FIXME: Maybe a door open speed parameter?
if (furniture.Parameters["openness"].ToFloat() >= 1) then
furniture.Parameters["is_opening"].SetValue(0)
end
elseif (furniture.Parameters["openness"].ToFloat() > 0.0) then
furniture.Parameters["openness"].ChangeFloatValue(deltaTime * -4)
end
furniture.Parameters["openness"].SetValue( ModUtils.Clamp01(furniture.Parameters["openness"].ToFloat()) )
if (furniture.verticalDoor == true) then
furniture.SetAnimationState("vertical")
else
furniture.SetAnimationState("horizontal")
end
furniture.SetAnimationProgressValue(furniture.Parameters["openness"].ToFloat(), 1)
end
function OnUpdate_AirlockDoor( furniture, deltaTime )
if (furniture.Parameters["pressure_locked"].ToFloat() >= 1.0) then
local neighbors = furniture.Tile.GetNeighbours(false)
local adjacentRooms = {}
local pressureEqual = true;
local count = 0
for k, tile in pairs(neighbors) do
if (tile.Room != nil) then
count = count + 1
adjacentRooms[count] = tile.Room
end
end
if(ModUtils.Round(adjacentRooms[1].GetTotalGasPressure(),3) == ModUtils.Round(adjacentRooms[2].GetTotalGasPressure(),3)) then
OnUpdate_Door(furniture, deltaTime)
end
else
OnUpdate_Door(furniture, deltaTime)
end
end
function AirlockDoor_Toggle_Pressure_Lock(furniture, character)
ModUtils.ULog("Toggling Pressure Lock")
if (furniture.Parameters["pressure_locked"].ToFloat() == 1) then
furniture.Parameters["pressure_locked"].SetValue(0)
else
furniture.Parameters["pressure_locked"].SetValue(1)
end
ModUtils.ULog(furniture.Parameters["pressure_locked"].ToFloat())
end
function OnUpdate_Leak_Door( furniture, deltaTime )
furniture.Tile.EqualiseGas(deltaTime * 10.0 * (furniture.Parameters["openness"].ToFloat() + 0.1))
end
function OnUpdate_Leak_Airlock( furniture, deltaTime )
furniture.Tile.EqualiseGas(deltaTime * 10.0 * (furniture.Parameters["openness"].ToFloat()))
end
function IsEnterable_Door( furniture )
furniture.Parameters["is_opening"].SetValue(1)
if (furniture.Parameters["openness"].ToFloat() >= 1) then
return ENTERABILITY_YES --ENTERABILITY.Yes
end
return ENTERABILITY_SOON --ENTERABILITY.Soon
end
function Stockpile_GetItemsFromFilter( furniture )
-- TODO: This should be reading from some kind of UI for this
-- particular stockpile
-- Probably, this doesn't belong in Lua at all and instead we should
-- just be calling a C# function to give us the list.
-- Since jobs copy arrays automatically, we could already have
-- an Inventory[] prepared and just return that (as a sort of example filter)
--return { Inventory.__new("Steel Plate", 50, 0) }
return furniture.AcceptsForStorage()
end
function Stockpile_UpdateAction( furniture, deltaTime )
-- We need to ensure that we have a job on the queue
-- asking for either:
-- (if we are empty): That ANY loose inventory be brought to us.
-- (if we have something): Then IF we are still below the max stack size,
-- that more of the same should be brought to us.
-- TODO: This function doesn't need to run each update. Once we get a lot
-- of furniture in a running game, this will run a LOT more than required.
-- Instead, it only really needs to run whenever:
-- -- It gets created
-- -- A good gets delivered (at which point we reset the job)
-- -- A good gets picked up (at which point we reset the job)
-- -- The UI's filter of allowed items gets changed
if( furniture.Tile.Inventory != nil and furniture.Tile.Inventory.StackSize >= furniture.Tile.Inventory.MaxStackSize ) then
-- We are full!
furniture.Jobs.CancelAll()
return
end
-- Maybe we already have a job queued up?
if( furniture.Jobs.Count > 0 ) then
-- Cool, all done.
return
end
-- We Currently are NOT full, but we don't have a job either.
-- Two possibilities: Either we have SOME inventory, or we have NO inventory.
-- Third possibility: Something is WHACK
if( furniture.Tile.Inventory != nil and furniture.Tile.Inventory.StackSize == 0 ) then
furniture.Jobs.CancelAll()
return "Stockpile has a zero-size stack. This is clearly WRONG!"
end
-- TODO: In the future, stockpiles -- rather than being a bunch of individual
-- 1x1 tiles -- should manifest themselves as single, large objects. This
-- would respresent our first and probably only VARIABLE sized "furniture" --
-- at what happenes if there's a "hole" in our stockpile because we have an
-- actual piece of furniture (like a cooking stating) installed in the middle
-- of our stockpile?
-- In any case, once we implement "mega stockpiles", then the job-creation system
-- could be a lot smarter, in that even if the stockpile has some stuff in it, it
-- can also still be requestion different object types in its job creation.
local itemsDesired = {}
if( furniture.Tile.Inventory == nil ) then
--ModUtils.ULog("Creating job for new stack.")
itemsDesired = Stockpile_GetItemsFromFilter( furniture )
else
--ModUtils.ULog("Creating job for existing stack.")
desInv = furniture.Tile.Inventory.Clone()
desInv.MaxStackSize = desInv.MaxStackSize - desInv.StackSize
desInv.StackSize = 0
itemsDesired = { desInv }
end
local job = Job.__new(
furniture.Tile,
nil,
nil,
0,
itemsDesired,
Job.JobPriority.Low,
false
)
job.JobDescription = "job_stockpile_moving_desc"
job.acceptsAny = true
-- TODO: Later on, add stockpile priorities, so that we can take from a lower
-- priority stockpile for a higher priority one.
job.canTakeFromStockpile = false
job.RegisterJobWorkedCallback("Stockpile_JobWorked")
furniture.Jobs.Add(job)
end
function Stockpile_JobWorked(job)
job.CancelJob()
-- TODO: Change this when we figure out what we're doing for the all/any pickup job.
--values = job.GetInventoryRequirementValues();
for k, inv in pairs(job.inventoryRequirements) do
if(inv.StackSize > 0) then
World.Current.inventoryManager.PlaceInventory(job.tile, inv)
return -- There should be no way that we ever end up with more than on inventory requirement with StackSize > 0
end
end
end
function MiningDroneStation_UpdateAction( furniture, deltaTime )
local outputSpot = furniture.Jobs.OutputSpotTile
if (furniture.Jobs.Count > 0) then
-- Check to see if the Metal Plate destination tile is full.
if (outputSpot.Inventory != nil and outputSpot.Inventory.StackSize >= outputSpot.Inventory.MaxStackSize) then
-- We should stop this job, because it's impossible to make any more items.
furniture.Jobs.CancelAll()
end
return
end
-- If we get here, then we have no Current job. Check to see if our destination is full.
if (outputSpot.Inventory != nil and outputSpot.Inventory.StackSize >= outputSpot.Inventory.MaxStackSize) then
-- We are full! Don't make a job!
return
end
if (outputSpot.Inventory != nil and outputSpot.Inventory.Type != furniture.Parameters["mine_type"].ToString()) then
return
end
-- If we get here, we need to CREATE a new job.
local job = Job.__new(
furniture.Jobs.WorkSpotTile,
nil,
nil,
1,
nil,
Job.JobPriority.Medium,
true -- This job repeats until the destination tile is full.
)
job.RegisterJobCompletedCallback("MiningDroneStation_JobComplete")
job.JobDescription = "job_mining_drone_station_mining_desc"
furniture.Jobs.Add(job)
end
function MiningDroneStation_JobComplete(job)
if (job.buildable.Jobs.OutputSpotTile.Inventory == nil or job.buildable.Jobs.OutputSpotTile.Inventory.Type == job.buildable.Parameters["mine_type"].ToString()) then
World.Current.inventoryManager.PlaceInventory(job.buildable.Jobs.OutputSpotTile, Inventory.__new(job.buildable.Parameters["mine_type"].ToString(), 2))
else
job.CancelJob()
end
end
function MiningDroneStation_Change_to_Raw_Iron(furniture, character)
furniture.Parameters["mine_type"].SetValue("Raw Iron")
end
function MiningDroneStation_Change_to_Raw_Copper(furniture, character)
furniture.Parameters["mine_type"].SetValue("Raw Copper")
end
function MetalSmelter_UpdateAction(furniture, deltaTime)
local inputSpot = furniture.Jobs.InputSpotTile
local outputSpot = furniture.Jobs.OutputSpotTile
if (inputSpot.Inventory ~= nil and inputSpot.Inventory.StackSize >= 5) then
furniture.Parameters["smelttime"].ChangeFloatValue(deltaTime)
if (furniture.Parameters["smelttime"].ToFloat() >= furniture.Parameters["smelttime_required"].ToFloat()) then
furniture.Parameters["smelttime"].SetValue(0)
ModUtils.LogError("MetalSmelter: Placing inventory at :" .. outputSpot.x .. ":" .. outputSpot.y)
if (outputSpot.Inventory == nil) then
World.Current.inventoryManager.PlaceInventory(outputSpot, Inventory.__new("Steel Plate", 5))
inputSpot.Inventory.StackSize = inputSpot.Inventory.StackSize - 5
elseif (outputSpot.Inventory.StackSize <= outputSpot.Inventory.MaxStackSize - 5) then
outputSpot.Inventory.StackSize = outputSpot.Inventory.StackSize + 5
inputSpot.Inventory.StackSize = inputSpot.Inventory.StackSize - 5
end
if (inputSpot.Inventory.StackSize <= 0) then
inputSpot.Inventory = nil
end
end
end
if (inputSpot.Inventory ~= nil and inputSpot.Inventory.StackSize == inputSpot.Inventory.MaxStackSize) then
-- We have the max amount of resources, cancel the job.
-- This check exists mainly, because the job completed callback doesn't
-- seem to be reliable.
furniture.Jobs.CancelAll()
return
end
if (furniture.Jobs.Count > 0) then
return
end
-- Create job depending on the already available stack size.
local desiredStackSize = 50
local itemsDesired = { Inventory.__new("Raw Iron", 0, desiredStackSize) }
if (inputSpot.Inventory ~= nil and inputSpot.Inventory.StackSize < inputSpot.Inventory.MaxStackSize) then
desiredStackSize = inputSpot.Inventory.MaxStackSize - inputSpot.Inventory.StackSize
itemsDesired[1].MaxStackSize = desiredStackSize
end
ModUtils.ULog("MetalSmelter: Creating job for " .. desiredStackSize .. " raw iron." .. inputSpot.x .. ":" .. inputSpot.y)
local job = Job.__new(
furniture.Jobs.WorkSpotTile,
nil,
nil,
0.4,
itemsDesired,
Job.JobPriority.Medium,
false
)
job.RegisterJobWorkedCallback("MetalSmelter_JobWorked")
furniture.Jobs.Add(job)
return
end
function MetalSmelter_JobWorked(job)
job.CancelJob()
local inputSpot = job.tile.Furniture.Jobs.InputSpotTile
for k, inv in pairs(job.inventoryRequirements) do
if (inv ~= nil and inv.StackSize > 0) then
World.Current.inventoryManager.PlaceInventory(inputSpot, inv)
inputSpot.Inventory.Locked = true
return
end
end
end
function CloningPod_UpdateAction(furniture, deltaTime)
if (furniture.JobWorkSpotOffset > 0) then
return
end
local job = Job.__new(
furniture.Jobs.WorkSpotTile,
nil,
nil,
10,
nil,
Job.JobPriority.Medium,
false
)
furniture.SetAnimationState("idle")
job.RegisterJobWorkedCallback("CloningPod_JobRunning")
job.RegisterJobCompletedCallback("CloningPod_JobComplete")
job.JobDescription = "job_cloning_pod_cloning_desc"
furniture.Jobs.Add(job)
end
function CloningPod_JobRunning(job)
job.buildable.SetAnimationState("running")
end
function CloningPod_JobComplete(job)
World.Current.CharacterManager.Create(job.buildable.Jobs.OutputSpotTile())
job.buildable.Deconstruct()
end
function PowerGenerator_UpdateAction(furniture, deltatime)
if (furniture.Jobs.Count < 1 and furniture.Parameters["burnTime"].ToFloat() == 0) then
furniture.PowerConnection.OutputRate = 0
local itemsDesired = {Inventory.__new("Power Cell", 0, 1)}
local job = Job.__new(
furniture.Jobs.WorkSpotTile,
nil,
nil,
0.5,
itemsDesired,
Job.JobPriority.High,
false
)
job.RegisterJobCompletedCallback("PowerGenerator_JobComplete")
job.JobDescription = "job_power_generator_fulling_desc"
furniture.Jobs.Add(job)
else
furniture.Parameters["burnTime"].ChangeFloatValue(-deltatime)
if ( furniture.Parameters["burnTime"].ToFloat() < 0 ) then
furniture.Parameters["burnTime"].SetValue(0)
end
end
if (furniture.Parameters["burnTime"].ToFloat() == 0) then
furniture.SetAnimationState("idle")
else
furniture.SetAnimationState("running")
end
end
function PowerGenerator_JobComplete(job)
job.buildable.Parameters["burnTime"].SetValue(job.buildable.Parameters["burnTimeRequired"].ToFloat())
job.buildable.PowerConnection.OutputRate = 5
end
function PowerGenerator_FuelInfo(furniture)
local curBurn = furniture.Parameters["burnTime"].ToFloat()
local maxBurn = furniture.Parameters["burnTimeRequired"].ToFloat()
local perc = 0
if (maxBurn != 0) then
perc = curBurn * 100 / maxBurn
end
return "Fuel: " .. string.format("%.1f", perc) .. "%"
end
function LandingPad_Test_CallTradeShip(furniture, character)
WorldController.Instance.TradeController.CallTradeShipTest(furniture)
end
-- This function gets called once, when the furniture is installed
function Heater_InstallAction( furniture, deltaTime)
-- TODO: find elegant way to register heat source and sinks to Temperature
furniture.EventActions.Register("OnUpdateTemperature", "Heater_UpdateTemperature")
World.Current.temperature.RegisterSinkOrSource(furniture)
end
-- This function gets called once, when the furniture is uninstalled
function Heater_UninstallAction( furniture, deltaTime)
furniture.EventActions.Deregister("OnUpdateTemperature", "Heater_UpdateTemperature")
World.Current.temperature.DeregisterSinkOrSource(furniture)
-- TODO: find elegant way to unregister previous register
end
function Heater_UpdateTemperature( furniture, deltaTime)
if (furniture.tile.Room.IsOutsideRoom() == true) then
return
end
tile = furniture.tile
pressure = tile.Room.GetGasPressure() / tile.Room.TileCount
efficiency = ModUtils.Clamp01(pressure / furniture.Parameters["pressure_threshold"].ToFloat())
temperatureChangePerSecond = furniture.Parameters["base_heating"].ToFloat() * efficiency
temperatureChange = temperatureChangePerSecond * deltaTime
World.Current.temperature.ChangeTemperature(tile.X, tile.Y, temperatureChange)
--ModUtils.ULogChannel("Temperature", "Heat change: " .. temperatureChangePerSecond .. " => " .. World.current.temperature.GetTemperature(tile.X, tile.Y))
end
-- Should maybe later be integrated with GasGenerator function by
-- someone who knows how that would work in this case
function OxygenCompressor_OnUpdate(furniture, deltaTime)
local room = furniture.Tile.Room
local pressure = room.GetGasPressure("O2")
local gasAmount = furniture.Parameters["flow_rate"].ToFloat() * deltaTime
if (pressure < furniture.Parameters["give_threshold"].ToFloat()) then
-- Expel gas if available
if (furniture.Parameters["gas_content"].ToFloat() > 0) then
furniture.Parameters["gas_content"].ChangeFloatValue(-gasAmount)
room.ChangeGas("O2", gasAmount / room.TileCount)
furniture.UpdateOnChanged(furniture)
end
elseif (pressure > furniture.Parameters["take_threshold"].ToFloat()) then
-- Suck in gas if not full
if (furniture.Parameters["gas_content"].ToFloat() < furniture.Parameters["max_gas_content"].ToFloat()) then
furniture.Parameters["gas_content"].ChangeFloatValue(gasAmount)
room.ChangeGas("O2", -gasAmount / room.TileCount)
furniture.UpdateOnChanged(furniture)
end
end
furniture.SetAnimationState("running")
furniture.SetAnimationProgressValue(furniture.Parameters["gas_content"].ToFloat(), furniture.Parameters["max_gas_content"].ToFloat());
end
function OxygenCompressor_OnPowerOff(furniture, deltaTime)
-- lose half of gas, in case of blackout
local gasContent = furniture.Parameters["gas_content"].ToFloat()
if (gasContent > 0) then
furniture.Parameters["gas_content"].ChangeFloatValue(-gasContent/2)
furniture.UpdateOnChanged(furniture)
end
furniture.SetAnimationProgressValue(furniture.Parameters["gas_content"].ToFloat(), furniture.Parameters["max_gas_content"].ToFloat());
end
function SolarPanel_OnUpdate(furniture, deltaTime)
local baseOutput = furniture.Parameters["base_output"].ToFloat()
local efficiency = furniture.Parameters["efficiency"].ToFloat()
local powerPerSecond = baseOutput * efficiency
furniture.PowerConnection.OutputRate = powerPerSecond
end
function AirPump_OnUpdate(furniture, deltaTime)
if (furniture.HasPower() == false) then
return
end
local t = furniture.Tile
local north = World.Current.GetTileAt(t.X, t.Y + 1, t.Z)
local south = World.Current.GetTileAt(t.X, t.Y - 1, t.Z)
local west = World.Current.GetTileAt(t.X - 1, t.Y, t.Z)
local east = World.Current.GetTileAt(t.X + 1, t.Y, t.Z)
-- Find the correct rooms for source and target
-- Maybe in future this could be cached. it only changes when the direction changes
local sourceRoom = nil
local targetRoom = nil
if (north.Room != nil and south.Room != nil) then
if (furniture.Parameters["flow_direction_up"].ToFloat() > 0) then
sourceRoom = south.Room
targetRoom = north.Room
else
sourceRoom = north.Room
targetRoom = south.Room
end
elseif (west.Room != nil and east.Room != nil) then
if (furniture.Parameters["flow_direction_up"].ToFloat() > 0) then
sourceRoom = west.Room
targetRoom = east.Room
else
sourceRoom = east.Room
targetRoom = west.Room
end
else
ModUtils.UChannelLogWarning("Furniture", "Air Pump blocked. Direction unclear")
return
end
local sourcePressureLimit = furniture.Parameters["source_pressure_limit"].ToFloat()
local targetPressureLimit = furniture.Parameters["target_pressure_limit"].ToFloat()
local flow = furniture.Parameters["gas_throughput"].ToFloat() * deltaTime
-- Only transfer gas if the pressures are within the defined bounds
if (sourceRoom.GetTotalGasPressure() > sourcePressureLimit and targetRoom.GetTotalGasPressure() < targetPressureLimit) then
sourceRoom.MoveGasTo(targetRoom, flow)
end
end
function AirPump_GetSpriteName(furniture)
local t = furniture.Tile
if (furniture.Tile == nil) then
return furniture.Type
end
local north = World.Current.GetTileAt(t.X, t.Y + 1, t.Z)
local south = World.Current.GetTileAt(t.X, t.Y - 1, t.Z)
local west = World.Current.GetTileAt(t.X - 1, t.Y, t.Z)
local east = World.Current.GetTileAt(t.X + 1, t.Y, t.Z)
suffix = ""
if (north.Room != nil and south.Room != nil) then
if (furniture.Parameters["flow_direction_up"].ToFloat() > 0) then
suffix = "_SN"
else
suffix = "_NS"
end
elseif (west.Room != nil and east.Room != nil) then
if (furniture.Parameters["flow_direction_up"].ToFloat() > 0) then
suffix = "_WE"
else
suffix = "_EW"
end
end
return furniture.Type .. suffix
end
function Vent_OnUpdate(furniture, deltaTime)
furniture.SetAnimationProgressValue(furniture.Parameters["openness"].ToFloat(), 1)
furniture.Tile.EqualiseGas(deltaTime * furniture.Parameters["gas_throughput"].ToFloat() * furniture.Parameters["openness"].ToInt())
end
function Vent_SetOrientationState(furniture)
if (furniture.Tile == nil) then
return
end
local tile = furniture.Tile
if (tile.North().Room != nil and tile.South().Room != nil) then
furniture.SetAnimationState("vertical")
elseif (tile.West().Room != nil and tile.East().Room != nil) then
furniture.SetAnimationState("horizontal")
end
end
function Vent_Open(furniture)
furniture.Parameters["openness"].SetValue("1")
end
function Vent_Close(furniture)
furniture.Parameters["openness"].SetValue("0")
end
function AirPump_FlipDirection(furniture, character)
if (furniture.Parameters["flow_direction_up"].ToFloat() > 0) then
furniture.Parameters["flow_direction_up"].SetValue(0)
else
furniture.Parameters["flow_direction_up"].SetValue(1)
end
furniture.UpdateOnChanged(furniture)
end
function Accumulator_GetSpriteName(furniture)
local baseName = furniture.Type
local suffix = furniture.PowerConnection.CurrentThreshold
return baseName .. "_" .. suffix
end
function Door_GetSpriteName(furniture)
if (furniture.verticalDoor) then
return furniture.Type .. "Vertical_0"
else
return furniture.Type .. "Horizontal_0"
end
end
function OreMine_CreateMiningJob(furniture, character)
-- Creates job for a character to go and "mine" the Ore
local job = Job.__new(
furniture.Tile,
nil,
nil,
0,
nil,
Job.JobPriority.High,
false
)
job.RegisterJobWorkedCallback("OreMine_OreMined")
furniture.Jobs.Add(job)
ModUtils.ULog("Ore Mine - Mining Job Created")
end
function OreMine_OreMined(job)
-- Defines the ore to be spawned by the mine
local inventory = Inventory.__new(job.buildable.Parameters["ore_type"], 10)
-- Place the "mined" ore on the tile
World.Current.inventoryManager.PlaceInventory(job.tile, inventory)
-- Deconstruct the ore mine
job.buildable.Deconstruct()
job.CancelJob()
end
function OreMine_GetSpriteName(furniture)
return "mine_" .. furniture.Parameters["ore_type"].ToString()
end
-- This function gets called once, when the furniture is installed
function Rtg_InstallAction( furniture, deltaTime)
-- TODO: find elegant way to register heat source and sinks to Temperature
furniture.EventActions.Register("OnUpdateTemperature", "Rtg_UpdateTemperature")
World.Current.temperature.RegisterSinkOrSource(furniture)
end
-- This function gets called once, when the furniture is uninstalled
function Rtg_UninstallAction( furniture, deltaTime)
furniture.EventActions.Deregister("OnUpdateTemperature", "Rtg_UpdateTemperature")
World.Current.temperature.DeregisterSinkOrSource(furniture)
-- TODO: find elegant way to unregister previous register
end
function Rtg_UpdateTemperature( furniture, deltaTime)
if (furniture.tile.Room.IsOutsideRoom() == true) then
return
end
tile = furniture.tile
pressure = tile.Room.GetGasPressure() / tile.Room.TileCount
efficiency = ModUtils.Clamp01(pressure / furniture.Parameters["pressure_threshold"].ToFloat())
temperatureChangePerSecond = furniture.Parameters["base_heating"].ToFloat() * efficiency
temperatureChange = temperatureChangePerSecond * deltaTime
World.Current.temperature.ChangeTemperature(tile.X, tile.Y, temperatureChange)
--ModUtils.ULogChannel("Temperature", "Heat change: " .. temperatureChangePerSecond .. " => " .. World.current.temperature.GetTemperature(tile.X, tile.Y))
end
ModUtils.ULog("Furniture.lua loaded")
return "LUA Script Parsed!"
| gpl-3.0 |
lizh06/premake-4.x | tests/base/test_api.lua | 54 | 11362 | --
-- tests/base/test_api.lua
-- Automated test suite for the project API support functions.
-- Copyright (c) 2008-2011 Jason Perkins and the Premake project
--
T.api = { }
local suite = T.api
local sln
function suite.setup()
sln = solution "MySolution"
end
--
-- premake.getobject() tests
--
function suite.getobject_RaisesError_OnNoContainer()
premake.CurrentContainer = nil
c, err = premake.getobject("container")
test.istrue(c == nil)
test.isequal("no active solution or project", err)
end
function suite.getobject_RaisesError_OnNoActiveSolution()
premake.CurrentContainer = { }
c, err = premake.getobject("solution")
test.istrue(c == nil)
test.isequal("no active solution", err)
end
function suite.getobject_RaisesError_OnNoActiveConfig()
premake.CurrentConfiguration = nil
c, err = premake.getobject("config")
test.istrue(c == nil)
test.isequal("no active solution, project, or configuration", err)
end
--
-- premake.setarray() tests
--
function suite.setarray_Inserts_OnStringValue()
premake.CurrentConfiguration = { }
premake.CurrentConfiguration.myfield = { }
premake.setarray("config", "myfield", "hello")
test.isequal("hello", premake.CurrentConfiguration.myfield[1])
end
function suite.setarray_Inserts_OnTableValue()
premake.CurrentConfiguration = { }
premake.CurrentConfiguration.myfield = { }
premake.setarray("config", "myfield", { "hello", "goodbye" })
test.isequal("hello", premake.CurrentConfiguration.myfield[1])
test.isequal("goodbye", premake.CurrentConfiguration.myfield[2])
end
function suite.setarray_Appends_OnNewValues()
premake.CurrentConfiguration = { }
premake.CurrentConfiguration.myfield = { "hello" }
premake.setarray("config", "myfield", "goodbye")
test.isequal("hello", premake.CurrentConfiguration.myfield[1])
test.isequal("goodbye", premake.CurrentConfiguration.myfield[2])
end
function suite.setarray_FlattensTables()
premake.CurrentConfiguration = { }
premake.CurrentConfiguration.myfield = { }
premake.setarray("config", "myfield", { {"hello"}, {"goodbye"} })
test.isequal("hello", premake.CurrentConfiguration.myfield[1])
test.isequal("goodbye", premake.CurrentConfiguration.myfield[2])
end
function suite.setarray_RaisesError_OnInvalidValue()
premake.CurrentConfiguration = { }
premake.CurrentConfiguration.myfield = { }
ok, err = pcall(function () premake.setarray("config", "myfield", "bad", { "Good", "Better", "Best" }) end)
test.isfalse(ok)
end
function suite.setarray_CorrectsCase_OnConstrainedValue()
premake.CurrentConfiguration = { }
premake.CurrentConfiguration.myfield = { }
premake.setarray("config", "myfield", "better", { "Good", "Better", "Best" })
test.isequal("Better", premake.CurrentConfiguration.myfield[1])
end
--
-- premake.setstring() tests
--
function suite.setstring_Sets_OnNewProperty()
premake.CurrentConfiguration = { }
premake.setstring("config", "myfield", "hello")
test.isequal("hello", premake.CurrentConfiguration.myfield)
end
function suite.setstring_Overwrites_OnExistingProperty()
premake.CurrentConfiguration = { }
premake.CurrentConfiguration.myfield = "hello"
premake.setstring("config", "myfield", "goodbye")
test.isequal("goodbye", premake.CurrentConfiguration.myfield)
end
function suite.setstring_RaisesError_OnInvalidValue()
premake.CurrentConfiguration = { }
ok, err = pcall(function () premake.setstring("config", "myfield", "bad", { "Good", "Better", "Best" }) end)
test.isfalse(ok)
end
function suite.setstring_CorrectsCase_OnConstrainedValue()
premake.CurrentConfiguration = { }
premake.setstring("config", "myfield", "better", { "Good", "Better", "Best" })
test.isequal("Better", premake.CurrentConfiguration.myfield)
end
--
-- premake.setkeyvalue() tests
--
function suite.setkeyvalue_Inserts_OnStringValue()
premake.CurrentConfiguration = { }
premake.setkeyvalue("config", "vpaths", { ["Headers"] = "*.h" })
test.isequal({"*.h"}, premake.CurrentConfiguration.vpaths["Headers"])
end
function suite.setkeyvalue_Inserts_OnTableValue()
premake.CurrentConfiguration = { }
premake.setkeyvalue("config", "vpaths", { ["Headers"] = {"*.h","*.hpp"} })
test.isequal({"*.h","*.hpp"}, premake.CurrentConfiguration.vpaths["Headers"])
end
function suite.setkeyvalue_Inserts_OnEmptyStringKey()
premake.CurrentConfiguration = { }
premake.setkeyvalue("config", "vpaths", { [""] = "src" })
test.isequal({"src"}, premake.CurrentConfiguration.vpaths[""])
end
function suite.setkeyvalue_RaisesError_OnString()
premake.CurrentConfiguration = { }
ok, err = pcall(function () premake.setkeyvalue("config", "vpaths", "Headers") end)
test.isfalse(ok)
end
function suite.setkeyvalue_InsertsString_IntoExistingKey()
premake.CurrentConfiguration = { }
premake.setkeyvalue("config", "vpaths", { ["Headers"] = "*.h" })
premake.setkeyvalue("config", "vpaths", { ["Headers"] = "*.hpp" })
test.isequal({"*.h","*.hpp"}, premake.CurrentConfiguration.vpaths["Headers"])
end
function suite.setkeyvalue_InsertsTable_IntoExistingKey()
premake.CurrentConfiguration = { }
premake.setkeyvalue("config", "vpaths", { ["Headers"] = {"*.h"} })
premake.setkeyvalue("config", "vpaths", { ["Headers"] = {"*.hpp"} })
test.isequal({"*.h","*.hpp"}, premake.CurrentConfiguration.vpaths["Headers"])
end
--
-- accessor tests
--
function suite.accessor_CanRetrieveString()
sln.blocks[1].kind = "ConsoleApp"
test.isequal("ConsoleApp", kind())
end
--
-- solution() tests
--
function suite.solution_SetsCurrentContainer_OnName()
test.istrue(sln == premake.CurrentContainer)
end
function suite.solution_CreatesNewObject_OnNewName()
solution "MySolution2"
test.isfalse(sln == premake.CurrentContainer)
end
function suite.solution_ReturnsPrevious_OnExistingName()
solution "MySolution2"
local sln2 = solution "MySolution"
test.istrue(sln == sln2)
end
function suite.solution_SetsCurrentContainer_OnExistingName()
solution "MySolution2"
solution "MySolution"
test.istrue(sln == premake.CurrentContainer)
end
function suite.solution_ReturnsNil_OnNoActiveSolutionAndNoName()
premake.CurrentContainer = nil
test.isnil(solution())
end
function suite.solution_ReturnsCurrentSolution_OnActiveSolutionAndNoName()
test.istrue(sln == solution())
end
function suite.solution_ReturnsCurrentSolution_OnActiveProjectAndNoName()
project "MyProject"
test.istrue(sln == solution())
end
function suite.solution_LeavesProjectActive_OnActiveProjectAndNoName()
local prj = project "MyProject"
solution()
test.istrue(prj == premake.CurrentContainer)
end
function suite.solution_LeavesConfigActive_OnActiveSolutionAndNoName()
local cfg = configuration "windows"
solution()
test.istrue(cfg == premake.CurrentConfiguration)
end
function suite.solution_LeavesConfigActive_OnActiveProjectAndNoName()
project "MyProject"
local cfg = configuration "windows"
solution()
test.istrue(cfg == premake.CurrentConfiguration)
end
function suite.solution_SetsName_OnNewName()
test.isequal("MySolution", sln.name)
end
function suite.solution_AddsNewConfig_OnNewName()
test.istrue(#sln.blocks == 1)
end
function suite.solution_AddsNewConfig_OnName()
local num = #sln.blocks
solution "MySolution"
test.istrue(#sln.blocks == num + 1)
end
--
-- configuration() tests
--
function suite.configuration_RaisesError_OnNoContainer()
premake.CurrentContainer = nil
local fn = function() configuration{"Debug"} end
ok, err = pcall(fn)
test.isfalse(ok)
end
function suite.configuration_SetsCurrentConfiguration_OnKeywords()
local cfg = configuration {"Debug"}
test.istrue(premake.CurrentConfiguration == cfg)
end
function suite.configuration_AddsToContainer_OnKeywords()
local cfg = configuration {"Debug"}
test.istrue(cfg == sln.blocks[#sln.blocks])
end
function suite.configuration_ReturnsCurrent_OnNoKeywords()
local cfg = configuration()
test.istrue(cfg == sln.blocks[1])
end
function suite.configuration_SetsTerms()
local cfg = configuration {"aa", "bb"}
test.isequal({"aa", "bb"}, cfg.terms)
end
function suite.configuration_SetsTermsWithNestedTables()
local cfg = configuration { {"aa", "bb"}, "cc" }
test.isequal({"aa", "bb", "cc"}, cfg.terms)
end
function suite.configuration_CanReuseTerms()
local cfg = configuration { "aa", "bb" }
local cfg2 = configuration { cfg.terms, "cc" }
test.isequal({"aa", "bb", "cc"}, cfg2.terms)
end
--
-- project() tests
--
function suite.project_RaisesError_OnNoSolution()
premake.CurrentContainer = nil
local fn = function() project("MyProject") end
ok, err = pcall(fn)
test.isfalse(ok)
end
function suite.project_SetsCurrentContainer_OnName()
local prj = project "MyProject"
test.istrue(prj == premake.CurrentContainer)
end
function suite.project_CreatesNewObject_OnNewName()
local prj = project "MyProject"
local pr2 = project "MyProject2"
test.isfalse(prj == premake.CurrentContainer)
end
function suite.project_AddsToSolution_OnNewName()
local prj = project "MyProject"
test.istrue(prj == sln.projects[1])
end
function suite.project_ReturnsPrevious_OnExistingName()
local prj = project "MyProject"
local pr2 = project "MyProject2"
local pr3 = project "MyProject"
test.istrue(prj == pr3)
end
function suite.project_SetsCurrentContainer_OnExistingName()
local prj = project "MyProject"
local pr2 = project "MyProject2"
local pr3 = project "MyProject"
test.istrue(prj == premake.CurrentContainer)
end
function suite.project_ReturnsNil_OnNoActiveProjectAndNoName()
test.isnil(project())
end
function suite.project_ReturnsCurrentProject_OnActiveProjectAndNoName()
local prj = project "MyProject"
test.istrue(prj == project())
end
function suite.project_LeavesProjectActive_OnActiveProjectAndNoName()
local prj = project "MyProject"
project()
test.istrue(prj == premake.CurrentContainer)
end
function suite.project_LeavesConfigActive_OnActiveProjectAndNoName()
local prj = project "MyProject"
local cfg = configuration "Windows"
project()
test.istrue(cfg == premake.CurrentConfiguration)
end
function suite.project_SetsName_OnNewName()
prj = project("MyProject")
test.isequal("MyProject", prj.name)
end
function suite.project_SetsSolution_OnNewName()
prj = project("MyProject")
test.istrue(sln == prj.solution)
end
function suite.project_SetsConfiguration()
prj = project("MyProject")
test.istrue(premake.CurrentConfiguration == prj.blocks[1])
end
function suite.project_SetsUUID()
local prj = project "MyProject"
test.istrue(prj.uuid)
end
--
-- uuid() tests
--
function suite.uuid_makes_uppercase()
premake.CurrentContainer = {}
uuid "7CBB5FC2-7449-497f-947F-129C5129B1FB"
test.isequal(premake.CurrentContainer.uuid, "7CBB5FC2-7449-497F-947F-129C5129B1FB")
end
--
-- Fields with allowed value lists should be case-insensitive.
--
function suite.flags_onCaseMismatch()
premake.CurrentConfiguration = {}
flags "symbols"
test.isequal(premake.CurrentConfiguration.flags[1], "Symbols")
end
function suite.flags_onCaseMismatchAndAlias()
premake.CurrentConfiguration = {}
flags "optimisespeed"
test.isequal(premake.CurrentConfiguration.flags[1], "OptimizeSpeed")
end
| bsd-3-clause |
graydon/monotone | tests/annotate_accidental_clean_merge/__driver__.lua | 1 | 1305 | -- -*-lua-*-
--
-- We are testing annotate on this graph:
--
-- a
-- /|\
-- / | \
-- b* c* d*
-- | | |
-- e* e* e*
-- \ \/
-- \ e
-- \ /
-- e
-- |
-- f*
--
-- The current annotate code will arbitrarily select one of the marked
-- e-revisions for lines coming from e.
--
mtn_setup()
addfile("foo", "first\nfoo\nthird\n")
commit()
rev_a = base_revision()
econtents = "first\nsecond\nthird\n"
writefile("foo", "first\nb\nthird\n")
commit()
writefile("foo", econtents)
commit()
rev_e1 = base_revision()
revert_to(rev_a)
writefile("foo", "first\nc\nthird\n")
commit()
writefile("foo", econtents)
commit()
rev_e2 = base_revision()
revert_to(rev_a)
writefile("foo", "first\nd\nthird\n")
commit()
writefile("foo", econtents)
commit()
rev_e3 = base_revision()
check(mtn("merge"), 0, false, false)
check(mtn("update"), 0, false, false)
writefile("foo", econtents .. "fourth\n")
commit()
rev_f = base_revision()
check(mtn("annotate", "foo", "--revs-only"), 0, true, true)
check(qgrep(rev_a .. ": first", "stdout"))
check(qgrep(rev_e1 .. ": second", "stdout")
or qgrep(rev_e2 .. ": second", "stdout")
or qgrep(rev_e3 .. ": second", "stdout"))
check(qgrep(rev_a .. ": third", "stdout"))
check(qgrep(rev_f .. ": fourth", "stdout"))
| gpl-2.0 |
Bierbuikje/Mr.Green-MTA-Resources | resources/[race]/race/race_server.lua | 3 | 56451 | g_Root = getRootElement()
g_ResRoot = getResourceRootElement(getThisResource())
allowRPC('setElementPosition')
g_MotorBikeIDs = table.create({ 448, 461, 462, 463, 468, 471, 521, 522, 523, 581, 586 }, true)
g_ArmedVehicleIDs = table.create({ 425, 447, 520, 430, 464, 432 }, true)
g_AircraftIDs = table.create({ 592, 577, 511, 548, 512, 593, 425, 520, 417, 487, 553, 488, 497, 563, 476, 447, 519, 460, 469, 513 }, true)
g_RCVehicleIDs = table.create({ 441, 464, 465, 501, 564, 594 }, true)
g_VehicleClothes = {
[{ 490, 523, 598, 596, 597, 599}] = { [16] = false, [17] = 4 }
}
g_CurrentRaceMode = nil
g_Spawnpoints = {} -- { i = { position={x, y, z}, rotation=rotation, vehicle=vehicleID, paintjob=paintjob, upgrades={...} } }
g_Checkpoints = {} -- { i = { position={x, y, z}, size=size, color={r, g, b}, type=type, vehicle=vehicleID, paintjob=paintjob, upgrades={...} } }
g_Objects = {} -- { i = { position={x, y, z}, rotation={x, y, z}, model=modelID } }
g_Pickups = {} -- { i = { position={x, y, z}, type=type, vehicle=vehicleID, paintjob=paintjob, upgrades={...} }
g_Players = {} -- { i = player }
g_Vehicles = {} -- { player = vehicle }
local unloadedPickups = {}
addEventHandler('onPlayerJoin', g_Root,
function()
outputConsole ( 'Race version ' .. getBuildString(), source, 255, 127, 0 )
for _,line in ipairs(Addons.report) do
outputConsole ( 'Race addon: ' .. line, source )
end
end
)
addEventHandler('onGamemodeMapStart', g_Root,
function(mapres)
-- outputDebugString('onGamemodeMapStart(' .. getResourceName(mapres) .. ')')
if getTotalPlayerCount() == 0 then
outputDebugString('Stopping map')
triggerEvent('onGamemodeMapStop', g_Root)
return
end
gotoState('LoadingMap')
-- set up all players as not ready
for i,player in ipairs(getElementsByType('player')) do
setPlayerNotReady(player)
end
-- tell clients new map is loading
clientCall(g_Root, 'notifyLoadingMap', getResourceInfo(mapres, "name") or getResourceName(mapres), g_GameOptions.showauthorname and getResourceInfo( mapres , "author"), getResourceName(mapres) )
if g_CurrentRaceMode then
outputDebugString('Unloading previous map')
unloadAll()
end
TimerManager.createTimerFor("raceresource","loadmap"):setTimer( doLoadMap, 50, 1 ,mapres )
end
)
-- continue loading map after onGamemodeMapStart has completed
function doLoadMap(mapres)
if not loadMap(mapres) then
-- Select another map on load error
problemChangingMap()
return
end
g_CurrentRaceMode = RaceMode.getApplicableMode():create()
if not g_CurrentRaceMode:isMapValid() then
-- Select another map on load error
problemChangingMap()
return
end
g_CurrentRaceMode:start()
g_MapInfo.modename = g_CurrentRaceMode:getName()
-- Edit #1, removed useless string
outputDebugString('Loaded race mode ' .. g_MapInfo.modename .. ' ' .. getResourceName(mapres))
startRace()
end
-- Called from the admin panel when a setting is changed there
addEvent ( "onSettingChange" )
addEventHandler('onSettingChange', g_ResRoot,
function(name, oldvalue, value, player)
outputDebug( 'MISC', 'Setting changed: ' .. tostring(name) .. ' value:' .. tostring(value) .. ' value:' .. tostring(oldvalue).. ' by:' .. tostring(player and getPlayerName(player) or 'n/a') )
cacheGameOptions()
if g_SavedMapSettings then
cacheMapOptions(g_SavedMapSettings)
clientCall(g_Root,'updateOptions', g_GameOptions, g_MapOptions)
updateGhostmode()
end
end
)
function cacheGameOptions()
g_GameOptions = {}
g_GameOptions.timeafterfirstfinish = getNumber('race.timeafterfirstfinish',30) * 1000
g_GameOptions.hurrytime = getNumber('race.hurrytime',15) * 1000
g_GameOptions.defaultrespawnmode = getString('race.respawnmode','none')
g_GameOptions.defaultrespawntime = getNumber('race.respawntime',5) * 1000
g_GameOptions.defaultduration = getNumber('race.duration',6000) * 1000
g_GameOptions.ghostmode = getBool('race.ghostmode',false)
g_GameOptions.ghostalpha = getBool('race.ghostalpha',false)
g_GameOptions.randommaps = getBool('race.randommaps',false)
g_GameOptions.statskey = getString('race.statskey','name')
g_GameOptions.vehiclecolors = getString('race.vehiclecolors','file')
g_GameOptions.skins = getString('race.skins','cj')
g_GameOptions.autopimp = getBool('race.autopimp',true)
g_GameOptions.vehicleweapons = getBool('race.vehicleweapons',true)
g_GameOptions.firewater = getBool('race.firewater',false)
g_GameOptions.classicchangez = getBool('race.classicchangez',false)
g_GameOptions.admingroup = getString('race.admingroup','Admin')
g_GameOptions.blurlevel = getNumber('race.blur',36)
g_GameOptions.cloudsenable = getBool('race.clouds',true)
g_GameOptions.joinspectating = getBool('race.joinspectating',true)
g_GameOptions.stealthspectate = getBool('race.stealthspectate',true)
g_GameOptions.countdowneffect = getBool('race.countdowneffect',true)
g_GameOptions.showmapname = getBool('race.showmapname',true)
g_GameOptions.hunterminigun = getBool('race.hunterminigun',true)
g_GameOptions.securitylevel = getNumber('race.securitylevel',2)
g_GameOptions.anyonecanspec = getBool('race.anyonecanspec',true)
g_GameOptions.norsadminspectate = getBool('race.norsadminspectate',false)
g_GameOptions.racerespawn = getBool('race.racerespawn',true)
g_GameOptions.joinrandomvote = getBool('race.joinrandomvote',true)
g_GameOptions.asyncloading = getBool('race.asyncloading',true)
g_GameOptions.showauthorname = getBool('race.showauthorname',true)
g_GameOptions.ghostmode_map_can_override = getBool('race.ghostmode_map_can_override',true)
g_GameOptions.skins_map_can_override = getBool('race.skins_map_can_override',true)
g_GameOptions.vehicleweapons_map_can_override = getBool('race.vehicleweapons_map_can_override',true)
g_GameOptions.autopimp_map_can_override = getBool('race.autopimp_map_can_override',true)
g_GameOptions.firewater_map_can_override = getBool('race.firewater_map_can_override',true)
g_GameOptions.classicchangez_map_can_override = getBool('race.classicchangez_map_can_override',true)
g_GameOptions.ghostmode_warning_if_map_override = getBool('race.ghostmode_warning_if_map_override',true)
g_GameOptions.vehicleweapons_warning_if_map_override = getBool('race.vehicleweapons_warning_if_map_override',true)
g_GameOptions.hunterminigun_map_can_override = getBool('race.hunterminigun_map_can_override',true)
if g_GameOptions.statskey ~= 'name' and g_GameOptions.statskey ~= 'serial' then
outputWarning( "statskey is not set to 'name' or 'serial'" )
g_GameOptions.statskey = 'name'
end
end
function cacheMapOptions(map, bDontUseMode)
local mode = (not bDontUseMode) and RaceMode.getApplicableMode() and RaceMode.getApplicableMode().modeOptions or {}
g_MapOptions = {}
g_MapOptions.duration = map.duration and tonumber(map.duration) > 0 and map.duration*1000 or g_GameOptions.defaultduration
if mode.duration and g_MapOptions.duration > mode.duration then
g_MapOptions.duration = mode.duration
elseif g_MapOptions.duration > 20*60*1000 then
g_MapOptions.duration = 20*60*1000
end
g_MapOptions.respawn = map.respawn or g_GameOptions.defaultrespawnmode
g_MapOptions.respawn = mode.respawn ~= nil and mode.respawn or g_MapOptions.respawn
if g_MapOptions.respawn ~= 'timelimit' and g_MapOptions.respawn ~= 'none' then
g_MapOptions.respawn = 'timelimit'
end
g_MapOptions.respawntime = g_MapOptions.respawn == 'timelimit' and (map.respawntime and map.respawntime*1000 or g_GameOptions.defaultrespawntime)
g_MapOptions.respawntime = mode.respawntime ~= nil and mode.respawntime*1000 or g_MapOptions.respawntime
g_MapOptions.time = map.time or '12:00'
g_MapOptions.weather = map.weather or 0
g_MapOptions.skins = map.skins or 'cj'
g_MapOptions.vehicleweapons = map.vehicleweapons == 'true'
g_MapOptions.ghostmode = map.ghostmode == 'true'
g_MapOptions.autopimp = map.autopimp == 'true'
g_MapOptions.firewater = map.firewater == 'true'
g_MapOptions.classicchangez = map.classicchangez == 'true'
g_MapOptions.hunterminigun = map.hunterminigun == 'true'
outputDebug("MISC", "duration = "..g_MapOptions.duration.." respawn = "..g_MapOptions.respawn.." respawntime = "..tostring(g_MapOptions.respawntime).." time = "..g_MapOptions.time.." weather = "..g_MapOptions.weather)
if g_MapOptions.time then
setTime(g_MapOptions.time:match('(%d+):(%d+)'))
end
if g_MapOptions.weather then
setWeather(g_MapOptions.weather)
end
-- Set ghostmode from g_GameOptions if not defined in the map, or map override not allowed
if not map.ghostmode or not g_GameOptions.ghostmode_map_can_override then
g_MapOptions.ghostmode = g_GameOptions.ghostmode
if mode.ghostmode ~= nil then
g_MapOptions.ghostmode = mode.ghostmode
end
end
if mode.ghostmode ~= nil and mode.ghostmode_map_can_override == true then
g_MapOptions.ghostmode = mode.ghostmode
end
if not bDontUseMode and map.ghostmode and g_GameOptions.ghostmode_warning_if_map_override and g_MapOptions.ghostmode ~= (mode.ghostmode ~= nil and mode.ghostmode or g_GameOptions.ghostmode) then
if g_MapOptions.ghostmode then
outputChatBox( 'Notice: Ghostmode is turned ON for this map' )
else
outputChatBox( 'Notice: Ghostmode is turned OFF for this map' )
end
end
-- Set skins from g_GameOptions if not defined in the map, or map override not allowed
if not map.skins or not g_GameOptions.skins_map_can_override then
g_MapOptions.skins = g_GameOptions.skins
if mode.skins ~= nil then
g_MapOptions.skins = mode.skins
end
end
if mode.skins ~= nil and not mode.skins_map_can_override == true then
g_MapOptions.skins = mode.skins
end
-- Set vehicleweapons from g_GameOptions if not defined in the map, or map override not allowed
if not map.vehicleweapons or not g_GameOptions.vehicleweapons_map_can_override then
g_MapOptions.vehicleweapons = g_GameOptions.vehicleweapons
if mode.vehicleweapons ~= nil then
g_MapOptions.vehicleweapons = mode.vehicleweapons
end
end
if mode.vehicleweapons ~= nil and not mode.vehicleweapons_map_can_override == true then
g_MapOptions.vehicleweapons = mode.vehicleweapons
end
if not bDontUseMode and map.vehicleweapons and g_GameOptions.vehicleweapons_warning_if_map_override and g_MapOptions.vehicleweapons ~= (mode.vehicleweapons ~= nil and mode.vehicleweapons or g_GameOptions.vehicleweapons) then
if g_MapOptions.vehicleweapons then
outputChatBox( 'Notice: Vehicle weapons are turned ON for this map' )
else
outputChatBox( 'Notice: Vehicle weapons are turned OFF for this map' )
end
end
-- Set autopimp from g_GameOptions if not defined in the map, or map override not allowed
if not map.autopimp or not g_GameOptions.autopimp_map_can_override then
g_MapOptions.autopimp = g_GameOptions.autopimp
if mode.autopimp ~= nil then
g_MapOptions.autopimp = mode.autopimp
end
end
if mode.autopimp ~= nil and not mode.autopimp_map_can_override == true then
g_MapOptions.autopimp = mode.autopimp
end
-- Set firewater from g_GameOptions if not defined in the map, or map override not allowed
if not map.firewater or not g_GameOptions.firewater_map_can_override then
g_MapOptions.firewater = g_GameOptions.firewater
if mode.firewater ~= nil then
g_MapOptions.firewater = mode.firewater
end
end
if mode.firewater ~= nil and not mode.firewater_map_can_override == true then
g_MapOptions.firewater = mode.firewater
end
-- Set classicchangez from g_GameOptions if not defined in the map, or map override not allowed
if not map.classicchangez or not g_GameOptions.classicchangez_map_can_override then
g_MapOptions.classicchangez = g_GameOptions.classicchangez
if mode.classicchangez ~= nil then
g_MapOptions.classicchangez = mode.classicchangez
end
end
if mode.classicchangez ~= nil and not mode.classicchangez_map_can_override == true then
g_MapOptions.classicchangez = mode.classicchangez
end
-- Set hunterminigun from g_GameOptions if not defined in the map, or map override not allowed
if not map.hunterminigun or not g_GameOptions.hunterminigun_map_can_override then
g_MapOptions.hunterminigun = g_GameOptions.hunterminigun
if mode.hunterminigun ~= nil then
g_MapOptions.hunterminigun = mode.hunterminigun
end
end
if mode.hunterminigun ~= nil and not mode.hunterminigun_map_can_override == true then
g_MapOptions.hunterminigun = mode.hunterminigun
end
end
-- Called from:
-- onGamemodeMapStart
function loadMap(res)
local map = RaceMap.load(res)
if not map then
outputDebugString( 'Error loading map ' .. tostring(getResourceName(res)) )
outputChatBox( 'Error loading map ' .. tostring(getResourceName(res)) )
return false
end
-- set options
-- Edit #1a
g_MapInfo = {}
g_MapInfo.name = getResourceInfo(res, 'name') or 'unnamed'
g_MapInfo.author = getResourceInfo(res, 'author') or ''
g_MapInfo.metamode = getResourceInfo(res, 'racemode') or ''
g_MapInfo.resname = getResourceName(res)
-- Edit #1a
g_SavedMapSettings = {}
g_SavedMapSettings.duration = map.duration
g_SavedMapSettings.respawn = map.respawn
g_SavedMapSettings.respawntime = map.respawntime
g_SavedMapSettings.time = map.time
g_SavedMapSettings.weather = map.weather
g_SavedMapSettings.skins = map.skins
g_SavedMapSettings.vehicleweapons = map.vehicleweapons
g_SavedMapSettings.ghostmode = map.ghostmode
g_SavedMapSettings.autopimp = map.autopimp
g_SavedMapSettings.firewater = map.firewater
g_SavedMapSettings.classicchangez = map.classicchangez
g_SavedMapSettings.firewater = map.firewater
g_SavedMapSettings.hunterminigun = map.hunterminigun
cacheMapOptions(g_SavedMapSettings, true)
-- If no checkpoints and ghostmode no defined in the map, turn ghostmode off for this map
if #map:getAll('checkpoint') == 0 and not map.ghostmode and g_MapOptions.ghostmode then
g_MapOptions.ghostmode = false
if g_GameOptions.ghostmode_warning_if_map_override then
outputChatBox( 'Notice: Collisions are turned on for this map' )
end
end
-- Check race can start ok
-- if g_IgnoreSpawnCountProblems ~= res and not g_MapOptions.ghostmode then
-- local numSpawnPoints = #map:getAll('spawnpoint')
-- if getTotalPlayerCount() > numSpawnPoints then
-- -- unload map xml
-- map:unload()
-- outputRace( (numSpawnPoints).." or less players are required to start '"..tostring(getResourceName(res)).."' if not using ghostmode" )
-- return false
-- end
-- end
-- read spawnpoints
g_Spawnpoints = map:getAll('spawnpoint')
-- read checkpoints
g_Checkpoints = map:getAll('checkpoint')
-- if map isn't made in the new editor or map is an old race map multiplicate the checkpointsize with 4
local madeInNewEditor = map.def and map.def:find("editor_main")
if not madeInNewEditor or map:isRaceFormat() then
for i,checkpoint in ipairs(g_Checkpoints) do
checkpoint.size = checkpoint.size and checkpoint.size*4 or 4
end
end
if map:isDMFormat() then
-- sort checkpoints
local chains = {} -- a chain is a list of checkpoints that immediately follow each other
local prevchainnum, chainnum, nextchainnum
for i,checkpoint in ipairs(g_Checkpoints) do
--check size
checkpoint.size = checkpoint.size or 4
-- any chain we can place this checkpoint after?
chainnum = table.find(chains, '[last]', 'nextid', checkpoint.id)
if chainnum then
table.insert(chains[chainnum], checkpoint)
if checkpoint.nextid then
nextchainnum = table.find(chains, 1, 'id', checkpoint.nextid)
if nextchainnum then
table.merge(chains[chainnum], chains[nextchainnum])
table.remove(chains, nextchainnum)
end
end
elseif checkpoint.nextid then
-- any chain we can place it before?
chainnum = table.find(chains, 1, 'id', checkpoint.nextid)
if chainnum then
table.insert(chains[chainnum], 1, checkpoint)
prevchainnum = table.find(chains, '[last]', 'nextid', checkpoint.id)
if prevchainnum then
table.merge(chains[prevchainnum], chains[chainnum])
table.remove(chains, chainnum)
end
else
-- new chain
table.insert(chains, { checkpoint })
end
else
table.insert(chains, { checkpoint })
end
end
g_Checkpoints = chains[1] or {}
end
-- read objects
g_Objects = map:getAll('object')
-- read pickups
g_Pickups = map:getAll('pickup')
cacheMapOptions(g_SavedMapSettings)
-- unload map xml
map:unload()
return true
end
-- Called from:
-- onGamemodeMapStart
function startRace()
gotoState('PreGridCountdown')
triggerClientEvent( "resetCustomCountdown", root )
setElementData( g_ResRoot, "info", {mapInfo = g_MapInfo, mapOptions = g_MapOptions, gameOptions = g_GameOptions}, false )
AddonOverride.removeAll()
triggerEvent('onMapStarting', g_Root, g_MapInfo, g_MapOptions, g_GameOptions )
g_Players = {}
TimerManager.createTimerFor("map","spawn"):setTimer(joinHandlerByTimer, 200, 0)
if g_CurrentRaceMode:isRanked() then
TimerManager.createTimerFor("map","rank"):setTimer(updateRank, 1000, 0)
end
end
-- Called from:
-- g_RaceStartCountdown
function launchRace()
for i,player in pairs(g_Players) do
unfreezePlayerWhenReady(player)
end
clientCall(g_Root, 'launchRace', g_MapOptions.duration, g_MapOptions.vehicleweapons)
if g_MapOptions.duration then
TimerManager.createTimerFor("map","raceend"):setTimer(raceTimeout, g_MapOptions.duration, 1)
end
g_CurrentRaceMode:launch()
g_CurrentRaceMode.running = true
gotoState('Running')
end
-- OLD COUNTDOWN
-- g_RaceStartCountdown = Countdown.create(6, launchRace)
-- g_RaceStartCountdown:useImages('img/countdown_%d.png', 474, 204)
-- g_RaceStartCountdown:enableFade(true)
-- g_RaceStartCountdown:addClientHook(3, 'playSoundFrontEnd', 44)
-- g_RaceStartCountdown:addClientHook(2, 'playSoundFrontEnd', 44)
-- g_RaceStartCountdown:addClientHook(1, 'playSoundFrontEnd', 44)
-- g_RaceStartCountdown:addClientHook(0, 'playSoundFrontEnd', 45)
-- Called from:
-- event onPlayerJoin
-- g_SpawnTimer = setTimer(joinHandler, 500, 0) in startRace
-- Interesting calls to:
-- g_RaceStartCountdown:start()
--
-- note: player is always nil on entry
function joinHandlerByEvent()
setPlayerNotReady(source)
joinHandlerBoth()
end
function joinHandlerByTimer()
joinHandlerBoth()
end
function joinHandlerBoth(player)
if #g_Spawnpoints == 0 then
-- start vote if no map is loaded
if not TimerManager.hasTimerFor("watchdog") then
TimerManager.createTimerFor("map","watchdog"):setTimer(
function()
if #g_Spawnpoints == 0 then
outputDebugString('No map loaded; showing votemanager')
TimerManager.destroyTimersFor("spawn")
RaceMode:endMap()
end
end,
1000, 1 )
end
return
else
TimerManager.destroyTimersFor("watchdog")
end
if TimerManager.hasTimerFor("spawn") then
for i,p in ipairs(getElementsByType('player')) do
if not table.find(g_Players, p) and getElementData(p, 'player state') ~= 'away' then
player = p
break
end
end
if not player then
for i,p in ipairs(getElementsByType('player')) do
if not table.find(g_Players, p)then
player = p
break
end
end
end
if not player then
-- Is everyone ready?
if howManyPlayersNotReady() == 0 then
TimerManager.destroyTimersFor("spawn")
if stateAllowsGridCountdown() then
gotoState('GridCountdown')
-- g_RaceStartCountdown:start() -- OLD COUNTDOWN
startCustomCountdown()
end
end
return
end
end
local bPlayerJoined = not player
if bPlayerJoined then
player = source
setPlayerStatus( player, "joined", "" )
else
setPlayerStatus( player, "not ready", "" )
end
if not player then
outputDebug( 'MISC', 'joinHandler: player==nil' )
return
end
table.insert(g_Players, player)
local vehicle
if true then
local spawnpoint = g_CurrentRaceMode:pickFreeSpawnpoint(player)
local x, y, z = unpack(spawnpoint.position)
-- Set random seed dependant on map name, so everyone gets the same models
setRandomSeedForMap('clothes')
if g_MapOptions.skins == 'cj' then
spawnPlayer(player, x + 4, y, z, 0, 0)
local clothes = { [16] = math.random(12, 13), [17] = 7 } -- 16=Hats(12:helmet 13:moto) 17=Extra(7:garageleg)
for vehicles,vehicleclothes in pairs(g_VehicleClothes) do
if table.find(vehicles, spawnpoint.vehicle) then
for type,index in pairs(vehicleclothes) do
clothes[type] = index or nil
end
end
end
local texture, model
for type,index in pairs(clothes) do
texture, model = getClothesByTypeIndex(type, index)
addPedClothes(player, texture, model, type)
end
elseif g_MapOptions.skins == 'random' then
repeat until spawnPlayer(player, x + 4, y, z, 0, math.random(9, 288))
else
local ok
for i=1,20 do
ok = spawnPlayer(player, x + 4, y, z, 0, getRandomFromRangeList(g_MapOptions.skins))
if ok then break end
end
if not ok then
spawnPlayer(player, x + 4, y, z, 0, 264)
end
end
setPlayerSpectating(player, false)
setPlayerNotReady( player )
setPedStat(player, 160, 1000)
setPedStat(player, 229, 1000)
setPedStat(player, 230, 1000)
if spawnpoint.vehicle then
setRandomSeedForMap('vehiclecolors')
-- Replace groups of unprintable characters with a space, and then remove any leading space
local plate = getPlayerName(player):gsub( '[^%a%d]+', ' ' ):gsub( '^ ', '' )
-- Edit #2
if not spawnpoint.rotation then --Binslayer: wtf, fixing some weirdass bug with maps that dont have rotation and make createVehicle fail thus integrity check fail
spawnpoint.rotation = 0
end
vehicle = createVehicle(spawnpoint.vehicle, x, y, z, 0, 0, spawnpoint.rotation, plate:sub(1, 8))
if setElementSyncer then
setElementSyncer( vehicle, false )
end
g_Vehicles[player] = vehicle
Override.setAlpha( "ForRCVehicles", player, g_RCVehicleIDs[spawnpoint.vehicle] and 0 or nil )
g_CurrentRaceMode:playerFreeze(player)
outputDebug( 'MISC', 'joinHandlerBoth: setElementFrozen true for ' .. tostring(getPlayerName(player)) .. ' vehicle:' .. tostring(vehicle) )
if bPlayerJoined and g_CurrentRaceMode.running then
unfreezePlayerWhenReady(player)
end
if g_MapOptions.respawn == 'none' and not stateAllowsSpawnInNoRespawnMap() then
g_CurrentRaceMode.setPlayerIsFinished(player)
setElementPosition(vehicle, 0, 0, 0)
end
if spawnpoint.paintjob or spawnpoint.upgrades then
setVehiclePaintjobAndUpgrades(vehicle, spawnpoint.paintjob, spawnpoint.upgrades)
else
if g_MapOptions.autopimp then
pimpVehicleRandom(vehicle)
end
if g_GameOptions.vehiclecolors == 'random' then
setRandomSeedForMap('vehiclecolors')
local vehicleColorFixed = false
for vehicleID,color in pairs(g_FixedColorVehicles) do
if vehicleID == tonumber(spawnpoint.vehicle) then
if color then
setVehicleColor(vehicle, color[1], color[2], color[3], color[4])
end
vehicleColorFixed = true
break
end
end
if not vehicleColorFixed then
setVehicleColor(vehicle, math.random(0, 126), math.random(0, 126), 0, 0)
end
end
end
warpPedIntoVehicle(player, vehicle)
end
destroyBlipsAttachedTo(player)
createBlipAttachedTo(player, 0, 1, 200, 200, 200)
g_CurrentRaceMode:onPlayerJoin(player, spawnpoint)
end
-- Send client all info
local playerInfo = {}
playerInfo.admin = isPlayerInACLGroup(player, g_GameOptions.admingroup)
playerInfo.testing = _TESTING
playerInfo.joined = bPlayerJoined
local duration = bPlayerJoined and (g_MapOptions.duration and (g_MapOptions.duration - g_CurrentRaceMode:getTimePassed()) or true)
clientCall(player, 'initRace', vehicle, g_Checkpoints, g_Objects, g_Pickups, g_MapOptions, g_CurrentRaceMode:isRanked(), duration, g_GameOptions, g_MapInfo, playerInfo )
if bPlayerJoined and getPlayerCount() == 2 and stateAllowsRandomMapVote() and g_GameOptions.joinrandomvote then
-- Start random map vote if someone joined a lone player mid-race
TimerManager.createTimerFor("map"):setTimer(startMidMapVoteForRandomMap,7000,1)
end
-- Handle spectating when joined
if g_CurrentRaceMode.isPlayerFinished(player) then
-- Joining 'finished'
clientCall(player, "Spectate.start", 'auto' )
setPlayerStatus( player, nil, "waiting" )
else
if bPlayerJoined and g_CurrentRaceMode.running then
-- Joining after start
addActivePlayer(player)
if g_GameOptions.joinspectating then
clientCall(player, "Spectate.start", 'manual' )
setPlayerStatus( player, nil, "spectating")
Override.setCollideOthers( "ForSpectating", g_CurrentRaceMode.getPlayerVehicle( player ), 0 )
end
end
end
end
addEventHandler('onPlayerJoin', g_Root, joinHandlerByEvent)
-- Called from:
-- joinHandler
-- unfreezePlayerWhenReady
-- launchRace
function unfreezePlayerWhenReady(player)
if not isValidPlayer(player) then
outputDebug( 'MISC', 'unfreezePlayerWhenReady: not isValidPlayer(player)' )
return
end
if isPlayerNotReady(player) then
outputDebug( 'MISC', 'unfreezePlayerWhenReady: isPlayerNotReady(player) for ' .. tostring(getPlayerName(player)) )
TimerManager.createTimerFor("map",player):setTimer( unfreezePlayerWhenReady, 500, 1, player )
else
g_CurrentRaceMode:playerUnfreeze(player)
outputDebug( 'MISC', 'unfreezePlayerWhenReady: setElementFrozen false for ' .. tostring(getPlayerName(player)) )
end
end
-- Called from:
-- g_RankTimer = setTimer(updateRank, 1000, 0) in startRace
function updateRank()
if g_CurrentRaceMode then
g_CurrentRaceMode:updateRanks()
end
end
-- Set random seed dependent on map name
--
-- Note: Some clients will experience severe stutter and stalls if any
-- players have different skin/clothes.
-- For smooth gameplay, ensure everyone has the same skin setup including crash helmet etc.
function setRandomSeedForMap( type )
local seed = 0
if type == 'clothes' then
seed = 100 -- All players get the same driver skin/clothes
elseif type == 'upgrades' then
seed = 0 -- All players get the same set of vehicle upgrades
elseif type == 'vehiclecolors' then
seed = getTickCount() -- Allow vehicle colors to vary between players
else
outputWarning( 'Unknown setRandomSeedForMap type ' .. type )
end
for i,char in ipairs( { string.byte(g_MapInfo.name,1,g_MapInfo.name:len()) } ) do
seed = math.mod( seed * 11 + char, 216943)
end
math.randomseed(seed)
end
addEvent('onPlayerReachCheckpoint')
addEvent('onPlayerFinish')
addEvent('onPlayerReachCheckpointInternal', true)
addEventHandler('onPlayerReachCheckpointInternal', g_Root,
function(checkpointNum, nitroLevel, nitroActive)
if checkClient( false, source, 'onPlayerReachCheckpointInternal' ) then return end
if not stateAllowsCheckpoint() then
return
end
local vehicle = g_Vehicles[source]
local checkpoint = g_CurrentRaceMode:getCheckpoint(checkpointNum)
if checkpoint.vehicle then
if getElementModel(vehicle) ~= tonumber(checkpoint.vehicle) then
if checkpointNum < #g_Checkpoints then
clientCall(source, 'alignVehicleWithUp')
end
setVehicleID(vehicle, checkpoint.vehicle)
if nitroLevel then
addVehicleUpgrade(vehicle, 1010)
clientCall(root, 'setVehicleNitroLevel', vehicle, nitroLevel)
clientCall(root, 'setVehicleNitroActivated', vehicle, nitroActive)
end
clientCall(source, 'vehicleChanging', g_MapOptions.classicchangez, tonumber(checkpoint.vehicle))
if checkpoint.paintjob or checkpoint.upgrades then
setVehiclePaintjobAndUpgrades(vehicle, checkpoint.paintjob, checkpoint.upgrades)
else
if g_MapOptions.autopimp then
pimpVehicleRandom(vehicle)
end
end
end
end
local rank, time = g_CurrentRaceMode:onPlayerReachCheckpoint(source, checkpointNum, nitroLevel, nitroActive)
if checkpointNum < #g_Checkpoints then
triggerEvent('onPlayerReachCheckpoint', source, checkpointNum, time)
else
triggerEvent('onPlayerFinish', source, rank, time)
end
end
)
addEvent('onPlayerPickUpRacePickup')
addEvent('onPlayerPickUpRacePickupInternal', true)
addEventHandler('onPlayerPickUpRacePickupInternal', g_Root,
function(pickupID, respawntime, nitroLevel, nitroActive)
if checkClient( false, source, 'onPlayerPickUpRacePickupInternal' ) then return end
local pickup = g_Pickups[table.find(g_Pickups, 'id', pickupID)]
local vehicle = g_Vehicles[source]
if not pickup or not vehicle then return end
if respawntime and tonumber(respawntime) >= 50 then
table.insert(unloadedPickups, pickupID)
clientCall(g_Root, 'unloadPickup', pickupID)
TimerManager.createTimerFor("map"):setTimer(ServerLoadPickup, tonumber(respawntime), 1, pickupID)
end
if pickup.type == 'repair' then
fixVehicle(vehicle)
elseif pickup.type == 'nitro' then
if getVehicleUpgradeOnSlot(vehicle, 8) == 0 then
addVehicleUpgrade(vehicle, 1010)
else
clientCall(root, 'setVehicleNitroLevel', vehicle, 1)
end
elseif pickup.type == 'vehiclechange' then
if getElementModel(vehicle) ~= tonumber(pickup.vehicle) then
-- clientCall(source, 'removeVehicleNitro')
setVehicleID(vehicle, pickup.vehicle)
if pickup.paintjob or pickup.upgrades then
setVehiclePaintjobAndUpgrades(vehicle, pickup.paintjob, pickup.upgrades)
end
if nitroLevel then
addVehicleUpgrade(vehicle, 1010)
clientCall(root, 'setVehicleNitroLevel', vehicle, nitroLevel)
clientCall(root, 'setVehicleNitroActivated', vehicle, nitroActive)
end
end
end
g_CurrentRaceMode:onPlayerPickUpRacePickup(source, pickup)
triggerEvent('onPlayerPickUpRacePickup', source, pickupID, pickup.type, pickup.vehicle)
end
)
function ServerLoadPickup(pickupID)
table.removevalue(unloadedPickups, pickupID)
clientCall(g_Root, 'loadPickup', pickupID)
end
addEventHandler('onPlayerWasted', g_Root,
function()
if g_CurrentRaceMode then
if not g_CurrentRaceMode.startTick then
local x, y, z = getElementPosition(source)
spawnPlayer(source, x, y, z, 0, getElementModel(source))
if g_Vehicles[source] then
warpPedIntoVehicle(source, g_Vehicles[source])
end
else
setPlayerStatus( source, "dead", "" )
local player = source
g_CurrentRaceMode:onPlayerWasted(source)
triggerEvent( 'onPlayerRaceWasted', player, g_CurrentRaceMode.getPlayerVehicle( player ) )
end
end
end
)
-- Called from:
-- g_RaceEndTimer = setTimer(raceTimeout, g_MapOptions.duration, 1)
function raceTimeout()
if stateAllowsTimesUp() then
gotoState('TimesUp')
for i,player in pairs(g_Players) do
if not isPlayerFinished(player) then
showMessage('Time\'s up!')
end
end
clientCall(g_Root, 'raceTimeout')
TimerManager.destroyTimersFor("raceend")
g_CurrentRaceMode:timeout()
g_CurrentRaceMode:endMap()
end
end
-- Called from:
-- onGamemodeMapStart
-- onGamemodeMapStop
-- onResourceStop
function unloadAll()
if getPlayerCount() > 0 then
clientCall(g_Root, 'unloadAll')
end
TimerManager.destroyTimersFor("map")
Countdown.destroyAll()
triggerEvent("StopCountDown",resourceRoot)
for i,player in pairs(g_Players) do
setPlayerFinished(player, false)
destroyMessage(player)
end
destroyMessage(g_Root)
table.each(g_Vehicles, destroyElement)
g_Vehicles = {}
g_Spawnpoints = {}
g_Checkpoints = {}
g_Objects = {}
g_Pickups = {}
unloadedPickups = {}
if g_CurrentRaceMode then
g_CurrentRaceMode:destroy()
end
g_CurrentRaceMode = nil
Override.resetAll()
end
addEventHandler('onGamemodeMapStop', g_Root,
function(mapres)
--Clear the scoreboard
for i,player in ipairs(getElementsByType"player") do
setElementData ( player, "race rank", "" )
setElementData ( player, "checkpoint", "" )
end
fadeCamera ( g_RootPlayers, false, 0.0, 0,0, 0 )
gotoState('NoMap')
unloadAll()
end
)
-- Called from:
-- nowhere
addEventHandler('onPollDraw', g_Root,
function()
outputDebugString('Poll ended in a draw')
end
)
-- Recharge scoreboard columns if required
addEventHandler('onResourceStart', g_Root,
function(res)
local resourceName = getResourceName(res)
if resourceName == 'scoreboard' then
TimerManager.createTimerFor("raceresource"):setTimer( addRaceScoreboardColumns, 1000, 1 )
end
end
)
addEventHandler('onResourceStart', g_ResRoot,
function()
outputDebugString('Race resource starting')
startAddons()
end
)
addEventHandler('onGamemodeStart', g_ResRoot,
function()
outputDebugString('Race onGamemodeStart')
addRaceScoreboardColumns()
if not g_GameOptions then
cacheGameOptions()
end
end
)
function addRaceScoreboardColumns()
exports.scoreboard:scoreboardAddColumn("race rank", root, 40, "Rank", 4)
exports.scoreboard:scoreboardAddColumn("checkpoint", root, 77, "Checkpoint", 5)
exports.scoreboard:scoreboardAddColumn("player state", root, 60, "State", 9)
setTimer ( function() exports.scoreboard:scoreboardSetSortBy("race rank") end, 2000, 1 )
end
addEventHandler('onResourceStop', g_ResRoot,
function()
gotoState( 'Race resource stopping' )
fadeCamera ( g_Root, false, 0.0, 0,0, 0 )
outputDebugString('Resource stopping')
unloadAll()
exports.scoreboard:removeScoreboardColumn('race rank')
exports.scoreboard:removeScoreboardColumn('checkpoint')
exports.scoreboard:removeScoreboardColumn('player state')
end
)
addEventHandler('onPlayerQuit', g_Root,
function()
destroyBlipsAttachedTo(source)
table.removevalue(g_Players, source)
if g_Vehicles[source] then
if isElement(g_Vehicles[source]) then
destroyElement(g_Vehicles[source])
end
g_Vehicles[source] = nil
end
if g_CurrentRaceMode then
g_CurrentRaceMode:onPlayerQuit(source)
end
for i,player in pairs(g_Players) do
if not isPlayerFinished(player) then
return
end
end
if getTotalPlayerCount() < 2 then
outputDebugString('Stopping map')
triggerEvent('onGamemodeMapStop', g_Root)
else
-- Edit #3 warning fix
if stateAllowsPostFinish() and g_CurrentRaceMode and g_CurrentRaceMode.running then
gotoState('EveryoneFinished')
g_CurrentRaceMode:endMap()
end
end
end
)
addEventHandler('onVehicleStartExit', g_Root, function() cancelEvent() end)
function getPlayerCurrentCheckpoint(player)
return getElementData(player, 'race.checkpoint') or 1
end
function setPlayerCurrentCheckpoint(player, i)
clientCall(player, 'setCurrentCheckpoint', i)
end
function setPlayerFinished(player, toggle)
setElementData(player, 'race.finished', toggle)
end
function isPlayerFinished(player)
return getElementData(player, 'race.finished') or false
end
function distanceFromPlayerToCheckpoint(player, i)
local checkpoint = g_Checkpoints[i]
local x, y, z = getElementPosition(player)
-- Edit #4 bugfix
if not checkpoint then --workaround
local cp = getPlayerCurrentCheckpoint(player)
local cps = getElementsByType('checkpoint')
checkpoint = cps[cp]
local rx, ry, rz = getElementData(checkpoint, 'posX'), getElementData(checkpoint, 'posY'), getElementData(checkpoint, 'posZ')
return getDistanceBetweenPoints3D(x, y, z, rx, ry, rz)
else
return getDistanceBetweenPoints3D(x, y, z, unpack(checkpoint.position))
end
end
addEvent('onRequestKillPlayer', true)
addEventHandler('onRequestKillPlayer', g_Root,
function(reason)
if checkClient( false, source, 'onRequestKillPlayer' ) then return end
local player = source
if stateAllowsKillPlayer() then
if reason ~= "water" then
triggerEvent("onRacePlayerSuicide",source)
end
setElementHealth(player, 0)
toggleAllControls(player,false, true, false)
end
end
)
function toggleServerGhostmode(player)
if not _TESTING and not isPlayerInACLGroup(player, g_GameOptions.admingroup) then
return
end
g_MapOptions.ghostmode = not g_MapOptions.ghostmode
g_GameOptions.ghostmode = not g_GameOptions.ghostmode
set('*ghostmode', g_GameOptions.ghostmode and 'true' or 'false' )
updateGhostmode()
if g_MapOptions.ghostmode then
outputChatBox('Ghostmode enabled by ' .. getPlayerName(player), g_Root, 0, 240, 0)
else
outputChatBox('Ghostmode disabled by ' .. getPlayerName(player), g_Root, 240, 0, 0)
end
end
-- Edit #5 removed commands
addCommandHandler('gm', toggleServerGhostmode)
addCommandHandler('ghostmode', toggleServerGhostmode)
function updateGhostmode()
for i,player in ipairs(g_Players) do
local vehicle = g_CurrentRaceMode.getPlayerVehicle(player)
if vehicle then
Override.setCollideOthers( "ForGhostCollisions", vehicle, g_MapOptions.ghostmode and 0 or nil )
Override.setAlpha( "ForGhostAlpha", {player, vehicle}, g_MapOptions.ghostmode and g_GameOptions.ghostalpha and 180 or nil )
end
end
end
g_SavedVelocity = {}
-- Handle client request for manual spectate
addEvent('onClientRequestSpectate', true)
addEventHandler('onClientRequestSpectate', g_Root,
function(enable)
if checkClient( false, source, 'onClientRequestSpectate' ) then return end
-- Checks if switching on
local player = source
if enable then
if not stateAllowsManualSpectate() then return end
if not _TESTING then
if isPlayerInACLGroup(player, g_GameOptions.admingroup) then
if not g_CurrentRaceMode:isMapRespawn() and g_GameOptions.norsadminspectate then
return false
end
else
if not g_CurrentRaceMode:isMapRespawn() or not g_GameOptions.anyonecanspec then
return false
end
end
end
end
if isPlayerSpectating(player) ~= enable then
if enable then -- Go to spectator request
-- Edit #6 Extra spectator features
if isPlayerInACLGroup(player, g_GameOptions.admingroup) then
clientCall(player, "Spectate.start", 'manual' )
else
if g_CurrentRaceMode:getTimeRemaining() - g_CurrentRaceMode.getMapOption('respawntime') > 1000 then
Countdown.create(g_CurrentRaceMode.getMapOption('respawntime')/1000, clientCall, 'You will be able to respawn in:', 255, 255, 255, 0.25, 2.5, true, player, "Spectate.allowUnspectate"):start(player)
end
clientCall(player, "Spectate.start", 'manual', true )
end
if not g_GameOptions.stealthspectate or not isPlayerInACLGroup(player, g_GameOptions.admingroup) then
setPlayerStatus( player, nil, "spectating")
end
if isPlayerInACLGroup(player, g_GameOptions.admingroup) then
setElementData(player, "kKey", "spectating")
end
Override.setCollideOthers( "ForSpectating", g_CurrentRaceMode.getPlayerVehicle( player ), 0 )
g_SavedVelocity[player] = {}
g_SavedVelocity[player].velocity = {getElementVelocity(g_Vehicles[player])}
g_SavedVelocity[player].turnvelocity = {getVehicleTurnVelocity(g_Vehicles[player])}
g_CurrentRaceMode:playerSpectating(player)
elseif g_CurrentRaceMode:getTimeRemaining() > 500 then
clientCall(player, "Spectate.stop", 'manual' )
setPlayerStatus( player, nil, "")
if isPlayerInACLGroup(player, g_GameOptions.admingroup) then
setElementData(player, "kKey", "alive")
end
Override.setCollideOthers( "ForSpectating", g_CurrentRaceMode.getPlayerVehicle( player ), nil )
if g_GameOptions.racerespawn and (g_CurrentRaceMode.getNumberOfCheckpoints() > 0 or g_CurrentRaceMode:forceRespawnRestore()) and not (isPlayerInACLGroup(player, g_GameOptions.admingroup) and g_GameOptions.norsadminspectate) then
-- Edit #6
-- Do respawn style restore
g_CurrentRaceMode:restorePlayer( g_CurrentRaceMode.id, player, true, true )
else
-- Do 'freeze/collision off' stuff when stopping spectate
g_CurrentRaceMode:playerFreeze(player, true, true)
TimerManager.createTimerFor("map",player):setTimer(afterSpectatePlayerUnfreeze, 2000, 1, player, true)
end
end
end
end
)
function afterSpectatePlayerUnfreeze(player, bDontFix)
g_CurrentRaceMode:playerUnfreeze(player, bDontFix)
if g_SavedVelocity[player] then
setElementVelocity(g_Vehicles[player], unpack(g_SavedVelocity[player].velocity))
setVehicleTurnVelocity(g_Vehicles[player], unpack(g_SavedVelocity[player].turnvelocity))
g_SavedVelocity[player] = nil
end
end
-- Handle client going to/from spectating
addEvent('onClientNotifySpectate', true)
addEventHandler('onClientNotifySpectate', g_Root,
function(enable)
if checkClient( false, source, 'onClientNotifySpectate' ) then return end
setPlayerSpectating(source, enable)
end
)
function setPlayerSpectating(player, toggle)
showBlipsAttachedTo ( player, not toggle ) -- Hide blips if spectating
setElementData(player, 'race.spectating', toggle)
end
function isPlayerSpectating(player)
return getElementData(player, 'race.spectating') or false
end
addEvent('onNotifyPlayerReady', true)
addEventHandler('onNotifyPlayerReady', g_Root,
function()
if checkClient( false, source, 'onNotifyPlayerReady' ) then return end
setPlayerReady( source )
for i, pickupID in ipairs(unloadedPickups) do
-- outputDebugString(getPlayerName(source).." unload "..tostring(pickupID))
clientCall(source, "unloadPickup", pickupID )
end
end
)
------------------------
-- Players not ready stuff
g_NotReady = {} -- { player = bool }
g_NotReadyDisplay = nil
g_NotReadyTextItems = {}
g_NotReadyDisplayOnTime = 0
g_JoinerExtraWait = nil
g_NotReadyTimeout = nil
g_NotReadyMaxWait = nil
-- Remove ref if player quits
addEventHandler('onPlayerQuit', g_Root,
function()
g_NotReady[source] = nil
g_SavedVelocity[source] = nil
end
)
-- Give 10 seconds for joining players to become not ready
addEventHandler('onPlayerJoining', g_Root,
function()
g_JoinerExtraWait = getTickCount() + 10000
end
)
-- Give 5 seconds for first player to start joining
addEventHandler('onGamemodeMapStart', g_Root,
function(mapres)
g_JoinerExtraWait = getTickCount() + 5000
g_NotReadyMaxWait = false
end
)
-- Give 30 seconds for not ready players to become ready
function setPlayerNotReady( player )
g_NotReady[player] = true
g_NotReadyTimeout = getTickCount() + 20000 + 10000
if _DEBUG_TIMING then g_NotReadyTimeout = g_NotReadyTimeout - 15000 end
activateNotReadyText()
end
-- Alter not ready timeout
function setPlayerReady( player )
setPlayerStatus( player, "alive", nil )
g_NotReady[player] = false
g_NotReadyTimeout = getTickCount() + 20000
if _DEBUG_TIMING then g_NotReadyTimeout = g_NotReadyTimeout - 10000 end
-- Set max timeout to 30 seconds after first person is ready
if not g_NotReadyMaxWait then
g_NotReadyMaxWait = getTickCount() + 30000
end
-- If more than 10 players, and only one player not ready, limit max wait time to 5 seconds
if #g_Players > 10 and howManyPlayersNotReady() == 1 then
g_NotReadyMaxWait = math.min( g_NotReadyMaxWait, getTickCount() + 5000 )
end
end
function isPlayerNotReady( player )
return g_NotReady[player] and getElementData(player, 'player state') ~= 'away'
end
function howManyPlayersNotReady()
local count = 0
local names = ''
for i,player in ipairs(g_Players) do
if isPlayerNotReady(player) then
count = count + 1
names = names .. (count > 1 and ', ' or '') .. getPlayerName(player)
end
end
if g_JoinerExtraWait and g_JoinerExtraWait > getTickCount() then
count = count + 1 -- If the JoinerExtraWait is set, pretend someone is not ready
end
if g_NotReadyTimeout and g_NotReadyTimeout < getTickCount() then
count = 0 -- If the NotReadyTimeout has passed, pretend everyone is ready
end
if g_NotReadyMaxWait and g_NotReadyMaxWait < getTickCount() then
count = 0 -- If the NotReadyMaxWait has passed, pretend everyone is ready
end
return count, names
end
function activateNotReadyText()
if stateAllowsNotReadyMessage() then
if not g_NotReadyDisplay then
TimerManager.createTimerFor("raceresource","notready"):setTimer( updateNotReadyText, 100, 0 )
g_NotReadyDisplay = textCreateDisplay()
g_NotReadyTextItems[1] = textCreateTextItem('', 0.5, 0.7, 'medium', 255, 235, 215, 255, 1.5, 'center', 'center')
textDisplayAddText(g_NotReadyDisplay, g_NotReadyTextItems[1])
end
end
end
function updateNotReadyText()
local count, names = howManyPlayersNotReady()
if count == 0 then
deactiveNotReadyText()
end
if g_NotReadyDisplay then
-- Make sure all ready players are observers
for i,player in ipairs(g_Players) do
if isPlayerNotReady(player) then
textDisplayRemoveObserver(g_NotReadyDisplay, player)
else
if not textDisplayIsObserver(g_NotReadyDisplay, player) then
textDisplayAddObserver(g_NotReadyDisplay, player)
g_NotReadyDisplayOnTime = getTickCount()
end
end
end
-- Only show 'Waiting for other players...' if there actually are any other players
if getTotalPlayerCount() > 1 then
textItemSetText(g_NotReadyTextItems[1], 'Waiting for ' .. count .. ' player(s):\n' .. names)
end
end
end
function deactiveNotReadyText()
if g_NotReadyDisplay then
TimerManager.destroyTimersFor("notready")
-- Ensure message is displayed for at least 2 seconds
local hideDisplayDelay = math.max(50,math.min(2000,2000+g_NotReadyDisplayOnTime - getTickCount()))
local display = g_NotReadyDisplay;
local textItems = { g_NotReadyTextItems[1] };
TimerManager.createTimerFor("raceresource"):setTimer(
function()
textDestroyDisplay(display)
textDestroyTextItem(textItems[1])
end,
hideDisplayDelay, 1 )
g_NotReadyDisplay = nil
g_NotReadyTextItems[1] = nil
end
end
------------------------
-- addon management
Addons = {}
Addons.report = {}
Addons.reportShort = ''
-- Start addon resources listed in the setting 'race.addons'
function startAddons()
Addons.report = {}
Addons.reportShort = ''
-- Check permissions
local bCanStartResource = hasObjectPermissionTo ( getThisResource(), "function.startResource", false )
local bCanStopResource = hasObjectPermissionTo ( getThisResource(), "function.stopResource", false )
if not bCanStartResource or not bCanStopResource then
local line1 = 'WARNING: Race does not have permission to start/stop resources'
local line2 = 'WARNING: Addons may not function correctly'
outputDebugString( line1 )
outputDebugString( line2 )
table.insert(Addons.report,line1)
table.insert(Addons.report,line2)
end
for idx,name in ipairs(string.split(getString('race.addons'),',')) do
if name ~= '' then
local resource = getResourceFromName(name)
if not resource then
outputWarning( "Can't use addon '" .. name .. "', as it is not the name of a resource" )
else
if getResourceInfo ( resource, 'addon' ) ~= 'race' then
outputWarning( "Can't use addon " .. name .. ', as it does not have addon="race" in the info section' )
else
-- Start or restart resource
if getResourceState(resource) == 'running' then
-- stopResource(resource)
-- TimerManager.createTimerFor("raceresource"):setTimer( function() startResource(resource) end, 200, 1 )
else
startResource(resource, true)
end
-- Update Addons.report
local tag = getResourceInfo ( resource, 'name' ) or getResourceName(resource)
local build = getResourceInfo ( resource, 'build' ) or ''
local version = getResourceInfo ( resource, 'version' ) or ''
local author = getResourceInfo ( resource, 'author' ) or ''
local description = getResourceInfo ( resource, 'description' ) or ''
local line = tag .. ' - ' .. description .. ' - by ' .. author .. ' - version [' .. version .. '] [' .. build .. ']'
table.insert(Addons.report,line)
-- Update Addons.reportShort
if Addons.reportShort ~= '' then
Addons.reportShort = Addons.reportShort .. ', '
end
Addons.reportShort = Addons.reportShort .. tag
end
end
end
end
end
------------------------
-- Server side move away
MoveAway = {}
MoveAway.list = {}
addEvent( "onRequestMoveAwayBegin", true )
addEventHandler( "onRequestMoveAwayBegin", g_Root,
function()
if checkClient( false, source, 'onRequestMoveAwayBegin' ) then return end
MoveAway.list [ source ] = true
if not TimerManager.hasTimerFor("moveaway") then
TimerManager.createTimerFor("map","moveaway"):setTimer( MoveAway.update, 1000, 0 )
end
end
)
addEventHandler( "onPlayerQuit", g_Root,
function()
MoveAway.list [ source ] = nil
end
)
addEvent( "onRequestMoveAwayEnd", true )
addEventHandler( "onRequestMoveAwayEnd", g_Root,
function()
if checkClient( false, source, 'onRequestMoveAwayEnd' ) then return end
MoveAway.list [ source ] = nil
end
)
function MoveAway.update ()
for player,_ in pairs(MoveAway.list) do
if not isElement(player) then
MoveAway.list [ player ] = nil
end
end
for player,_ in pairs(MoveAway.list) do
if isPedDead(player) or getElementHealth(player) == 0 then
local vehicle = g_Vehicles[player]
if isElement(vehicle) then
setElementVelocity(vehicle,0,0,0)
setVehicleTurnVelocity(vehicle,0,0,0)
Override.setCollideOthers( "ForMoveAway", vehicle, 0 )
Override.setAlpha( "ForMoveAway", {player, vehicle}, 0 )
end
end
end
end
function setPlayerStatus( player, status1, status2 )
if status1 then
setElementData ( player, "status1", status1 )
end
if status2 then
setElementData ( player, "status2", status2 )
end
local status = getElementData ( player, "status2" )
if not status or status=="" then
status = getElementData ( player, "status1" )
end
if status then
setElementData ( player, "state", status )
end
end
------------------------
-- Keep players in vehicles
g_checkPedIndex = 0
TimerManager.createTimerFor("raceresource","warppeds"):setTimer(
function ()
-- Make sure all players are in a vehicle
local maxCheck = 6 -- Max number to check per call
local maxWarp = 3 -- Max number to warp per call
local warped = 0
for checked = 0, #g_Players - 1 do
if checked >= maxCheck or warped >= maxWarp then
break
end
g_checkPedIndex = g_checkPedIndex + 1
if g_checkPedIndex > #g_Players then
g_checkPedIndex = 1
end
local player = g_Players[g_checkPedIndex]
if not getPedOccupiedVehicle(player) then
local vehicle = g_Vehicles[player]
if vehicle and isElement(vehicle) and not isPlayerRaceDead(player) then
-- Edit #7 Removed spam
-- outputDebugString( "Warping player into vehicle for " .. tostring(getPlayerName(player)) )
warpPedIntoVehicle( player, vehicle )
warped = warped + 1
end
end
end
end,
50,0
)
function isPlayerRaceDead(player)
return not getElementHealth(player) or getElementHealth(player) < 1e-45 or isPedDead(player)
end
------------------------
-- Script integrity test
g_IntegrityFailCount = 0
TimerManager.createTimerFor("raceresource","integrity"):setTimer(
function ()
local fail = false
-- Make sure all vehicles are valid - Invalid vehicles really mess up the race script
for player,vehicle in pairs(g_Vehicles) do
if not isElement(vehicle) then
fail = true
outputRace( "Race integrity test fail: Invalid vehicle for player " .. tostring(getPlayerName(player)) )
kickPlayer( player, nil, "Connection terminated to protect the core" )
end
end
-- Increment or reset fail counter
g_IntegrityFailCount = fail and g_IntegrityFailCount + 1 or 0
-- Two fails in a row triggers a script restart
if g_IntegrityFailCount > 1 then
outputRace( "Race script integrity compromised - Restarting" )
exports.mapmanager:changeGamemode( getThisResource() )
end
end,
1000,0
)
------------------------
-- Testing commands
addCommandHandler('restartracemode',
function(player)
if not _TESTING and not isPlayerInACLGroup(player, g_GameOptions.admingroup) then
return
end
outputChatBox('Race restarted by ' .. getPlayerName(player), g_Root, 0, 240, 0)
exports.mapmanager:changeGamemode( getThisResource() )
end
)
addCommandHandler('pipedebug',
function(player, command, arg)
if not _TESTING and not isPlayerInACLGroup(player, g_GameOptions.admingroup) then
return
end
if g_PipeDebugTo then
clientCall(g_PipeDebugTo, 'setPipeDebug', false)
end
g_PipeDebugTo = (arg == "1") and player
if g_PipeDebugTo then
clientCall(g_PipeDebugTo, 'setPipeDebug', true)
end
end
)
------------------------
-- Exported functions
function getPlayerRank(player)
if not g_CurrentRaceMode or not g_CurrentRaceMode:isRanked() then
return false
end
return g_CurrentRaceMode:getPlayerRank(player)
end
function getTimePassed()
if not g_CurrentRaceMode then
return false
end
return g_CurrentRaceMode:getTimePassed()
end
function getPlayerVehicle( player )
return g_CurrentRaceMode.getPlayerVehicle( player )
end
function getRaceMode()
return g_CurrentRaceMode and g_MapInfo.modename or false
end
function getCheckPoints()
return g_Checkpoints
end
function export_setPlayerVehicle(player,vehicleID) -- Used in gc perk: reroll vehicle
if isElement(player) and getElementType(player) == "player" and type(vehicleID) == "number" then
local vehicle = g_CurrentRaceMode.getPlayerVehicle(player)
if not vehicle then return false end
local nitrous = getElementData(vehicle, 'nitro')
if type(nitrous) ~= "table" or type(nitrous[1]) ~= "boolean" or type(nitrous[2]) ~= "number" then
nitrous = false
end
local isset = setVehicleID(vehicle, vehicleID)
local notifyClient = clientCall(player, 'vehicleChanging', g_MapOptions.classicchangez, vehicleID)
if nitrous and nitrous[2] then
addVehicleUpgrade(vehicle, 1010)
clientCall(root, 'setVehicleNitroLevel', vehicle, nitrous[2])
if nitrous[1] then
clientCall(root, 'setVehicleNitroActivated', vehicle, true)
end
end
return not not isset
end
end
------------------------
-- Checks
addEventHandler('onElementDataChange', root,
function(dataName, oldValue )
if getElementType(source)=='player' and checkClient( false, source, 'onElementDataChange', dataName ) then
setElementData( source, dataName, oldValue )
return
end
end
)
-- returns true if there is trouble
function checkClient(checkAccess,player,...)
if client and client ~= player and g_GameOptions.securitylevel >= 2 then
local desc = table.concat({...}," ")
local ipAddress = getPlayerIP(client)
outputDebugString( "Race security - Client/player mismatch from " .. tostring(ipAddress) .. " (" .. tostring(desc) .. ")", 1 )
cancelEvent()
if g_GameOptions.clientcheckban then
local reason = "race checkClient (" .. tostring(desc) .. ")"
addBan ( ipAddress, nil, nil, getRootElement(), reason )
end
return true
end
if checkAccess and g_GameOptions.securitylevel >= 1 then
if not isPlayerInACLGroup(player, g_GameOptions.admingroup) then
local desc = table.concat({...}," ")
local ipAddress = getPlayerIP(client or player)
outputDebugString( "Race security - Client without required rights trigged a race event. " .. tostring(ipAddress) .. " (" .. tostring(desc) .. ")", 2 )
return true
end
end
return false
end
| mit |
Bierbuikje/Mr.Green-MTA-Resources | resources/[admin]/admin/server/admin_ACL.lua | 7 | 2730 | --[[**********************************
*
* Multi Theft Auto - Admin Panel
*
* admin_ACL.lua
*
* Original File by lil_Toady
*
**************************************]]
function aSetupACL ()
local temp_acl_nodes = {}
local node = xmlLoadFile ( "conf\\ACL.xml" )
if ( node ) then
--Get ACLs
local acls = 0
while ( xmlFindChild ( node, "acl", acls ) ~= false ) do
local aclNode = xmlFindChild ( node, "acl", acls )
local aclName = xmlNodeGetAttribute ( aclNode, "name" )
if ( ( aclNode ) and ( aclName ) ) then
temp_acl_nodes[aclName] = aclNode
end
acls = acls + 1
end
-- Add missing rights
local totalAdded = 0
for id, acl in ipairs ( aclList () ) do
local aclName = aclGetName ( acl )
if string.sub(aclName,1,8) ~= "autoACL_" then
local node = temp_acl_nodes[aclName] or temp_acl_nodes["Default"]
if node then
totalAdded = totalAdded + aACLLoad ( acl, node )
end
end
end
if totalAdded > 0 then
outputServerLog ( "Admin access list successfully updated " )
outputConsole ( "Admin access list successfully updated " )
outputDebugString ( "Admin added " .. totalAdded .. " missing rights" )
end
xmlUnloadFile ( node )
else
outputServerLog ( "Failed to install admin access list - File missing" )
outputConsole ( "Failed to install admin access list - File missing" )
end
end
function aACLLoad ( acl, node )
local added = 0
local rights = 0
while ( xmlFindChild ( node, "right", rights ) ~= false ) do
local rightNode = xmlFindChild ( node, "right", rights )
local rightName = xmlNodeGetAttribute ( rightNode, "name" )
local rightAccess = xmlNodeGetAttribute ( rightNode, "access" )
if ( ( rightName ) and ( rightAccess ) ) then
-- Add if missing from this acl
if not aclRightExists ( acl, rightName ) then
aclSetRight ( acl, rightName, rightAccess == "true" )
added = added + 1
end
end
rights = rights + 1
end
return added
end
function aclGetAccount ( player )
local account = getPlayerAccount ( player )
if ( isGuestAccount ( account ) ) then return false
else return "user."..getAccountName ( account ) end
end
function aclGetAccountGroups ( account )
local acc = getAccountName ( account )
if ( not acc ) then return false end
local res = {}
acc = "user."..acc
local all = "user.*"
for ig, group in ipairs ( aclGroupList() ) do
for io, object in ipairs ( aclGroupListObjects ( group ) ) do
if ( ( acc == object ) or ( all == object ) ) then
table.insert ( res, aclGroupGetName ( group ) )
break
end
end
end
return res
end
function aclRightExists( acl, right )
for _,name in ipairs( aclListRights( acl ) ) do
if name == right then
return true
end
end
return false
end
| mit |
ntop/ntopng | scripts/lua/rest/v2/acknowledge/mac/alerts.lua | 1 | 1072 | --
-- (C) 2013-22 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
package.path = dirs.installdir .. "/scripts/lua/modules/alert_store/?.lua;" .. package.path
local alert_utils = require "alert_utils"
local alert_consts = require "alert_consts"
local alert_entities = require "alert_entities"
local rest_utils = require("rest_utils")
local mac_alert_store = require "mac_alert_store".new()
--
-- Read alerts data
-- Example: curl -u admin:admin -H "Content-Type: application/json" -d '{"ifid": "1"}' http://localhost:3000/lua/rest/v2/acknowledge/mac/alerts.lua
--
-- NOTE: in case of invalid login, no error is returned but redirected to login
--
local rc = rest_utils.consts.success.ok
local res = {}
local ifid = _GET["ifid"]
if isEmptyString(ifid) then
rc = rest_utils.consts.err.invalid_interface
rest_utils.answer(rc)
return
end
interface.select(ifid)
-- Add filters
mac_alert_store:add_request_filters(true)
mac_alert_store:acknowledge(_GET["label"])
rest_utils.answer(rc)
| gpl-3.0 |
FelixMaxwell/ReDead | entities/weapons/rad_g3/shared.lua | 1 | 1580 | if SERVER then
AddCSLuaFile("shared.lua")
end
if CLIENT then
SWEP.ViewModelFlip = true
SWEP.PrintName = "G3 SG1"
SWEP.IconLetter = "i"
SWEP.Slot = 4
SWEP.Slotpos = 3
end
SWEP.HoldType = "ar2"
SWEP.Base = "rad_base"
SWEP.ViewModel = "models/weapons/v_snip_g3sg1.mdl"
SWEP.WorldModel = "models/weapons/w_snip_g3sg1.mdl"
SWEP.SprintPos = Vector(-2.8398, -3.656, 0.5519)
SWEP.SprintAng = Vector(0.1447, -34.0929, 0)
SWEP.ZoomModes = { 0, 35, 10 }
SWEP.ZoomSpeeds = { 0.25, 0.40, 0.40 }
SWEP.IsSniper = true
SWEP.AmmoType = "Sniper"
SWEP.Primary.Sound = Sound( "Weapon_G3SG1.Single" )
SWEP.Primary.Recoil = 5.5
SWEP.Primary.Damage = 100
SWEP.Primary.NumShots = 1
SWEP.Primary.Cone = 0.002
SWEP.Primary.SniperCone = 0.035
SWEP.Primary.Delay = 0.380
SWEP.Primary.ClipSize = 20
SWEP.Primary.Automatic = true
function SWEP:PrimaryAttack()
if not self.Weapon:CanPrimaryAttack() then
self.Weapon:SetNextPrimaryFire( CurTime() + 0.25 )
return
end
self.Weapon:SetNextPrimaryFire( CurTime() + self.Primary.Delay )
self.Weapon:EmitSound( self.Primary.Sound, 100, math.random(95,105) )
self.Weapon:SetClip1( self.Weapon:Clip1() - 1 )
self.Weapon:ShootEffects()
if self.IsSniper and self.Weapon:GetZoomMode() == 1 then
self.Weapon:ShootBullets( self.Primary.Damage, self.Primary.NumShots, self.Primary.SniperCone, 1 )
else
self.Weapon:ShootBullets( self.Primary.Damage, self.Primary.NumShots, self.Primary.Cone, self.Weapon:GetZoomMode() )
end
if SERVER then
self.Owner:AddAmmo( self.AmmoType, -1 )
end
end | mit |
ntop/ntopng | scripts/lua/rest/v1/acknowledge/host/alerts.lua | 1 | 1077 | --
-- (C) 2013-22 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
package.path = dirs.installdir .. "/scripts/lua/modules/alert_store/?.lua;" .. package.path
local alert_utils = require "alert_utils"
local alert_consts = require "alert_consts"
local alert_entities = require "alert_entities"
local rest_utils = require("rest_utils")
local host_alert_store = require "host_alert_store".new()
--
-- Read alerts data
-- Example: curl -u admin:admin -H "Content-Type: application/json" -d '{"ifid": "1"}' http://localhost:3000/lua/rest/v1/acknowledge/host/alerts.lua
--
-- NOTE: in case of invalid login, no error is returned but redirected to login
--
local rc = rest_utils.consts.success.ok
local res = {}
local ifid = _GET["ifid"]
if isEmptyString(ifid) then
rc = rest_utils.consts.err.invalid_interface
rest_utils.answer(rc)
return
end
interface.select(ifid)
-- Add filters
host_alert_store:add_request_filters(true)
host_alert_store:acknowledge(_GET["label"])
rest_utils.answer(rc)
| gpl-3.0 |
Star2Billing/newfies-dialer | lua/scheduled_event.lua | 5 | 7846 | -- Version: MPL 1.1
--
-- The contents of this file are subject to the Mozilla Public License Version
-- 1.1 (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.mozilla.org/MPL
--
-- Software distributed under the License is distributed on an "AS IS" basis
-- WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-- for the specific language governing rights and limitations under the
-- License
--
-- The Original Code is FreeSWITCH[tm] LUA event scheduler
--
-- The primary maintainer of this project is
-- Bret McDanel <bret AT 0xdecafbad dot com>
--
-- Portions created by the Initial Developer are Copyright (C) 2007
-- the Initial Developer. All Rights Reserved
--
-- Contributor(s)
--
-- Why use this?
-- No reason in particular, however if you use sched_api and shut down you lose your scheduled events, by
-- placing them in a database you get the advantage of them being able to survive a shutdown/crash/reboot/etc
-- Additionally this script is written in a way to allow for multiple switch boxes to access the same database
-- and look for events to process, in this way you can scale this to a very large amount of actions
--
--
-- Usage: in FreeSWITCH console or fs_cli,
-- luarun scheduled_event.lua
-- starts the script - this is not needed if its auto loaded
-- luarun scheduled_event.lua <dbuser username> <dbhost hostname> <dbpass password> <dbname database_name>
-- changes the DB info allowing you to do load management, maintenence, or other things
-- luarun scheduled_event.lua stop
-- stops the running script
--
-- in lua.conf.xml:
-- <param name="startup-script" value="scheduled_event.lua"/>
--
--
-- You need to get "mysql.so" for lua and install it in <freeswitch install>/luasql/mysql.so
-- (or some other place that is in the search path)
--
-- Minimal DB schema **AUTOMAGICALLY CREATED IF IT DOES NOT EXIST** (at script start)
-- CREATE TABLE scheduler (
-- acctid int(11) NOT NULL auto_increment,
-- action varchar(1024) NOT NULL,
-- timestamp timestamp NOT NULL,
-- server varchar(64) NOT NULL DEFAULT '*',
-- primary key (acctid)
-- );
--
-- "actions" in the scheduler table should be api commands eg:
-- insert into scheduler (action,timestamp) values ("pa call 1234",NOW())
--
--
-- Every "heartbeat" events are pulled 1 at a time using write locks on mysql
-- if your MySQL supports those locks, then only one process can access the DB at a time
-- events are immediately deleted, and then processed to keep the lock time low
-- failed events are NOT rescheduled
-- many boxes can pull events and process them, however I did not attempt to process more
-- events than time allows for in a given heartbeat interval, some backlog may exist which
-- may cause this script to totally freak
-- currently this script requires http://jira.freeswitch.org/browse/MODAPP-357
local luasql = require "luasql.postgres"
-- Database setup
DATABASE = "newfies2"
USERNAME = "newfiesuser"
PASSWORD = "password"
DBHOST = "localhost"
TABLENAME = "scheduler"
-- LOGGING
LOGLEVEL = "info"
-- PROGNAME
PROGNAME = "scheduled_event.lua"
function logger(message)
freeswitch.console_log(LOGLEVEL,"["..PROGNAME.."] "..message.."\n")
end
if argv[1] then
i=1
while argv[i] do
if argv[i] == "stop" then
--Send Stop message
local event = freeswitch.Event("custom", "lua::scheduled_event")
event:addHeader("Action", "stop")
event:fire()
logger("Sent stop message to lua script")
return
elseif (argv[i] == "dbuser") then
i=i+1
if argv[i] then
logger("Setting DB Username to "..argv[i])
USERNAME = argv[i]
else
logger("You must specify a username!")
end
elseif (argv[i] == "dbhost") then
i=i+1
if argv[i] then
logger("Setting DB Hostname to "..argv[i])
DBHOST = argv[i]
else
logger("You must specify a hostname!")
end
elseif (argv[i] == "dbpass") then
i=i+1
if argv[i] then
logger("Setting DB Password to "..argv[i])
PASSWORD = argv[i]
else
logger("You must specify a password!")
end
elseif (argv[i] == "dbname") then
i=i+1
if argv[i] then
logger("Setting DB to "..argv[i])
DATABASE = argv[i]
else
logger("You must specify a database name!")
end
end
i=i+1
end
return
end
--Main function starts here
logger("Starting")
-- ensure DB works, create table if it doesnt exist
env = assert (luasql.postgres())
dbcon = assert (env:connect(DATABASE,USERNAME,PASSWORD,DBHOST, 5432))
blah = assert(dbcon:execute("CREATE TABLE if not exists "..TABLENAME.." ("..
"acctid serial NOT NULL PRIMARY KEY,"..
"action varchar(1024) NOT NULL,"..
"timestamp timestamp with time zone NOT NULL,"..
"server varchar(64) NOT NULL DEFAULT '*'"..
")"))
dbcon:close()
env:close()
local event_name
local event_subclass
con = freeswitch.EventConsumer("all") -- too lazy to figure out why "heartbeat CUSTOM lua::scheduled_event"
-- does not work properly, that is really all we need
api = freeswitch.API()
hostname = api:execute("hostname")
if blah ~= 0 then
logger("Unable to connect to DB or create the table, something is broken.")
else
for e in (function() return con:pop(1) end) do
event_name = e:getHeader("Event-Name") or ""
event_subclass = e:getHeader("Event-Subclass") or ""
if(event_name == "HEARTBEAT") then
-- check the system load
load = api:execute("status")
print(load)
--cur_sessions,rate_sessions,max_rate,max_sessions = string.match(load, "%d+ session.s. - %d+ out of max %d+ per sec\n%d+ session.s. max")
cur_sessions = "1"
rate_sessions = "1"
max_rate = "1"
max_sessions = "1"
if ((tonumber(cur_sessions) < tonumber(max_sessions)) and (tonumber(rate_sessions) < tonumber(max_rate))) then
env = assert (luasql.postgres())
dbcon = assert (env:connect(DATABASE,USERNAME,PASSWORD,DBHOST, 5432))
while true do
assert (dbcon:execute("LOCK TABLE "..TABLENAME.." WRITE"))
cur = assert (dbcon:execute("select * from "..TABLENAME.." where timestamp < NOW() and (server = '"..hostname.."' or server = '*') order by timestamp limit 1"))
row = cur:fetch({},"a")
if not row then
break
end
assert (dbcon:execute("delete from "..TABLENAME.." where acctid = "..row.acctid));
assert (dbcon:execute("UNLOCK TABLES"))
apicmd,apiarg = string.match(row.action,"(%w+) (.*)")
api:execute(apicmd,apiarg)
end -- while
dbcon:close()
env:close()
end -- rate limiting
else
if (event_name == "CUSTOM" and event_subclass == "lua::scheduled_event") then
action = e:getHeader("Action") or ""
if (action == "stop") then
logger("got stop message, Exiting")
break
end
end -- not a custom message
end -- not a processable event
end -- foreach event
end -- main loop, DB connection established
| mpl-2.0 |
pinghe/nginx-openresty-windows | lua-resty-string-0.09/lib/resty/md5.lua | 13 | 1209 | -- Copyright (C) by Yichun Zhang (agentzh)
local ffi = require "ffi"
local ffi_new = ffi.new
local ffi_str = ffi.string
local C = ffi.C
local setmetatable = setmetatable
local error = error
local _M = { _VERSION = '0.09' }
local mt = { __index = _M }
ffi.cdef[[
typedef unsigned long MD5_LONG ;
enum {
MD5_CBLOCK = 64,
MD5_LBLOCK = MD5_CBLOCK/4
};
typedef struct MD5state_st
{
MD5_LONG A,B,C,D;
MD5_LONG Nl,Nh;
MD5_LONG data[MD5_LBLOCK];
unsigned int num;
} MD5_CTX;
int MD5_Init(MD5_CTX *c);
int MD5_Update(MD5_CTX *c, const void *data, size_t len);
int MD5_Final(unsigned char *md, MD5_CTX *c);
]]
local buf = ffi_new("char[16]")
local ctx_ptr_type = ffi.typeof("MD5_CTX[1]")
function _M.new(self)
local ctx = ffi_new(ctx_ptr_type)
if C.MD5_Init(ctx) == 0 then
return nil
end
return setmetatable({ _ctx = ctx }, mt)
end
function _M.update(self, s)
return C.MD5_Update(self._ctx, s, #s) == 1
end
function _M.final(self)
if C.MD5_Final(buf, self._ctx) == 1 then
return ffi_str(buf, 16)
end
return nil
end
function _M.reset(self)
return C.MD5_Init(self._ctx) == 1
end
return _M
| bsd-2-clause |
mohammad8/123456 | plugins/btc.lua | 289 | 1375 | -- See https://bitcoinaverage.com/api
local function getBTCX(amount,currency)
local base_url = 'https://api.bitcoinaverage.com/ticker/global/'
-- Do request on bitcoinaverage, the final / is critical!
local res,code = https.request(base_url..currency.."/")
if code ~= 200 then return nil end
local data = json:decode(res)
-- Easy, it's right there
text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid
-- If we have a number as second parameter, calculate the bitcoin amount
if amount~=nil then
btc = tonumber(amount) / tonumber(data.ask)
text = text.."\n "..currency .." "..amount.." = BTC "..btc
end
return text
end
local function run(msg, matches)
local cur = 'EUR'
local amt = nil
-- Get the global match out of the way
if matches[1] == "!btc" then
return getBTCX(amt,cur)
end
if matches[2] ~= nil then
-- There is a second match
amt = matches[2]
cur = string.upper(matches[1])
else
-- Just a EUR or USD param
cur = string.upper(matches[1])
end
return getBTCX(amt,cur)
end
return {
description = "Bitcoin global average market value (in EUR or USD)",
usage = "!btc [EUR|USD] [amount]",
patterns = {
"^!btc$",
"^!btc ([Ee][Uu][Rr])$",
"^!btc ([Uu][Ss][Dd])$",
"^!btc (EUR) (%d+[%d%.]*)$",
"^!btc (USD) (%d+[%d%.]*)$"
},
run = run
}
| gpl-2.0 |
maikerumine/aftermath | mods/mobs_fallout/nssm_api.lua | 2 | 9781 | -- set content id's
local c_air = minetest.get_content_id("air")
local c_ignore = minetest.get_content_id("ignore")
local c_obsidian = minetest.get_content_id("default:obsidian")
local c_brick = minetest.get_content_id("default:obsidianbrick")
local c_chest = minetest.get_content_id("default:chest_locked")
-- get node but use fallback for nil or unknown
function mobs:node_ok(pos, fallback)
fallback = fallback or "default:dirt"
local node = minetest.get_node_or_nil(pos)
if not node then
return minetest.registered_nodes[fallback]
end
if minetest.registered_nodes[node.name] then
return node
end
return minetest.registered_nodes[fallback]
end
--check_for_death functions customized for monsters who respawns (Masticone)
function mobs:check_for_death_hydra(self)
local hp = self.object:get_hp()
if hp > 0 then
self.health = hp
if self.sounds.damage ~= nil then
minetest.sound_play(self.sounds.damage,{
object = self.object,
max_hear_distance = self.sounds.distance
})
end
return false
end
local pos = self.object:getpos()
local obj = nil
if self.sounds.death ~= nil then
minetest.sound_play(self.sounds.death,{
object = self.object,
max_hear_distance = self.sounds.distance
})
end
self.object:remove()
return true
end
function mobs:round(n)
if (n>0) then
return n % 1 >= 0.5 and math.ceil(n) or math.floor(n)
else
n=-n
local t = n % 1 >= 0.5 and math.ceil(n) or math.floor(n)
return -t
end
end
function mobs:explosion_particles(pos, exp_radius)
minetest.add_particlespawner(
100*exp_radius/2, --amount
0.1, --time
{x=pos.x-exp_radius, y=pos.y-exp_radius, z=pos.z-exp_radius}, --minpos
{x=pos.x+exp_radius, y=pos.y+exp_radius, z=pos.z+exp_radius}, --maxpos
{x=0, y=0, z=0}, --minvel
{x=0.1, y=0.3, z=0.1}, --maxvel
{x=-0.5,y=1,z=-0.5}, --minacc
{x=0.5,y=1,z=0.5}, --maxacc
0.1, --minexptime
4, --maxexptime
6, --minsize
12, --maxsize
false, --collisiondetection
"tnt_smoke.png" --texture
)
end
function mobs:explosion(pos, exp_radius, fire)
local radius = exp_radius
-- if area protected or near map limits then no blast damage
if minetest.is_protected(pos, "")
or not within_limits(pos, radius) then
return
end
--sound
minetest.sound_play("boom", {
pos = pos,
max_hear_distance = exp_radius*4,
})
--particles:
mobs:explosion_particles(pos, exp_radius)
--Damages entities around (not the player)
local objects = minetest.env:get_objects_inside_radius(pos, exp_radius)
for _,obj in ipairs(objects) do
local obj_p = obj:getpos()
local vec = {x=obj_p.x-pos.x, y=obj_p.y-pos.y, z=obj_p.z-pos.z}
local dist = (vec.x^2+vec.y^2+vec.z^2)^0.5
local damage = (-exp_radius*dist+exp_radius^2)*2
obj:set_hp(obj:get_hp()-damage)
if (obj:get_hp() <= 0) then
if (not obj:is_player()) then
obj:remove()
end
end
end
--damages blocks around and if necessary put some fire
pos = vector.round(pos) -- voxelmanip doesn't work properly unless pos is rounded ?!?!
local vm = VoxelManip()
local minp, maxp = vm:read_from_map(vector.subtract(pos, radius), vector.add(pos, radius))
local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
local data = vm:get_data()
local p = {}
local pr = PseudoRandom(os.time())
--remove everything near the center of the explosion
for dz=-radius,radius do
for dy=-radius,radius do
local vi = a:index(pos.x + (-radius), pos.y + dy, pos.z + dz)
for dx=-radius,radius do
local p = {x=pos.x+dx, y=pos.y+dy, z=pos.z+dz}
if (dx * dx) + (dy * dy) + (dz * dz) <= (radius * radius) + pr:next(-radius, radius)
and data[vi] ~= c_air
and data[vi] ~= c_ignore
and data[vi] ~= c_obsidian
and data[vi] ~= c_brick
and data[vi] ~= c_chest then
local n = mobs:node_ok(p).name
local on_blast = minetest.registered_nodes[n].on_blast
if on_blast then
return on_blast(p)
end
if minetest.get_item_group(n, "unbreakable") ~= 1 then
-- if chest then drop items inside
if n == "default:chest"
or n == "3dchest:chest"
or n == "bones:bones" then
local meta = minetest.get_meta(p)
local inv = meta:get_inventory()
for i = 1, inv:get_size("main") do
local m_stack = inv:get_stack("main", i)
local obj = minetest.add_item(p, m_stack)
if obj then
obj:setvelocity({
x = math.random(-2, 2),
y = 7,
z = math.random(-2, 2)
})
end
end
end
-- after effects
if fire > 0
and (minetest.registered_nodes[n].groups.flammable
or math.random(1, 100) <= 3) then
minetest.set_node(p, {name = "fire:basic_flame"})
else
local dist = mobs:round(((pos.x-p.x)^2 + (pos.y-p.y)^2 + (pos.z-p.z)^2)^1/2)
local prob = 2/dist
if math.random(1,100)<=prob*100 then
minetest.env:remove_node(p)
end
end
end
end
vi = vi+1
end
end
end
end
-- SPECIAL ABILITIES OF SOME MOBS
function mobs:digging_ability(
self, --the entity of the mob
group, --group of the blocks the mob can dig: nil=everything
max_vel, --max velocity of the mob
dim --vector representing the dimensions of the mob
)
local v = self.object:getvelocity()
local pos = self.object:getpos()
if minetest.is_protected(pos, "") then
return
end
local h = dim.y
local max = 0
--local posmax = 0 -- 1 = x, -1=-x, 2 = z, -2 = -z
local yaw = (self.object:getyaw() + self.rotate) or 0
local x = math.sin(yaw)*-1
local z = math.cos(yaw)
local i = 1
local i1 = -1
local k = 1
local k1 = -1
local multiplier = 2
if x>0 then
i = nssm:round(x*max_vel)*multiplier
else
i1 = nssm:round(x*max_vel)*multiplier
end
if z>0 then
k = nssm:round(z*max_vel)*multiplier
else
k1 = nssm:round(z*max_vel)*multiplier
end
for dx = i1, i do
for dy = 0, h do
for dz = k1, k do
local p = {x=pos.x+dx, y=pos.y+dy, z=pos.z+dz}
local n = minetest.env:get_node(p).name
--local up = {x=pos.x+dx, y=pos.y+dy, z=pos.z+dz}
if group == nil then
if minetest.get_item_group(n, "unbreakable") == 1 or minetest.is_protected(p, "") then
else
minetest.env:set_node(p, {name="air"})
end
else
if (minetest.get_item_group(n, group)==1) and (minetest.get_item_group(n, "unbreakable") ~= 1) and not (minetest.is_protected(p, "")) then
minetest.env:set_node(p, {name="air"})
end
end
end
end
end
end
function mobs:putting_ability( --puts under the mob the block defined as 'p_block'
self, --the entity of the mob
p_block, --definition of the block to use
max_vel --max velocity of the mob
)
local v = self.object:getvelocity()
local dx = 0
local dz = 0
if (math.abs(v.x)>math.abs(v.z)) then
if (v.x)>0 then
dx = 1
else
dx = -1
end
else
if (v.z)>0 then
dz = 1
else
dz = -1
end
end
local pos = self.object:getpos()
local pos1
pos.y=pos.y-1
pos1 = {x = pos.x+dx, y = pos.y, z = pos.z+dz}
local n = minetest.env:get_node(pos).name
local n1 = minetest.env:get_node(pos1).name
if n~=p_block and not minetest.is_protected(pos, "") then
minetest.env:set_node(pos, {name=p_block})
end
if n1~=p_block and not minetest.is_protected(pos1, "") then
minetest.env:set_node(pos1, {name=p_block})
end
end
function mobs:webber_ability( --puts randomly around the block defined as w_block
self, --the entity of the mob
w_block, --definition of the block to use
radius --max distance the block can be put
)
local pos = self.object:getpos()
if (math.random(1,5)==1) then
local dx=math.random(1,radius)
local dz=math.random(1,radius)
local p = {x=pos.x+dx, y=pos.y-1, z=pos.z+dz}
local t = {x=pos.x+dx, y=pos.y, z=pos.z+dz}
local n = minetest.env:get_node(p).name
local k = minetest.env:get_node(t).name
if ((n~="air")and(k=="air")) and not minetest.is_protected(t, "") then
minetest.env:set_node(t, {name=w_block})
end
end
end
function mobs:midas_ability( --ability to transform every blocks it touches in the m_block block
self, --the entity of the mob
m_block,
max_vel, --max velocity of the mob
mult, --multiplier of the dimensions of the area around that need the transformation
height --height of the mob
)
local v = self.object:getvelocity()
local pos = self.object:getpos()
if minetest.is_protected(pos, "") then
return
end
local max = 0
local yaw = (self.object:getyaw() + self.rotate) or 0
local x = math.sin(yaw)*-1
local z = math.cos(yaw)
local i = 1
local i1 = -1
local k = 1
local k1 = -1
local multiplier = mult
if x>0 then
i = mobs:round(x*max_vel)*multiplier
else
i1 = mobs:round(x*max_vel)*multiplier
end
if z>0 then
k = mobs:round(z*max_vel)*multiplier
else
k1 = mobs:round(z*max_vel)*multiplier
end
for dx = i1, i do
for dy = -1, height do
for dz = k1, k do
local p = {x=pos.x+dx, y=pos.y+dy, z=pos.z+dz}
local n = minetest.env:get_node(p).name
if minetest.get_item_group(n, "unbreakable") == 1 or minetest.is_protected(p, "") or n=="air" then
else
minetest.env:set_node(p, {name=m_block})
end
end
end
end
end
| lgpl-2.1 |
Noneatme/MTA-NFS | client/CVehicleControls.lua | 1 | 2054 | -- ###############################
-- ## Project: MTA:Speedrace ##
-- ## Name: VehicleControls ##
-- ## Author: Noneatme ##
-- ## Version: 1.0 ##
-- ## License: See top Folder ##
-- ###############################
-- FUNCTIONS / METHODS --
local cFunc = {}; -- Local Functions
local cSetting = {}; -- Local Settings
VehicleControls = {};
VehicleControls.__index = VehicleControls;
--[[
]]
-- ///////////////////////////////
-- ///// New //////
-- ///////////////////////////////
function VehicleControls:New(...)
local obj = setmetatable({}, {__index = self});
if obj.Constructor then
obj:Constructor(...);
end
return obj;
end
-- ///////////////////////////////
-- ///// ToggleMouse //////
-- ///////////////////////////////
function VehicleControls:ToggleMouse(_, state)
if(state == "down") then
showCursor(false);
else
showCursor(true, false);
end
end
-- ///////////////////////////////
-- ///// ToggleReset //////
-- ///////////////////////////////
function VehicleControls:ToggleReset(_, state)
if not(isTimer(self.vcTimer)) then
if(localPlayer:GetVehicle():GetSpeed() < 10) then
localPlayer:GetVehicle():Reset();
self.vcTimer = setTimer(function() end, 5000, 1);
end
end
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///////////////////////////////
function VehicleControls:Constructor(...)
self.toggleMouseFunction = function(...)
self:ToggleMouse(...)
end
self.toggleResetFunction = function(...)
self:ToggleReset(...);
end
bindKey("mouse2", "both", self.toggleMouseFunction);
bindKey("backspace", "down", self.toggleResetFunction);
logger:OutputInfo("[CALLING] VehicleControls: Constructor");
end
-- ///////////////////////////////
-- ///// Destructor //////
-- ///////////////////////////////
function VehicleControls:Destructor(...)
unbindKey("mouse2", "both", self.toggleMouseFunction);
unbindKey("backspace", "down", self.toggleResetFunction);
logger:OutputInfo("[CALLING] VehicleControls: Destructor");
end
-- EVENT HANDLER --
| mit |
Bierbuikje/Mr.Green-MTA-Resources | resources/[race]/race/modes/nts.lua | 3 | 5316 | NTS = setmetatable({}, RaceMode)
NTS.__index = NTS
NTS:register('nts')
function NTS:isMapValid()
if self.getNumberOfCheckpoints() < 1 then
outputRace('Error starting NTS map: At least 1 CP needed')
return false
end
for _, checkpoint in ipairs(self.getCheckpoints()) do
if not self:isValidCheckpoint(checkpoint) then
outputChatBox('Error starting NTS map: Problem with NTS checkpoint #' .. _ .. ' (' .. checkpoint.id .. ')')
return false
end
end
return true
end
function NTS:isValidCheckpoint(checkpoint)
return checkpoint.nts == 'vehicle' or checkpoint.nts == 'boat' or checkpoint.nts == 'air' or checkpoint.nts == 'custom'
end
function NTS:onPlayerWasted(player)
if not self.checkpointBackups[player] then
return
end
TimerManager.destroyTimersFor("checkpointBackup",player)
if not self.isPlayerFinished(source) then
-- See if its worth doing a respawn
local respawnTime = tonumber(getElementData(player, 'gcshop.respawntime')) or self.getMapOption('respawntime')
if self:getTimeRemaining() - respawnTime > 3000 then
Countdown.create(respawnTime/1000, self.restorePlayer, 'You will respawn in:', 255, 255, 255, 0.25, 2.5, true, self, self.id, player):start(player)
end
if respawnTime >= 5000 then
TimerManager.createTimerFor("map",player):setTimer(clientCall, 2000, 1, player, 'Spectate.start', 'auto')
end
end
end
function NTS:start()
NTS.custom = {nil}
math.randomseed(getTickCount())
end
function NTS:playerUnfreeze(player, bDontFix)
if not isValidPlayer(player) then
return
end
toggleAllControls(player,true)
clientCall( player, "updateVehicleWeapons" )
local vehicle = self.getPlayerVehicle(player)
if not bDontFix then
fixVehicle(vehicle)
end
setVehicleDamageProof(vehicle, false)
setVehicleEngineState(vehicle, true)
setElementFrozen(vehicle, false)
-- Remove things added for freeze only
Override.setCollideWorld( "ForVehicleJudder", vehicle, nil )
Override.setCollideOthers( "ForVehicleSpawnFreeze", vehicle, nil )
Override.setAlpha( "ForRespawnEffect", {player, vehicle}, nil )
Override.flushAll()
addVehicleUpgrade(vehicle, 1010)
end
function NTS:getCheckpoint(i)
local realcheckpoint = g_Checkpoints[i]
local checkpoint = {}
for k,v in pairs(realcheckpoint) do
checkpoint[k] = v
end
checkpoint.vehicle = self:getRandomVehicle(checkpoint)
return checkpoint
end
local function betterRandom(floor,limit)
if not limit or not floor then return false end
local randomPlayer = getAlivePlayers()
local randomPlayer = randomPlayer[math.random(1,#randomPlayer)]
local x,y,z = getElementPosition(randomPlayer)
local seed = math.ceil((getTickCount()+math.abs(x)+math.abs(y)+math.abs(z))*math.random(1,10))
math.randomseed(seed)
local rand = math.random(limit)
return rand
end
function NTS:getRandomVehicle(checkpoint)
if checkpoint.nts == 'boat' then
list = NTS._boats
elseif checkpoint.nts == 'air' then
list = NTS._planes
elseif checkpoint.nts == 'vehicle' then
list = NTS._cars
elseif checkpoint.nts == 'custom' then
local models = tostring(checkpoint.models)
if models then
if NTS.custom[checkpoint.id] then
if #NTS.custom[checkpoint.id] == 0 then return false end
list = NTS.custom[checkpoint.id]
else
NTS.custom[checkpoint.id] = {}
local modelCount = 1
for model in string.gmatch(models, "([^;]+)") do
if tonumber(model) then
if getVehicleNameFromModel(model) == "" then
outputDebugString("Model " .. model .. " not valid for checkpoint " .. checkpoint.id, 0, 255, 0, 213)
else
NTS.custom[checkpoint.id][modelCount] = model
modelCount = modelCount + 1
end
end
end
if #NTS.custom[checkpoint.id] == 0 then return false end
list = NTS.custom[checkpoint.id]
end
else
return false
end
else
return false
end
return list[betterRandom(1, #list)]
end
NTS._cars = { 602, 545, 496, 517, 401, 410, 518, 600, 527, 436, 589, 580, 419, 439, 533, 549, 526, 491, 474, 445, 467, 604, 426, 507, 547, 585,
405, 587, 409, 466, 550, 492, 566, 546, 540, 551, 421, 516, 529, 581, 510, 509, 522, 481, 461, 462, 448, 521, 468, 463, 586, 485, 552, 431,
438, 437, 574, 420, 525, 408, 416, 596, 433, 597, 427, 599, 490, 528, 601, 407, 428, 544, 523, 470, 598, 499, 588, 609, 403, 498, 514, 524,
423, 532, 414, 578, 443, 486, 406, 531, 573, 456, 455, 459, 543, 422, 583, 482, 478, 605, 554, 530, 418, 572, 582, 413, 440, 536, 575, 534,
567, 535, 576, 412, 402, 542, 603, 475, 568, 557, 424, 471, 504, 495, 457, 539, 483, 508, 571, 500, 411, 515,
444, 556, 429, 541, 559, 415, 561, 480, 560, 562, 506, 565, 451, 434, 558, 494, 555, 502, 477, 503, 579, 400, 404, 489, 505, 479, 442, 458 }
-- rc's: 441, 464, 594, 501, 465, 564
-- tank: 432,
NTS._planes = {592, 577, 511, 548, 512, 593, 425, 520, 417, 487, 553, 488, 497, 563, 476, 447, 519, 460, 469, 513}
NTS._boats = {472,473,493,595,484,430,453,452,446,454}
NTS.name = 'Never the same'
NTS.modeOptions = {
respawn = 'timelimit',
respawntime = 5,
autopimp = false,
autopimp_map_can_override = false,
vehicleweapons = false,
vehicleweapons_map_can_override = false,
hunterminigun = false,
hunterminigun_map_can_override = false,
-- ghostmode = true,
-- ghostmode_map_can_override = false,
}
| mit |
huangleiBuaa/CenteredWN | module/Linear_ForDebug.lua | 1 | 8950 | local Linear_ForDebug, parent = torch.class('nn.Linear_ForDebug', 'nn.Module')
function Linear_ForDebug:__init(inputSize, outputSize,orth_flag,isBias)
parent.__init(self)
if isBias ~= nil then
assert(type(isBias) == 'boolean', 'isBias has to be true/false')
self.isBias = isBias
else
self.isBias = true
end
self.weight = torch.Tensor(outputSize, inputSize)
if self.isBias then
self.bias = torch.Tensor(outputSize)
self.gradBias = torch.Tensor(outputSize)
end
self.gradWeight = torch.Tensor(outputSize, inputSize)
self.FIM=torch.Tensor()
self.conditionNumber={}
self.epcilo=10^-100
self.counter=0
self.FIM_updateInterval=100
--for debug
self.printDetail=false
self.debug=false
self.debug_detailInfo=false
self.printInterval=1
self.count=0
if orth_flag ~= nil then
assert(type(orth_flag) == 'boolean', 'orth_flag has to be true/false')
if orth_flag then
self:reset_orthogonal()
else
self:reset()
end
else
self:reset()
end
end
function Linear_ForDebug:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.weight:size(2))
end
if nn.oldSeed then
for i=1,self.weight:size(1) do
self.weight:select(1, i):apply(function()
return torch.uniform(-stdv, stdv)
end)
if self.isBias then
self.bias[i] = torch.uniform(-stdv, stdv)
end
end
else
self.weight:uniform(-stdv, stdv)
if self.isBias then
self.bias:uniform(-stdv, stdv)
end
end
return self
end
function Linear_ForDebug:reset_orthogonal()
local initScale = 1.1 -- math.sqrt(2)
-- local initScale = math.sqrt(2)
local M1 = torch.randn(self.weight:size(1), self.weight:size(1))
local M2 = torch.randn(self.weight:size(2), self.weight:size(2))
local n_min = math.min(self.weight:size(1), self.weight:size(2))
-- QR decomposition of random matrices ~ N(0, 1)
local Q1, R1 = torch.qr(M1)
local Q2, R2 = torch.qr(M2)
self.weight:copy(Q1:narrow(2,1,n_min) * Q2:narrow(1,1,n_min)):mul(initScale)
self.bias:zero()
end
function Linear_ForDebug:updateOutput(input)
--self.bias:fill(0)
if input:dim() == 1 then
self.output:resize(self.bias:size(1))
self.output:copy(self.bias)
self.output:addmv(1, self.weight, input)
elseif input:dim() == 2 then
local nframe = input:size(1)
local nElement = self.output:nElement()
self.output:resize(nframe, self.weight:size(1))
if self.output:nElement() ~= nElement then
self.output:zero()
end
self.addBuffer = self.addBuffer or input.new()
if self.addBuffer:nElement() ~= nframe then
self.addBuffer:resize(nframe):fill(1)
end
self.output:addmm(0, self.output, 1, input, self.weight:t())
if self.isBias then
self.output:addr(1, self.addBuffer, self.bias)
end
else
error('input must be vector or matrix')
end
if self.printDetail then
print("Linear_ForDebug: activation, number fo example=20")
print(self.output[{{1,20},{}}])
end
if self.debug and (self.count % self.printInterval==0)then
-- local input_norm=torch.norm(input,1)/input:numel()
local input_norm=torch.norm(input,1)
local output_norm=torch.norm(self.output,1)
-- print('debug_LinearModule--input_norm_elementWise:'..input_norm..' --output_norm_elementWise:'..output_norm)
end
if self.debug_detailInfo and (self.count % self.printInterval==0)then
local input_mean=input:mean(1)
local input_normPerDim=torch.norm(input,1,1)/input:size(1)
local output_mean=self.output:mean(1)
local output_normPerDim=torch.norm(self.output,1,1)/self.output:size(1)
print('debug_LinearModule--input_mean:')
print(input_mean)
print('debug_LinearModule--input_normPerDim:')
print(input_normPerDim)
print('debug_LinearModule--output_mean:')
print(output_mean)
print('debug_LinearModule--output_normPerDim:')
print(output_normPerDim)
end
return self.output
end
function Linear_ForDebug:updateGradInput(input, gradOutput)
if self.gradInput then
local nElement = self.gradInput:nElement()
self.gradInput:resizeAs(input)
if self.gradInput:nElement() ~= nElement then
self.gradInput:zero()
end
if input:dim() == 1 then
self.gradInput:addmv(0, 1, self.weight:t(), gradOutput)
elseif input:dim() == 2 then
self.gradInput:addmm(0, 1, gradOutput, self.weight)
end
if self.printDetail then
print("Linear_ForDebug: gradOutput, number fo example=20")
print(gradOutput[{{1,20},{}}])
end
if self.debug and (self.count % self.printInterval==0)then
local gradOutput_norm=torch.norm(gradOutput,1)
local gradInput_norm=torch.norm(self.gradInput,1)
-- print('debug_LinearModule--gradOutput_norm_elementWise:'..gradOutput_norm..' --gradInput_norm_elementWise:'..gradInput_norm)
end
if self.debug_detailInfo and (self.count % self.printInterval==0)then
local gradInput_mean=self.gradInput:mean(1)
local gradInput_normPerDim=torch.norm(self.gradInput,1,1)/self.gradInput:size(1)
local gradOutput_mean=gradOutput:mean(1)
local gradOutput_normPerDim=torch.norm(gradOutput,1,1)/gradOutput:size(1)
print('debug_LinearModule--gradInput_mean:')
print(gradInput_mean)
print('debug_LinearModule--gradInput_normPerDim:')
print(gradInput_normPerDim)
print('debug_LinearModule--gradOutput_mean:')
print(gradOutput_mean)
print('debug_LinearModule--gradOutput_normPerDim:')
print(gradOutput_normPerDim)
end
return self.gradInput
end
end
function Linear_ForDebug:accGradParameters(input, gradOutput, scale)
scale = scale or 1
if input:dim() == 1 then
self.gradWeight:addr(scale, gradOutput, input)
self.gradBias:add(scale, gradOutput)
elseif input:dim() == 2 then
self.gradWeight:addmm(scale, gradOutput:t(), input)
if self.isBias then
self.gradBias:addmv(scale, gradOutput:t(), self.addBuffer)
end
end
if self.debug and (self.count % self.printInterval==0) then
local weight_norm=torch.norm(self.weight,1)
local bias_norm=torch.norm(self.bias,1)
local gradWeight_norm=torch.norm(self.gradWeight,1)
local gradBias_norm=torch.norm(self.gradBias,1)
print('debug_LinearModule:--weight_norm_elementWise:'..weight_norm..' --bias_norm_elementWise:'..bias_norm)
print(' --gradWeight_norm_elementWise:'..gradWeight_norm..' --gradBias_norm_elementWise:'..gradBias_norm)
end
if self.debug_detailInfo and (self.count % self.printInterval==0)then
local gradWeight_mean_rowWise=self.gradWeight:mean(1)
local gradWeight_mean_columnWise=self.gradWeight:mean(2)
local gradWeight_normPerDim_rowWise=torch.norm(self.gradWeight,1,1)/self.gradWeight:size(1)
local gradWeight_normPerDim_columnWise=torch.norm(self.gradWeight,1,2)/self.gradWeight:size(2)
local weight_mean_rowWise=self.weight:mean(1)
local weight_mean_columnWise=self.weight:mean(2)
local weight_normPerDim_rowWise=torch.norm(self.weight,1,1)/self.weight:size(1)
local weight_normPerDim_columnWise=torch.norm(self.weight,1,2)/self.weight:size(2)
print('debug_LinearModule--gradWeight_mean_rowWise:')
print(gradWeight_mean_rowWise)
print('debug_LinearModule--gradWeight_mean_columnWise:')
print(gradWeight_mean_columnWise)
print('debug_LinearModule--gradWeight_normPerDim_rowWise:')
print(gradWeight_normPerDim_rowWise)
print('debug_LinearModule--gradWeight_normPerDim_columnWise:')
print(gradWeight_normPerDim_columnWise)
print('debug_LinearModule--weight_mean_rowWise:')
print(weight_mean_rowWise)
print('debug_LinearModule--weight_mean_columnWise:')
print(weight_mean_columnWise)
print('debug_LinearModule--weight_normPerDim_rowWise:')
print(weight_normPerDim_rowWise)
print('debug_LinearModule--weight_normPerDim_columnWise:')
print(weight_normPerDim_columnWise)
end
self.count=self.count+1 --the ending of all the operation in this module
end
-- we do not need to accumulate parameters when sharing
Linear_ForDebug.sharedAccUpdateGradParameters = Linear_ForDebug.accUpdateGradParameters
function Linear_ForDebug:__tostring__()
return torch.type(self) ..
string.format('(%d -> %d)', self.weight:size(2), self.weight:size(1))
end
| bsd-2-clause |
DiscoverySpaces/roman-numeral-game | TestRomanNumeralAddition.lua | 1 | 5084 | require "RomanNumeralAddition"
local lunatest = require "lunatest"
--lunatest.suite("basic-roman-numerals")
function test_sort()
lunatest.assert_equal(SortLargerToSmallerSymbols("LXXIXXDCCCXCCCMCCXXDXVIIIIIIID"),'MDDDCCCCCCCCLXXXXXXXXVIIIIIIII')
end
function test_UpConvert()
lunatest.assert_equal(UpConvert('IIIII'),'V',"this should be converted to 'V' because that is the equivalent of 5 I's")
lunatest.assert_equal(UpConvert('DCCCCCCCCLXXXXXXXXVIIIIIIII'),'MCCCCXXXXIII',"this test includes all roman numerals")
--THESE ARE SUBTRACTIVE TO SUBTRACTIVE UPCONVERSIONS
lunatest.assert_equal(UpConvert('DCD'),'CM',"an odd Case, program wants to return DCD")
lunatest.assert_equal(UpConvert('VIV'),'IX',"an odd Case, program wants to return VIV")
lunatest.assert_equal(UpConvert('LXL'),'XC',"an odd Case, program wants to return LXL")
lunatest.assert_equal(UpConvert('MMMM'),'(IV)',"anything over 3k uses (parens) or added bar to denote time 1000")
lunatest.assert_equal('(V)', UpConvert('MMMMM')," 'MMMMM' to '(V)' anything over 3k uses (parens) or added bar to denote time 1000")
lunatest.assert_equal(UpConvert('MMMMMM'),'(VI)',"anything over 3k uses (parens) or added bar to denote time 1000")
end
function test_add_romans()
--COUNT FROM 1 TO 12 switching input order
BasicNumeralTestData = {{'I','I','II'},{'I','II','III'},{'I','III','IV'},{'IV','I','V'},{'V','I','VI'},{'VI','I','VII'},{'I','VII','VIII'},{'I','VIII','IX'},{'I','IX','X'},{'I','X','XI'},{'XI','I','XII'}}
--instead of BasicNumeralTestData array, read in from a file entered by spreadsheet
for i, v in ipairs(BasicNumeralTestData) do
-- law of commutation applies to Roman Numerals:
lunatest.assert_equal(AddTwoRomanNumerals(v[1],v[2]),v[3])
lunatest.assert_equal(AddTwoRomanNumerals(v[2],v[1]),v[3])
end
--OTHER ADDS
lunatest.assert_equal(AddTwoRomanNumerals('MCMXLVIII','DCCXLIV'),'MMDCXCII')-- which is 1948+744=2692')
lunatest.assert_equal(AddTwoRomanNumerals('MMM','CMXCIX'),'MMMCMXCIX')-- 3000+999=3999') --3999
lunatest.assert_equal(AddTwoRomanNumerals('MMM','M'),'(IV)') --Search for a count of more than 3 M's in the final number, then...MMMM to IV with an overline or easier to represent: embraced in parens (IV). It should be placed all the way to the left since it is the highest number except for subtractive form C(IV)CMXIX ? verify this!! 4000 would be M(V) --see http://able2know.org/topic/54469-1
lunatest.assert_equal(AddTwoRomanNumerals('MMMCX','MMVIII'),'(V)CXVIII')
lunatest.assert_equal(AddTwoRomanNumerals('MMMXIV','MMM'),'(VI)XIV')
--[[
I II III IV V VI VII VIII IX
X XX XXX XL L LX LXX LXXX XC
C CC CCC CD D DC DCC DCCC CM
M MM MMM MV V VM VMM VMMM MX --this is the logical consistency,
--but what really happens is it reverts back to 1-10 counting all multiplied times 1000. IV is treated as a single numeral then x1000
--------------------------------------------
M MM MMM IV V VI VII VIII IX --this is the way the romans did it, we think
URL: http://able2know.org/topic/54469-1
]]--
end
function test_subtractives()
--test basics of individual pairs subtractives using Ipairs to avoid repetition:
AllSubtractives = {{'IV','IIII'},{'IX','VIIII'},{'XL','XXXX'},{'XC','LXXXX'},{'CD','CCCC'},{'CM','DCCCC'}}
for i, v in ipairs(AllSubtractives) do
lunatest.assert_equal(SwitchSubtractives(v[1],'extract'),v[2])
lunatest.assert_equal(SwitchSubtractives(v[2],'restore'),v[1])
end
--test all in combo subtractive pairs
lunatest.assert_equal(SwitchSubtractives('XCCMCDXLIXIV','extract'),'LXXXXDCCCCCCCCXXXXVIIIIIIII','an extraction')
lunatest.assert_equal(SwitchSubtractives( 'MCCCCXXXXIII','restore'),'MCDXLIII','1443')
end
function test_importcsv()
allRomans=importsinglefieldcsv("roman-numeral-addition-truth-table.csv")
print(allRomans[39])
for i, v in ipairs(allRomans) do
-- law of commutation applies to Roman Numerals:
lunatest.assert_equal(AddTwoRomanNumerals('I',allRomans[i]),allRomans[i+1],"Testing number "..i)
lunatest.assert_equal(AddTwoRomanNumerals('II',allRomans[i]),allRomans[i+2],"Testing number "..i)
lunatest.assert_equal(AddTwoRomanNumerals('III',allRomans[i]),allRomans[i+3],"Testing number "..i)
lunatest.assert_equal(AddTwoRomanNumerals('IV',allRomans[i]),allRomans[i+4],"Testing number "..i)
lunatest.assert_equal(AddTwoRomanNumerals('V',allRomans[i]),allRomans[i+5],"Testing number "..i)
lunatest.assert_equal(AddTwoRomanNumerals('VI',allRomans[i]),allRomans[i+6],"Testing number "..i)
lunatest.assert_equal(AddTwoRomanNumerals('VII',allRomans[i]),allRomans[i+7],"Testing number "..i)
lunatest.assert_equal(AddTwoRomanNumerals('VIII',allRomans[i]),allRomans[i+8],"Testing number "..i)
lunatest.assert_equal(AddTwoRomanNumerals('IX',allRomans[i]),allRomans[i+9],"Testing number "..i)
lunatest.assert_equal(AddTwoRomanNumerals('X',allRomans[i]),allRomans[i+10],"Testing number "..i)
lunatest.assert_equal(AddTwoRomanNumerals('XI',allRomans[i]),allRomans[i+11],"Testing number "..i)
end
end
lunatest.run()
| apache-2.0 |
Fawk/CleanUI | modules/units/targettarget.lua | 1 | 2474 | local A, L = unpack(select(2, ...))
local E, T, U, Units, media = A.enum, A.Tools, A.Utils, A.Units, LibStub("LibSharedMedia-3.0")
local GetSpecializationInfo, GetSpecialization = GetSpecializationInfo, GetSpecialization
local InCombatLockdown = InCombatLockdown
local TargetTarget = {}
local frameName = "Target of Target"
local unitName = "TargetTarget"
function TargetTarget:Init()
local db = A.db.profile.units[unitName:lower()]
local frame = Units:Get(frameName) or A:CreateUnit(unitName)
frame.GetDbName = function(self) return frameName end
frame.db = db
frame.orderedElements = A:OrderedMap()
frame.tags = A:OrderedMap()
frame:SetScript("OnShow", function(self)
self:Update(UnitEvent.UPDATE_DB)
end)
frame.Update = function(self, ...)
TargetTarget:Update(self, ...)
end
Units:Add(frame, frame:GetDbName())
Units:Position(frame, db.position)
frame:Update(UnitEvent.UPDATE_IDENTIFIER)
frame:Update(UnitEvent.UPDATE_DB)
A:CreateMover(frame, db, frameName)
return frame
end
function TargetTarget:Update(...)
local self, event, arg2, arg3, arg4, arg5 = ...
if (self.super) then
self.super:Update(...)
-- Update player specific things based on the event
if (event == UnitEvent.UPDATE_DB) then
local db = self.db
if (not InCombatLockdown()) then
Units:Position(self, db.position)
self:SetSize(db.size.width, db.size.height)
self:SetAttribute("*type1", "target")
self:SetAttribute("*type2", "togglemenu")
A.general.clickcast:Setup(self, db.clickcast)
end
--[[ Bindings ]]--
self:RegisterForClicks("AnyUp")
--[[ Background ]]--
U:CreateBackground(self, db, false)
for i = 1, self.tags:len() do
if (not db.tags.list[self.tags(i)]) then
if (self.tags[i]) then
self.tags[i]:Hide()
end
self.tags[i] = nil
end
end
for name,tag in next, db.tags.list do
Units:Tag(self, name, tag)
end
self:ForceTagUpdate()
for i = 1, self.orderedElements:len() do
self.orderedElements[i]:Update(event)
end
end
end
end
A.modules[frameName] = TargetTarget | gpl-3.0 |
Jar-Chi/JarChi | libs/fakeredis.lua | 650 | 40405 | local unpack = table.unpack or unpack
--- Bit operations
local ok,bit
if _VERSION == "Lua 5.3" then
bit = (load [[ return {
band = function(x, y) return x & y end,
bor = function(x, y) return x | y end,
bxor = function(x, y) return x ~ y end,
bnot = function(x) return ~x end,
rshift = function(x, n) return x >> n end,
lshift = function(x, n) return x << n end,
} ]])()
else
ok,bit = pcall(require,"bit")
if not ok then bit = bit32 end
end
assert(type(bit) == "table", "module for bitops not found")
--- default sleep
local default_sleep
do
local ok, mod = pcall(require, "socket")
if ok and type(mod) == "table" then
default_sleep = mod.sleep
else
default_sleep = function(n)
local t0 = os.clock()
while true do
local delta = os.clock() - t0
if (delta < 0) or (delta > n) then break end
end
end
end
end
--- Helpers
local xdefv = function(ktype)
if ktype == "list" then
return {head = 0, tail = 0}
elseif ktype == "zset" then
return {
list = {},
set = {},
}
else return {} end
end
local xgetr = function(self, k, ktype)
if self.data[k] then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
assert(self.data[k].value)
return self.data[k].value
else return xdefv(ktype) end
end
local xgetw = function(self, k, ktype)
if self.data[k] and self.data[k].value then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
else
self.data[k] = {ktype = ktype, value = xdefv(ktype)}
end
return self.data[k].value
end
local empty = function(self, k)
local v, t = self.data[k].value, self.data[k].ktype
if t == nil then
return true
elseif t == "string" then
return not v[1]
elseif (t == "hash") or (t == "set") then
for _,_ in pairs(v) do return false end
return true
elseif t == "list" then
return v.head == v.tail
elseif t == "zset" then
if #v.list == 0 then
for _,_ in pairs(v.set) do error("incoherent") end
return true
else
for _,_ in pairs(v.set) do return(false) end
error("incoherent")
end
else error("unsupported") end
end
local cleanup = function(self, k)
if empty(self, k) then self.data[k] = nil end
end
local is_integer = function(x)
return (type(x) == "number") and (math.floor(x) == x)
end
local overflows = function(n)
return (n > 2^53-1) or (n < -2^53+1)
end
local is_bounded_integer = function(x)
return (is_integer(x) and (not overflows(x)))
end
local is_finite_number = function(x)
return (type(x) == "number") and (x > -math.huge) and (x < math.huge)
end
local toint = function(x)
if type(x) == "string" then x = tonumber(x) end
return is_bounded_integer(x) and x or nil
end
local tofloat = function(x)
if type(x) == "number" then return x end
if type(x) ~= "string" then return nil end
local r = tonumber(x)
if r then return r end
if x == "inf" or x == "+inf" then
return math.huge
elseif x == "-inf" then
return -math.huge
else return nil end
end
local tostr = function(x)
if is_bounded_integer(x) then
return string.format("%d", x)
else return tostring(x) end
end
local char_bitcount = function(x)
assert(
(type(x) == "number") and
(math.floor(x) == x) and
(x >= 0) and (x < 256)
)
local n = 0
while x ~= 0 do
x = bit.band(x, x-1)
n = n+1
end
return n
end
local chkarg = function(x)
if type(x) == "number" then x = tostr(x) end
assert(type(x) == "string")
return x
end
local chkargs = function(n, ...)
local arg = {...}
assert(#arg == n)
for i=1,n do arg[i] = chkarg(arg[i]) end
return unpack(arg)
end
local getargs = function(...)
local arg = {...}
local n = #arg; assert(n > 0)
for i=1,n do arg[i] = chkarg(arg[i]) end
return arg
end
local getargs_as_map = function(...)
local arg, r = getargs(...), {}
assert(#arg%2 == 0)
for i=1,#arg,2 do r[arg[i]] = arg[i+1] end
return r
end
local chkargs_wrap = function(f, n)
assert( (type(f) == "function") and (type(n) == "number") )
return function(self, ...) return f(self, chkargs(n, ...)) end
end
local lset_to_list = function(s)
local r = {}
for v,_ in pairs(s) do r[#r+1] = v end
return r
end
local nkeys = function(x)
local r = 0
for _,_ in pairs(x) do r = r + 1 end
return r
end
--- Commands
-- keys
local del = function(self, ...)
local arg = getargs(...)
local r = 0
for i=1,#arg do
if self.data[arg[i]] then r = r + 1 end
self.data[arg[i]] = nil
end
return r
end
local exists = function(self, k)
return not not self.data[k]
end
local keys = function(self, pattern)
assert(type(pattern) == "string")
-- We want to convert the Redis pattern to a Lua pattern.
-- Start by escaping dashes *outside* character classes.
-- We also need to escape percents here.
local t, p, n = {}, 1, #pattern
local p1, p2
while true do
p1, p2 = pattern:find("%[.+%]", p)
if p1 then
if p1 > p then
t[#t+1] = {true, pattern:sub(p, p1-1)}
end
t[#t+1] = {false, pattern:sub(p1, p2)}
p = p2+1
if p > n then break end
else
t[#t+1] = {true, pattern:sub(p, n)}
break
end
end
for i=1,#t do
if t[i][1] then
t[i] = t[i][2]:gsub("[%%%-]", "%%%0")
else t[i] = t[i][2]:gsub("%%", "%%%%") end
end
-- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]'
-- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is.
-- Wrap in '^$' to enforce bounds.
local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0")
:gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$"
local r = {}
for k,_ in pairs(self.data) do
if k:match(lp) then r[#r+1] = k end
end
return r
end
local _type = function(self, k)
return self.data[k] and self.data[k].ktype or "none"
end
local randomkey = function(self)
local ks = lset_to_list(self.data)
local n = #ks
if n > 0 then
return ks[math.random(1, n)]
else return nil end
end
local rename = function(self, k, k2)
assert((k ~= k2) and self.data[k])
self.data[k2] = self.data[k]
self.data[k] = nil
return true
end
local renamenx = function(self, k, k2)
if self.data[k2] then
return false
else
return rename(self, k, k2)
end
end
-- strings
local getrange, incrby, set
local append = function(self, k, v)
local x = xgetw(self, k, "string")
x[1] = (x[1] or "") .. v
return #x[1]
end
local bitcount = function(self, k, i1, i2)
k = chkarg(k)
local s
if i1 or i2 then
assert(i1 and i2, "ERR syntax error")
s = getrange(self, k, i1, i2)
else
s = xgetr(self, k, "string")[1] or ""
end
local r, bytes = 0,{s:byte(1, -1)}
for i=1,#bytes do
r = r + char_bitcount(bytes[i])
end
return r
end
local bitop = function(self, op, k, ...)
assert(type(op) == "string")
op = op:lower()
assert(
(op == "and") or
(op == "or") or
(op == "xor") or
(op == "not"),
"ERR syntax error"
)
k = chkarg(k)
local arg = {...}
local good_arity = (op == "not") and (#arg == 1) or (#arg > 0)
assert(good_arity, "ERR wrong number of arguments for 'bitop' command")
local l, vals = 0, {}
local s
for i=1,#arg do
s = xgetr(self, arg[i], "string")[1] or ""
if #s > l then l = #s end
vals[i] = s
end
if l == 0 then
del(self, k)
return 0
end
local vector_mt = {__index=function() return 0 end}
for i=1,#vals do
vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt)
end
local r = {}
if op == "not" then
assert(#vals[1] == l)
for i=1,l do
r[i] = bit.band(bit.bnot(vals[1][i]), 0xff)
end
else
local _op = bit["b" .. op]
for i=1,l do
local t = {}
for j=1,#vals do t[j] = vals[j][i] end
r[i] = _op(unpack(t))
end
end
set(self, k, string.char(unpack(r)))
return l
end
local decr = function(self, k)
return incrby(self, k, -1)
end
local decrby = function(self, k, n)
n = toint(n)
assert(n, "ERR value is not an integer or out of range")
return incrby(self, k, -n)
end
local get = function(self, k)
local x = xgetr(self, k, "string")
return x[1]
end
local getbit = function(self, k, offset)
k = chkarg(k)
offset = toint(offset)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
if bytepos >= #s then return 0 end
local char = s:sub(bytepos+1, bytepos+1):byte()
return bit.band(bit.rshift(char, 7-bitpos), 1)
end
getrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetr(self, k, "string")
x = x[1] or ""
if i1 >= 0 then i1 = i1 + 1 end
if i2 >= 0 then i2 = i2 + 1 end
return x:sub(i1, i2)
end
local getset = function(self, k, v)
local r = get(self, k)
set(self, k, v)
return r
end
local incr = function(self, k)
return incrby(self, k, 1)
end
incrby = function(self, k, n)
k, n = chkarg(k), toint(n)
assert(n, "ERR value is not an integer or out of range")
local x = xgetw(self, k, "string")
local i = toint(x[1] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[1] = tostr(i)
return i
end
local incrbyfloat = function(self, k, n)
k, n = chkarg(k), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "string")
local i = tofloat(x[1] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[1] = tostr(i)
return i
end
local mget = function(self, ...)
local arg, r = getargs(...), {}
for i=1,#arg do r[i] = get(self, arg[i]) end
return r
end
local mset = function(self, ...)
local argmap = getargs_as_map(...)
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
local msetnx = function(self, ...)
local argmap = getargs_as_map(...)
for k,_ in pairs(argmap) do
if self.data[k] then return false end
end
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
set = function(self, k, v)
self.data[k] = {ktype = "string", value = {v}}
return true
end
local setbit = function(self, k, offset, b)
k = chkarg(k)
offset, b = toint(offset), toint(b)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
assert(
(b == 0) or (b == 1),
"ERR bit is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
local pad = {s}
for i=2,bytepos+2-#s do pad[i] = "\0" end
s = table.concat(pad)
assert(#s >= bytepos+1)
local before = s:sub(1, bytepos)
local char = s:sub(bytepos+1, bytepos+1):byte()
local after = s:sub(bytepos+2, -1)
local old = bit.band(bit.rshift(char, 7-bitpos), 1)
if b == 1 then
char = bit.bor(bit.lshift(1, 7-bitpos), char)
else
char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char)
end
local r = before .. string.char(char) .. after
set(self, k, r)
return old
end
local setnx = function(self, k, v)
if self.data[k] then
return false
else
return set(self, k, v)
end
end
local setrange = function(self, k, i, s)
local k, s = chkargs(2, k, s)
i = toint(i)
assert(i and (i >= 0))
local x = xgetw(self, k, "string")
local y = x[1] or ""
local ly, ls = #y, #s
if i > ly then -- zero padding
local t = {}
for i=1, i-ly do t[i] = "\0" end
y = y .. table.concat(t) .. s
else
y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly)
end
x[1] = y
return #y
end
local strlen = function(self, k)
local x = xgetr(self, k, "string")
return x[1] and #x[1] or 0
end
-- hashes
local hdel = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local r = 0
local x = xgetw(self, k, "hash")
for i=1,#arg do
if x[arg[i]] then r = r + 1 end
x[arg[i]] = nil
end
cleanup(self, k)
return r
end
local hget
local hexists = function(self, k, k2)
return not not hget(self, k, k2)
end
hget = function(self, k, k2)
local x = xgetr(self, k, "hash")
return x[k2]
end
local hgetall = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,v in pairs(x) do r[_k] = v end
return r
end
local hincrby = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), toint(n)
assert(n, "ERR value is not an integer or out of range")
assert(type(n) == "number")
local x = xgetw(self, k, "hash")
local i = toint(x[k2] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[k2] = tostr(i)
return i
end
local hincrbyfloat = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "hash")
local i = tofloat(x[k2] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[k2] = tostr(i)
return i
end
local hkeys = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,_ in pairs(x) do r[#r+1] = _k end
return r
end
local hlen = function(self, k)
local x = xgetr(self, k, "hash")
return nkeys(x)
end
local hmget = function(self, k, k2s)
k = chkarg(k)
assert((type(k2s) == "table"))
local r = {}
local x = xgetr(self, k, "hash")
for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end
return r
end
local hmset = function(self, k, ...)
k = chkarg(k)
local arg = {...}
if type(arg[1]) == "table" then
assert(#arg == 1)
local x = xgetw(self, k, "hash")
for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end
else
assert(#arg % 2 == 0)
local x = xgetw(self, k, "hash")
local t = getargs(...)
for i=1,#t,2 do x[t[i]] = t[i+1] end
end
return true
end
local hset = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
local r = not x[k2]
x[k2] = v
return r
end
local hsetnx = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
if x[k2] == nil then
x[k2] = v
return true
else
return false
end
end
local hvals = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _,v in pairs(x) do r[#r+1] = v end
return r
end
-- lists (head = left, tail = right)
local _l_real_i = function(x, i)
if i < 0 then
return x.tail+i+1
else
return x.head+i+1
end
end
local _l_len = function(x)
return x.tail - x.head
end
local _block_for = function(self, timeout)
if timeout > 0 then
local sleep = self.sleep or default_sleep
if type(sleep) == "function" then
sleep(timeout)
else
error("sleep function unavailable", 0)
end
else
error("operation would block", 0)
end
end
local rpoplpush
local blpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpoplpush = function(self, k1, k2, timeout)
k1, k2 = chkargs(2, k1, k2)
timeout = toint(timeout)
if not self.data[k1] then _block_for(self, timeout) end
return rpoplpush(self, k1, k2)
end
local lindex = function(self, k, i)
k = chkarg(k)
i = assert(toint(i))
local x = xgetr(self, k, "list")
return x[_l_real_i(x, i)]
end
local linsert = function(self, k, mode, pivot, v)
mode = mode:lower()
assert((mode == "before") or (mode == "after"))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local p = nil
for i=x.head+1, x.tail do
if x[i] == pivot then
p = i
break
end
end
if not p then return -1 end
if mode == "after" then
for i=x.head+1, p do x[i-1] = x[i] end
x.head = x.head - 1
else
for i=x.tail, p, -1 do x[i+1] = x[i] end
x.tail = x.tail + 1
end
x[p] = v
return _l_len(x)
end
local llen = function(self, k)
local x = xgetr(self, k, "list")
return _l_len(x)
end
local lpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return r
end
local lpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x[x.head] = vs[i]
x.head = x.head - 1
end
return _l_len(x)
end
local lpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x[x.head] = v
x.head = x.head - 1
return _l_len(x)
end
local lrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x, r = xgetr(self, k, "list"), {}
i1 = math.max(_l_real_i(x, i1), x.head+1)
i2 = math.min(_l_real_i(x, i2), x.tail)
for i=i1,i2 do r[#r+1] = x[i] end
return r
end
local _lrem_i = function(x, p)
for i=p,x.tail do
x[i] = x[i+1]
end
x.tail = x.tail - 1
end
local _lrem_l = function(x, v, s)
assert(v)
if not s then s = x.head+1 end
for i=s,x.tail do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local _lrem_r = function(x, v, s)
assert(v)
if not s then s = x.tail end
for i=s,x.head+1,-1 do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local lrem = function(self, k, count, v)
k, v = chkarg(k), chkarg(v)
count = assert(toint(count))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local n, last = 0, nil
local op = (count < 0) and _lrem_r or _lrem_l
local limited = (count ~= 0)
count = math.abs(count)
while true do
last = op(x, v, last)
if last then
n = n+1
if limited then
count = count - 1
if count == 0 then break end
end
else break end
end
return n
end
local lset = function(self, k, i, v)
k, v = chkarg(k), chkarg(v)
i = assert(toint(i))
if not self.data[k] then
error("ERR no such key")
end
local x = xgetw(self, k, "list")
local l = _l_len(x)
if i >= l or i < -l then
error("ERR index out of range")
end
x[_l_real_i(x, i)] = v
return true
end
local ltrim = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetw(self, k, "list")
i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2)
for i=x.head+1,i1-1 do x[i] = nil end
for i=i2+1,x.tail do x[i] = nil end
x.head = math.max(i1-1, x.head)
x.tail = math.min(i2, x.tail)
assert(
(x[x.head] == nil) and
(x[x.tail+1] == nil)
)
cleanup(self, k)
return true
end
local rpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return r
end
rpoplpush = function(self, k1, k2)
local v = rpop(self, k1)
if not v then return nil end
lpush(self, k2, v)
return v
end
local rpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x.tail = x.tail + 1
x[x.tail] = vs[i]
end
return _l_len(x)
end
local rpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x.tail = x.tail + 1
x[x.tail] = v
return _l_len(x)
end
-- sets
local sadd = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if not x[arg[i]] then
x[arg[i]] = true
r = r + 1
end
end
return r
end
local scard = function(self, k)
local x = xgetr(self, k, "set")
return nkeys(x)
end
local _sdiff = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
for v,_ in pairs(x) do r[v] = true end
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = nil end
end
return r
end
local sdiff = function(self, k, ...)
return lset_to_list(_sdiff(self, k, ...))
end
local sdiffstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sdiff(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local _sinter = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
local y
for v,_ in pairs(x) do
r[v] = true
for i=1,#arg do
y = xgetr(self, arg[i], "set")
if not y[v] then r[v] = nil; break end
end
end
return r
end
local sinter = function(self, k, ...)
return lset_to_list(_sinter(self, k, ...))
end
local sinterstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sinter(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local sismember = function(self, k, v)
local x = xgetr(self, k, "set")
return not not x[v]
end
local smembers = function(self, k)
local x = xgetr(self, k, "set")
return lset_to_list(x)
end
local smove = function(self, k, k2, v)
local x = xgetr(self, k, "set")
if x[v] then
local y = xgetw(self, k2, "set")
x[v] = nil
y[v] = true
return true
else return false end
end
local spop = function(self, k)
local x, r = xgetw(self, k, "set"), nil
local l = lset_to_list(x)
local n = #l
if n > 0 then
r = l[math.random(1, n)]
x[r] = nil
end
cleanup(self, k)
return r
end
local srandmember = function(self, k, count)
k = chkarg(k)
local x = xgetr(self, k, "set")
local l = lset_to_list(x)
local n = #l
if not count then
if n > 0 then
return l[math.random(1, n)]
else return nil end
end
count = toint(count)
if (count == 0) or (n == 0) then return {} end
if count >= n then return l end
local r = {}
if count > 0 then -- distinct elements
for i=0,count-1 do
r[#r+1] = table.remove(l, math.random(1, n-i))
end
else -- allow repetition
for i=1,-count do
r[#r+1] = l[math.random(1, n)]
end
end
return r
end
local srem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if x[arg[i]] then
x[arg[i]] = nil
r = r + 1
end
end
cleanup(self, k)
return r
end
local _sunion = function(self, ...)
local arg = getargs(...)
local r = {}
local x
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = true end
end
return r
end
local sunion = function(self, k, ...)
return lset_to_list(_sunion(self, k, ...))
end
local sunionstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sunion(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
-- zsets
local _z_p_mt = {
__eq = function(a, b)
if a.v == b.v then
assert(a.s == b.s)
return true
else return false end
end,
__lt = function(a, b)
if a.s == b.s then
return (a.v < b.v)
else
return (a.s < b.s)
end
end,
}
local _z_pair = function(s, v)
assert(
(type(s) == "number") and
(type(v) == "string")
)
local r = {s = s, v = v}
return setmetatable(r, _z_p_mt)
end
local _z_pairs = function(...)
local arg = {...}
assert((#arg > 0) and (#arg % 2 == 0))
local ps = {}
for i=1,#arg,2 do
ps[#ps+1] = _z_pair(
assert(tofloat(arg[i])),
chkarg(arg[i+1])
)
end
return ps
end
local _z_insert = function(x, ix, p)
assert(
(type(x) == "table") and
(type(ix) == "number") and
(type(p) == "table")
)
local l = x.list
table.insert(l, ix, p)
for i=ix+1,#l do
x.set[l[i].v] = x.set[l[i].v] + 1
end
x.set[p.v] = ix
end
local _z_remove = function(x, v)
if not x.set[v] then return false end
local l, ix = x.list, x.set[v]
assert(l[ix].v == v)
table.remove(l, ix)
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - 1
end
x.set[v] = nil
return true
end
local _z_remove_range = function(x, i1, i2)
local l = x.list
i2 = i2 or i1
assert(
(i1 > 0) and
(i2 >= i1) and
(i2 <= #l)
)
local ix, n = i1, i2-i1+1
for i=1,n do
x.set[l[ix].v] = nil
table.remove(l, ix)
end
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - n
end
return n
end
local _z_update = function(x, p)
local l = x.list
local found = _z_remove(x, p.v)
local ix = nil
for i=1,#l do
if l[i] > p then
ix = i; break
end
end
if not ix then ix = #l+1 end
_z_insert(x, ix, p)
return found
end
local _z_coherence = function(x)
local l, s = x.list, x.set
local found, n = {}, 0
for val,pos in pairs(s) do
if found[pos] then return false end
found[pos] = true
n = n + 1
if not (l[pos] and (l[pos].v == val)) then
return false
end
end
if #l ~= n then return false end
for i=1, n-1 do
if l[i].s > l[i+1].s then return false end
end
return true
end
local _z_normrange = function(l, i1, i2)
i1, i2 = assert(toint(i1)), assert(toint(i2))
if i1 < 0 then i1 = #l+i1 end
if i2 < 0 then i2 = #l+i2 end
i1, i2 = math.max(i1+1, 1), i2+1
if (i2 < i1) or (i1 > #l) then return nil end
i2 = math.min(i2, #l)
return i1, i2
end
local _zrbs_opts = function(...)
local arg = {...}
if #arg == 0 then return {} end
local ix, opts = 1, {}
while type(arg[ix]) == "string" do
if arg[ix] == "withscores" then
opts.withscores = true
ix = ix + 1
elseif arg[ix] == "limit" then
opts.limit = {
offset = assert(toint(arg[ix+1])),
count = assert(toint(arg[ix+2])),
}
ix = ix + 3
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.withscores = opts.withscores or _o.withscores
if _o.limit then
opts.limit = {
offset = assert(toint(_o.limit.offset or _o.limit[1])),
count = assert(toint(_o.limit.count or _o.limit[2])),
}
end
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.limit then
assert(
(opts.limit.count >= 0) and
(opts.limit.offset >= 0)
)
end
return opts
end
local _z_store_params = function(dest, numkeys, ...)
dest = chkarg(dest)
numkeys = assert(toint(numkeys))
assert(numkeys > 0)
local arg = {...}
assert(#arg >= numkeys)
local ks = {}
for i=1, numkeys do ks[i] = chkarg(arg[i]) end
local ix, opts = numkeys+1,{}
while type(arg[ix]) == "string" do
if arg[ix] == "weights" then
opts.weights = {}
ix = ix + 1
for i=1, numkeys do
opts.weights[i] = assert(toint(arg[ix]))
ix = ix + 1
end
elseif arg[ix] == "aggregate" then
opts.aggregate = assert(chkarg(arg[ix+1]))
ix = ix + 2
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.weights = opts.weights or _o.weights
opts.aggregate = opts.aggregate or _o.aggregate
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.aggregate then
assert(
(opts.aggregate == "sum") or
(opts.aggregate == "min") or
(opts.aggregate == "max")
)
else opts.aggregate = "sum" end
if opts.weights then
assert(#opts.weights == numkeys)
for i=1,#opts.weights do
assert(type(opts.weights[i]) == "number")
end
else
opts.weights = {}
for i=1, numkeys do opts.weights[i] = 1 end
end
opts.keys = ks
opts.dest = dest
return opts
end
local _zrbs_limits = function(x, s1, s2, descending)
local s1_incl, s2_incl = true, true
if s1:sub(1, 1) == "(" then
s1, s1_incl = s1:sub(2, -1), false
end
s1 = assert(tofloat(s1))
if s2:sub(1, 1) == "(" then
s2, s2_incl = s2:sub(2, -1), false
end
s2 = assert(tofloat(s2))
if descending then
s1, s2 = s2, s1
s1_incl, s2_incl = s2_incl, s1_incl
end
if s2 < s1 then return nil end
local l = x.list
local i1, i2
local fst, lst = l[1].s, l[#l].s
if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end
if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end
if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end
if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end
for i=1,#l do
if (i1 and i2) then break end
if (not i1) then
if l[i].s > s1 then i1 = i end
if s1_incl and l[i].s == s1 then i1 = i end
end
if (not i2) then
if l[i].s > s2 then i2 = i-1 end
if (not s2_incl) and l[i].s == s2 then i2 = i-1 end
end
end
assert(i1 and i2)
if descending then
return #l-i2, #l-i1
else
return i1-1, i2-1
end
end
local dbg_zcoherence = function(self, k)
local x = xgetr(self, k, "zset")
return _z_coherence(x)
end
local zadd = function(self, k, ...)
k = chkarg(k)
local ps = _z_pairs(...)
local x = xgetw(self, k, "zset")
local n = 0
for i=1,#ps do
if not _z_update(x, ps[i]) then n = n+1 end
end
return n
end
local zcard = function(self, k)
local x = xgetr(self, k, "zset")
return #x.list
end
local zcount = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return i2 - i1 + 1
end
local zincrby = function(self, k, n, v)
k,v = chkargs(2, k, v)
n = assert(tofloat(n))
local x = xgetw(self, k, "zset")
local p = x.list[x.set[v]]
local s = p and (p.s + n) or n
_z_update(x, _z_pair(s, v))
return s
end
local zinterstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local aggregate
if params.aggregate == "sum" then
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
aggregate = math.min
elseif params.aggregate == "max" then
aggregate = math.max
else error() end
local y = xgetr(self, params.keys[1], "zset")
local p1, p2
for j=1,#y.list do
p1 = _z_pair(y.list[j].s, y.list[j].v)
_z_update(x, p1)
end
for i=2,#params.keys do
y = xgetr(self, params.keys[i], "zset")
local to_remove, to_update = {}, {}
for j=1,#x.list do
p1 = x.list[j]
if y.set[p1.v] then
p2 = _z_pair(
aggregate(
p1.s,
params.weights[i] * y.list[y.set[p1.v]].s
),
p1.v
)
to_update[#to_update+1] = p2
else
to_remove[#to_remove+1] = p1.v
end
end
for j=1,#to_remove do _z_remove(x, to_remove[j]) end
for j=1,#to_update do _z_update(x, to_update[j]) end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
local _zranger = function(descending)
return function(self, k, i1, i2, opts)
k = chkarg(k)
local withscores = false
if type(opts) == "table" then
withscores = opts.withscores
elseif type(opts) == "string" then
assert(opts:lower() == "withscores")
withscores = true
else assert(opts == nil) end
local x = xgetr(self, k, "zset")
local l = x.list
i1, i2 = _z_normrange(l, i1, i2)
if not i1 then return {} end
local inc = 1
if descending then
i1 = #l - i1 + 1
i2 = #l - i2 + 1
inc = -1
end
local r = {}
if withscores then
for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end
else
for i=i1, i2, inc do r[#r+1] = l[i].v end
end
return r
end
end
local zrange = _zranger(false)
local zrevrange = _zranger(true)
local _zrangerbyscore = function(descending)
return function(self, k, s1, s2, ...)
k, s1, s2 = chkargs(3, k, s1, s2)
local opts = _zrbs_opts(...)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, descending)
if not (i1 and i2) then return {} end
if opts.limit then
if opts.limit.count == 0 then return {} end
i1 = i1 + opts.limit.offset
if i1 > i2 then return {} end
i2 = math.min(i2, i1+opts.limit.count-1)
end
if descending then
return zrevrange(self, k, i1, i2, opts)
else
return zrange(self, k, i1, i2, opts)
end
end
end
local zrangebyscore = _zrangerbyscore(false)
local zrevrangebyscore = _zrangerbyscore(true)
local zrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return r-1
else return nil end
end
local zrem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "zset"), 0
for i=1,#arg do
if _z_remove(x, arg[i]) then r = r + 1 end
end
cleanup(self, k)
return r
end
local zremrangebyrank = function(self, k, i1, i2)
k = chkarg(k)
local x = xgetw(self, k, "zset")
i1, i2 = _z_normrange(x.list, i1, i2)
if not i1 then
cleanup(self, k)
return 0
end
local n = _z_remove_range(x, i1, i2)
cleanup(self, k)
return n
end
local zremrangebyscore = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return zremrangebyrank(self, k, i1, i2)
end
local zrevrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return #x.list-r
else return nil end
end
local zscore = function(self, k, v)
local x = xgetr(self, k, "zset")
local p = x.list[x.set[v]]
if p then
return p.s
else return nil end
end
local zunionstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local default_score, aggregate
if params.aggregate == "sum" then
default_score = 0
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
default_score = math.huge
aggregate = math.min
elseif params.aggregate == "max" then
default_score = -math.huge
aggregate = math.max
else error() end
local y, p1, p2
for i=1,#params.keys do
y = xgetr(self, params.keys[i], "zset")
for j=1,#y.list do
p1 = y.list[j]
p2 = _z_pair(
aggregate(
params.weights[i] * p1.s,
x.set[p1.v] and x.list[x.set[p1.v]].s or default_score
),
p1.v
)
_z_update(x, p2)
end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
-- connection
local echo = function(self, v)
return v
end
local ping = function(self)
return true
end
-- server
local flushdb = function(self)
self.data = {}
return true
end
--- Class
local methods = {
-- keys
del = del, -- (...) -> #removed
exists = chkargs_wrap(exists, 1), -- (k) -> exists?
keys = keys, -- (pattern) -> list of keys
["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none]
randomkey = randomkey, -- () -> [k|nil]
rename = chkargs_wrap(rename, 2), -- (k,k2) -> true
renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2
-- strings
append = chkargs_wrap(append, 2), -- (k,v) -> #new
bitcount = bitcount, -- (k,[start,end]) -> n
bitop = bitop, -- ([and|or|xor|not],k,...)
decr = chkargs_wrap(decr, 1), -- (k) -> new
decrby = decrby, -- (k,n) -> new
get = chkargs_wrap(get, 1), -- (k) -> [v|nil]
getbit = getbit, -- (k,offset) -> b
getrange = getrange, -- (k,start,end) -> string
getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil]
incr = chkargs_wrap(incr, 1), -- (k) -> new
incrby = incrby, -- (k,n) -> new
incrbyfloat = incrbyfloat, -- (k,n) -> new
mget = mget, -- (k1,...) -> {v1,...}
mset = mset, -- (k1,v1,...) -> true
msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k)
set = chkargs_wrap(set, 2), -- (k,v) -> true
setbit = setbit, -- (k,offset,b) -> old
setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?)
setrange = setrange, -- (k,offset,val) -> #new
strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0]
-- hashes
hdel = hdel, -- (k,sk1,...) -> #removed
hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists?
hget = chkargs_wrap(hget,2), -- (k,sk) -> v
hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map
hincrby = hincrby, -- (k,sk,n) -> new
hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new
hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys
hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0]
hmget = hmget, -- (k,{sk1,...}) -> {v1,...}
hmset = hmset, -- (k,{sk1=v1,...}) -> true
hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed?
hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?)
hvals = chkargs_wrap(hvals, 1), -- (k) -> values
-- lists
blpop = blpop, -- (k1,...) -> k,v
brpop = brpop, -- (k1,...) -> k,v
brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v
lindex = lindex, -- (k,i) -> v
linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after)
llen = chkargs_wrap(llen, 1), -- (k) -> #list
lpop = chkargs_wrap(lpop, 1), -- (k) -> v
lpush = lpush, -- (k,v1,...) -> #list (after)
lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after)
lrange = lrange, -- (k,start,stop) -> list
lrem = lrem, -- (k,count,v) -> #removed
lset = lset, -- (k,i,v) -> true
ltrim = ltrim, -- (k,start,stop) -> true
rpop = chkargs_wrap(rpop, 1), -- (k) -> v
rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v
rpush = rpush, -- (k,v1,...) -> #list (after)
rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after)
-- sets
sadd = sadd, -- (k,v1,...) -> #added
scard = chkargs_wrap(scard, 1), -- (k) -> [n|0]
sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...)
sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0
sinter = sinter, -- (k1,...) -> set
sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0
sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member?
smembers = chkargs_wrap(smembers, 1), -- (k) -> set
smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1)
spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil]
srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...]
srem = srem, -- (k,v1,...) -> #removed
sunion = sunion, -- (k1,...) -> set
sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0
-- zsets
zadd = zadd, -- (k,score,member,[score,member,...])
zcard = chkargs_wrap(zcard, 1), -- (k) -> n
zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count
zincrby = zincrby, -- (k,score,v) -> score
zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card
zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts
zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank
zrem = zrem, -- (k,v1,...) -> #removed
zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed
zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed
zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts
zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank
zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score
zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card
-- connection
echo = chkargs_wrap(echo, 1), -- (v) -> v
ping = ping, -- () -> true
-- server
flushall = flushdb, -- () -> true
flushdb = flushdb, -- () -> true
-- debug
dbg_zcoherence = dbg_zcoherence,
}
local new = function()
local r = {data = {}}
return setmetatable(r,{__index = methods})
end
return {
new = new,
}
| gpl-3.0 |
Bierbuikje/Mr.Green-MTA-Resources | resources/[admin]/maptools/mm.lua | 3 | 20903 | local maxuploaded_maps = 3
-------------
-- newMap --
-------------
local uploadedfolder = "[maps]\\[uploadedmaps]"
function newMap(map, forumid, mta_name)
local mapname = tostring(map) .. '_newupload'
outputDebugString('newMap ' .. mapname)
refreshResources()
setTimer(refreshResources, 2000, 1)
local mapres = getResourceFromName(map)
if mapres then
if getResourceInfo(mapres, "forumid") then
if getResourceInfo(mapres, "forumid") ~= tostring(forumid) then
return 'This mapname is already in use on the server, only ' .. getResourceInfo(mapres, "mta_name") .. ' can update ' .. map, ''
end
-- else
-- outputDebugString('new map already exists ' .. map)
-- outputConsole('new map already exists ' .. map)
-- return 'This map is already on the server (' .. map .. '), contact a mapmanager if you want to update it', ''
end
else
local mapsInQ = 0
for k, r in ipairs(getResources()) do
if getResourceInfo(r, "forumid") == tostring(forumid) and getResourceInfo(r, "newupload") == "true" then
mapsInQ = mapsInQ + 1
end
end
if mapsInQ >= maxuploaded_maps then
return 'You already have the max amount of maps (' .. maxuploaded_maps .. ') uploaded, wait untill a mapmanager tests your maps before uploading another one', ''
end
end
local res = getResourceFromName(mapname)
if not res then
outputDebugString('loading failed ' .. mapname)
outputConsole('loading failed ' .. mapname)
return 'Could not load ' .. tostring(map), ''
end
local s = getResourceLoadFailureReason(res)
setResourceInfo(res, "newupload", "true")
setResourceInfo(res, "forumid", tostring(forumid))
setResourceInfo(res, "mta_name", mta_name)
setResourceInfo(res, "uploadtick", tostring(getRealTime().timestamp))
if s ~= '' then
if getResourceState(res) == "running" then
stopResource(res)
end
deleteResource(mapname)
outputDebugString(s..': deleting ' .. mapname)
outputConsole(s..': deleting ' .. mapname)
end
return tostring(s), mapres and getResourceInfo(mapres, "forumid") == tostring(forumid) and "Update" or "New"
end
function handlemap(p, c, resname, ...)
if not handlerConnect or not resname then return false end
local mapname = resname .. '_newupload'
local res = getResourceFromName(mapname)
if not res then
return outputChatBox(c..': could not find res ' .. resname, p)
elseif getResourceInfo(res, "newupload") ~= "true" then
return outputChatBox(c..': resource is not a new map ' .. resname, p)
end
if getResourceState(res) == "running" then
-- deleteRes = res
return outputChatBox(c..': can\'t use this while the map is running ' .. resname, p)
end
local mta_name = getResourceInfo(res, "mta_name")
local comment = table.concat({...}, ' ')
local manager = tostring(getAccountName(getPlayerAccount(p)))
local status = (c == "acceptmap" and "Accepted" or "Declined")
if c == "acceptmap" then
if getResourceFromName(resname) then
deleteResource(getResourceFromName(resname))
end
local newRes = copyResource(res, resname, uploadedfolder)
setResourceInfo(newRes, "newupload", "false")
end
deleteResource(mapname)
local query = "INSERT INTO uploaded_maps (resname, uploadername, comment, manager, status) VALUES (?,?,?,?,?)"
local theExec = dbExec ( handlerConnect, query, resname, mta_name, comment, manager, status)
outputChatBox(c..': done ' .. resname, p)
fetchMaps(p)
end
addCommandHandler('acceptmap', handlemap, true)
addCommandHandler('declinemap', handlemap, true)
function checkDeleteMap()
if deleteRes and deleteRes ~= exports.mapmanager:getRunningGamemodeMap() then
deleteResource(getResourceName(deleteRes))
deleteRes = nil
end
end
addEventHandler('onMapStarting', root, checkDeleteMap)
--facilitating map deletion--
deletedMapsPath = "[maps]\\[deletedmaps]"
addEvent('onMapStarting', true)
function connectToDB()
if handlerConnect then return true end
handlerConnect = dbConnect( 'mysql', 'host=' .. get"*gcshop.host" .. ';dbname=' .. get"*gcshop.dbname", get("*gcshop.user"), get("*gcshop.pass"))
if not handlerConnect then
return outputDebugString('maptools: could not connect to the mysql db')
end
moveMapDeletionCache() -- Map deletion entries are stored locally if the mysql database does not work, if it works again move them to mysql
end
addEventHandler('onResourceStart', resourceRoot, connectToDB)
function onNewMapStart()
local map = g_Map
if map == exports.mapmanager:getRunningGamemodeMap() then --if map that was deleted gets replayed before deletion, halt deletion for the next map.
return
end
local name = getResourceInfo(map, "name")
local authr = getResourceInfo(map,"author")
if not authr then authr = "N/A" end
-- First copy resource to "[deletedmaps]" folder, then deleteResource(), because the trash folder is unreliable
local resname = getResourceName(map)
-- set
setResourceInfo(map,"gamemodes","race_deleted")
setResourceInfo(map,"deleted","true")
setResourceInfo(map,"deleteReason",g_Reason)
setResourceInfo(map,"deletedBy",g_AccName)
setResourceInfo(map,"deleteTimeStamp",tostring(getRealTime().timestamp))
-- Check if copied deleted resource exists, if so then delete first.
if getResourceFromName( resname.."_deleted" ) then
deleteResource( resname.."_deleted" )
end
copyResource(map,resname.."_deleted",deletedMapsPath)
local delete = deleteResource(resname)
if not delete then
if isElement(g_P) then outputChatBox("Error: Map cannot be deleted.", g_P) end
canUseCommand = true
g_Map = nil
g_P = nil
g_Reason = nil
g_AccName = nil
removeEventHandler('onMapStarting', root, onNewMapStart)
return
end
if isElement(g_P) then
outputChatBox("Map deleted: "..name, g_P)
end
addMapDeletionRecord(name,authr,g_Reason,g_AccName,resname)
refreshResources()
canUseCommand = true
g_Map = nil
g_P = nil
g_Reason = nil
g_AccName = nil
removeEventHandler('onMapStarting', root, onNewMapStart)
-- fetchMaps()
end
canUseCommand = true
g_Map = nil
g_P = nil
g_Reason = nil
g_AccName = nil
addCommandHandler('deletemap',
function(p,_,...)
if not (hasObjectPermissionTo(p, "function.banPlayer", false)) then return end
if not arg then outputChatBox("Error: Give a reason for map deletion. ( /deletemap full reason )", p) return end
local fullReason = table.concat(arg," ")
if not fullReason or #fullReason < 1 then outputChatBox("Error: Give a reason for map deletion. ( /deletemap full reason )", p) return end
--get current map running, copy it over as a backup and delete it from map list via refresh.
if not canUseCommand then outputChatBox("Error: Can't use command. An admin has already deleted this map.", p) return end
local map = exports.mapmanager:getRunningGamemodeMap()
if not map then outputChatBox("Error: No map.", p) return end
local adminAccName = getAccountName(getPlayerAccount(p))
if not adminAccName then outputChatBox("Error: Unable to retrieve account name, contact a developer if this keeps happening.", p) return end
outputChatBox("Deleting current map at the start of the next map! (reason: "..fullReason..") by "..getPlayerName(p), root, 255, 0, 0)
g_Map = map
g_P = p
g_Reason = fullReason
g_AccName = adminAccName
addEventHandler('onMapStarting', root, onNewMapStart)
canUseCommand = false
end
)
function addMapDeletionRecord(mapname,author,reason,adminName,resname)
connectToDB() -- Retry db connection
if handlerConnect then -- if there is db connection, else save in local db file
moveMapDeletionCache()
local query = "INSERT INTO uploaded_maps (mapname, uploadername, comment, manager, resname, status) VALUES (?,?,?,?,?,'Deleted')"
dbExec ( handlerConnect, query,tostring(mapname),tostring(author),tostring(reason),tostring(adminName),tostring(resname) )
else -- save to local db
local theXML = xmlLoadFile("mapdeletioncache.xml")
if not theXML then
theXML = xmlCreateFile("mapdeletioncache.xml","entries")
end
if not theXML then return false end
local child = xmlCreateChild(theXML,"map")
xmlNodeSetAttribute(child,"name",tostring(mapname))
xmlNodeSetAttribute(child,"author",tostring(author))
xmlNodeSetAttribute(child,"reason",tostring(reason))
xmlNodeSetAttribute(child,"admin_name",tostring(adminName))
xmlNodeSetAttribute(child,"resname",tostring(resname))
xmlSaveFile(theXML)
xmlUnloadFile(theXML)
end
end
function moveMapDeletionCache() -- Moves from cache xml to mysql db
if not handlerConnect then return false end
local theXML = xmlLoadFile("mapdeletioncache.xml")
if not theXML then return end
local children = xmlNodeGetChildren(theXML)
if not children or (#children < 1 )then xmlUnloadFile(theXML) return false end
for i,child in ipairs(children) do
local mapname = xmlNodeGetAttribute(child,"name")
local author = xmlNodeGetAttribute(child,"author")
local reason = xmlNodeGetAttribute(child,"reason")
local adminName = xmlNodeGetAttribute(child,"admin_name")
local resname = xmlNodeGetAttribute(child,"resname")
local query = "INSERT INTO uploaded_maps (mapname, uploadername, comment, manager, resname, status) VALUES (?,?,?,?,?,'Deleted')"
local theExec = dbExec ( handlerConnect, query,tostring(mapname),tostring(author),tostring(reason),tostring(adminName),tostring(resname) )
if theExec then
xmlDestroyNode(child)
end
xmlSaveFile(theXML)
xmlUnloadFile(theXML)
end
end
--Get Maplist and deletedMap list for client gui
function fetchMaps(player)
refreshResources()
local mapList = {}
local deletedMapList = {}
local uploadedMapList = {}
-- Get race and uploaded maps
local raceMps = exports.mapmanager:getMapsCompatibleWithGamemode(getResourceFromName("race"))
local mapRatings = exports.mapratings:getTableOfRatedMaps()
if not raceMps or not mapRatings then return false end
for _,map in ipairs(raceMps) do
local name = getResourceInfo(map,"name")
local author = getResourceInfo(map,"author")
local resname = getResourceName(map)
if not name then name = resname end
if not author then author = "N/A" end
local t = {name = name, author = author, resname = resname, likes = "-", dislikes = "-"}
local rating = mapRatings[resname]
if rating then
t.likes = rating.likes
t.dislikes = rating.dislikes
end
table.insert(mapList,t)
end
-- Deleted and uploaded maps
local allRes = getResources()
if not allRes then return false end
for _,map in ipairs(allRes) do
if getResourceInfo(map,"gamemodes") == "race_deleted" then
local name = getResourceInfo(map,"name")
local author = getResourceInfo(map,"author")
local deletedBy = getResourceInfo(map,"deletedBy")
local deleteTimeStamp = getResourceInfo(map,"deleteTimeStamp")
local deleteReason = getResourceInfo(map,"deleteReason")
local resname = getResourceName(map)
local t = {name = name, author = author, resname = resname, deletedBy = deletedBy, deleteTimeStamp = deleteTimeStamp, deleteReason = deleteReason}
table.insert(deletedMapList,t)
elseif getResourceInfo(map,"newupload") == "true" then
local name = getResourceInfo(map,"name")
local author = getResourceInfo(map,"author")
local uploadtick = tonumber(getResourceInfo(map,"uploadtick"))
local resname = getResourceName(map)
local new = getResourceFromName(string.gsub(resname, "_newupload", "")) and "Update" or "New"
local t = {name = name, author = author, resname = resname, uploadtick = uploadtick, new = new}
table.insert(uploadedMapList,t)
end
end
table.sort(uploadedMapList,function(a,b) return tostring(a.uploadtick) > tostring(b.uploadtick) end)
table.sort(deletedMapList,function(a,b) return tostring(a.deleteTimeStamp) > tostring(b.deleteTimeStamp) end)
table.sort(mapList,function(a,b) return tostring(a.name) < tostring(b.name) end)
triggerClientEvent(player,"mm_receiveMapLists",resourceRoot,uploadedMapList,deletedMapList,mapList,hasObjectPermissionTo(player,"command.deletemap",false))
end
addCommandHandler("managemaps",fetchMaps)
addCommandHandler("mm",fetchMaps)
addCommandHandler("deletedmaps",fetchMaps)
addCommandHandler("maps",fetchMaps)
-- Editing resources --
function editmap(player, cmd, mapname)
local map = mapname and getResourceFromName(mapname) or false
if not map then return outputChatBox("Map not found ", player) end
local accName = getAccountName ( getPlayerAccount ( player ) )
if not exports.mapmanager:isMap(map) and not isObjectInACLGroup ("user."..accName, aclGetGroup ( "ServerManager" )) then
outputChatBox("This resource does not exist or can not be edited", player)
return
end
local meta = xmlLoadFile(':' .. mapname .. '/meta.xml')
if not meta then return outputChatBox("Could not open meta " .. mapname, player) end
local files = {{file="meta.xml",type="meta"}}
for k, node in ipairs(xmlNodeGetChildren(meta)) do
if xmlNodeGetAttribute(node, "src") and (xmlNodeGetName(node) == "map" or xmlNodeGetName(node) == "script") then
table.insert(files, {file=xmlNodeGetAttribute(node, "src"), type=xmlNodeGetName(node)})
end
end
triggerClientEvent(player, "editMapFilesList", resourceRoot, mapname, files)
xmlUnloadFile(meta)
end
addCommandHandler("editmap", editmap, true)
function editfile(player, cmd, mapname, src)
local map = mapname and getResourceFromName(mapname) or false
if not map then return outputChatBox("Map not found ", player) end
local accName = getAccountName ( getPlayerAccount ( player ) )
if not exports.mapmanager:isMap(map) and not isObjectInACLGroup ("user."..accName, aclGetGroup ( "ServerManager" )) then
outputChatBox("This resource does not exist or can not be edited", player)
return
end
local file = fileOpen(':' .. mapname .. '/' .. src)
if not file then return outputChatBox("Could not open :" .. mapname .. '/' ..src, player) end
local text = fileRead(file, fileGetSize(file))
fileClose(file)
triggerClientEvent(player, "editFileText", resourceRoot, mapname, src, text)
end
addCommandHandler("editfile", editfile, true)
function savefile(mapname, src, text)
local player = client
local map = mapname and getResourceFromName(mapname) or false
if not map then return outputChatBox("Map not found ", player) end
local accName = getAccountName ( getPlayerAccount ( player ) )
if not (hasObjectPermissionTo(player, "command.editfile", false)) then
outputChatBox("You have no access to this", player)
return
elseif not exports.mapmanager:isMap(map) and not isObjectInACLGroup ("user."..accName, aclGetGroup ( "ServerManager" )) then
outputChatBox("This resource does not exist or can not be edited", player)
return
end
-- create a backup
local backup = fileCopy(':' .. mapname .. '/' .. src, ':' .. mapname .. '/' .. src .. '.' .. getRealTime().timestamp .. '.bak', true)
if not backup then return outputChatBox("Could not create backup. Changes aren't saved.", player) end
local deletefile = fileDelete(':' .. mapname .. '/' .. src)
if not deletefile then return outputChatBox("Could not overwrite:" .. mapname .. '/' ..src, player) end
local file = fileCreate(':' .. mapname .. '/' .. src)
if not file then return outputChatBox("Could not overwrite:" .. mapname .. '/' ..src, player) end
fileWrite(file, text)
fileClose(file)
outputChatBox("Saved file " .. ':' .. mapname .. '/' .. src .. " and made a backup", player)
end
addEvent("savefile", true)
addEventHandler("savefile", resourceRoot, savefile)
-- Clientside events for commands
addEvent("cmm_restoreMap",true)
function restoreMap(map)
if hasObjectPermissionTo(client,"command.deletemap",false) then
local theRes = getResourceFromName(map.resname)
if not theRes then outputChatBox("Error: map can not be restored (can't find map resource)",client,255,0,0) return end
local properName = string.gsub(map.resname,"_deleted","")
local raceMode = getResourceInfo(theRes,"racemode")
if not raceMode then raceMode = "[maps]/[dd]" else raceMode = "[maps]/["..raceMode.."]" end
local theCopy
local sn = string.lower(getServerName())
if string.find(sn,"mix") then -- looks if mix or race server
theCopy = copyResource(theRes,properName,raceMode)
else
theCopy = copyResource(theRes,properName,"[maps]")
end
if not theCopy then outputChatBox("Can't copy map, resource may already exist",client,255,0,0) return end
deleteResource(theRes)
setResourceInfo(theCopy,"gamemodes","race")
setResourceInfo(theCopy,"deleted","false")
if handlerConnect then -- if there is db connection, else save in local db file
local query = "INSERT INTO uploaded_maps (mapname, uploadername, manager, resname, status) VALUES (?,?,?,?,'Restored')"
dbExec ( handlerConnect, query,getResourceInfo(theCopy, "name") or properName,getResourceInfo(theCopy,"author") or "N/A",tostring(getAccountName(getPlayerAccount(client))),properName)
end
outputChatBox("Map '".. getResourceName(theCopy) .."' restored!",client)
refreshResources()
fetchMaps(client)
end
end
addEventHandler("cmm_restoreMap",root,restoreMap)
addEvent("cmm_deleteMap",true)
function deleteMapFromGUI(map,reason) -- Admin deleted map via the gui
if hasObjectPermissionTo(client,"command.deletemap",false) then
if map == exports.mapmanager:getRunningGamemodeMap() then
outputChatBox("The map you are trying to delete is currently playing, use /deletemap instead!",client,255,0,0)
return
end
local theRes = getResourceFromName(map.resname)
if not theRes then
outputChatBox("error: Can't find map resource!",client,255,0,0)
end
local adminAccName = getAccountName(getPlayerAccount(client))
if not adminAccName then outputChatBox("Error: Unable to retrieve account name, contact a developer if this keeps happening.", client,255,0,0) return end
setResourceInfo(theRes,"gamemodes","race_deleted")
setResourceInfo(theRes,"deleted","true")
setResourceInfo(theRes,"deleteReason",reason)
setResourceInfo(theRes,"deletedBy",adminAccName)
setResourceInfo(theRes,"deleteTimeStamp",tostring(getRealTime().timestamp))
-- Check if copied deleted resource exists, if so then delete first.
if getResourceFromName( map.resname.."_deleted" ) then
deleteResource( map.resname.."_deleted" )
end
copyResource(theRes,map.resname.."_deleted",deletedMapsPath)
local delete = deleteResource(map.resname)
if not delete and isElement(client) then
outputChatBox("Error: Map cannot be deleted.",client,255,0,0)
return
end
if isElement(client) then
outputChatBox("Map deleted: "..tostring(map.name),client)
end
addMapDeletionRecord(map.name,map.author,reason,adminAccName,map.resname)
refreshResources()
fetchMaps(client)
end
end
addEventHandler("cmm_deleteMap",root,deleteMapFromGUI)
addEvent("nextmap",true)
function nextMapFromGUI(map) -- Admin next upload map via the gui
if hasObjectPermissionTo(client,"command.nextmap",false) then
executeCommandHandler("nextmap", client, map.."_newupload")
end
end
addEventHandler("nextmap",root,nextMapFromGUI)
addEvent("acceptmap",true)
function acceptMapFromGUI(map, comment) -- Admin accept upload map via the gui
if hasObjectPermissionTo(client,"command.acceptmap",false) then
executeCommandHandler("acceptmap", client, map .. ' ' .. (comment or ''))
end
end
addEventHandler("acceptmap",root,acceptMapFromGUI)
addEvent("declinemap",true)
function declineMapFromGUI(map, comment) -- Admin decline upload map via the gui
if hasObjectPermissionTo(client,"command.declinemap",false) then
executeCommandHandler("declinemap", client, map .. ' ' .. (comment or ''))
end
end
addEventHandler("declinemap",root,declineMapFromGUI)
addEvent("editmap",true)
function editMapFromGUI(map) -- Admin editing map via the gui
if hasObjectPermissionTo(client,"command.editmap",false) then
executeCommandHandler("editmap", client, map)
end
end
addEventHandler("editmap",root,editMapFromGUI)
addEvent("editfile",true)
function editFileFromGUI(map,src) -- Admin editing file via the gui
if hasObjectPermissionTo(client,"command.editfile",false) then
executeCommandHandler("editfile", client, map..' '..src)
end
end
addEventHandler("editfile",root,editFileFromGUI)
| mit |
ckaotik/ckaosCraft | libs/AceAddon-3.0/AceAddon-3.0.lua | 66 | 25788 | --- **AceAddon-3.0** provides a template for creating addon objects.
-- It'll provide you with a set of callback functions that allow you to simplify the loading
-- process of your addon.\\
-- Callbacks provided are:\\
-- * **OnInitialize**, which is called directly after the addon is fully loaded.
-- * **OnEnable** which gets called during the PLAYER_LOGIN event, when most of the data provided by the game is already present.
-- * **OnDisable**, which is only called when your addon is manually being disabled.
-- @usage
-- -- A small (but complete) addon, that doesn't do anything,
-- -- but shows usage of the callbacks.
-- local MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
--
-- function MyAddon:OnInitialize()
-- -- do init tasks here, like loading the Saved Variables,
-- -- or setting up slash commands.
-- end
--
-- function MyAddon:OnEnable()
-- -- Do more initialization here, that really enables the use of your addon.
-- -- Register Events, Hook functions, Create Frames, Get information from
-- -- the game that wasn't available in OnInitialize
-- end
--
-- function MyAddon:OnDisable()
-- -- Unhook, Unregister Events, Hide frames that you created.
-- -- You would probably only use an OnDisable if you want to
-- -- build a "standby" mode, or be able to toggle modules on/off.
-- end
-- @class file
-- @name AceAddon-3.0.lua
-- @release $Id: AceAddon-3.0.lua 1084 2013-04-27 20:14:11Z nevcairiel $
local MAJOR, MINOR = "AceAddon-3.0", 12
local AceAddon, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceAddon then return end -- No Upgrade needed.
AceAddon.frame = AceAddon.frame or CreateFrame("Frame", "AceAddon30Frame") -- Our very own frame
AceAddon.addons = AceAddon.addons or {} -- addons in general
AceAddon.statuses = AceAddon.statuses or {} -- statuses of addon.
AceAddon.initializequeue = AceAddon.initializequeue or {} -- addons that are new and not initialized
AceAddon.enablequeue = AceAddon.enablequeue or {} -- addons that are initialized and waiting to be enabled
AceAddon.embeds = AceAddon.embeds or setmetatable({}, {__index = function(tbl, key) tbl[key] = {} return tbl[key] end }) -- contains a list of libraries embedded in an addon
-- Lua APIs
local tinsert, tconcat, tremove = table.insert, table.concat, table.remove
local fmt, tostring = string.format, tostring
local select, pairs, next, type, unpack = select, pairs, next, type, unpack
local loadstring, assert, error = loadstring, assert, error
local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: LibStub, IsLoggedIn, geterrorhandler
--[[
xpcall safecall implementation
]]
local xpcall = xpcall
local function errorhandler(err)
return geterrorhandler()(err)
end
local function CreateDispatcher(argCount)
local code = [[
local xpcall, eh = ...
local method, ARGS
local function call() return method(ARGS) end
local function dispatch(func, ...)
method = func
if not method then return end
ARGS = ...
return xpcall(call, eh)
end
return dispatch
]]
local ARGS = {}
for i = 1, argCount do ARGS[i] = "arg"..i end
code = code:gsub("ARGS", tconcat(ARGS, ", "))
return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(xpcall, errorhandler)
end
local Dispatchers = setmetatable({}, {__index=function(self, argCount)
local dispatcher = CreateDispatcher(argCount)
rawset(self, argCount, dispatcher)
return dispatcher
end})
Dispatchers[0] = function(func)
return xpcall(func, errorhandler)
end
local function safecall(func, ...)
-- we check to see if the func is passed is actually a function here and don't error when it isn't
-- this safecall is used for optional functions like OnInitialize OnEnable etc. When they are not
-- present execution should continue without hinderance
if type(func) == "function" then
return Dispatchers[select('#', ...)](func, ...)
end
end
-- local functions that will be implemented further down
local Enable, Disable, EnableModule, DisableModule, Embed, NewModule, GetModule, GetName, SetDefaultModuleState, SetDefaultModuleLibraries, SetEnabledState, SetDefaultModulePrototype
-- used in the addon metatable
local function addontostring( self ) return self.name end
-- Check if the addon is queued for initialization
local function queuedForInitialization(addon)
for i = 1, #AceAddon.initializequeue do
if AceAddon.initializequeue[i] == addon then
return true
end
end
return false
end
--- Create a new AceAddon-3.0 addon.
-- Any libraries you specified will be embeded, and the addon will be scheduled for
-- its OnInitialize and OnEnable callbacks.
-- The final addon object, with all libraries embeded, will be returned.
-- @paramsig [object ,]name[, lib, ...]
-- @param object Table to use as a base for the addon (optional)
-- @param name Name of the addon object to create
-- @param lib List of libraries to embed into the addon
-- @usage
-- -- Create a simple addon object
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceEvent-3.0")
--
-- -- Create a Addon object based on the table of a frame
-- local MyFrame = CreateFrame("Frame")
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon(MyFrame, "MyAddon", "AceEvent-3.0")
function AceAddon:NewAddon(objectorname, ...)
local object,name
local i=1
if type(objectorname)=="table" then
object=objectorname
name=...
i=2
else
name=objectorname
end
if type(name)~="string" then
error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2)
end
if self.addons[name] then
error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - Addon '%s' already exists."):format(name), 2)
end
object = object or {}
object.name = name
local addonmeta = {}
local oldmeta = getmetatable(object)
if oldmeta then
for k, v in pairs(oldmeta) do addonmeta[k] = v end
end
addonmeta.__tostring = addontostring
setmetatable( object, addonmeta )
self.addons[name] = object
object.modules = {}
object.orderedModules = {}
object.defaultModuleLibraries = {}
Embed( object ) -- embed NewModule, GetModule methods
self:EmbedLibraries(object, select(i,...))
-- add to queue of addons to be initialized upon ADDON_LOADED
tinsert(self.initializequeue, object)
return object
end
--- Get the addon object by its name from the internal AceAddon registry.
-- Throws an error if the addon object cannot be found (except if silent is set).
-- @param name unique name of the addon object
-- @param silent if true, the addon is optional, silently return nil if its not found
-- @usage
-- -- Get the Addon
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
function AceAddon:GetAddon(name, silent)
if not silent and not self.addons[name] then
error(("Usage: GetAddon(name): 'name' - Cannot find an AceAddon '%s'."):format(tostring(name)), 2)
end
return self.addons[name]
end
-- - Embed a list of libraries into the specified addon.
-- This function will try to embed all of the listed libraries into the addon
-- and error if a single one fails.
--
-- **Note:** This function is for internal use by :NewAddon/:NewModule
-- @paramsig addon, [lib, ...]
-- @param addon addon object to embed the libs in
-- @param lib List of libraries to embed into the addon
function AceAddon:EmbedLibraries(addon, ...)
for i=1,select("#", ... ) do
local libname = select(i, ...)
self:EmbedLibrary(addon, libname, false, 4)
end
end
-- - Embed a library into the addon object.
-- This function will check if the specified library is registered with LibStub
-- and if it has a :Embed function to call. It'll error if any of those conditions
-- fails.
--
-- **Note:** This function is for internal use by :EmbedLibraries
-- @paramsig addon, libname[, silent[, offset]]
-- @param addon addon object to embed the library in
-- @param libname name of the library to embed
-- @param silent marks an embed to fail silently if the library doesn't exist (optional)
-- @param offset will push the error messages back to said offset, defaults to 2 (optional)
function AceAddon:EmbedLibrary(addon, libname, silent, offset)
local lib = LibStub:GetLibrary(libname, true)
if not lib and not silent then
error(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Cannot find a library instance of %q."):format(tostring(libname)), offset or 2)
elseif lib and type(lib.Embed) == "function" then
lib:Embed(addon)
tinsert(self.embeds[addon], libname)
return true
elseif lib then
error(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Library '%s' is not Embed capable"):format(libname), offset or 2)
end
end
--- Return the specified module from an addon object.
-- Throws an error if the addon object cannot be found (except if silent is set)
-- @name //addon//:GetModule
-- @paramsig name[, silent]
-- @param name unique name of the module
-- @param silent if true, the module is optional, silently return nil if its not found (optional)
-- @usage
-- -- Get the Addon
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- -- Get the Module
-- MyModule = MyAddon:GetModule("MyModule")
function GetModule(self, name, silent)
if not self.modules[name] and not silent then
error(("Usage: GetModule(name, silent): 'name' - Cannot find module '%s'."):format(tostring(name)), 2)
end
return self.modules[name]
end
local function IsModuleTrue(self) return true end
--- Create a new module for the addon.
-- The new module can have its own embeded libraries and/or use a module prototype to be mixed into the module.\\
-- A module has the same functionality as a real addon, it can have modules of its own, and has the same API as
-- an addon object.
-- @name //addon//:NewModule
-- @paramsig name[, prototype|lib[, lib, ...]]
-- @param name unique name of the module
-- @param prototype object to derive this module from, methods and values from this table will be mixed into the module (optional)
-- @param lib List of libraries to embed into the addon
-- @usage
-- -- Create a module with some embeded libraries
-- MyModule = MyAddon:NewModule("MyModule", "AceEvent-3.0", "AceHook-3.0")
--
-- -- Create a module with a prototype
-- local prototype = { OnEnable = function(self) print("OnEnable called!") end }
-- MyModule = MyAddon:NewModule("MyModule", prototype, "AceEvent-3.0", "AceHook-3.0")
function NewModule(self, name, prototype, ...)
if type(name) ~= "string" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2) end
if type(prototype) ~= "string" and type(prototype) ~= "table" and type(prototype) ~= "nil" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'prototype' - table (prototype), string (lib) or nil expected got '%s'."):format(type(prototype)), 2) end
if self.modules[name] then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - Module '%s' already exists."):format(name), 2) end
-- modules are basically addons. We treat them as such. They will be added to the initializequeue properly as well.
-- NewModule can only be called after the parent addon is present thus the modules will be initialized after their parent is.
local module = AceAddon:NewAddon(fmt("%s_%s", self.name or tostring(self), name))
module.IsModule = IsModuleTrue
module:SetEnabledState(self.defaultModuleState)
module.moduleName = name
if type(prototype) == "string" then
AceAddon:EmbedLibraries(module, prototype, ...)
else
AceAddon:EmbedLibraries(module, ...)
end
AceAddon:EmbedLibraries(module, unpack(self.defaultModuleLibraries))
if not prototype or type(prototype) == "string" then
prototype = self.defaultModulePrototype or nil
end
if type(prototype) == "table" then
local mt = getmetatable(module)
mt.__index = prototype
setmetatable(module, mt) -- More of a Base class type feel.
end
safecall(self.OnModuleCreated, self, module) -- Was in Ace2 and I think it could be a cool thing to have handy.
self.modules[name] = module
tinsert(self.orderedModules, module)
return module
end
--- Returns the real name of the addon or module, without any prefix.
-- @name //addon//:GetName
-- @paramsig
-- @usage
-- print(MyAddon:GetName())
-- -- prints "MyAddon"
function GetName(self)
return self.moduleName or self.name
end
--- Enables the Addon, if possible, return true or false depending on success.
-- This internally calls AceAddon:EnableAddon(), thus dispatching a OnEnable callback
-- and enabling all modules of the addon (unless explicitly disabled).\\
-- :Enable() also sets the internal `enableState` variable to true
-- @name //addon//:Enable
-- @paramsig
-- @usage
-- -- Enable MyModule
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Enable()
function Enable(self)
self:SetEnabledState(true)
-- nevcairiel 2013-04-27: don't enable an addon/module if its queued for init still
-- it'll be enabled after the init process
if not queuedForInitialization(self) then
return AceAddon:EnableAddon(self)
end
end
--- Disables the Addon, if possible, return true or false depending on success.
-- This internally calls AceAddon:DisableAddon(), thus dispatching a OnDisable callback
-- and disabling all modules of the addon.\\
-- :Disable() also sets the internal `enableState` variable to false
-- @name //addon//:Disable
-- @paramsig
-- @usage
-- -- Disable MyAddon
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyAddon:Disable()
function Disable(self)
self:SetEnabledState(false)
return AceAddon:DisableAddon(self)
end
--- Enables the Module, if possible, return true or false depending on success.
-- Short-hand function that retrieves the module via `:GetModule` and calls `:Enable` on the module object.
-- @name //addon//:EnableModule
-- @paramsig name
-- @usage
-- -- Enable MyModule using :GetModule
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Enable()
--
-- -- Enable MyModule using the short-hand
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyAddon:EnableModule("MyModule")
function EnableModule(self, name)
local module = self:GetModule( name )
return module:Enable()
end
--- Disables the Module, if possible, return true or false depending on success.
-- Short-hand function that retrieves the module via `:GetModule` and calls `:Disable` on the module object.
-- @name //addon//:DisableModule
-- @paramsig name
-- @usage
-- -- Disable MyModule using :GetModule
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Disable()
--
-- -- Disable MyModule using the short-hand
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyAddon:DisableModule("MyModule")
function DisableModule(self, name)
local module = self:GetModule( name )
return module:Disable()
end
--- Set the default libraries to be mixed into all modules created by this object.
-- Note that you can only change the default module libraries before any module is created.
-- @name //addon//:SetDefaultModuleLibraries
-- @paramsig lib[, lib, ...]
-- @param lib List of libraries to embed into the addon
-- @usage
-- -- Create the addon object
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
-- -- Configure default libraries for modules (all modules need AceEvent-3.0)
-- MyAddon:SetDefaultModuleLibraries("AceEvent-3.0")
-- -- Create a module
-- MyModule = MyAddon:NewModule("MyModule")
function SetDefaultModuleLibraries(self, ...)
if next(self.modules) then
error("Usage: SetDefaultModuleLibraries(...): cannot change the module defaults after a module has been registered.", 2)
end
self.defaultModuleLibraries = {...}
end
--- Set the default state in which new modules are being created.
-- Note that you can only change the default state before any module is created.
-- @name //addon//:SetDefaultModuleState
-- @paramsig state
-- @param state Default state for new modules, true for enabled, false for disabled
-- @usage
-- -- Create the addon object
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
-- -- Set the default state to "disabled"
-- MyAddon:SetDefaultModuleState(false)
-- -- Create a module and explicilty enable it
-- MyModule = MyAddon:NewModule("MyModule")
-- MyModule:Enable()
function SetDefaultModuleState(self, state)
if next(self.modules) then
error("Usage: SetDefaultModuleState(state): cannot change the module defaults after a module has been registered.", 2)
end
self.defaultModuleState = state
end
--- Set the default prototype to use for new modules on creation.
-- Note that you can only change the default prototype before any module is created.
-- @name //addon//:SetDefaultModulePrototype
-- @paramsig prototype
-- @param prototype Default prototype for the new modules (table)
-- @usage
-- -- Define a prototype
-- local prototype = { OnEnable = function(self) print("OnEnable called!") end }
-- -- Set the default prototype
-- MyAddon:SetDefaultModulePrototype(prototype)
-- -- Create a module and explicitly Enable it
-- MyModule = MyAddon:NewModule("MyModule")
-- MyModule:Enable()
-- -- should print "OnEnable called!" now
-- @see NewModule
function SetDefaultModulePrototype(self, prototype)
if next(self.modules) then
error("Usage: SetDefaultModulePrototype(prototype): cannot change the module defaults after a module has been registered.", 2)
end
if type(prototype) ~= "table" then
error(("Usage: SetDefaultModulePrototype(prototype): 'prototype' - table expected got '%s'."):format(type(prototype)), 2)
end
self.defaultModulePrototype = prototype
end
--- Set the state of an addon or module
-- This should only be called before any enabling actually happend, e.g. in/before OnInitialize.
-- @name //addon//:SetEnabledState
-- @paramsig state
-- @param state the state of an addon or module (enabled=true, disabled=false)
function SetEnabledState(self, state)
self.enabledState = state
end
--- Return an iterator of all modules associated to the addon.
-- @name //addon//:IterateModules
-- @paramsig
-- @usage
-- -- Enable all modules
-- for name, module in MyAddon:IterateModules() do
-- module:Enable()
-- end
local function IterateModules(self) return pairs(self.modules) end
-- Returns an iterator of all embeds in the addon
-- @name //addon//:IterateEmbeds
-- @paramsig
local function IterateEmbeds(self) return pairs(AceAddon.embeds[self]) end
--- Query the enabledState of an addon.
-- @name //addon//:IsEnabled
-- @paramsig
-- @usage
-- if MyAddon:IsEnabled() then
-- MyAddon:Disable()
-- end
local function IsEnabled(self) return self.enabledState end
local mixins = {
NewModule = NewModule,
GetModule = GetModule,
Enable = Enable,
Disable = Disable,
EnableModule = EnableModule,
DisableModule = DisableModule,
IsEnabled = IsEnabled,
SetDefaultModuleLibraries = SetDefaultModuleLibraries,
SetDefaultModuleState = SetDefaultModuleState,
SetDefaultModulePrototype = SetDefaultModulePrototype,
SetEnabledState = SetEnabledState,
IterateModules = IterateModules,
IterateEmbeds = IterateEmbeds,
GetName = GetName,
}
local function IsModule(self) return false end
local pmixins = {
defaultModuleState = true,
enabledState = true,
IsModule = IsModule,
}
-- Embed( target )
-- target (object) - target object to embed aceaddon in
--
-- this is a local function specifically since it's meant to be only called internally
function Embed(target, skipPMixins)
for k, v in pairs(mixins) do
target[k] = v
end
if not skipPMixins then
for k, v in pairs(pmixins) do
target[k] = target[k] or v
end
end
end
-- - Initialize the addon after creation.
-- This function is only used internally during the ADDON_LOADED event
-- It will call the **OnInitialize** function on the addon object (if present),
-- and the **OnEmbedInitialize** function on all embeded libraries.
--
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
-- @param addon addon object to intialize
function AceAddon:InitializeAddon(addon)
safecall(addon.OnInitialize, addon)
local embeds = self.embeds[addon]
for i = 1, #embeds do
local lib = LibStub:GetLibrary(embeds[i], true)
if lib then safecall(lib.OnEmbedInitialize, lib, addon) end
end
-- we don't call InitializeAddon on modules specifically, this is handled
-- from the event handler and only done _once_
end
-- - Enable the addon after creation.
-- Note: This function is only used internally during the PLAYER_LOGIN event, or during ADDON_LOADED,
-- if IsLoggedIn() already returns true at that point, e.g. for LoD Addons.
-- It will call the **OnEnable** function on the addon object (if present),
-- and the **OnEmbedEnable** function on all embeded libraries.\\
-- This function does not toggle the enable state of the addon itself, and will return early if the addon is disabled.
--
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
-- Use :Enable on the addon itself instead.
-- @param addon addon object to enable
function AceAddon:EnableAddon(addon)
if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end
if self.statuses[addon.name] or not addon.enabledState then return false end
-- set the statuses first, before calling the OnEnable. this allows for Disabling of the addon in OnEnable.
self.statuses[addon.name] = true
safecall(addon.OnEnable, addon)
-- make sure we're still enabled before continueing
if self.statuses[addon.name] then
local embeds = self.embeds[addon]
for i = 1, #embeds do
local lib = LibStub:GetLibrary(embeds[i], true)
if lib then safecall(lib.OnEmbedEnable, lib, addon) end
end
-- enable possible modules.
local modules = addon.orderedModules
for i = 1, #modules do
self:EnableAddon(modules[i])
end
end
return self.statuses[addon.name] -- return true if we're disabled
end
-- - Disable the addon
-- Note: This function is only used internally.
-- It will call the **OnDisable** function on the addon object (if present),
-- and the **OnEmbedDisable** function on all embeded libraries.\\
-- This function does not toggle the enable state of the addon itself, and will return early if the addon is still enabled.
--
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
-- Use :Disable on the addon itself instead.
-- @param addon addon object to enable
function AceAddon:DisableAddon(addon)
if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end
if not self.statuses[addon.name] then return false end
-- set statuses first before calling OnDisable, this allows for aborting the disable in OnDisable.
self.statuses[addon.name] = false
safecall( addon.OnDisable, addon )
-- make sure we're still disabling...
if not self.statuses[addon.name] then
local embeds = self.embeds[addon]
for i = 1, #embeds do
local lib = LibStub:GetLibrary(embeds[i], true)
if lib then safecall(lib.OnEmbedDisable, lib, addon) end
end
-- disable possible modules.
local modules = addon.orderedModules
for i = 1, #modules do
self:DisableAddon(modules[i])
end
end
return not self.statuses[addon.name] -- return true if we're disabled
end
--- Get an iterator over all registered addons.
-- @usage
-- -- Print a list of all installed AceAddon's
-- for name, addon in AceAddon:IterateAddons() do
-- print("Addon: " .. name)
-- end
function AceAddon:IterateAddons() return pairs(self.addons) end
--- Get an iterator over the internal status registry.
-- @usage
-- -- Print a list of all enabled addons
-- for name, status in AceAddon:IterateAddonStatus() do
-- if status then
-- print("EnabledAddon: " .. name)
-- end
-- end
function AceAddon:IterateAddonStatus() return pairs(self.statuses) end
-- Following Iterators are deprecated, and their addon specific versions should be used
-- e.g. addon:IterateEmbeds() instead of :IterateEmbedsOnAddon(addon)
function AceAddon:IterateEmbedsOnAddon(addon) return pairs(self.embeds[addon]) end
function AceAddon:IterateModulesOfAddon(addon) return pairs(addon.modules) end
-- Event Handling
local function onEvent(this, event, arg1)
-- 2011-08-17 nevcairiel - ignore the load event of Blizzard_DebugTools, so a potential startup error isn't swallowed up
if (event == "ADDON_LOADED" and arg1 ~= "Blizzard_DebugTools") or event == "PLAYER_LOGIN" then
-- if a addon loads another addon, recursion could happen here, so we need to validate the table on every iteration
while(#AceAddon.initializequeue > 0) do
local addon = tremove(AceAddon.initializequeue, 1)
-- this might be an issue with recursion - TODO: validate
if event == "ADDON_LOADED" then addon.baseName = arg1 end
AceAddon:InitializeAddon(addon)
tinsert(AceAddon.enablequeue, addon)
end
if IsLoggedIn() then
while(#AceAddon.enablequeue > 0) do
local addon = tremove(AceAddon.enablequeue, 1)
AceAddon:EnableAddon(addon)
end
end
end
end
AceAddon.frame:RegisterEvent("ADDON_LOADED")
AceAddon.frame:RegisterEvent("PLAYER_LOGIN")
AceAddon.frame:SetScript("OnEvent", onEvent)
-- upgrade embeded
for name, addon in pairs(AceAddon.addons) do
Embed(addon, true)
end
-- 2010-10-27 nevcairiel - add new "orderedModules" table
if oldminor and oldminor < 10 then
for name, addon in pairs(AceAddon.addons) do
addon.orderedModules = {}
for module_name, module in pairs(addon.modules) do
tinsert(addon.orderedModules, module)
end
end
end
| bsd-3-clause |
LuaDist2/lunamark | standalone/src/cosmo/grammar.lua | 9 | 4696 |
local lpeg = require "lpeg"
local re = require "re"
module(..., package.seeall)
local function parse_selector(selector, env)
env = env or "env"
selector = string.sub(selector, 2, #selector)
local parts = {}
for w in string.gmatch(selector, "[^|]+") do
local n = tonumber(w)
if n then
table.insert(parts, "[" .. n .. "]")
else
table.insert(parts, "['" .. w .. "']")
end
end
return env .. table.concat(parts)
end
local function parse_exp(exp)
return exp
end
local start = "[" * lpeg.P"="^1 * "["
local start_ls = "[" * lpeg.P"="^0 * "["
local longstring1 = lpeg.P{
"longstring",
longstring = lpeg.P"[[" * (lpeg.V"longstring" + (lpeg.P(1) - lpeg.P"]]"))^0 * lpeg.P"]]"
}
local longstring2 = lpeg.P(function (s, i)
local l = lpeg.match(start, s, i)
if not l then return nil end
local p = lpeg.P("]" .. string.rep("=", l - i - 2) .. "]")
p = (1 - p)^0 * p
return lpeg.match(p, s, l)
end)
local longstring = #("[" * lpeg.S"[=") * (longstring1 + longstring2)
local function parse_longstring(s)
local start = s:match("^(%[=*%[)")
if start then
return string.format("%q", s:sub(#start + 1, #s - #start))
else
return s
end
end
local alpha = lpeg.R('__','az','AZ','\127\255')
local n = lpeg.R'09'
local alphanum = alpha + n
local name = alpha * (alphanum)^0
local number = (lpeg.P'.' + n)^1 * (lpeg.S'eE' * lpeg.S'+-'^-1)^-1 * (alphanum)^0
number = #(n + (lpeg.P'.' * n)) * number
local shortstring = (lpeg.P'"' * ( (lpeg.P'\\' * 1) + (1 - (lpeg.S'"\n\r\f')) )^0 * lpeg.P'"') +
(lpeg.P"'" * ( (lpeg.P'\\' * 1) + (1 - (lpeg.S"'\n\r\f")) )^0 * lpeg.P"'")
local space = (lpeg.S'\n \t\r\f')^0
local syntax = [[
template <- (<item>* -> {} !.) -> compiletemplate
item <- <text> / <templateappl> / (. => error)
text <- ({~ (!<selector> ('$$' -> '$' / .))+ ~}) -> compiletext
selector <- ('$(' %s {~ <exp> ~} %s ')') -> parseexp /
('$' %alphanum+ ('|' %alphanum+)*) -> parseselector
templateappl <- ({~ <selector> ~} {~ <args>? ~} !'{'
({%longstring} -> compilesubtemplate)? (%s ','? %s ({%longstring} -> compilesubtemplate))* -> {} !(','? %s %start))
-> compileapplication
args <- '{' %s '}' / '{' %s <arg> %s (',' %s <arg> %s)* ','? %s '}'
arg <- <attr> / <exp>
attr <- <symbol> %s '=' !'=' %s <exp> / '[' !'[' !'=' %s <exp> %s ']' %s '=' %s <exp>
symbol <- %alpha %alphanum*
explist <- <exp> (%s ',' %s <exp>)* (%s ',')?
exp <- <simpleexp> (%s <binop> %s <simpleexp>)*
simpleexp <- <args> / %string / %longstring -> parsels / %number / 'true' / 'false' /
'nil' / <unop> %s <exp> / <prefixexp> / (. => error)
unop <- '-' / 'not' / '#'
binop <- '+' / '-' / '*' / '/' / '^' / '%' / '..' / '<=' / '<' / '>=' / '>' / '==' / '~=' /
'and' / 'or'
prefixexp <- ( <selector> / {%name} -> addenv / '(' %s <exp> %s ')' )
( %s <args> / '.' %name / ':' %name %s ('(' %s ')' / '(' %s <explist> %s ')') /
'[' %s <exp> %s ']' / '(' %s ')' / '(' %s <explist> %s ')' /
%string / %longstring -> parsels %s )*
]]
local function pos_to_line(str, pos)
local s = str:sub(1, pos)
local line, start = 1, 0
local newline = string.find(s, "\n")
while newline do
line = line + 1
start = newline
newline = string.find(s, "\n", newline + 1)
end
return line, pos - start
end
local function ast_text(text)
return { tag = "text", text = text }
end
local function ast_template_application(selector, args, ast_first_subtemplate, ast_subtemplates)
if not ast_subtemplates then
ast_first_subtemplate = nil
end
local subtemplates = { ast_first_subtemplate, unpack(ast_subtemplates or {}) }
return { tag = "appl", selector = selector, args = args, subtemplates = subtemplates }
end
local function ast_template(parts)
return { tag = "template", parts = parts }
end
local function ast_subtemplate(text)
local start = text:match("^(%[=*%[)")
if start then text = text:sub(#start + 1, #text - #start) end
return _M.ast:match(text)
end
local syntax_defs = {
start = start_ls,
alpha = alpha,
alphanum = alphanum,
name = name,
number = number,
string = shortstring,
longstring = longstring,
s = space,
parseselector = parse_selector,
parseexp = parse_exp,
parsels = parse_longstring,
addenv = function (s) return "env['" .. s .. "']" end,
error = function (tmpl, pos)
local line, pos = pos_to_line(tmpl, pos)
error("syntax error in template at line " .. line .. " position " .. pos)
end,
compiletemplate = ast_template,
compiletext = ast_text,
compileapplication = ast_template_application,
compilesubtemplate = ast_subtemplate
}
ast = re.compile(syntax, syntax_defs)
| mit |
strukturag/vlc-2.2 | share/lua/playlist/koreus.lua | 57 | 4037 | --[[
Copyright © 2009 the VideoLAN team
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()
if vlc.access ~= "http" and vlc.access ~= "https" then
return false
end
koreus_site = string.match( vlc.path, "koreus" )
if not koreus_site then
return false
end
return ( string.match( vlc.path, "video" ) ) -- http://www.koreus.com/video/pouet.html
end
-- Parse function.
function parse()
while true do
line = vlc.readline()
if not line then break end
if string.match( line, "<meta name=\"title\"" ) then
_,_,name = string.find( line, "content=\"(.-)\"" )
name = vlc.strings.resolve_xml_special_chars( name )
end
if string.match( line, "<meta property=\"og:description\"" ) then
_,_,description = string.find( line, "content=\"(.-)\"" )
if (description ~= nil) then
description = vlc.strings.resolve_xml_special_chars( description )
end
end
if string.match( line, "<span id=\"spoil\" style=\"display:none\">" ) then
_,_,desc_spoil = string.find( line, "<span id=\"spoil\" style=\"display:none\">(.-)</span>" )
desc_spoil = vlc.strings.resolve_xml_special_chars( desc_spoil )
description = description .. "\n\r" .. desc_spoil
end
if string.match( line, "<meta name=\"author\"" ) then
_,_,artist = string.find( line, "content=\"(.-)\"" )
artist = vlc.strings.resolve_xml_special_chars( artist )
end
if string.match( line, "link rel=\"image_src\"" ) then
_,_,arturl = string.find( line, "href=\"(.-)\"" )
end
vid_url = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%.mp4)' )
if vid_url then
path_url = vid_url
end
vid_url_hd = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%-hd%.mp4)' )
if vid_url_hd then
path_url_hd = vid_url_hd
end
vid_url_webm = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%.webm)' )
if vid_url_webm then
path_url_webm = vid_url_webm
end
vid_url_flv = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%.flv)' )
if vid_ulr_flv then
path_url_flv = vid_url_flv
end
end
if path_url_hd then
if vlc.access == 'https' then path_url_hd = path_url_hd:gsub('http','https') end
return { { path = path_url_hd; name = name; description = description; artist = artist; arturl = arturl } }
elseif path_url then
if vlc.access == 'https' then path_url = path_url:gsub('http','https') end
return { { path = path_url; name = name; description = description; artist = artist; arturl = arturl } }
elseif path_url_webm then
if vlc.access == 'https' then path_url_webm = path_url_webm:gsub('http','https') end
return { { path = path_url_webm; name = name; description = description; artist = artist; arturl = arturl } }
elseif path_url_flv then
if vlc.access == 'https' then path_url_flv = path_url_flv:gsub('http','https') end
return { { path = path_url_flv; name = name; description = description; artist = artist; arturl = arturl } }
else
return {}
end
end
| gpl-2.0 |
eaufavor/AwesomeWM-powerarrow-dark | extern/vicious/widgets/net.lua | 1 | 2709 | ---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2010, Adrian C. <anrxc@sysphere.org>
-- * (c) 2009, Lucas de Vries <lucas@glacicle.com>
---------------------------------------------------
-- {{{ Grab environment
local tonumber = tonumber
local os = { time = os.time }
local io = { lines = io.lines }
local setmetatable = setmetatable
local string = { match = string.match }
local helpers = require("extern.vicious.helpers")
-- }}}
-- Net: provides state and usage statistics of all network interfaces
-- vicious.widgets.net
local net = {}
-- Initialize function tables
local nets = {}
-- Variable definitions
local unit = { ["b"] = 1, ["kb"] = 1024,
["mb"] = 1024^2, ["gb"] = 1024^3
}
-- {{{ Net widget type
local function worker(format)
local args = {}
-- Get NET stats
for line in io.lines("/proc/net/dev") do
-- Match wmaster0 as well as rt0 (multiple leading spaces)
local name = string.match(line, "^[%s]?[%s]?[%s]?[%s]?([%w]+):")
if name ~= nil then
-- Received bytes, first value after the name
local recv = tonumber(string.match(line, ":[%s]*([%d]+)"))
-- Transmited bytes, 7 fields from end of the line
local send = tonumber(string.match(line,
"([%d]+)%s+%d+%s+%d+%s+%d+%s+%d+%s+%d+%s+%d+%s+%d$"))
helpers.uformat(args, name .. " rx", recv, unit)
helpers.uformat(args, name .. " tx", send, unit)
-- Operational state and carrier detection
local sysnet = helpers.pathtotable("/sys/class/net/" .. name)
args["{"..name.." carrier}"] = tonumber(sysnet.carrier) or 0
local now = os.time()
if nets[name] == nil then
-- Default values on the first run
nets[name] = {}
helpers.uformat(args, name .. " down", 0, unit)
helpers.uformat(args, name .. " up", 0, unit)
else -- Net stats are absolute, substract our last reading
local interval = now - nets[name].time
if interval <= 0 then interval = 1 end
local down = (recv - nets[name][1]) / interval
local up = (send - nets[name][2]) / interval
helpers.uformat(args, name .. " down", down, unit)
helpers.uformat(args, name .. " up", up, unit)
end
nets[name].time = now
-- Store totals
nets[name][1] = recv
nets[name][2] = send
end
end
return args
end
-- }}}
return setmetatable(net, { __call = function(_, ...) return worker(...) end })
| apache-2.0 |
focusworld/focus | plugins/media.lua | 297 | 1590 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
Mortezarohandeh1/hack_shop2bot | plugins/media.lua | 297 | 1590 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
disslove3/MAX3-BOT | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
mbmahdiiii/m | plugins/weather.lua | 274 | 1531 | do
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local function get_weather(location)
print("Finding weather in ", location)
location = string.gsub(location," ","+")
local url = BASE_URL
url = url..'?q='..location
url = url..'&units=metric'
url = url..'&appid=bd82977b86bf27fb59a04b61b657fb6f'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'The temperature in '..city
..' (' ..country..')'
..' is '..weather.main.temp..'°C'
local conditions = 'Current conditions are: '
.. weather.weather[1].description
if weather.weather[1].main == 'Clear' then
conditions = conditions .. ' ☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. ' ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. ' ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. ' ☔☔☔☔'
end
return temp .. '\n' .. conditions
end
local function run(msg, matches)
local city = 'Madrid,ES'
if matches[1] ~= '!weather' then
city = matches[1]
end
local text = get_weather(city)
if not text then
text = 'Can\'t get weather from that city.'
end
return text
end
return {
description = "weather in that city (Madrid is default)",
usage = "!weather (city)",
patterns = {
"^!weather$",
"^!weather (.*)$"
},
run = run
}
end
| gpl-2.0 |
mamadtnt/um | plugins/weather.lua | 274 | 1531 | do
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local function get_weather(location)
print("Finding weather in ", location)
location = string.gsub(location," ","+")
local url = BASE_URL
url = url..'?q='..location
url = url..'&units=metric'
url = url..'&appid=bd82977b86bf27fb59a04b61b657fb6f'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'The temperature in '..city
..' (' ..country..')'
..' is '..weather.main.temp..'°C'
local conditions = 'Current conditions are: '
.. weather.weather[1].description
if weather.weather[1].main == 'Clear' then
conditions = conditions .. ' ☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. ' ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. ' ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. ' ☔☔☔☔'
end
return temp .. '\n' .. conditions
end
local function run(msg, matches)
local city = 'Madrid,ES'
if matches[1] ~= '!weather' then
city = matches[1]
end
local text = get_weather(city)
if not text then
text = 'Can\'t get weather from that city.'
end
return text
end
return {
description = "weather in that city (Madrid is default)",
usage = "!weather (city)",
patterns = {
"^!weather$",
"^!weather (.*)$"
},
run = run
}
end
| gpl-2.0 |
mohammadclashclash/mehdi002 | plugins/ingroup.lua | 527 | 44020 | do
-- Check Member
local function check_member_autorealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted.')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted.')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(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 = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_del_user' then
if not msg.service then
-- return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
--[[if matches[1] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == 'setowner' and matches[2] then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Group owner is ["..group_owner..']'
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
sevenbot/seventmbot | plugins/ingroup.lua | 527 | 44020 | do
-- Check Member
local function check_member_autorealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted.')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted.')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(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 = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_del_user' then
if not msg.service then
-- return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
--[[if matches[1] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == 'setowner' and matches[2] then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Group owner is ["..group_owner..']'
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
safavi1381/Master-bot | plugins/groupmanager.lua | 136 | 11323 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin!"
end
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.'
end
local function set_description(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = deskripsi
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..deskripsi
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function set_rules(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules
return rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ')
save_data(_config.moderation.data, data)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
-- show group settings
local function show_group_settings(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local settings = data[tostring(msg.to.id)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
function run(msg, matches)
--vardump(msg)
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
return create_group(msg)
end
if not is_chat_msg(msg) then
return "This is not a group chat."
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if msg.media and is_chat_msg(msg) and is_momod(msg) then
if msg.media.type == 'photo' and data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then
load_photo(msg.id, set_group_photo, msg)
end
end
end
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'setabout' and matches[2] then
deskripsi = matches[2]
return set_description(msg, data)
end
if matches[1] == 'about' then
return get_description(msg, data)
end
if matches[1] == 'setrules' then
rules = matches[2]
return set_rules(msg, data)
end
if matches[1] == 'rules' then
return get_rules(msg, data)
end
if matches[1] == 'group' and matches[2] == 'lock' then --group lock *
if matches[3] == 'name' then
return lock_group_name(msg, data)
end
if matches[3] == 'member' then
return lock_group_member(msg, data)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == 'unlock' then --group unlock *
if matches[3] == 'name' then
return unlock_group_name(msg, data)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == 'settings' then
return show_group_settings(msg, data)
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
end
end
return {
description = "Plugin to manage group chat.",
usage = {
"!creategroup <group_name> : Create a new group (admin only)",
"!setabout <description> : Set group description",
"!about : Read group description",
"!setrules <rules> : Set group rules",
"!rules : Read group rules",
"!setname <new_name> : Set group name",
"!setphoto : Set group photo",
"!group <lock|unlock> name : Lock/unlock group name",
"!group <lock|unlock> photo : Lock/unlock group photo",
"!group <lock|unlock> member : Lock/unlock group member",
"!group settings : Show group settings"
},
patterns = {
"^!(creategroup) (.*)$",
"^!(setabout) (.*)$",
"^!(about)$",
"^!(setrules) (.*)$",
"^!(rules)$",
"^!(setname) (.*)$",
"^!(setphoto)$",
"^!(group) (lock) (.*)$",
"^!(group) (unlock) (.*)$",
"^!(group) (settings)$",
"^!!tgservice (.+)$",
"%[(photo)%]",
},
run = run,
}
end | gpl-2.0 |
pbrazdil/deepmask | trainMeters.lua | 3 | 3828 | --[[----------------------------------------------------------------------------
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
Contains the tree metrics used during training/evaluation:
- lossmeter: measure the average loss.
- binarymeter: measure error of predicted objectness score and ground truth
objectness annotation.
- ioumeter: measure iou between infered and ground truth masks.
------------------------------------------------------------------------------]]
--------------------------------------------------------------------------------
-- loss meter
do
local LossMeter = torch.class('LossMeter')
-- init
function LossMeter:__init()
self:reset()
end
-- function: reset
function LossMeter:reset()
self.sum = 0; self.n = 0
end
-- function: add
function LossMeter:add(value,n)
n = n or 1
self.sum = self.sum + value
self.n = self.n + n
end
-- function: value
function LossMeter:value()
return self.sum / self.n
end
end
--------------------------------------------------------------------------------
-- binary meter
do
local BinaryMeter = torch.class('BinaryMeter')
-- init
function BinaryMeter:__init()
self:reset()
end
-- function: reset
function BinaryMeter:reset()
self.acc = 0; self.n = 0
end
-- function: add
function BinaryMeter:add(output, target)
target, output = target:squeeze(), output:squeeze()
assert(output:nElement() == target:nElement(),
'target and output do not match')
local acc = torch.cmul(output,target)
self.acc = self.acc + acc:ge(0):sum()
self.n = self.n + output:size(1)
end
-- function: value
function BinaryMeter:value()
local res = self.acc/self.n
return res*100
end
end
--------------------------------------------------------------------------------
-- iou meter
do
local IouMeter = torch.class('IouMeter')
-- init
function IouMeter:__init(thr,sz)
self.sz = sz
self.iou = torch.Tensor(sz)
self.thr = math.log(thr/(1-thr))
self:reset()
end
-- function: reset
function IouMeter:reset()
self.iou:zero(); self.n = 0
end
-- function: add
function IouMeter:add(output, target)
target, output = target:squeeze():float(), output:squeeze():float()
assert(output:nElement() == target:nElement(),
'target and output do not match')
local batch,h,w = output:size(1),output:size(2),output:size(3)
local nOuts = h*w
local iouptr = self.iou:data()
local int,uni
local pred = output:ge(self.thr)
local pPtr,tPtr = pred:data(), target:data()
for b = 0,batch-1 do
int,uni = 0,0
for i = 0,nOuts-1 do
local id = b*nOuts+i
if pPtr[id] == 1 and tPtr[id] == 1 then int = int + 1 end
if pPtr[id] == 1 or tPtr[id] == 1 then uni = uni + 1 end
end
if uni > 0 then iouptr[self.n+b] = int/uni end
end
self.n = self.n + batch
end
-- function: value
function IouMeter:value(s)
if s then
local res
local nb = math.max(self.iou:ne(0):sum(),1)
local iou = self.iou:narrow(1,1,nb)
if s == 'mean' then
res = iou:mean()
elseif s == 'median' then
res = iou:median():squeeze()
elseif tonumber(s) then
local iouSort, _ = iou:sort()
res = iouSort:ge(tonumber(s)):sum()/nb
elseif s == 'hist' then
res = torch.histc(iou,20)/nb
end
return res*100
else
local value = {}
for _,s in ipairs(self.stats) do
value[s] = self:value(s)
end
return value
end
end
end
| bsd-3-clause |
adib1380/BotiSmylife | plugins/anti-spam6.lua | 13 | 2433 | local NUM_MSG_MAX = 6 -- Max number of messages per TIME_CHECK seconds
local TIME_CHECK = 6
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 'Spam Limit Is now 6'
end
if matches[1] == 'disable' then
redis:del(hash)
return 'Spam limit is Not 6 now'
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 Spaming I Will Fuck He/She'
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
-- kick user
-- TODO: Check on this plugin kicks
local bhash = 'kicked:'..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 = {
'^!antiflood6 (enable)$',
'^!antiflood6 (disable)$'
},
run = run,
privileged = true,
pre_process = pre_process
}
| gpl-2.0 |
mandla99/the_king98 | plugins/owners.lua | 55 | 23720 | local function lock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_arabic(msg, data, target)
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic/Persian is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic/Persian has been unlocked'
end
end
local function lock_group_links(msg, data, target)
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'yes' then
return 'Link posting is already locked'
else
data[tostring(target)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
return 'Link posting has been locked'
end
end
local function unlock_group_links(msg, data, target)
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'no' then
return 'Link posting is not locked'
else
data[tostring(target)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return 'Link posting has been unlocked'
end
end
local function lock_group_spam(msg, data, target)
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'yes' then
return 'SuperGroup spam is already locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'yes'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been locked'
end
end
local function unlock_group_spam(msg, data, target)
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'no' then
return 'SuperGroup spam is not locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'no'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been unlocked'
end
end
local function lock_group_sticker(msg, data, target)
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'yes' then
return 'Sticker posting is already locked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
return 'Sticker posting has been locked'
end
end
local function unlock_group_sticker(msg, data, target)
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'no' then
return 'Sticker posting is already unlocked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'Sticker posting has been unlocked'
end
end
local function lock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'yes' then
return 'Contact posting is already locked'
else
data[tostring(target)]['settings']['lock_contacts'] = 'yes'
save_data(_config.moderation.data, data)
return 'Contact posting has been locked'
end
end
local function unlock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'no' then
return 'Contact posting is already unlocked'
else
data[tostring(target)]['settings']['lock_contacts'] = 'no'
save_data(_config.moderation.data, data)
return 'Contact posting has been unlocked'
end
end
local function enable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['strict']
if strict == 'yes' then
return 'Settings are already strictly enforced'
else
data[tostring(target)]['settings']['strict'] = 'yes'
save_data(_config.moderation.data, data)
return 'Settings will be strictly enforced'
end
end
local function disable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['strict']
if strict == 'no' then
return 'Settings will not be strictly enforced'
else
data[tostring(target)]['settings']['strict'] = 'no'
save_data(_config.moderation.data, data)
return 'Settings are not strictly enforced'
end
end
-- Show group settings
local function show_group_settingsmod(msg, data, target)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(target)]['settings']['lock_bots'] then
bots_protection = data[tostring(target)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(target)]['settings']['leave_ban'] then
leave_ban = data[tostring(target)]['settings']['leave_ban']
end
local public = "no"
if data[tostring(target)]['settings'] then
if data[tostring(target)]['settings']['public'] then
public = data[tostring(target)]['settings']['public']
end
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection.."\nPublic: "..public
return text
end
-- Show SuperGroup settings
local function show_super_group_settings(msg, data, target)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['public'] then
data[tostring(target)]['settings']['public'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_rtl'] then
data[tostring(target)]['settings']['lock_rtl'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_member'] then
data[tostring(target)]['settings']['lock_member'] = 'no'
end
end
local settings = data[tostring(target)]['settings']
local text = "SuperGroup settings for "..target..":\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict
return text
end
local function set_rules(target, rules)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function set_description(target, about)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function run(msg, matches)
if msg.to.type == 'user' then
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", " ")
local chat_id = matches[1]
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
if matches[2] == 'ban' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't ban yourself"
end
ban_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3])
return 'User '..user_id..' banned'
end
if matches[2] == 'unban' then
if tonumber(matches[3]) == tonumber(our_id) then return false end
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't unban yourself"
end
local hash = 'banned:'..matches[1]
redis:srem(hash, user_id)
savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3])
return 'User '..user_id..' unbanned'
end
if matches[2] == 'kick' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't kick yourself"
end
kick_user(matches[3], chat_id)
savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3])
return 'User '..user_id..' kicked'
end
if matches[2] == 'clean' then
if matches[3] == 'modlist' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
for k,v in pairs(data[tostring(matches[1])]['moderators']) do
data[tostring(matches[1])]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist")
end
if matches[3] == 'rules' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'rules'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules")
end
if matches[3] == 'about' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'description'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned about")
channel_set_about(receiver, about_text, ok_cb, false)
return "About has been cleaned"
end
if matches[3] == 'mutelist' then
chat_id = string.match(matches[1], '^%d+$')
local hash = 'mute_user:'..chat_id
redis:del(hash)
return "Mutelist Cleaned"
end
end
if matches[2] == "setflood" then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[3]
data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]")
return 'Group flood has been set to '..matches[3]
end
if matches[2] == 'lock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
local group_type = data[tostring(matches[1])]['group_type']
if matches[3] == 'name' then
savelog(matches[1], name.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
savelog(matches[1], name.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[3] == 'arabic' then
savelog(matches[1], name.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[3] == 'links' then
savelog(matches[1], name.." ["..msg.from.id.."] locked links ")
return lock_group_links(msg, data, target)
end
if matches[3] == 'spam' then
savelog(matches[1], name.." ["..msg.from.id.."] locked spam ")
return lock_group_spam(msg, data, target)
end
if matches[3] == 'rtl' then
savelog(matches[1], name.." ["..msg.from.id.."] locked RTL chars. in names")
return unlock_group_rtl(msg, data, target)
end
if matches[3] == 'sticker' then
savelog(matches[1], name.." ["..msg.from.id.."] locked sticker")
return lock_group_sticker(msg, data, target)
end
end
if matches[2] == 'unlock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
local group_type = data[tostring(matches[1])]['group_type']
if matches[3] == 'name' then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[3] == 'arabic' then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[3] == 'links' and group_type == "SuperGroup" then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked links ")
return unlock_group_links(msg, data, target)
end
if matches[3] == 'spam' and group_type == "SuperGroup" then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked spam ")
return unlock_group_spam(msg, data, target)
end
if matches[3] == 'rtl' then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked RTL chars. in names")
return unlock_group_rtl(msg, data, target)
end
if matches[3] == 'sticker' and group_type == "SuperGroup" then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked sticker")
return unlock_group_sticker(msg, data, target)
end
if matches[3] == 'contacts' and group_type == "SuperGroup" then
savelog(matches[1], name_log.." ["..msg.from.id.."] locked contact posting")
return lock_group_contacts(msg, data, target)
end
if matches[3] == 'strict' and group_type == "SuperGroup" then
savelog(matches[1], name_log.." ["..msg.from.id.."] locked enabled strict settings")
return enable_strict_rules(msg, data, target)
end
end
if matches[2] == 'new' then
if matches[3] == 'link' then
local group_type = data[tostring(matches[1])]['group_type']
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local function callback_grouplink (extra , success, result)
local receiver = 'chat#id'..matches[1]
if success == 0 then
send_large_msg(receiver, '*Error: Failed to retrieve link* \nReason: Not creator.')
end
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return
end
local function callback_superlink (extra , success, result)
vardump(result)
local receiver = 'channel#id'..matches[1]
local user = extra.user
if success == 0 then
data[tostring(matches[1])]['settings']['set_link'] = nil
save_data(_config.moderation.data, data)
return send_large_msg(user, '*Error: Failed to retrieve link* \nReason: Not creator.\n\nIf you have the link, please use /setlink to set it')
else
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return send_large_msg(user, "Created a new link")
end
end
if group_type == "Group" then
local receiver = 'chat#id'..matches[1]
savelog(matches[1], name.." ["..msg.from.id.."] created/revoked group link ")
export_chat_link(receiver, callback_grouplink, false)
return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link"
elseif group_type == "SuperGroup" then
local receiver = 'channel#id'..matches[1]
local user = 'user#id'..msg.from.id
savelog(matches[1], name.." ["..msg.from.id.."] attempted to create a new SuperGroup link")
export_channel_link(receiver, callback_superlink, {user = user})
end
end
end
if matches[2] == 'get' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local group_link = data[tostring(matches[1])]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
end
if matches[1] == 'changeabout' and matches[2] then
if not is_owner2(msg.from.id, matches[2]) then
return "You are not the owner of this group"
end
local group_type = data[tostring(matches[2])]['group_type']
if group_type == "Group" or group_type == "Realm" then
local target = matches[2]
local about = matches[3]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_description(target, about)
elseif group_type == "SuperGroup" then
local channel = 'channel#id'..matches[2]
local about_text = matches[3]
local data_cat = 'description'
local target = matches[2]
channel_set_about(channel, about_text, ok_cb, false)
data[tostring(target)][data_cat] = about_text
save_data(_config.moderation.data, data)
savelog(matches[2], name.." ["..msg.from.id.."] has changed SuperGroup description to ["..matches[3].."]")
return "Description has been set for ["..matches[2]..']'
end
end
if matches[1] == 'viewsettings' and data[tostring(matches[2])]['settings'] then
if not is_owner2(msg.from.id, matches[2]) then
return "You are not the owner of this group"
end
local target = matches[2]
local group_type = data[tostring(matches[2])]['group_type']
if group_type == "Group" or group_type == "Realm" then
savelog(matches[2], name.." ["..msg.from.id.."] requested group settings ")
return show_group_settings(msg, data, target)
elseif group_type == "SuperGroup" then
savelog(matches[2], name.." ["..msg.from.id.."] requested SuperGroup settings ")
return show_super_group_settings(msg, data, target)
end
end
if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then
local rules = matches[3]
local target = matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rules(target, rules)
end
if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
save_data(_config.moderation.data, data)
local chat_to_rename = 'chat#id'..matches[2]
local channel_to_rename = 'channel#id'..matches[2]
savelog(matches[2], "Group name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]")
rename_chat(chat_to_rename, group_name_set, ok_cb, false)
rename_channel(channel_to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then
savelog(matches[2], "log file created by owner/support/admin")
send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false)
end
end
end
return {
patterns = {
"^owners (%d+) ([^%s]+) (.*)$",
"^owners (%d+) ([^%s]+)$",
"^(changeabout) (%d+) (.*)$",
"^(changerules) (%d+) (.*)$",
"^(changename) (%d+) (.*)$",
"^(viewsettings) (%d+)$",
"^(loggroup) (%d+)$"
},
run = run
} | gpl-2.0 |
tcmug/kello | objects/clock.lua | 1 | 3109 |
-- The clock face.
local hand = require( "objects.hand" )
module = {}
-- Compute the difference in seconds between local time and UTC.
function get_timezone()
local now = os.time()
return os.difftime(now, os.time(os.date("!*t", now)))
end
function module:create(clock_size)
local clock = display.newGroup()
local circle = display.newCircle(320, 570, clock_size, clock_size)
circle.x = 0
circle.y = 0
circle:setFillColor( 0, 0, 0 )
circle.strokeWidth = 4
circle:setStrokeColor( 1, 1, 1 )
clock:insert(circle)
local anim_time = 300
delta = 0
clock.x, clock.y = display.contentCenterX, display.contentCenterY
local secondsMargin = 13
local numberMargin = 33
for number = 1,60 do
local sz = 2
if (number % 5 == 0) then
sz = 4
end
local seconds = display.newCircle(0, 0, sz, sz)
delta = ((math.pi * 2) / 60) * number
seconds.x = (math.sin(delta) * (clock_size - secondsMargin))
seconds.y = (math.cos(delta) * -(clock_size - secondsMargin))
seconds:setFillColor( 0.5, 0.5, 0.5 )
clock:insert(seconds)
end
for number = 1,12 do
local hours = display.newText(number, 0, 0, "Roboto-Regular.ttf", 15)
delta = ((math.pi * 2) / 12) * number
hours.x = (math.sin(delta) * (clock_size - numberMargin))
hours.y = (math.cos(delta) * -(clock_size - numberMargin))
clock:insert(hours)
end
clock.hour = hand:create(clock_size - 35, 12 * 60 * 60)
clock:insert(clock.hour)
clock.minute = hand:create(clock_size - 20, 60 * 60)
clock:insert(clock.minute)
clock.second = hand:create(clock_size - 10, 60)
clock:insert(clock.second)
local circle = display.newCircle(0, 0, 10, 10)
circle.x = 0
circle.y = 0
circle:setFillColor( 0, 0, 0 )
circle.strokeWidth = 4
circle:setStrokeColor( 1, 1, 1 )
clock:insert(circle)
local anim_time = 300
function clock:step()
if not self.paused then
self.time = {
tonumber(os.date("%H"):match("0*(%d+)")),
tonumber(os.date("%M"):match("0*(%d+)")),
tonumber(os.date("%S"):match("0*(%d+)"))
}
self.seconds = (self.time[1] * 60 * 60) + (self.time[2] * 60) + (self.time[3])
self.hour:set(self.seconds, true)
self.minute:set(self.seconds, true)
self.second:set(self.seconds, true)
end
end
function clock:advance(seconds)
self.seconds = self.seconds + seconds
self.hour:set(self.seconds, false)
self.minute:set(self.seconds, false)
self.second:set(self.seconds, false)
end
function clock:getTime()
local h = self.seconds
local m = self.seconds
local s = self.seconds
h = math.floor(h / 60 / 60)
m = math.floor(m / 60) - (h * 60)
if (s >= 60) then
s = math.floor(s - math.floor(s / 60) * 60)
end
return h, m, s
end
clock:step()
return clock
end
return module
| gpl-3.0 |
nuvie/nuvie | data/scripts/md/usecode.lua | 2 | 63722 | local USE_EVENT_USE = 0x01
local USE_EVENT_MOVE = 0x40
local USE_EVENT_READY = 0x0100
function search_container(obj)
local child
for child in container_objs(obj) do
Obj.moveToMap(child, obj.x, obj.y, obj.z)
end
end
function use_door(obj, actor)
if bit32.btest(obj.quality, 0x80) then
printl("IT_IS_LOCKED")
return
end
if map_get_actor(obj.x, obj.y, obj.z) ~= nil then
printl("BLOCKED")
return
end
obj.frame_n = bit32.bxor(obj.frame_n, 2)
end
function use_crate(obj, target_obj, actor)
if target_obj.frame_n == 2 then
target_obj.frame_n = 1
printl("YOU_PRIED_THE_NAILS_OUT_OF_THE_CRATE")
else
if target_obj.frame_n == 1 and obj.obj_n == 273 then
target_obj.frame_n = 2
printl("YOU_NAIL_THE_CRATE_SHUT")
else
printl("IT_HAS_NO_EFFECT")
end
end
end
function use_container(obj, actor)
if obj.frame_n == 2 then
if obj.obj_n == 86 or obj.obj_n == 284 then
printl("IT_IS_NAILED_SHUT")
else
printl("IT_IS_LOCKED")
end
else
if obj.frame_n == 1 then
obj.frame_n = 0
search_container(obj)
else
obj.frame_n = 1
end
end
end
function use_hammer_on_oxium_geode(obj, target_obj, actor)
if target_obj.frame_n ~= 0 then
printl("IT_HAS_NO_EFFECT")
return
end
play_md_sfx(0x20)
target_obj.frame_n = 1 --break the geode open
if target_obj.on_map then
local oxium = Obj.new(131) --OBJ_BLOB_OF_OXIUM
oxium.qty = math.random(1, 50) + math.random(1, 50)
Obj.moveToMap(oxium, target_obj.x, target_obj.y, target_obj.z)
else
--FIXME add to actor's inventory
local oxium = Actor.inv_get_obj_n(actor, 131) --OBJ_BLOB_OF_OXIUM
local qty = math.random(1, 50) + math.random(1, 50)
if oxium ~= nil then
oxium.qty = oxium.qty + qty
else
oxium = Obj.new(131, 0, 0, qty) --OBJ_BLOB_OF_OXIUM
Actor.inv_add_obj(actor, oxium)
end
end
end
function use_prybar_on_hatch(obj, target_obj, actor)
if actor.actor_num ~= 1 then
printfl("IS_NOT_STRONG_ENOUGH", actor.name)
return
end
local tesla = Actor.get(16)
if Actor.get_talk_flag(tesla, 4) == false then
Actor.set_talk_flag(tesla, 2)
Actor.talk(tesla)
else
play_midgame_sequence(1)
Actor.set_talk_flag(tesla, 5)
target_obj.obj_n = 428
target_obj.frame_n = 0;
target_obj.x = target_obj.x + 1
target_obj.y = target_obj.y + 1
local blood = Actor.get(18)
Actor.set_talk_flag(blood, 3)
Actor.set_talk_flag(blood, 6)
Actor.talk(blood)
end
end
function use_sextant(obj, actor)
if actor.z ~= 0 then
printl("NOT_WHILE_UNDERGROUND")
return
end
local lat_str = "N"
local long_str = "W"
local lat = math.modf(((actor.y - 512) * 240) / 1024)
local long = math.modf(((actor.x - 512) * 360) / 1024)
if lat > 0 then
lat_str = "S"
else
if lat == 0 then
lat_str = " "
end
end
if long == 180 or long == -180 or long == 0 then
long_str = " "
else
if long < 0 then
long_str = "E"
end
end
lat = math.abs(lat)
long = 180 - math.abs(long)
printl("YOU_ARE_SOMEWHERE_NEAR")
print(" \nLat:" ..lat.." "..lat_str.."\nLong:"..long.." "..long_str.."\n")
end
function use_berry(obj, actor)
local actor_num = actor.actor_num
if actor_num == 6 then
printl("A_MECHANICAL_PERSON_CANT_EAT_BERRIES")
return
end
play_md_sfx(0x32)
local berry_type = obj.obj_n - 73 --OBJ_BERRY
local first_berry = true
if (berry_type == 0 and actor_is_affected_by_purple_berries(actor_num))
or (berry_type == 1 and actor_is_affected_by_green_berries(actor_num))
or (berry_type == 2 and actor_is_affected_by_brown_berries(actor_num)) then
printl("YOU_EAT_A_MARTIAN_BERRY_YOU_FEEL_AN_INCREASE_IN_THE_STRANGE")
else
printl("YOU_EAT_A_MARTIAN_BERRY_YOU_FEEL_A_STRANGE")
end
if berry_type == 0 then
printl("RELATIONSHIP_WITH_THINGS_AROUND_YOU")
actor_increment_purple_berry_count(actor_num)
elseif berry_type == 1 then
printl("SENSITIVITY_TO_THE_FEELINGS_OF_OBJECTS_AROUND_YOU")
actor_increment_green_berry_count(actor_num)
elseif berry_type == 2 then
printl("SENSE_OF_YOUR_SPATIAL_LOCATION")
actor_increment_brown_berry_count(actor_num)
elseif berry_type == 3 then
printl("SUDDEN_FLUSH_DIZZINESS_AND_NAUSEA")
actor.poisoned = false
Actor.hit(actor, math.random(5, 0x14) + math.random(5, 0x14))
local counter = actor_get_blue_berry_counter()
actor_set_blue_berry_counter(counter + math.random(1, 2))
end
if obj.qty == 1 then
Obj.removeFromEngine(obj)
else
obj.qty = obj.qty - 1
end
end
function use_misc_text(obj)
local obj_n = obj.obj_n
if obj_n == 65 or obj_n == 66 or obj_n == 67 or obj_n == 263 or obj_n == 267 or obj_n == 327 then
printl("YOU_CANT_DIG_ANY_DEEPER")
elseif obj_n == 427 then
printl("IT_IS_STUCK")
elseif obj_n == 288 then
printl("THE_CONTROL_PANEL_OPERATES_THE_DREAM_MACHINE")
elseif obj_n == 199 then
printl("YOU_NEED_TO_USE_PLIERS_TO_ATTACH_THE_CABLE")
elseif obj_n == 131 then
printl("YOU_WILL_CHEW_IT_INSTINCTIVELY")
elseif obj_n == 184 then
printl("THE_PLATE_IN_THE_CAMERA_HAS_ALREADY_BEEN_EXPOSED")
elseif obj_n == 442 or obj_n == 443 or obj_n == 444 then
printl("YOU_MUST_USE_A_SHOVEL_TO_MOVE_THAT")
elseif obj_n == 293 then
printl("YOU_CANT_DETERMINE_HOW_TO_READ_THE_TIME")
elseif obj_n == 77 or obj_n == 78 then
printl("THE_BERRIES_ARE_NOT_EDIBLE")
elseif obj_n == 323 then
printl("YOU_DONT_KNOW_HOW_IT_WORKS")
else
printl("IT_HAS_NO_EFFECT")
end
end
function get_pile_obj_num(map_tile)
if (map_tile >= 32 and map_tile <= 36) or map_tile == 12 or map_tile == 13 or (map_tile >= 40 and map_tile <= 63) then
return 258 --OBJ_DIRT_PILE
elseif map_tile == 124 or map_tile == 125 or map_tile == 127 then
return 256 --OBJ_CHUNK_OF_ICE
end
return 0 --CANNOT DIG HERE
end
function get_free_location_around_actor(actor)
local x_tbl = {-1,0,1,1,1,0,-1,-1}
local y_tbl = {-1,-1,-1,0,1,1,1,0}
local pos = {}
local i
pos.z = actor.z
for i=1,8 do
pos.x = actor.x + x_tbl[i]
pos.y = actor.y + y_tbl[i]
if map_can_put(pos.x,pos.y,pos.z) == true and map_get_obj(pos.x,pos.y,pos.z) == nil then
return pos
end
end
return nil
end
function use_tool_on_ground(obj, target_obj, actor, target_x, target_y, target_z)
if target_obj ~= nil then
--check tile flag here.
printl("THE_GROUND_IS_NOT_CLEAR_FOR_DIGGING")
return
end
local map_tile = map_get_tile_num(target_x, target_y, target_z)
local pile_obj_num = get_pile_obj_num(map_tile)
if pile_obj_num == 0 then
printl("IT_HAS_NO_EFFECT")
return
end
local hole_obj_num = 257
if pile_obj_num == 256 then
hole_obj_num = 255
end
local hole = Obj.new(hole_obj_num)
hole.temporary = true
Obj.moveToMap(hole, target_x, target_y, target_z)
local loc = get_free_location_around_actor(actor)
if loc ~= nil then
local pile = Obj.new(pile_obj_num)
pile.temporary = true
Obj.moveToMap(pile, loc.x, loc.y, loc.z)
else
Obj.removeFromEngine(hole)
printl("YOU_CANT_DIG_HERE")
end
end
function use_shovel_on_pile_to_hole(obj, target_obj, to_obj, actor)
Obj.removeFromEngine(target_obj)
Obj.removeFromEngine(to_obj)
play_md_sfx(0x1b)
play_md_sfx(0x1b)
printl("YOU_FILLED_IN_THE_HOLE")
end
function use_shovel_on_ore_to_container(obj, target_obj, to_obj, actor)
print("\n")
local ore_quality = get_ore_container_quality(target_obj.obj_n)
if to_obj.obj_n == 268 then --OBJ_MARTIAN_WHEEL_BARROW
if to_obj.qty ~= 1 then
play_md_sfx(0x1b)
to_obj.qty = 1
to_obj.quality = ore_quality
printfl("YOU_PUT_THE_ORE_INTO_THE_WHEELBARROW", target_obj.name)
Obj.removeFromEngine(target_obj)
else
printl("THERE_IS_NO_MORE_ROOM")
play_md_sfx(5)
return false
end
elseif to_obj.obj_n == 410 then --OBJ_RAIL_CAR
local qty = to_obj.qty
if to_obj.qty < 7 then
if to_obj.qty > 0 and to_obj.quality ~= ore_quality then
printl("YOU_CANT_MIX_DIFFERENT_THINGS_IN_THE_SAME_LOAD")
play_md_sfx(5)
return false
else
to_obj.quality = ore_quality
to_obj.qty = to_obj.qty + 1
if to_obj.qty == 1 or to_obj.qty == 7 then
to_obj.frame_n = to_obj.frame_n + 2
end
printfl("YOU_PUT_THE_ORE_INTO_THE_RAIL_CAR", target_obj.name)
Obj.removeFromEngine(target_obj)
end
else
printl("THERE_IS_NO_MORE_ROOM")
play_md_sfx(5)
return false
end
end
return true
end
function use_shovel_to_unload_container(obj, target_obj, to_obj, actor)
if target_obj.qty == 0 then
printl("THERE_IS_NOTHING_TO_UNLOAD")
play_md_sfx(5)
return
end
local ore = Obj.new(get_obj_num_from_ore_quality(target_obj.quality))
--FIXME if to_obj == nil do something
local success_flag = false
if to_obj.obj_n == 268 or to_obj.obj_n == 410 then --OBJ_MARTIAN_WHEEL_BARROW
success_flag = use_shovel_on_ore_to_container(obj, ore, to_obj, actor)
elseif to_obj.obj_n == 233 then --OBJ_FURNACE
success_flag = use_shovel_on_ore_to_furnace(obj, ore, to_obj, actor)
elseif to_obj.obj_n == 257 then --OBJ_HOLE
--FIXME need to wire up this logic.
else
--FIXME need to implement burying logic
end
if success_flag then
target_obj.qty = target_obj.qty - 1
if target_obj.obj_n == 410 then --OBJ_RAIL_CAR
if target_obj.qty == 6 or target_obj.qty == 0 then
target_obj.frame_n = target_obj.frame_n - 2
end
end
end
end
function use_shovel_on_ore_to_furnace(obj, target_obj, to_obj, actor)
local obj_n = target_obj.obj_n
play_md_sfx(0x1b)
Obj.removeFromEngine(target_obj)
if obj_n == 444 then --OBJ_PILE_OF_COAL
if to_obj.frame_n < 4 then
activate_power_system()
end
else
printl("IT_HAS_NO_EFFECT")
end
return true
end
function activate_power_system()
printl("THE_COAL_BEGINS_MOVING_DOWN_THE_BELT")
Actor.set_talk_flag(0x73, 2)
Actor.set_talk_flag(0x71, 3)
activate_power_update_tiles()
update_conveyor_belt(false)
end
function activate_power_update_tiles()
anim_play(9)
anim_play(10)
anim_play(11)
anim_play(12)
local loc = player_get_location()
for obj in find_obj(loc.z, 208) do --OBJ_CRACK
if obj ~= nil then
if map_get_obj(obj.x, obj.y, obj.z, 209) == nil then
local steam = Obj.new(209, 1)
Obj.moveToMap(steam, obj.x, obj.y+1, obj.z)
end
end
end
for obj in find_obj(loc.z, 233) do --OBJ_FURNACE
if obj ~= nil then
local frame_n = obj.frame_n
if frame_n == 1 or frame_n == 3 then
obj.frame_n = frame_n + 4
end
end
end
for obj in find_obj(loc.z, 154) do --OBJ_LAMP
if obj ~= nil then
obj.frame_n = 1
end
end
for obj in find_obj(4, 154) do --OBJ_LAMP
if obj ~= nil then
obj.frame_n = 1
end
end
end
function shutdown_power_update_tiles()
anim_stop(9)
anim_stop(10)
anim_stop(11)
anim_stop(12)
local loc = player_get_location()
for obj in find_obj(loc.z, 209) do --OBJ_STEAM_LEAK
if obj ~= nil then
Obj.removeFromEngine(obj)
end
end
for obj in find_obj(loc.z, 233) do --OBJ_FURNACE
if obj ~= nil then
local frame_n = obj.frame_n
if frame_n == 5 or frame_n == 7 then
obj.frame_n = frame_n - 4
end
end
end
for obj in find_obj(loc.z, 154) do --OBJ_LAMP
if obj ~= nil then
obj.frame_n = 0
end
end
for obj in find_obj(4, 154) do --OBJ_LAMP
if obj ~= nil then
obj.frame_n = 0
end
end
end
function update_conveyor_belt(can_stop)
if Actor.get_talk_flag(0x73, 2) == false then
return
end
local player_loc = player_get_location()
if player_loc.z ~= 5 then
return
end
--NOTE. The original game used generalised logic to search for conveyors.
-- I haven't used that here as there is only one conveyor in the game.
local x = 0x3c
local y = 0x63
local z = 5
local conveyor = map_get_obj(x, y, z, 188) --OBJ_CONVEYOR_BELT
while conveyor ~= nil do
if conveyor.frame_n == 2 then
local seam = map_get_obj(x, y, z, 189) --OBJ_CONVEYOR_BELT1
if seam ~= nil then
Obj.removeFromEngine(seam)
end
elseif conveyor.frame_n == 0 then
if conveyor.qty == 0 then
local seam = Obj.new(189)
Obj.moveToMap(seam, x, y, z)
conveyor.qty = 4
end
conveyor.qty = conveyor.qty - 1
end
local seam = map_get_obj(x, y, z, 189) --OBJ_CONVEYOR_BELT1
if seam ~= nil then
seam.x = seam.x + 1
end
for obj in objs_at_loc(x, y, z) do
if obj.obj_n == 447 or obj.weight > 0 then --OBJ_HUGE_LUMP_OF_COAL
obj.x = obj.x + 1
end
end
local actor = map_get_actor(x, y, z)
if actor ~= nil then
Actor.move(actor, x+1, y, z)
end
x = x - 1
conveyor = map_get_obj(x, y, z, 188) --OBJ_CONVEYOR_BELT
end
if can_stop and Actor.get_talk_flag(0x71, 3) then
if math.random(0, 6) == 0 then
printl("THE_CONVEYOR_BELT_STOPS")
Actor.clear_talk_flag(0x73, 2)
Actor.clear_talk_flag(0x71, 3)
shutdown_power_update_tiles()
end
end
end
function midgame_cutscene_2()
play_midgame_sequence(2)
for tower in find_obj(0, 201) do --OBJ_TOWER_TOP
if tower.x >= 0x3d0 and tower.x <= 0x3f0 and tower.y >= 0x1d0 and tower.y <= 0x1e7 then
tower.frame_n = 4 + (tower.frame_n % 4)
end
end
for cable in find_obj(0, 214) do --OBJ_POWER_CABLE
if cable.x >= 0x3d0 and cable.x <= 0x3f0 and cable.y >= 0x1d0 and cable.y <= 0x1e7 then
cable.obj_n = 215
end
end
end
function use_fixed_belt_on_bare_rollers(obj, target_obj, actor)
local start_obj = nil
local rollers = target_obj
while rollers ~= nil do
if rollers.frame_n == 0 then
start_obj = rollers
break
end
rollers = map_get_obj(rollers.x-1,rollers.y,rollers.z, rollers.obj_n)
end
if start_obj == nil then
printl("OOOPS_THESE_ROLLERS_CAN_NEVER_BE_FIXED")
return
end
rollers = start_obj
local i = 4
while rollers ~= nil do
rollers.obj_n = 188
if i == 0 then
i = 4
local belt_join_obj = Obj.new(189)
Obj.moveToMap(belt_join_obj, rollers.x, rollers.y, rollers.z)
else
i = i - 1
end
rollers = map_get_obj(rollers.x+1,rollers.y,rollers.z, 192) --OBJ_BARE_ROLLERS
end
Obj.removeFromEngine(obj)
Actor.set_talk_flag(0x72, 2)
end
function use_ruby_slippers(obj, actor)
if obj.readied == false then
--FIXME check that we can ready this object.
Obj.removeFromEngine(obj)
Actor.inv_ready_obj(actor, obj)
return
end
if obj.quality == 2 then
printl("YOU_MAY_USE_THE_RUBY_SLIPPERS_TO_GO_HOME")
local input = input_select("yn", false)
if input == "Y" then
play_end_sequence()
else
play_midgame_sequence(13)
end
else
printl("CLICK")
obj.quality = obj.quality + 1
end
end
function foes_are_nearby()
local loc = player_get_location()
local i
for i=1,0xff do
local actor = Actor.get(i)
if actor.alive and (actor.align == ALIGNMENT_EVIL or actor.align == ALIGNMENT_CHAOTIC) and actor.z == loc.z then
if get_wrapped_dist(actor.x, loc.x) < 40 and get_wrapped_dist(actor.y, loc.y) < 40 then
return true
end
end
end
return false
end
function is_target_visible_to_actor(actor, target)
--FIXME
return true
end
function npcs_are_nearby()
local loc = player_get_location()
local i
local player = Actor.get_player_actor()
for i=1,0xff do
local actor = Actor.get(i)
if actor.alive and actor.asleep == false and actor.in_party == false and actor.z == loc.z then
if get_wrapped_dist(actor.x, loc.x) < 6 and get_wrapped_dist(actor.y, loc.y) < 6 and is_target_visible_to_actor(player, actor) then
return actor
end
end
end
return nil
end
function is_actor_able_to_talk_to_player(actor)
local player = Actor.get_player_actor()
local loc = player_get_location()
if actor.alive and actor.asleep == false and actor.z == loc.z then
if get_wrapped_dist(actor.x, loc.x) < 6 and get_wrapped_dist(actor.y, loc.y) < 6 and is_target_visible_to_actor(player, actor) then
return true
end
end
return false
end
function rest_heal_party(hours_to_rest)
local actor
for actor in party_members() do
local hp = math.random(3,8) + math.random(3,8) * math.floor(hours_to_rest / 2)
local max_hp = actor_get_max_hp(actor)
if actor.hp + hp > max_hp then
actor.hp = max_hp
else
actor.hp = actor.hp + hp
end
end
end
function rest_level_up_actor(actor)
if actor.actor_num > 15 then
return
end
local exp_level_tbl = {
[0] = 0,
[1] = 100,
[2] = 200,
[3] = 400,
[4] = 800,
[5] = 1600,
[6] = 3200,
[7] = 6400,
[8] = 32767,
}
if actor.exp <= exp_level_tbl[actor.level] then
return
end
actor.level = actor.level + 1
local max_hp = actor_get_max_hp(actor)
if actor.hp + 30 > max_hp then
actor.hp = max_hp
else
actor.hp = actor.hp + 30
end
Actor.show_portrait(actor)
local obj_n = actor.obj_n
local gender = math.random(0,1)
if obj_n == 342 or obj_n == 343 or obj_n == 345 or (obj_n >= 347 and obj_n <= 353) then
gender = 0
elseif obj_n == 344 or obj_n == 346 or (obj_n >= 354 and obj_n <= 357) then
gender = 1
end
local gender_pronoun = "He"
if gender == 1 then
gender_pronoun = "She"
end
printfl("HAS_A_DREAM", actor.name)
printfl("SEES_THREE_STONE_OBELISKS", gender_pronoun)
printfl("FEELS_DRAWN_TO_ONE_OF_THE_OBELISKS", gender_pronoun)
printfl("DOES_TOUCH_THE_OBELISK", actor.name)
printl("WHICH_BHS")
local answer = input_select("bhs", false)
if answer == "B" then
if actor.int < 30 then
actor.int = actor.int + 1
end
elseif answer == "H" then
if actor.dex < 30 then
actor.dex = actor.dex + 1
end
elseif answer == "S" then
if actor.str < 30 then
actor.str = actor.str + 1
end
end
end
function use_tent(obj, actor)
if player_is_in_solo_mode() then
printl("NOT_WHILE_IN_SOLO_MODE")
play_md_sfx(5)
return
end
if g_in_dream_mode then
printl("YOU_CANT_SLEEP_IN_A_DREAM")
play_md_sfx(5)
return
end
local tent_loc = {}
if obj.on_map then
tent_loc.x = obj.x
tent_loc.y = obj.y
tent_loc.z = obj.z
else
tent_loc = player_get_location()
end
local x, y
for y = tent_loc.y - 2, tent_loc.y do
for x = tent_loc.x - 1, tent_loc.x + 1 do
local map_obj = map_get_obj(x,y,tent_loc.z)
if map_obj ~= nil and map_obj.obj_n ~= 106 then
if tile_get_flag(map_obj.tile_num, 3, 4) == false then
printfl("TENT_OBJ_IN_THE_WAY", map_obj.name)
play_md_sfx(5)
return
end
end
end
end
for y = tent_loc.y - 2, tent_loc.y do
for x = tent_loc.x - 1, tent_loc.x + 1 do
if tile_get_flag(map_get_tile_num(x,y,tent_loc.z), 1, 1) == true then --if map tile is impassible
printl("THE_GROUND_IS_NOT_FLAT_ENOUGH")
play_md_sfx(5)
return
end
end
end
printl("REST")
if party_is_in_combat_mode() then
print(" - ")
printl("NOT_WHILE_IN_COMBAT_MODE")
play_md_sfx(5)
return
end
if foes_are_nearby() then
printl("NOT_WHILE_FOES_ARE_NEAR")
play_md_sfx(5)
return
end
local npc = npcs_are_nearby()
if npc ~= nil then
printfl("IS_TOO_NEAR_TO_SETUP_CAMP", npc.name)
play_md_sfx(5)
return
end
--poison check
local actor
local poisoned = false
for actor in party_members() do
if actor.poisoned then
poisoned = true
printfl("IS_POISONED", actor.name)
end
end
if poisoned then
printl("DO_YOU_REALLY_WANT_TO_SLEEP")
local answer = input_select("yn", false)
if answer == "N" or answer == "n" then
return
end
end
local party_is_using_berries = false
for actor in party_members() do
local actor_num = actor.actor_num
local green = actor_is_affected_by_green_berries(actor_num)
local brown = actor_is_affected_by_brown_berries(actor_num)
if brown or green then
party_is_using_berries = true
if brown and green then
printfl("COMPLAINS_OF_TOO_MUCH_LIGHT_AND_INANIMATE", actor.name)
elseif brown then
printfl("COMPLAINS_OF_TOO_MUCH_LIGHT", actor.name)
else --green
printfl("COMPLAINS_OF_INANIMATE_THINGS_TALKING", actor.name)
end
end
end
if party_is_using_berries then
if party_get_size() == 1 then
printl("YOU_CANT_SLEEP")
else
printl("NOBODY_CAN_SLEEP")
end
return
end
local player = Actor.get_player_actor()
player.x = tent_loc.x
player.y = tent_loc.y
local tent = Obj.new(134, 3)
Obj.moveToMap(tent, player.x, player.y-1, player.z)
tent = Obj.new(134, 5)
Obj.moveToMap(tent, player.x+1, player.y-1, player.z)
tent = Obj.new(134, 6)
Obj.moveToMap(tent, player.x-1, player.y, player.z)
tent = Obj.new(134, 9)
Obj.moveToMap(tent, player.x+1, player.y, player.z)
tent = Obj.new(134, 8)
Obj.moveToMap(tent, player.x, player.y, player.z)
party_move(player.x, player.y, player.z)
script_wait(500)
party_hide_all()
tent.frame_n = 7
local hour = clock_get_hour()
local time
local hours_to_rest
if hour < 7 or hour > 16 then
time = i18n("SUNRISE")
if hour < 7 then
hours_to_rest = 7 - hour
else
hours_to_rest = 24 - hour + 7
end
elseif hour <= 16 then
time = i18n("SUNSET")
hours_to_rest = 18 - hour
end
printfl("REST_UNTIL", time)
local answer = input_select("yn", false)
if answer == "N" or answer == "n" then
printl("HOW_MANY_HOURS")
hours_to_rest = input_select_integer("0123456789", true)
end
g_party_is_warm = true
if g_hours_till_next_healing == 0 and hours_to_rest > 4 then
rest_heal_party(hours_to_rest)
g_hours_till_next_healing = 6
end
local can_level_up = false
if hours_to_rest * 3 > party_get_size() then
can_level_up = true
end
local i
for i=0,hours_to_rest*3-1 do
advance_time(20)
script_wait(100)
if i < party_get_size() then
local actor = party_get_member(i)
rest_level_up_actor(actor)
end
end
local actor
local poisoned = false
for actor in party_members() do
if actor.poisoned then
if math.random(1, 8) + math.random(1, 8) >= 15 then
actor.poisoned = false
printfl("FEELS_BETTER", actor.name)
else
if actor.hp < hours_to_rest * 2 + 5 then
actor.hp = 5
else
actor.hp = actor.hp - (hours_to_rest * 2 + 5)
end
end
end
end
tent.frame_n = 8 --Open the tent flap
party_show_all()
party_move(player.x, player.y + 1, player.z)
script_wait(500)
--remove tent from map
local z = player.z
for tent in find_obj(z, 134) do
if tent ~= nil and
((tent.x == tent_loc.x and tent.y == tent_loc.y-1) or
(tent.x == wrap_coord(tent_loc.x+1,z) and tent.y == tent_loc.y-1) or
(tent.x == wrap_coord(tent_loc.x-1,z) and tent.y == tent_loc.y) or
(tent.x == wrap_coord(tent_loc.x+1,z) and tent.y == tent_loc.y) or
(tent.x == tent_loc.x and tent.y == tent_loc.y))
then
Obj.removeFromEngine(tent)
end
end
g_party_is_warm = false
end
function use_red_berry(obj, actor)
if not party_is_in_combat_mode() then
printl("THAT_WOULD_BE_A_WASTE_OUTSIDE_OF_COMBAT")
return
end
if actor.frenzy == false then
printfl("ENTERS_A_BATTLE_FRENZY", actor.name)
play_md_sfx(0x32)
end
actor.frenzy = true
local qty = obj.qty
if qty > 1 then
obj.qty = qty - 1
else
Obj.removeFromEngine(obj)
end
end
function use_spittoon(obj, actor)
if not actor.hypoxia then
printl("YOU_SPIT_INTO_THE_SPITTOON")
else
printl("YOUR_MOUTH_IS_TOO_DRY")
end
end
function use_gong(obj, target_obj, actor)
printl("GONG")
play_md_sfx(0xf)
end
function use_musical_instrument(obj, actor)
local obj_n = obj.obj_n
if obj_n == 280 then --OBJ_CYMBALS
printl("CHING")
play_md_sfx(0x36)
elseif obj_n == 281 then --OBJ_TAMBORINE
printl("SHING")
play_md_sfx(0x35)
elseif obj_n == 282 then --OBJ_DRUM
printl("THUMP_THUMP")
play_md_sfx(0x34)
script_wait(100)
play_md_sfx(0x34)
elseif obj_n == 283 then --OBJ_ACCORDION
printl("WHEEEEZE")
play_md_sfx(0x37)
else
printfl("YOU_PLAY_THE", obj.name)
end
end
function use_wrench_on_switchbar(obj, target_obj, actor)
if target_obj.quality == 1 then
if target_obj.on_map then
local turntable = map_get_obj(target_obj.x-1, target_obj.y-1, target_obj.z, 413)
if turntable ~= nil then
target_obj.frame_n = turntable.frame_n
target_obj.quality = 0
printl("THE_SWITCH_IS_FASTENED")
play_md_sfx(0x1f)
return
end
end
printl("THIS_SWITCH_CANNOT_BE_FIXED")
play_md_sfx(0x5)
else
printl("THE_SWITCH_IS_LOOSE")
play_md_sfx(0x1f)
target_obj.quality = 1
end
end
function use_wrench_on_drill(obj, target_obj, actor)
local drill_cart
if target_obj.on_map then
drill_cart = map_get_obj(target_obj.x, target_obj.y, target_obj.z, 439)
end
if drill_cart ~= nil then
local drill = Obj.new(441,1) --assembled drill
Obj.moveToMap(drill, target_obj.x, target_obj.y, target_obj.z)
Obj.removeFromEngine(target_obj)
Obj.removeFromEngine(drill_cart)
printl("THE_DRILLS_POWER_IS_CONNECTED")
play_md_sfx(0x1f)
else
printl("THE_DRILL_MUST_BE_INSTALLED_ONTO_A_DRILL_CART")
end
end
function use_wrench_on_panel(obj, target_obj, actor)
if target_obj.on_map == false then
printl("IT_HAS_NO_EFFECT")
return
end
local quality = target_obj.quality
local panel_qty = target_obj.qty
if quality == 0 then
target_obj.quality = 1
printl("THE_PANEL_IS_LOOSE")
play_md_sfx(0x1f)
elseif bit32.btest(quality, 2) then
printl("IT_MUST_BE_REPAIRED_FIRST")
play_md_sfx(0x5)
else
local cabinet = map_get_obj(target_obj.x, target_obj.y, target_obj.z, 457)
if cabinet == nil then
printl("PANELS_ARE_ONLY_INSTALLED_ONTO_CABINETS")
play_md_sfx(0x5)
else
quality = cabinet.quality
if (quality == 0 and panel_qty ~= 0) or
(quality ~= 0 and quality <= 3 and panel_qty == 0 and target_obj.frame_n ~= (quality - 1) ) or
(quality ~= 0 and (quality > 3 or panel_qty ~= 0) and quality ~= panel_qty) then
printl("THIS_CABINET_REQUIRES_A_DIFFERENT_TYPE_OF_PANEL")
play_md_sfx(0x5)
else
target_obj.quality = target_obj.quality - 1
printl("THE_PANEL_IS_FASTENED")
play_md_sfx(0x1f)
if target_obj.quality == 3 then
Actor.set_talk_flag(0x74, 3)
if Actor.get_talk_flag(0x74, 0) then
Actor.set_talk_flag(0x60, 2)
end
end
end
end
end
end
function use_oxium_bin(obj, actor)
if map_can_reach_point (actor.x, actor.y, obj.x, obj.y, obj.z) == false then
printl("BLOCKED")
return
end
local oxium = Obj.new(131) --OBJ_BLOB_OF_OXIUM
oxium.qty = 20
if Actor.can_carry_obj(actor, oxium) then
Actor.inv_add_obj(actor, oxium, STACK_OBJECT_QTY)
printl("YOU_GET_TWO_HANDFULS_OF_OXIUM_FROM_THE_BIN")
Actor.set_talk_flag(0x12, 4)
else
printl("YOU_ARE_CARRYING_TOO_MUCH_ALREADY")
end
end
function use_sledge_hammer_on_replacement_track_to_broken_track(obj, target_obj, to_obj, actor)
play_md_sfx(0x20)
printl("WHICH_SECTION_OF_RAIL_NEEDS_FIXING")
Obj.removeFromEngine(target_obj)
to_obj.obj_n = 414 --OBJ_TRACK
end
function use_pliers_on_spool_to_tower(obj, target_obj, to_obj, actor)
if actor_find_max_wrapped_xy_distance(actor, to_obj.x, to_obj.y) > 1 then
printl("THE_WORK_IS_TO_PRECISE_TO_PERFORM_TELEKINETICALLY")
return
end
if Actor.get_talk_flag(0x73, 2) == false or Actor.get_talk_flag(0x71, 3) == true then
printl("THE_CABLE_DOES_NOT_NEED_REPLACEMENT")
return
end
if actor_is_holding_obj(actor, 38) == false then --OBJ_RUBBER_GLOVES
Actor.hit(actor, math.random(0, math.floor(actor.max_hp/2)))
local spector = Actor.get(2)
if is_actor_able_to_talk_to_player(spector) then
Actor.set_talk_flag(spector, 2)
Actor.talk(spector)
end
else
play_md_sfx(0x1f)
Obj.removeFromEngine(target_obj)
Actor.set_talk_flag(0x73, 4)
play_midgame_sequence(3)
for obj in find_obj_from_area(0x3d0, 0x1d0, 0, 32, 17) do
if obj.obj_n == 215 then -- OBJ_POWER_CABLE1
obj.obj_n = 214 -- OBJ_POWER_CABLE
end
end
for obj in find_obj(0, 315) do --OBJ_CHAMBER1
Obj.removeFromEngine(obj)
end
end
end
function use_gate(obj, actor)
if bit32.btest(obj.quality, 128) == true then
printl("IT_IS_APPARENTLY_LOCKED")
return
end
local frame_n = obj.frame_n
if frame_n == 0 or frame_n == 1 then
obj.frame_n = 3
obj.x = obj.x - 1
elseif frame_n == 2 or frame_n == 3 then
obj.frame_n = 1
obj.x = obj.x + 1
elseif frame_n == 4 or frame_n == 5 then
obj.frame_n = 7
elseif frame_n == 6 or frame_n == 7 then
obj.frame_n = 5
end
end
function use_switch_bar(obj, actor)
if obj.frame_n == 0 then
obj.frame_n = 1
else
obj.frame_n = 0
end
if obj.on_map == false or map_get_obj(obj.x-1,obj.y-1,obj.z, 413) == nil then
printl("IT_HAS_NO_EFFECT")
return
end
if obj.quality == 1 then
printl("IT_TURNS_LOOSELY")
return
end
local turntable = map_get_obj(obj.x-1,obj.y-1,obj.z, 413)
turntable.frame_n = obj.frame_n
local railcar = map_get_obj(obj.x-1,obj.y-1,obj.z, 410)
if railcar ~= nil then
railcar.frame_n = railcar.frame_n - (railcar.frame_n % 2)
railcar.frame_n = railcar.frame_n + turntable.frame_n
end
end
function use_reading_material(obj, actor)
if obj.quality == 0 then
local signatures = ""
if Actor.get_talk_flag(5, 3) == true then
signatures = signatures .. " Richard Sherman"
end
signatures = signatures .. "\n"
if Actor.get_talk_flag(0x19, 3) == true then
signatures = signatures .. " Capt. Gregory Duprey"
end
signatures = signatures .. "\n"
if Actor.get_talk_flag(0x1a, 3) == true then
signatures = signatures .. " Doctor David Yellin"
end
signatures = signatures .. "\n"
display_text_in_scroll_gump(i18nf("AFFIDAVIT", player_get_name(), signatures))
else
local text = load_text_from_lzc("mdtext.lzc", obj.quality - 1)
if text ~= nil then
display_text_in_scroll_gump(text)
else
printl("YOU_CANT_READ_IT")
end
end
end
function use_pool_table(obj, actor)
if Actor.inv_get_readied_obj_n(actor, ARM) ~= 401 then --OBJ_POOL_CUE
printl("YOU_NEED_A_POOL_CUE")
return
end
local pool_table1 = map_get_obj(wrap_coord(obj.x - 1, obj.z), obj.y, obj.z, 400) -- OBJ_UNK_400
local rand = math.random
if pool_table1 == nil then
pool_table1 = Obj.new(400, rand(0, 6))
Obj.moveToMap(pool_table1, wrap_coord(obj.x - 1, obj.z), obj.y, obj.z)
end
local pool_table2 = map_get_obj(obj.x, obj.y, obj.z, 400) -- OBJ_UNK_400
if pool_table2 == nil then
pool_table2 = Obj.new(400, rand(0, 6))
Obj.moveToMap(pool_table2, wrap_coord(obj.x - 1, obj.z), obj.y, obj.z)
end
for i=1,10 do
if i~= 1 then
script_wait(rand(200,500))
end
play_md_sfx(0x1c + rand(0, 2))
script_wait(rand(10,200))
play_md_sfx(0x1c + rand(0, 2))
pool_table1.frame_n = rand(0, 6)
pool_table2.frame_n = rand(0, 6)
if rand(0, 40) >= actor_dex_adj(actor) then
break
end
end
if rand(0, 40) < actor_dex_adj(actor) then
printl("GOOD_SHOT_OLD_BEAN")
end
end
function use_ready_obj(obj, actor)
if not Actor.can_carry_obj(actor, obj) then
printl("YOU_ARE_CARRYING_TOO_MUCH_ALREADY")
return
end
if obj.readied == true then
return
end
Obj.removeFromEngine(obj)
Obj.moveToInv(obj, actor.actor_num)
Actor.inv_ready_obj(actor, obj)
end
function use_heartstone_on_metal_woman(obj, target_obj, actor)
if target_obj.quality == 1 then
printl("THE_ROBOT_ALREADY_HAS_A_HEARTSTONE")
else
target_obj.quality = 1
Obj.removeFromEngine(obj)
play_md_sfx(0x1f)
printl("THE_HEARTSTONE_IS_INSTALLED")
end
end
function use_manuscript_on_mailbox(obj, target_obj, actor)
local twain = Actor.get(0x57)
finish_dream_quest(twain)
Actor.set_talk_flag(twain, 6)
Actor.talk(twain)
wake_from_dream()
end
function use_assembled_drill(obj, actor)
play_md_sfx(0x10)
local x = obj.x
local y = obj.y
local z = obj.z
if obj.frame_n == 1 then
x = x - 1
elseif obj.frame_n == 3 then
y = y - 1
elseif obj.frame_n == 4 then
y = y + 1
else
x = x + 1
end
local target_obj
for obj in objs_at_loc(x, y, z) do
if obj.obj_n == 445 --OBJ_IRON_ORE
or obj.obj_n == 446 -- OBJ_VEIN_OF_COAL
or obj.obj_n == 213 then --OBJ_CAVE_IN
target_obj = obj
break
end
end
if target_obj == nil then
target_obj = map_get_obj(x, y, z, 213, true)
end
local drilled_matterial
if target_obj == nil then
if can_drill_at_loc(x, y, z) == true then
drilled_matterial = 442 --OBJ_PILE_OF_ROCKS
else
local target_actor = map_get_actor(x, y, z)
if target_actor ~= nil then
--FIXME attack actor here. 40 points of damage
else
printl("THERE_IS_NOTHING_TO_DRILL_INTO")
end
return
end
elseif target_obj.obj_n == 445 then --OBJ_IRON_ORE
drilled_matterial = 443 --OBJ_PILE_OF_IRON_ORE
elseif target_obj.obj_n == 446 then --OBJ_VEIN_OF_COAL
drilled_matterial = 444 --OBJ_PILE_OF_COAL
end
if drilled_matterial ~= nil then
local spoil_location = get_free_location_around_drill(obj)
if spoil_location ~= nil then
local spoil_obj = Obj.new(drilled_matterial)
Obj.moveToMap(spoil_obj, spoil_location)
else
printl("THERE_IS_NO_ROOM_LEFT_FOR_THE_ORE")
end
end
if target_obj then
if target_obj.quality > 1 then
target_obj.quality = target_obj.quality - 1
else
Obj.removeFromEngine(target_obj)
end
end
if drilled_matterial == nil then
Obj.removeFromEngine(target_obj)
end
end
function get_free_location_around_drill(drill)
local x_tbl = {-1,0,1,1,1,0,-1,-1}
local y_tbl = {-1,-1,-1,0,1,1,1,0}
local pos = {}
local i
pos.z = drill.z
for i=1,8 do
pos.x = drill.x + x_tbl[i]
pos.y = drill.y + y_tbl[i]
local obj = map_get_obj(pos.x, pos.y, pos.z)
if obj == nil or is_blood(obj.obj_num) then
if tile_get_flag(map_get_tile_num(pos), 1, 1) == false then --not blocked.
return pos
end
end
end
return nil
end
function get_ore_container_quality(ore_obj_num)
local tbl = {[258]=1,[442]=2,[443]=3,[444]=4} --OBJ_DIRT_PILE, OBJ_PILE_OF_ROCKS, OBJ_PILE_OF_IRON_ORE, OBJ_PILE_OF_COAL
local quality = tbl[ore_obj_num]
if quality == nil then
quality = 1
end
return quality
end
function get_obj_num_from_ore_quality(ore_quality)
if ore_quality == 2 then
return 442 --OBJ_PILE_OF_ROCKS
elseif ore_quality == 3 then
return 443 --OBJ_PILE_OF_IRON_ORE
elseif ore_quality == 4 then
return 444 --OBJ_PILE_OF_COAL
end
return 258 --OBJ_DIRT_PILE
end
function can_drill_at_loc(x,y,z)
local tile_num = map_get_tile_num(x, y, z)
if tile_num >= 0xf0 and tile_num <= 0xfb then
return true
end
return false
end
local use_shovel_on_tbl = {
--on
[255]=use_misc_text,
[257]=use_misc_text,
[258]={[257]=use_shovel_on_pile_to_hole},
[268]={
[233]=use_shovel_to_unload_container, --use OBJ_SHOVEL on OBJ_MARTIAN_WHEEL_BARROW to OBJ_FURNACE
[257]=use_shovel_to_unload_container, --use OBJ_SHOVEL on OBJ_MARTIAN_WHEEL_BARROW to OBJ_HOLE
[268]=use_shovel_to_unload_container, --use OBJ_SHOVEL on OBJ_MARTIAN_WHEEL_BARROW to OBJ_MARTIAN_WHEEL_BARROW
[410]=use_shovel_to_unload_container, --use OBJ_SHOVEL on OBJ_MARTIAN_WHEEL_BARROW to OBJ_RAIL_CAR
},
[410]={
[233]=use_shovel_to_unload_container, --use OBJ_SHOVEL on OBJ_RAIL_CAR to OBJ_FURNACE
[257]=use_shovel_to_unload_container, --use OBJ_SHOVEL on OBJ_RAIL_CAR to OBJ_HOLE
[268]=use_shovel_to_unload_container, --use OBJ_SHOVEL on OBJ_RAIL_CAR to OBJ_MARTIAN_WHEEL_BARROW
[410]=use_shovel_to_unload_container, --use OBJ_SHOVEL on OBJ_RAIL_CAR to OBJ_RAIL_CAR
},
[442]={
[268]=use_shovel_on_ore_to_container, --use OBJ_SHOVEL on OBJ_PILE_OF_ROCKS to OBJ_MARTIAN_WHEEL_BARROW
[410]=use_shovel_on_ore_to_container}, --use OBJ_SHOVEL on OBJ_PILE_OF_ROCKS to OBJ_RAIL_CAR
[443]={
[268]=use_shovel_on_ore_to_container, --use OBJ_SHOVEL on OBJ_PILE_OF_IRON_ORE to OBJ_MARTIAN_WHEEL_BARROW
[410]=use_shovel_on_ore_to_container}, --use OBJ_SHOVEL on OBJ_PILE_OF_IRON_ORE to OBJ_RAIL_CAR
[444]={
[268]=use_shovel_on_ore_to_container, --use OBJ_SHOVEL on OBJ_PILE_OF_COAL to OBJ_MARTIAN_WHEEL_BARROW
[410]=use_shovel_on_ore_to_container}, --use OBJ_SHOVEL on OBJ_PILE_OF_COAL to OBJ_RAIL_CAR
[0]=use_tool_on_ground, --hole in ice, hole
}
function use_oil_on_door(obj, target_obj, actor)
if obj.obj_n == 235 and obj.frame_n ~= 4 then
printl("IT_HAS_NO_EFFECT")
return
end
if target_obj ~= nil then
if bit32.band(target_obj.quality, 0x80) == 0 then
printl("THIS_DOOR_IS_NOT_RUSTED")
else
target_obj.quality = bit32.band(target_obj.quality, 0x7f) --unset bit 7
printl("THE_DOOR_IS_UNSTUCK")
play_md_sfx(4)
if obj.stackable then
if obj.qty == 1 then
Obj.removeFromEngine(obj)
else
obj.qty = obj.qty - 1
end
else
Obj.removeFromEngine(obj)
end
end
end
end
function use_oil_on_dream_door(obj, target_obj, actor, target_x, target_y, target_z)
if map_get_tile_num(target_x, target_y, target_z) == 8 then
local melies = Actor.get(0x51)
Actor.set_talk_flag(melies, 6)
Actor.talk(melies)
finish_dream_quest(melies)
wake_from_dream()
else
printl("IT_HAS_NO_EFFECT")
end
end
function use_hand_mirror(obj, actor)
if actor.x >= 0x76 and actor.x <= 0x78 and actor.y >= 0xca and actor.y <= 0xcc and actor.z == 2 then
local lowell = Actor.get(0x50)
Actor.set_talk_flag(lowell, 6)
Actor.talk(lowell)
finish_dream_quest(lowell)
wake_from_dream()
else
printl("YOU_SEE_YOURSELF")
end
end
function use_radium(obj, target_obj, actor)
actor_radiation_check(actor, obj)
if obj.obj_n == 448 then --OBJ_BLOCK_OF_RADIUM
if target_obj.obj_n == 448 and target_obj.on_map then
local power_unit = map_get_obj(obj.x, obj.y, obj.z, 290) --OBJ_POWER_UNIT
if power_unit ~= nil then
target_obj = power_unit
end
end
if target_obj.obj_n == 290 then --OBJ_POWER_UNIT
if target_obj.frame_n == 1 then
printl("RADIUM_HAS_ALREADY_BEEN_INSTALLED")
else
Obj.removeFromEngine(obj)
play_md_sfx(4)
printl("THE_RADIUM_HAS_BEEN_INSTALLED")
target_obj.frame_n = 1
Actor.set_talk_flag(0x74, 2)
if Actor.get_talk_flag(0x74, 0) then
Actor.set_talk_flag(0x60, 2)
end
end
else
printl("IT_HAS_NO_EFFECT")
end
elseif obj.obj_n == 449 then --OBJ_CHIP_OF_RADIUM
if target_obj.qty < 0xf0 then
local qty = input_select_obj_qty(obj)
if qty == 0 then
return
end
if target_obj.qty + qty * 30 > 0xf0 then
qty = math.ceil((0xf0 - target_obj.qty) / 30)
printfl("THE_OBJ_ONLY_NEEDED_N_RADIUM_BLOCKS", target_obj.name, qty)
printfl("THE_OBJ_IS_FULLY_CHARGED", target_obj.name)
target_obj.qty = 0xf0
else
target_obj.qty = target_obj.qty + qty * 30
end
if obj.qty == qty then
Obj.removeFromEngine(obj)
else
obj.qty = obj.qty - qty
end
else
printfl("THE_OBJ_IS_FULLY_CHARGED", target_obj.name)
end
end
end
function use_head_gear(obj, target_obj, actor)
local machine
if target_obj.obj_n == 289 then --OBJ_DREAM_MACHINE2
local machine = map_get_obj(target_obj.x, target_obj.y, target_obj.z, 288)
if machine == nil then
printl("IT_HAS_NO_EFFECT")
return
end
else
machine = target_obj
end
local loc = machine.xyz
machine = Obj.new(100)
machine.frame_n = 1
Obj.moveToMap(machine, loc)
printl("THE_HEADGEAR_IS_INSTALLED")
Actor.set_talk_flag(0x74, 4)
if Actor.get_talk_flag(0x74, 0) then
Actor.set_talk_flag(0x60, 2)
end
end
function use_dream_machine(panel_obj)
if Actor.get_talk_flag(0x46, 3) then
printl("THE_DREAM_MACHINES_SEEM_TO_HAVE_CEASED_FUNCTIONING")
return
end
local z = panel_obj.z
local power_unit
local dream_quality
local headgear_installed = false
local seat_x, seat_y
for obj in find_obj_from_area(panel_obj.x - 5, panel_obj.y - 5, z, 11, 11) do
local obj_n = obj.obj_n
if obj_n == 290 and obj.frame_n == 1 then --OBJ_POWER_UNIT
power_unit = obj
elseif obj_n == 100 then --OBJ_DREAM_MACHINE
headgear_installed = true
elseif obj_n == 289 then --OBJ_DREAM_MACHINE2
seat_x = obj.x
seat_y = obj.y
elseif obj_n == 288 then --OBJ_DREAM_MACHINE2
dream_quality = obj.quality
end
end
local actor_in_seat = map_get_actor(seat_x, seat_y, z)
if power_unit == nil or dream_quality == nil or not headgear_installed then
printl("THE_MACHINE_DOES_NOT_WORK")
return
end
local martian_obj = map_get_obj(seat_x, seat_y, z, 291) --OBJ_UNCONSCIOUS_MARTIAN
if martian_obj ~= nil then
if Actor.get_talk_flag(0x21, 2) or not Actor.get_talk_flag(0x61, 4) then
printl("IT_HAS_NO_EFFECT")
else
play_midgame_sequence(5)
local martian = Actor.get(0x21)
Actor.talk(martian)
Actor.set_talk_flag(martian, 2)
martian.x = seat_x
martian.y = seat_y + 1
martian.z = panel_obj.z
kill_actor(martian)
Obj.removeFromEngine(martian_obj)
end
return
end
local metal_woman_obj = map_get_obj(seat_x, seat_y, z, 287) --OBJ_METAL_WOMAN
if metal_woman_obj ~= nil then
if metal_woman_obj.quality == 0 then
printl("IT_HAS_NO_EFFECT")
else
--FIXME implement metal woman activation logic
end
elseif actor_in_seat ~= nil then
if z ~= 0 then
wake_from_dream()
else
if dream_quality < 2 then
Actor.set_talk_flag(0x60, 3)
end
if dream_quality == 3 then
if Actor.get_talk_flag(0x46, 0) then
--FIXME call sub_3F624
else
printl("THE_MACHINE_DOES_NOT_WORK")
end
else
actor_use_dream_machine(actor_in_seat, dream_quality)
end
end
else
printl("THERE_IS_NOBODY_SITTING_IN_THE_MACHINE")
end
end
function use_sprayer_system(panel_obj)
end
function use_lens_controls(panel_obj)
end
function use_pump_controls(panel_obj)
end
local use_panel_tbl = {
[0]=function() printl("YOU_ARE_COMPLETELY_UNSURE_WHAT_YOU_JUST_DID") end,
[1]=function() printl("YOU_ACTUATE_THE_MECHANISM_TO_NO_APPARENT_EFFECT") end,
[2]=function() printl("STATUS_LIGHTS_CHANGE_BUT_YOU_SEE_NO_OTHER_EFFECT") end,
[3]=function() printl("LIGHTS_FLASH_AND_CHANGE_COLOR_BUT_NOTHING_ELSE_HAPPENS") end,
[4]=use_dream_machine,
[5]=use_sprayer_system,
[6]=use_lens_controls,
[7]=use_pump_controls,
}
function use_panel(obj, actor)
if bit32.band(obj.quality, 2) ~= 0 then
printl("THE_PANEL_IS_BROKEN")
return
end
if bit32.band(obj.quality, 1) ~= 0 then
printl("THE_PANEL_IS_NOT_INSTALLED")
return
end
local cabinet = map_get_obj(obj.x, obj.y, obj.z, 457) --OBJ_CABINET
if cabinet == nil then
printl("PANELS_ARE_ONLY_INSTALLED_ONTO_CABINETS")
return
end
local quality = cabinet.quality
if use_panel_tbl[quality] ~= nil then
use_panel_tbl[quality](obj)
else
printl("IT_HAS_NO_EFFECT")
end
end
function has_minotaur_left_the_shop(cur_z)
for i=1,0xff do
local actor = Actor.get(i)
if actor.obj_n == 398 then --OBJ_MINOTAUR
if actor.z == cur_z and not Actor.get_talk_flag(0x54, 6)
and actor.x >= 0x37 and actor.y <= 0x37 then
return true
end
end
end
return false
end
function use_switch(obj, actor)
local switch_qty = obj.qty
local switch_quality = obj.quality
local target_obj
local num_switches = 0
local switches = {}
for obj in find_obj_from_area(obj.x - 32, obj.y - 32, obj.z, 64, 64) do
if obj.obj_n == 179 or obj.obj_n == 227 then --OBJ_CLOSED_DOOR, OBJ_DOOR3
if bit32.band(obj.quality, 0x7f) == switch_qty then
target_obj = obj
end
elseif (obj.obj_n == 311 or obj.obj_n == 312 or obj.obj_n == 196) then --and obj.quality < 2 then
if num_switches < 4 then
num_switches = num_switches + 1
switches[num_switches] = obj
end
end
end
if target_obj == nil then
printl("STRANGELY_NOTHING_HAPPENS")
return
end
if num_switches == 0 then
printl("STRANGELY_IT_DOESNT_MOVE")
return
end
local frame_n = 0
if switch_quality == 1 then
if bit32.band(target_obj.quality, 0x80) == 0 then
target_obj.quality = bit32.bor(target_obj.quality, 0x80)
else
target_obj.quality = bit32.band(target_obj.quality, 0x7f)
frame_n = 1
end
else
local old_frame_n = target_obj.frame_n
target_obj.frame_n = bit32.band(old_frame_n, 2) + 5
play_door_sfx()
if old_frame_n < 4 then
target_obj.frame_n = bit32.band(old_frame_n, 2) + 9
frame_n = 1
else
target_obj.frame_n = bit32.band(old_frame_n, 2) + 1
if g_in_dream_mode and g_current_dream_stage == 0x44 and has_minotaur_left_the_shop(target_obj.z) then
complete_tiffany_stage()
return
end
end
play_door_sfx()
end
for i=1,num_switches do
switches[i].frame_n = frame_n
end
play_md_sfx(0x11)
end
function use_drawbridge_lever(obj, actor)
--FIXME
end
function use_cheat_lever(obj, actor)
--FIXME
end
function use_cheat_lever2(obj, actor)
--FIXME
end
local switch_qual_tbl = {
[1] = use_switch,
[2] = use_switch,
[10] = use_drawbridge_lever,
[20] = use_cheat_lever,
[21] = use_cheat_lever2,
}
function use_switch_device(obj, actor)
if switch_qual_tbl[obj.quality] ~= nil then
switch_qual_tbl[obj.quality](obj, actor)
else
printl("WHAT_AN_ODD_LEVER")
end
end
function use_dreamstuff(obj, actor)
printl("YOU_IMAGINE")
for item in container_objs(obj) do
if item.obj_n < 342 then -- OBJ_POOR_MONK
--object
print(item.look_string.."\n")
if obj.on_map then
Obj.moveToMap(item, obj.xyz)
else
local parent = obj.parent
if parent.luatype == "actor" then
Obj.moveToInv(item, parent.actor_num)
else
Obj.moveToCont(item, parent)
end
end
else
--actor
print(item.name.."\n")
local spawned_actor = Actor.new(item.obj_n, actor.x, actor.y, actor.z)
actor_init(spawned_actor, obj.quality + 1) -- alignment
toss_actor(spawned_actor, actor.x, actor.y, actor.z)
spawned_actor.wt = item.quality
end
Obj.removeFromEngine(obj)
return
end
printl("NOTHING")
end
function use_obj_on_spray_gun(obj, target_obj, actor)
if obj.obj_n == 119 and target_obj.quality == 0 then --OBJ_BOTTLE_OF_GREEN_PAINT
target_obj.quality = 1
target_obj.qty = 20
printl("SPRAY_GUN_GREEN_PAINT")
elseif obj.obj_n == 128 and target_obj.quality ~= 0 then --OBJ_WEED_KILLER
target_obj.quality = 0
target_obj.qty = 10
printl("SPRAY_GUN_WEED_KILLER")
else
local spray_gun_qty = target_obj.qty + 10
if spray_gun_qty > 0x1e then
spray_gun_qty = 0x1e
end
target_obj.qty = spray_gun_qty
printl("SPRAY_GUN_10_MORE_CHARGES")
end
Obj.removeFromEngine(obj)
end
function use_spray_gun(obj, target_obj, actor)
if obj.qty == 0 then
printl("THERE_IS_NOTHING_IN_THE_GUN")
return
end
if obj.quality ~= 0 then
obj.qty = obj.qty - 1
if target_obj.luatype == "actor" and target_obj.obj_n == 145 then --OBJ_MONSTER_FOOTPRINTS
target_obj.obj_n = 364 --OBJ_PROTO_MARTIAN
printfl("BECOMES_VISIBLE", target_obj.name)
else
if target_obj.luatype == "actor" and not target_obj.visible then
target_obj.visible = true
printfl("BECOMES_VISIBLE", target_obj.name)
elseif target_obj.luatype == "obj" and target_obj.invisible then
target_obj.invisible = false
printfl("BECOMES_VISIBLE", target_obj.name)
else
printl("IT_HAS_NO_EFFECT")
end
end
elseif target_obj.luatype == "actor" then
attack_target_with_weapon(actor, target_obj.x, target_obj.y, obj)
elseif is_plant_obj(target_obj) then
hit_target(target_obj, RED_HIT_TILE)
printl("YOU_KILLED_THE_PLANT")
if target_obj.obj_n == 205 then --OBJ_VINE
Actor.set_talk_flag(0x30, 7)
Obj.removeFromEngine(target_obj)
elseif target_obj.obj_n == 408 then --OBJ_TREE
target_obj.obj_n = 166 --OBJ_DEAD_TREE
else
Obj.removeFromEngine(target_obj)
end
else
obj.qty = obj.qty - 1
printl("IT_HAS_NO_EFFECT")
end
end
local usecode_table = {
--OBJ_RUBY_SLIPPERS
[12]=use_ruby_slippers,
--OBJ_RUBBER_GLOVES
[38]=use_ready_obj,
--OBJ_SLEDGE_HAMMER
[52]={
--on
[404]={ --OBJ_REPLACEMENT_TRACK
--to
[405]=use_sledge_hammer_on_replacement_track_to_broken_track
}
},
--OBJ_PLIERS
[53]={
--on
[199]={--OBJ_CABLE_SPOOL
--to
[201]=use_pliers_on_spool_to_tower, --OBJ_TOWER_TOP
[215]=use_pliers_on_spool_to_tower, --OBJ_POWER_CABLE1
}
},
--OBJ_PICK
[65]={[255]=use_misc_text,[257]=use_misc_text}, --hole in ice, hole
--OBJ_SHOVEL
[66]=use_shovel_on_tbl,
--OBJ_HOE
[67]={[255]=use_misc_text,[257]=use_misc_text}, --hole in ice, hole
--OBJ_BERRY
[73]=use_berry,
--OBJ_BERRY1
[74]=use_berry,
--OBJ_BERRY2
[75]=use_berry,
--OBJ_BERRY3
[76]=use_berry,
--OBJ_BERRY4
[77]=use_red_berry,
--OBJ_CLUMP_OF_ROUGE_BERRIES
[78]=use_misc_text,
[86]=use_container,
[87]=use_container,
--OBJ_MANUSCRIPT
[88]={
--on
[84]=use_manuscript_on_mailbox, --OBJ_MAILBOX
},
[96]=use_sextant,
[102]={[86]=use_crate,[427]=use_prybar_on_hatch},
[104]=use_container,
--OBJ_FOLDED_TENT
[106]=use_tent,
--OBJ_BOTTLE_OF_GREEN_PAINT
[119]={
--on
--OBJ_WEED_SPRAYER
[129]=use_obj_on_spray_gun,
--OBJ_SPRAY_GUN
[261]=use_obj_on_spray_gun,
},
--OBJ_CAN_OF_LAMP_OIL
[124]={
--on
--OBJ_CLOSED_DOOR
[179]=use_oil_on_door,
--OBJ_DOOR3
[227]=use_oil_on_door,
--OBJ_CLOSED_HATCH
[421]=use_oil_on_door,
--OBJ_DOOR
[152]=use_oil_on_door,
--OBJ_DOOR1
[219]=use_oil_on_door,
--OBJ_DOOR2
[222]=use_oil_on_door,
[0]=use_oil_on_dream_door,
},
--OBJ_WEED_KILLER
[128]={
--on
--OBJ_WEED_SPRAYER
[129]=use_obj_on_spray_gun,
--OBJ_SPRAY_GUN
[261]=use_obj_on_spray_gun,
},
--OBJ_WEED_SPRAYER
[129]={
--on
[0]=use_spray_gun
},
--OBJ_BLOB_OF_OXIUM
[131]=use_misc_text,
--OBJ_WRENCH
[135]={
--on
[411]=use_wrench_on_switchbar,
[440]=use_wrench_on_drill,
[458]=use_wrench_on_panel
},
--OBJ_TONGS
[136]=use_ready_obj,
--OBJ_REPAIRED_BELT
[144]={
--on
[192]=use_fixed_belt_on_bare_rollers,
},
--OBJ_HAND_MIRROR
[147]=use_hand_mirror,
--OBJ_BOOK
[148]=use_reading_material,
--OBJ_NOTE
[151]=use_reading_material,
--OBJ_DOOR
[152]=use_door,
[181]=use_gate,
--OBJ_CAMERA
[184]=use_misc_text,
--OBJ_LEVER
[196]=use_switch_device,
--OBJ_CABLE_SPOOL
[199]=use_misc_text,
[212]=use_oxium_bin,
[222]=use_door,
--OBJ_GONG_HAMMER
[231]={
--on
[130]=use_hammer_on_oxium_geode, --OBJ_OXIUM_GEODE
[298]=use_gong, --OBJ_GONG
--FIXME OBJ_BRASS_CHEST, OBJ_OBSIDIAN_BOX, OBJ_STEAMER_TRUNK, OBJ_OPEN_BRASS_TRUNK use_crate
},
--OBJ_POTASH (this is actually oil when frame_n == 4)
[235]={
--on
--OBJ_CLOSED_DOOR
[179]=use_oil_on_door,
--OBJ_DOOR3
[227]=use_oil_on_door,
--OBJ_CLOSED_HATCH
[421]=use_oil_on_door,
--OBJ_DOOR
[152]=use_oil_on_door,
--OBJ_DOOR1
[219]=use_oil_on_door,
--OBJ_DOOR2
[222]=use_oil_on_door,
[0]=use_oil_on_dream_door,
},
--OBJ_SCROLL
[243]=use_reading_material,
--OBJ_SPRAY_GUN
[261]={
--on
[0]=use_spray_gun
},
--OBJ_MARTIAN_HOE
[263]={[255]=use_misc_text,[257]=use_misc_text}, --hole in ice, hole
--OBJ_MARTIAN_SHOVEL
[267]=use_shovel_on_tbl,
[273]={[86]=use_crate}, --Hammer needs more codes
--OBJ_CYMBALS
[280]=use_musical_instrument,
--OBJ_TAMBORINE
[281]=use_musical_instrument,
--OBJ_DRUM
[282]=use_musical_instrument,
--OBJ_ACCORDION
[283]=use_musical_instrument,
[284]=use_container,
--OBJ_SPITTOON
[286]=use_spittoon,
--OBJ_DREAM_MACHINE1
[288]=use_misc_text,
--OBJ_MARTIAN_CLOCK
[293]=use_misc_text,
--OBJ_HEADGEAR
[296]={
--on
[288]=use_head_gear, --OBJ_DREAM_MACHINE1
[289]=use_head_gear, --OBJ_DREAM_MACHINE2
},
--OBJ_SWITCH
[311]=use_switch_device,
--OBJ_SWITCH1
[312]=use_switch_device,
--OBJ_OXYGENATED_AIR_MACHINE
[323]=use_misc_text,
--OBJ_MARTIAN_PICK
[327]={[255]=use_misc_text,[257]=use_misc_text}, --hole in ice, hole
[331]=use_dreamstuff,
[399]=use_pool_table,
--OBJ_POOL_QUE
[401]=use_ready_obj,
[411]=use_switch_bar,
--OBJ_CLOSED_HATCH
[421]=use_door,
--OBJ_HEART_STONE
[426]={
--on
[287]= use_heartstone_on_metal_woman, --OBJ_METAL_WOMAN
},
[427]=use_misc_text,
--OBJ_ASSEMBLED_DRILL
[441]=use_assembled_drill,
--OBJ_PILE_OF_ROCKS
[442]=use_misc_text,
--OBJ_PILE_OF_IRON_ORE
[443]=use_misc_text,
--OBJ_PILE_OF_COAL
[444]=use_misc_text,
--OBJ_BLOCK_OF_RADIUM
[448]={
--on
[290]=use_radium, --OBJ_POWER_UNIT
[448]=use_radium, --OBJ_BLOCK_OF_RADIUM
},
--OBJ_CHIP_OF_RADIUM
[449]={
--on
[240]=use_radium, --OBJ_HEAT_RAY_GUN
[241]=use_radium, --OBJ_FREEZE_RAY_GUN
},
--OBJ_PANEL
[458]=use_panel,
}
function ready_winged_shoes(obj, actor)
local player_loc = player_get_location()
if player_loc.z == 2 then
local bridge = Obj.new(146)
bridge.temporary = false
Obj.moveToMap(bridge, 0xc9, 0x9b, 2)
end
return true
end
function ready_tongs(obj, actor)
printl("THE_TONGS_WILL_NOW_PROTECT_YOUR_HANDS")
return true
end
function ready_throw_rug(obj, actor)
obj.obj_n = 162 --Change to red cape
return true
end
local usecode_ready_obj_table = {
[15]=ready_winged_shoes,
[136]=ready_tongs,
[161]=ready_throw_rug,
}
function unready_winged_shoes(obj, actor)
printl("THEY_WONT_COME_OFF")
return false
end
local usecode_unready_obj_table = {
[15]=unready_winged_shoes,
}
function move_drill(obj, rel_x, rel_y)
if rel_x ~= 0 and rel_y ~= 0 then
return false
end
if rel_x < 0 then
obj.frame_n = 1
elseif rel_x > 0 then
obj.frame_n = 4
elseif rel_y < 0 then
obj.frame_n = 3
elseif rel_y > 0 then
obj.frame_n = 5
end
return true
end
function move_wheelbarrow(obj, rel_x, rel_y)
if rel_x ~= 0 and rel_y ~= 0 then
return false
end
if rel_x < 0 then
obj.frame_n = 3
elseif rel_x > 0 then
obj.frame_n = 1
elseif rel_y < 0 then
obj.frame_n = 0
elseif rel_y > 0 then
obj.frame_n = 2
end
return true
end
function move_rail_cart(obj, rel_x, rel_y)
local frame_n = obj.frame_n
if rel_x ~= 0 and rel_y ~= 0 then
printl("IT_WONT_GO_IN_THAT_DIRECTION")
return false
end
if (rel_x < 0 or rel_x > 0) and (frame_n == 1 or frame_n == 3 or frame_n == 5) then
printl("IT_WONT_GO_IN_THAT_DIRECTION")
return false
end
if (rel_y < 0 or rel_y > 0) and (frame_n == 0 or frame_n == 2 or frame_n == 4) then
printl("IT_WONT_GO_IN_THAT_DIRECTION")
return false
end
if check_for_track(obj, rel_x, rel_y) == false then
printl("IT_WONT_GO_IN_THAT_DIRECTION")
return false
end
move_car_obj(obj, rel_x, rel_y)
return false
end
function check_for_track(car, rel_x, rel_y)
local x = car.x + rel_x
local y = car.y + rel_y
for obj in objs_at_loc(x, y, car.z) do
if (obj.obj_n >= 412 and obj.obj_n <= 414) or obj.obj_n == 419 or obj.obj_n == 175 or obj.obj_n == 163 then --track object
local track_frame_n = obj.frame_n
if (car.frame_n % 2) == track_frame_n or track_frame_n == 2 or obj.obj_n == 412 or obj.obj_n == 175 or obj.obj_n == 163 then
return true
else
return false
end
elseif is_blood(obj.obj_n) == false and obj.obj_n ~= 417 then --MARTIAN_BARGE
return false
end
end
if map_get_obj(x, y, car.z, 175, true) then
return true
end
if map_get_obj(x, y, car.z, 412, true) then
return true
end
local tile_num = map_get_tile_num(x,y, car.z)
if is_track_tile(tile_num) then
return true
end
return false
end
function move_car_obj(obj, rel_x, rel_y)
obj.x = obj.x + rel_x
obj.y = obj.y + rel_y
return true
end
function move_plank(obj, rel_x, rel_y)
obj.x = obj.x + rel_x
obj.y = obj.y + rel_y
return true
end
function is_track_tile(tile_num)
if tile_num == 108 or tile_num == 109 or tile_num == 110 or tile_num == 77 or tile_num == 79 then
return true
end
return false
end
local usecode_move_obj_table = {
[268]=move_wheelbarrow,
[395]=move_plank,
[410]=move_rail_cart,
[441]=move_drill,
}
function has_usecode(obj, usecode_type)
--print("has_usecode("..obj.obj_n..", "..usecode_type..")\n")
if usecode_type == USE_EVENT_USE and usecode_table[obj.obj_n] ~= nil then
return true
elseif usecode_type == USE_EVENT_READY and (usecode_ready_obj_table[obj.obj_n] ~= nil or usecode_unready_obj_table[obj.obj_n] ~= nil)then
return true
elseif usecode_type == USE_EVENT_MOVE and usecode_move_obj_table[obj.obj_n] ~= nil then
return true
end
return false
end
function use_obj_on_to(obj, target_obj, actor, use_to_tbl)
local dir = get_direction(i18n("TO"))
if dir == nil then
printl("NOTHING")
return
end
local to_x, to_y = direction_get_loc(dir, actor.x, actor.y)
local to_obj = map_get_obj(to_x, to_y, actor.z)
if to_obj ~= nil then
print(to_obj.name.."\n\n")
local func = use_to_tbl[to_obj.obj_n]
if func ~= nil then
func(obj, target_obj, to_obj, actor)
end
else
printl("SOMETHING")
end
end
function use_obj_on(obj, actor, use_on_tbl)
local dir = get_direction(i18n("ON"))
if dir == nil then
printl("NOTHING")
return
end
local target_x, target_y = direction_get_loc(dir, actor.x, actor.y)
local target_entity = map_get_actor(target_x, target_y, actor.z)
if target_entity == nil then
target_entity = map_get_obj(target_x, target_y, actor.z)
end
if target_entity ~= nil then
print(target_entity.name.."\n\n")
local on = use_on_tbl[target_entity.obj_n]
if on ~= nil then
if type(on) == "function" then
local func = on
func(obj, target_entity, actor)
else
use_obj_on_to(obj, target_entity, actor, on)
end
else
local func = use_on_tbl[0]
if func ~= nil then
func(obj, target_entity, actor)
else
printl("NO_EFFECT")
end
end
else
local func = use_on_tbl[0]
if func ~= nil then
func(obj, nil, actor, target_x, target_y, actor.z)
else
printl("NOTHING")
end
end
end
function can_interact_with_obj(actor, obj)
if obj.on_map then
--FIXME get_combat_range()
local distance = actor_find_max_wrapped_xy_distance(actor, obj.x, obj.y)
if actor_is_affected_by_purple_berries(actor.actor_num) and distance <= actor.level then
return true
end
if distance > 1 then
printl("OUT_OF_RANGE")
return false
end
end
return true
end
function use_obj(obj, actor)
if not can_interact_with_obj(actor, obj) then
return
end
if type(usecode_table[obj.obj_n]) == "function" then
local func = usecode_table[obj.obj_n]
if func ~= nil then
print("\n")
func(obj, actor)
end
else
use_obj_on(obj, actor, usecode_table[obj.obj_n])
end
update_objects_around_party()
end
function ready_obj(obj, actor)
if type(usecode_ready_obj_table[obj.obj_n]) == "function" and obj.readied == false then
local func = usecode_ready_obj_table[obj.obj_n]
if func ~= nil then
print("\n")
return func(obj, actor)
end
end
if type(usecode_unready_obj_table[obj.obj_n]) == "function" and obj.readied == true then
local func = usecode_unready_obj_table[obj.obj_n]
if func ~= nil then
print("\n")
return func(obj, actor)
end
end
return true
end
function move_obj(obj, rel_x, rel_y)
if usecode_move_obj_table[obj.obj_n] ~= nil then
return usecode_move_obj_table[obj.obj_n](obj, rel_x, rel_y)
end
return true
end
function is_ranged_select(operation)
return actor_is_affected_by_purple_berries(Actor.get_player_actor().actor_num)
end | gpl-2.0 |
maikerumine/aftermath | mods/default/crafting.lua | 2 | 29837 | -- mods/default/crafting.lua
minetest.register_craft({
output = 'default:wood 4',
recipe = {
{'default:tree'},
}
})
minetest.register_craft({
output = 'default:junglewood 4',
recipe = {
{'default:jungletree'},
}
})
minetest.register_craft({
output = 'default:pine_wood 4',
recipe = {
{'default:pine_tree'},
}
})
minetest.register_craft({
output = 'default:acacia_wood 4',
recipe = {
{'default:acacia_tree'},
}
})
minetest.register_craft({
output = 'default:aspen_wood 4',
recipe = {
{'default:aspen_tree'},
}
})
minetest.register_craft({
output = 'default:wood',
recipe = {
{'default:bush_stem'},
}
})
minetest.register_craft({
output = 'default:acacia_wood',
recipe = {
{'default:acacia_bush_stem'},
}
})
minetest.register_craft({
output = 'default:stick 4',
recipe = {
{'group:wood'},
}
})
minetest.register_craft({
output = 'default:wood',
recipe = {
{'group:stick', 'group:stick'},
{'group:stick', 'group:stick'},
}
})
minetest.register_craft({
output = 'default:stick 6',
recipe = {
{'default:dry_shrub', 'default:dry_shrub', 'default:dry_shrub'},
{'default:dry_shrub', 'default:dry_shrub', 'default:dry_shrub'},
{'default:dry_shrub', 'default:dry_shrub', 'default:dry_shrub'},
}
})
minetest.register_craft({
output = 'default:sign_wall_steel 3',
recipe = {
{'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'},
{'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'},
{'', 'group:stick', ''},
}
})
minetest.register_craft({
output = 'default:sign_wall_wood 3',
recipe = {
{'group:wood', 'group:wood', 'group:wood'},
{'group:wood', 'group:wood', 'group:wood'},
{'', 'group:stick', ''},
}
})
minetest.register_craft({
output = 'default:fence_wood 2',
recipe = {
{'group:stick', 'group:stick', 'group:stick'},
{'group:stick', 'group:stick', 'group:stick'},
}
})
minetest.register_craft({
output = 'default:torch 4',
recipe = {
{'default:coal_lump'},
{'group:stick'},
}
})
minetest.register_craft({
output = 'default:pick_wood',
recipe = {
{'group:wood', 'group:wood', 'group:wood'},
{'default:duct_tape', 'group:stick', ''},
{'', 'group:stick', ''},
}
})
minetest.register_craft({
output = 'default:pick_stone',
recipe = {
{'group:stone', 'group:stone', 'group:stone'},
{'default:duct_tape', 'group:stick', ''},
{'', 'group:stick', ''},
}
})
minetest.register_craft({
output = 'default:pick_steel',
recipe = {
{'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'},
{'default:duct_tape', 'group:stick', ''},
{'', 'group:stick', ''},
}
})
minetest.register_craft({
output = 'default:pick_bronze',
recipe = {
{'default:bronze_ingot', 'default:bronze_ingot', 'default:bronze_ingot'},
{'', 'group:stick', ''},
{'default:duct_tape', 'group:stick', ''},
}
})
--[[
minetest.register_craft({
output = 'default:pick_mese',
recipe = {
{'default:mese_crystal', 'default:mese_crystal', 'default:mese_crystal'},
{'', 'group:stick', ''},
{'', 'group:stick', ''},
}
})
minetest.register_craft({
output = 'default:pick_diamond',
recipe = {
{'default:diamond', 'default:diamond', 'default:diamond'},
{'', 'group:stick', ''},
{'', 'group:stick', ''},
}
})
]]
--moreores
minetest.register_craft({
output = 'default:pick_mithril',
recipe = {
{'default:mithril_ingot', 'default:mithril_ingot', 'default:mithril_ingot'},
{'', 'group:stick', ''},
{'default:duct_tape', 'group:stick', ''},
}
})
minetest.register_craft({
output = 'default:shovel_wood',
recipe = {
{'default:duct_tape','group:wood',''},
{'','group:stick',''},
{'','group:stick',''},
}
})
minetest.register_craft({
output = 'default:shovel_stone',
recipe = {
{'default:duct_tape','group:stone',''},
{'','group:stick',''},
{'','group:stick',''},
}
})
minetest.register_craft({
output = 'default:shovel_steel',
recipe = {
{'default:duct_tape','default:steel_ingot',''},
{'','group:stick',''},
{'','group:stick',''},
}
})
minetest.register_craft({
output = 'default:shovel_bronze',
recipe = {
{'default:duct_tape','default:bronze_ingot',''},
{'','group:stick',''},
{'','group:stick',''},
}
})
--[[
minetest.register_craft({
output = 'default:shovel_mese',
recipe = {
{'default:mese_crystal'},
{'group:stick'},
{'group:stick'},
}
})
minetest.register_craft({
output = 'default:shovel_diamond',
recipe = {
{'default:diamond'},
{'group:stick'},
{'group:stick'},
}
})
]]
minetest.register_craft({
output = 'default:axe_wood',
recipe = {
{'group:wood', 'group:wood',''},
{'group:wood', 'group:stick',''},
{'', 'group:stick','default:duct_tape'},
}
})
minetest.register_craft({
output = 'default:axe_stone',
recipe = {
{'group:stone', 'group:stone',''},
{'group:stone', 'group:stick',''},
{'', 'group:stick','default:duct_tape'},
}
})
minetest.register_craft({
output = 'default:axe_steel',
recipe = {
{'default:steel_ingot', 'default:steel_ingot',''},
{'default:steel_ingot', 'group:stick',''},
{'', 'group:stick','default:duct_tape',},
}
})
minetest.register_craft({
output = 'default:axe_bronze',
recipe = {
{'default:bronze_ingot', 'default:bronze_ingot',''},
{'default:bronze_ingot', 'group:stick',''},
{'', 'group:stick','default:duct_tape'},
}
})
--[[
minetest.register_craft({
output = 'default:axe_mese',
recipe = {
{'default:mese_crystal', 'default:mese_crystal'},
{'default:mese_crystal', 'group:stick'},
{'', 'group:stick'},
}
})
minetest.register_craft({
output = 'default:axe_diamond',
recipe = {
{'default:diamond', 'default:diamond'},
{'default:diamond', 'group:stick'},
{'', 'group:stick'},
}
})
]]
minetest.register_craft({
output = 'default:axe_wood',
recipe = {
{'','group:wood', 'group:wood'},
{'','group:stick', 'group:wood'},
{'default:duct_tape','group:stick',''},
}
})
minetest.register_craft({
output = 'default:axe_stone',
recipe = {
{'','group:stone', 'group:stone'},
{'','group:stick', 'group:stone'},
{'default:duct_tape','group:stick', ''},
}
})
minetest.register_craft({
output = 'default:axe_steel',
recipe = {
{'','default:steel_ingot', 'default:steel_ingot'},
{'','group:stick', 'default:steel_ingot'},
{'default:duct_tape','group:stick', ''},
}
})
minetest.register_craft({
output = 'default:axe_bronze',
recipe = {
{'','default:bronze_ingot', 'default:bronze_ingot'},
{'','group:stick', 'default:bronze_ingot'},
{'default:duct_tape','group:stick', ''},
}
})
--[[
minetest.register_craft({
output = 'default:axe_mese',
recipe = {
{'default:mese_crystal', 'default:mese_crystal'},
{'group:stick', 'default:mese_crystal'},
{'group:stick', ''},
}
})
minetest.register_craft({
output = 'default:axe_diamond',
recipe = {
{'default:diamond', 'default:diamond'},
{'group:stick', 'default:diamond'},
{'group:stick', ''},
}
})
]]
minetest.register_craft({
output = 'default:bokken',
recipe = {
{'','group:wood',''},
{'','group:wood',''},
{'default:duct_tape','group:stick',''},
}
})
minetest.register_craft({
output = 'default:club_stone',
recipe = {
{'','group:stone',''},
{'','group:stone',''},
{'default:duct_tape','group:stick',''},
}
})
minetest.register_craft({
output = 'default:machete_steel',
recipe = {
{'','default:steel_ingot',''},
{'','default:steel_ingot',''},
{'default:duct_tape','group:stick',''},
}
})
minetest.register_craft({
output = 'default:machete_bronze',
recipe = {
{'','default:bronze_ingot',''},
{'','default:bronze_ingot',''},
{'default:duct_tape','group:stick',''},
}
})
--[[
minetest.register_craft({
output = 'default:sword_mese',
recipe = {
{'default:mese_crystal'},
{'default:mese_crystal'},
{'group:stick'},
}
})
minetest.register_craft({
output = 'default:sword_diamond',
recipe = {
{'default:diamond'},
{'default:diamond'},
{'group:stick'},
}
})
]]
--moreores
minetest.register_craft({
output = 'default:sword_mithril',
recipe = {
{'','default:mithril_ingot',''},
{'','default:mithril_ingot',''},
{'default:duct_tape','group:stick',''},
}
})
minetest.register_craft({
output = 'default:skeleton_key',
recipe = {
{'default:gold_ingot'},
}
})
minetest.register_craft({
output = 'default:chest',
recipe = {
{'group:wood', 'group:wood', 'group:wood'},
{'group:wood', '', 'group:wood'},
{'group:wood', 'group:wood', 'group:wood'},
}
})
minetest.register_craft({
output = 'default:chest_locked',
recipe = {
{'group:wood', 'group:wood', 'group:wood'},
{'group:wood', 'default:steel_ingot', 'group:wood'},
{'group:wood', 'group:wood', 'group:wood'},
}
})
minetest.register_craft( {
type = "shapeless",
output = "default:chest_locked",
recipe = {"default:chest", "default:steel_ingot"},
})
minetest.register_craft({
output = 'default:furnace',
recipe = {
{'group:stone', 'group:stone', 'group:stone'},
{'group:stone', 'default:dry_shrub', 'group:stone'},
{'group:stone', 'group:stone', 'group:stone'},
}
})
minetest.register_craft({
type = "shapeless",
output = "default:bronze_ingot",
recipe = {"default:steel_ingot", "default:copper_ingot"},
})
minetest.register_craft({
type = "shapeless",
output = "default:bronze_ingot",
recipe = {"default:tin_ingot", "default:copper_ingot"},
})
minetest.register_craft({
output = 'default:coalblock',
recipe = {
{'default:coal_lump', 'default:coal_lump', 'default:coal_lump'},
{'default:coal_lump', 'default:coal_lump', 'default:coal_lump'},
{'default:coal_lump', 'default:coal_lump', 'default:coal_lump'},
}
})
minetest.register_craft({
output = 'default:coal_lump 9',
recipe = {
{'default:coalblock'},
}
})
minetest.register_craft({
output = 'default:steelblock',
recipe = {
{'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'},
{'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'},
{'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'},
}
})
minetest.register_craft({
output = 'default:steel_ingot 9',
recipe = {
{'default:steelblock'},
}
})
minetest.register_craft({
output = 'default:copperblock',
recipe = {
{'default:copper_ingot', 'default:copper_ingot', 'default:copper_ingot'},
{'default:copper_ingot', 'default:copper_ingot', 'default:copper_ingot'},
{'default:copper_ingot', 'default:copper_ingot', 'default:copper_ingot'},
}
})
minetest.register_craft({
output = 'default:copper_ingot 9',
recipe = {
{'default:copperblock'},
}
})
minetest.register_craft({
output = 'default:bronzeblock',
recipe = {
{'default:bronze_ingot', 'default:bronze_ingot', 'default:bronze_ingot'},
{'default:bronze_ingot', 'default:bronze_ingot', 'default:bronze_ingot'},
{'default:bronze_ingot', 'default:bronze_ingot', 'default:bronze_ingot'},
}
})
minetest.register_craft({
output = 'default:bronze_ingot 9',
recipe = {
{'default:bronzeblock'},
}
})
minetest.register_craft({
output = 'default:goldblock',
recipe = {
{'default:gold_ingot', 'default:gold_ingot', 'default:gold_ingot'},
{'default:gold_ingot', 'default:gold_ingot', 'default:gold_ingot'},
{'default:gold_ingot', 'default:gold_ingot', 'default:gold_ingot'},
}
})
minetest.register_craft({
output = 'default:gold_ingot 9',
recipe = {
{'default:goldblock'},
}
})
minetest.register_craft({
output = 'default:diamondblock',
recipe = {
{'default:diamond', 'default:diamond', 'default:diamond'},
{'default:diamond', 'default:diamond', 'default:diamond'},
{'default:diamond', 'default:diamond', 'default:diamond'},
}
})
minetest.register_craft({
output = 'default:diamond 9',
recipe = {
{'default:diamondblock'},
}
})
--moreores
minetest.register_craft({
output = 'default:tinblock',
recipe = {
{'default:tin_ingot', 'default:tin_ingot', 'default:tin_ingot'},
{'default:tin_ingot', 'default:tin_ingot', 'default:tin_ingot'},
{'default:tin_ingot', 'default:tin_ingot', 'default:tin_ingot'},
}
})
minetest.register_craft({
output = 'default:tin_ingot 9',
recipe = {
{'default:tinblock'},
}
})
minetest.register_craft({
output = 'default:silverblock',
recipe = {
{'default:silver_ingot', 'default:silver_ingot', 'default:silver_ingot'},
{'default:silver_ingot', 'default:silver_ingot', 'default:silver_ingot'},
{'default:silver_ingot', 'default:silver_ingot', 'default:silver_ingot'},
}
})
minetest.register_craft({
output = 'default:silver_ingot 9',
recipe = {
{'default:silverblock'},
}
})
minetest.register_craft({
output = 'default:mithrilblock',
recipe = {
{'default:mithril_ingot', 'default:mithril_ingot', 'default:mithril_ingot'},
{'default:mithril_ingot', 'default:mithril_ingot', 'default:mithril_ingot'},
{'default:mithril_ingot', 'default:mithril_ingot', 'default:mithril_ingot'},
}
})
minetest.register_craft({
output = 'default:mithril_ingot 9',
recipe = {
{'default:mithrilblock'},
}
})
--stones
minetest.register_craft({
output = 'default:sandstone',
recipe = {
{'group:sand', 'group:sand'},
{'group:sand', 'group:sand'},
}
})
minetest.register_craft({
output = 'default:sand 4',
recipe = {
{'default:sandstone'},
}
})
minetest.register_craft({
output = 'default:sandstonebrick 4',
recipe = {
{'default:sandstone', 'default:sandstone'},
{'default:sandstone', 'default:sandstone'},
}
})
minetest.register_craft({
output = 'default:sandstone_block 9',
recipe = {
{'default:sandstone', 'default:sandstone', 'default:sandstone'},
{'default:sandstone', 'default:sandstone', 'default:sandstone'},
{'default:sandstone', 'default:sandstone', 'default:sandstone'},
}
})
minetest.register_craft({
output = "default:desert_sandstone",
recipe = {
{"default:desert_sand", "default:desert_sand"},
{"default:desert_sand", "default:desert_sand"},
}
})
minetest.register_craft({
output = "default:desert_sand 4",
recipe = {
{"default:desert_sandstone"},
}
})
minetest.register_craft({
output = "default:desert_sandstone_brick 4",
recipe = {
{"default:desert_sandstone", "default:desert_sandstone"},
{"default:desert_sandstone", "default:desert_sandstone"},
}
})
minetest.register_craft({
output = "default:desert_sandstone_block 9",
recipe = {
{"default:desert_sandstone", "default:desert_sandstone", "default:desert_sandstone"},
{"default:desert_sandstone", "default:desert_sandstone", "default:desert_sandstone"},
{"default:desert_sandstone", "default:desert_sandstone", "default:desert_sandstone"},
}
})
minetest.register_craft({
output = "default:silver_sandstone",
recipe = {
{"default:silver_sand", "default:silver_sand"},
{"default:silver_sand", "default:silver_sand"},
}
})
minetest.register_craft({
output = "default:silver_sand 4",
recipe = {
{"default:silver_sandstone"},
}
})
minetest.register_craft({
output = "default:silver_sandstone_brick 4",
recipe = {
{"default:silver_sandstone", "default:silver_sandstone"},
{"default:silver_sandstone", "default:silver_sandstone"},
}
})
minetest.register_craft({
output = "default:silver_sandstone_block 9",
recipe = {
{"default:silver_sandstone", "default:silver_sandstone", "default:silver_sandstone"},
{"default:silver_sandstone", "default:silver_sandstone", "default:silver_sandstone"},
{"default:silver_sandstone", "default:silver_sandstone", "default:silver_sandstone"},
}
})
minetest.register_craft({
output = 'default:clay',
recipe = {
{'default:clay_lump', 'default:clay_lump'},
{'default:clay_lump', 'default:clay_lump'},
}
})
minetest.register_craft({
output = 'default:brick',
recipe = {
{'default:clay_brick', 'default:clay_brick'},
{'default:clay_brick', 'default:clay_brick'},
}
})
minetest.register_craft({
output = 'default:clay_brick 4',
recipe = {
{'default:brick'},
}
})
minetest.register_craft({
output = 'default:paper',
recipe = {
{'default:papyrus', 'default:papyrus', 'default:papyrus'},
}
})
minetest.register_craft({
output = 'default:book',
recipe = {
{'default:paper'},
{'default:paper'},
{'default:paper'},
}
})
minetest.register_craft({
output = 'default:bookshelf',
recipe = {
{'group:wood', 'group:wood', 'group:wood'},
{'default:book', 'default:book', 'default:book'},
{'group:wood', 'group:wood', 'group:wood'},
}
})
minetest.register_craft({
output = 'default:ladder',
recipe = {
{'group:stick', '', 'group:stick'},
{'group:stick', 'group:stick', 'group:stick'},
{'group:stick', '', 'group:stick'},
}
})
minetest.register_craft({
output = 'default:ladder_steel 15',
recipe = {
{'default:steel_ingot', '', 'default:steel_ingot'},
{'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'},
{'default:steel_ingot', '', 'default:steel_ingot'},
}
})
minetest.register_craft({
output = 'default:ladder_steel 15',
recipe = {
{'default:tin_ingot', '', 'default:tin_ingot'},
{'default:tin_ingot', 'default:tin_ingot', 'default:tin_ingot'},
{'default:tin_ingot', '', 'default:tin_ingot'},
}
})
minetest.register_craft({
output = 'default:mese',
recipe = {
{'default:mese_crystal', 'default:mese_crystal', 'default:mese_crystal'},
{'default:mese_crystal', 'default:mese_crystal', 'default:mese_crystal'},
{'default:mese_crystal', 'default:mese_crystal', 'default:mese_crystal'},
}
})
minetest.register_craft({
output = 'default:meselamp 1',
recipe = {
{'', 'default:mese_crystal',''},
{'default:mese_crystal', 'default:glass', 'default:mese_crystal'},
}
})
minetest.register_craft({
output = "default:mese_post_light 3",
recipe = {
{"", "default:glass", ""},
{"default:mese_crystal", "default:mese_crystal", "default:mese_crystal"},
{"", "group:wood", ""},
}
})
minetest.register_craft({
output = 'default:mese_crystal 9',
recipe = {
{'default:mese'},
}
})
--Playing with a new mese recipie mobs_futuremobs:alien_skin
minetest.register_craft({
output = 'default:mese_crystal_fragment_stasis 4',
recipe = {
{'', 'mobs_futuremobs:alien_skin',''},
{'default:obsidian_shard', 'default:copper_ingot', 'default:glass'},
}
})
minetest.register_craft({
output = 'default:mese_crystal_fragment_stasis 4',
recipe = {
{'', 'mobs_futuremobs:alien_skin',''},
{'default:obsidian_shard', 'default:tin_ingot', 'default:glass'},
}
})
minetest.register_craft({
output = 'default:mese_crystal_fragment_stasis 4',
recipe = {
{'', 'mobs_futuremobs:alien_skin',''},
{'default:obsidian_shard', 'default:silver_ingot', 'default:glass'},
}
})
minetest.register_craft({
output = 'default:mese_crystal 4',
recipe = {
{'', 'mobs_futuremobs:claw',''},
{'', 'default:mese_crystal_fragment_stasis', ''},
}
})
minetest.register_craft({
output = 'default:duct_tape 4',
recipe = {
{'default:glue','default:paper','default:glue'},
{'default:glue','default:glue','default:glue'},
{'default:glue','default:paper','default:glue'},
}
})
minetest.register_craft({
output = 'default:mese_crystal_fragment 9',
recipe = {
{'default:mese_crystal'},
}
})
minetest.register_craft({
output = 'default:mese_crystal',
recipe = {
{'default:mese_crystal_fragment', 'default:mese_crystal_fragment', 'default:mese_crystal_fragment'},
{'default:mese_crystal_fragment', 'default:mese_crystal_fragment', 'default:mese_crystal_fragment'},
{'default:mese_crystal_fragment', 'default:mese_crystal_fragment', 'default:mese_crystal_fragment'},
}
})
minetest.register_craft({
type = "cooking",
output = "default:mese_crystal_fragment",
recipe = "default:mese_crystal_fragment_stasis",
cooktime = 40,
})
minetest.register_craft({
output = 'default:meselamp 1',
recipe = {
{'', 'default:mese_crystal',''},
{'default:mese_crystal', 'default:glass', 'default:mese_crystal'},
}
})
minetest.register_craft({
output = 'default:obsidian_shard 9',
recipe = {
{'default:obsidian'}
}
})
minetest.register_craft({
output = 'default:obsidian',
recipe = {
{'default:obsidian_shard', 'default:obsidian_shard', 'default:obsidian_shard'},
{'default:obsidian_shard', 'default:obsidian_shard', 'default:obsidian_shard'},
{'default:obsidian_shard', 'default:obsidian_shard', 'default:obsidian_shard'},
}
})
minetest.register_craft({
output = 'default:obsidianbrick 4',
recipe = {
{'default:obsidian', 'default:obsidian'},
{'default:obsidian', 'default:obsidian'}
}
})
minetest.register_craft({
output = 'default:obsidian_block 9',
recipe = {
{'default:obsidian', 'default:obsidian', 'default:obsidian'},
{'default:obsidian', 'default:obsidian', 'default:obsidian'},
{'default:obsidian', 'default:obsidian', 'default:obsidian'},
}
})
minetest.register_craft({
output = 'default:stonebrick 4',
recipe = {
{'default:stone', 'default:stone'},
{'default:stone', 'default:stone'},
}
})
minetest.register_craft({
output = 'default:stone_block 9',
recipe = {
{'default:stone', 'default:stone', 'default:stone'},
{'default:stone', 'default:stone', 'default:stone'},
{'default:stone', 'default:stone', 'default:stone'},
}
})
minetest.register_craft({
output = 'default:desert_stonebrick 4',
recipe = {
{'default:desert_stone', 'default:desert_stone'},
{'default:desert_stone', 'default:desert_stone'},
}
})
minetest.register_craft({
output = 'default:desert_stone_block 9',
recipe = {
{'default:desert_stone', 'default:desert_stone', 'default:desert_stone'},
{'default:desert_stone', 'default:desert_stone', 'default:desert_stone'},
{'default:desert_stone', 'default:desert_stone', 'default:desert_stone'},
}
})
minetest.register_craft({
output = 'default:snowblock',
recipe = {
{'default:snow', 'default:snow', 'default:snow'},
{'default:snow', 'default:snow', 'default:snow'},
{'default:snow', 'default:snow', 'default:snow'},
}
})
minetest.register_craft({
output = 'default:snow 9',
recipe = {
{'default:snowblock'},
}
})
minetest.register_craft({
output = 'default:cobble 5',
recipe = {
{'default:furnace'},
}
})
minetest.register_craft({
output = 'default:desert_cobble 3',
recipe = {
{'default:clay_brick',},
{'default:cobble', },
{'default:cobble', },
}
})
minetest.register_craft({
output = 'default:car_parts 6',
recipe = {
{'default:wrecked_car_1'},
}
})
--
-- Crafting (tool repair)
--
minetest.register_craft({
type = "toolrepair",
additional_wear = -0.02,
})
--
-- Cooking recipes
--
minetest.register_craft({
type = "cooking",
output = "default:mese_crystal",
recipe = "default:mese_crystal_fragment_stasis",
cooktime = 90,
})
minetest.register_craft({
type = "cooking",
output = "default:glass",
recipe = "group:sand",
})
minetest.register_craft({
type = "cooking",
output = "default:obsidian_glass",
recipe = "default:obsidian_shard",
})
minetest.register_craft({
type = "cooking",
output = "default:stone",
recipe = "default:cobble",
})
minetest.register_craft({
type = "cooking",
output = "default:stone",
recipe = "default:mossycobble",
})
minetest.register_craft({
type = "cooking",
output = "default:desert_stone",
recipe = "default:desert_cobble",
})
minetest.register_craft({
type = "cooking",
output = "default:steel_ingot",
recipe = "default:iron_lump",
})
minetest.register_craft({
type = "cooking",
output = "default:copper_ingot",
recipe = "default:copper_lump",
})
minetest.register_craft({
type = "cooking",
output = "default:gold_ingot",
recipe = "default:gold_lump",
})
--moreores
minetest.register_craft({
type = "cooking",
output = "default:tin_ingot",
recipe = "default:tin_lump",
})
minetest.register_craft({
type = "cooking",
output = "default:silver_ingot",
recipe = "default:silver_lump",
})
minetest.register_craft({
type = "cooking",
output = "default:mithril_ingot",
recipe = "default:mithril_lump",
})
minetest.register_craft({
type = "cooking",
output = "default:clay_brick",
recipe = "default:clay_lump",
})
minetest.register_craft({
type = 'cooking',
output = 'default:gold_ingot',
recipe = 'default:skeleton_key',
cooktime = 5,
})
minetest.register_craft({
type = 'cooking',
output = 'default:gold_ingot',
recipe = 'default:key',
cooktime = 5,
})
minetest.register_craft({
type = "cooking",
output = "default:coal_lump 3",
recipe = "default:dead_tree",
})
minetest.register_craft({
type = "cooking",
cooktime = 90,
output = "default:steel_ingot 5",
recipe = "default:car_parts",
})
--[[
--CUSTOM
minetest.register_craft({
type = "cooking",
cooktime = 90,
output = "default:machete_carbon_steel",
recipe = "default:machete_steel",
})
minetest.register_craft({
type = "cooking",
cooktime = 90,
output = "default:pick_carbon_steel",
recipe = "default:pick_steel",
})
minetest.register_craft({
type = "cooking",
cooktime = 90,
output = "default:bronze_ingot 2",
recipe = "default:sword_bronze",
})
minetest.register_craft({
type = "cooking",
cooktime = 90,
output = "default:bronze_ingot 2",
recipe = "default:pick_bronze",
})
minetest.register_craft({
type = "cooking",
cooktime = 15,
output = "default:glue 7",
recipe = "default:duct_tape",
})
minetest.register_craft({
type = "cooking",
cooktime = 60,
output = "default:steel_ingot 3",
recipe = "default:ladder_steel",
})
minetest.register_craft({
type = "cooking",
cooktime = 60,
output = "default:steel_ingot 2",
recipe = "default:sign_wall_steel",
})
minetest.register_craft({
type = "cooking",
cooktime = 60,
output = "default:steel_ingot 1",
recipe = "default:shovel_steel",
})
minetest.register_craft({
type = "cooking",
cooktime = 60,
output = "default:bronze_ingot 1",
recipe = "default:shovel_bronze",
})
minetest.register_craft({
type = "cooking",
cooktime = 60,
output = "default:steel_ingot 2",
recipe = "default:axe_steel",
})
minetest.register_craft({
type = "cooking",
cooktime = 60,
output = "default:bronze_ingot 2",
recipe = "default:axe_bronze",
})
]]
--
-- Fuels
--
-- Support use of group:tree
minetest.register_craft({
type = "fuel",
recipe = "group:tree",
burntime = 30,
})
-- Burn time for all woods are in order of wood density,
-- which is also the order of wood colour darkness:
-- aspen, pine, apple, acacia, jungle
minetest.register_craft({
type = "fuel",
recipe = "default:aspen_tree",
burntime = 22,
})
minetest.register_craft({
type = "fuel",
recipe = "default:pine_tree",
burntime = 26,
})
minetest.register_craft({
type = "fuel",
recipe = "default:tree",
burntime = 30,
})
minetest.register_craft({
type = "fuel",
recipe = "default:acacia_tree",
burntime = 34,
})
minetest.register_craft({
type = "fuel",
recipe = "default:jungletree",
burntime = 38,
})
-- Support use of group:wood
minetest.register_craft({
type = "fuel",
recipe = "group:wood",
burntime = 7,
})
minetest.register_craft({
type = "fuel",
recipe = "default:aspen_wood",
burntime = 5,
})
minetest.register_craft({
type = "fuel",
recipe = "default:pine_wood",
burntime = 6,
})
minetest.register_craft({
type = "fuel",
recipe = "default:wood",
burntime = 7,
})
minetest.register_craft({
type = "fuel",
recipe = "default:acacia_wood",
burntime = 8,
})
minetest.register_craft({
type = "fuel",
recipe = "default:junglewood",
burntime = 9,
})
-- Support use of group:sapling
minetest.register_craft({
type = "fuel",
recipe = "group:sapling",
burntime = 10,
})
minetest.register_craft({
type = "fuel",
recipe = "default:aspen_sapling",
burntime = 8,
})
minetest.register_craft({
type = "fuel",
recipe = "default:pine_sapling",
burntime = 9,
})
minetest.register_craft({
type = "fuel",
recipe = "default:sapling",
burntime = 10,
})
minetest.register_craft({
type = "fuel",
recipe = "default:acacia_sapling",
burntime = 11,
})
minetest.register_craft({
type = "fuel",
recipe = "default:junglesapling",
burntime = 12,
})
minetest.register_craft({
type = "fuel",
recipe = "default:fence_aspen_wood",
burntime = 11,
})
minetest.register_craft({
type = "fuel",
recipe = "default:fence_pine_wood",
burntime = 13,
})
minetest.register_craft({
type = "fuel",
recipe = "default:fence_wood",
burntime = 15,
})
minetest.register_craft({
type = "fuel",
recipe = "default:fence_acacia_wood",
burntime = 17,
})
minetest.register_craft({
type = "fuel",
recipe = "default:fence_junglewood",
burntime = 19,
})
minetest.register_craft({
type = "fuel",
recipe = "default:bush_stem",
burntime = 7,
})
minetest.register_craft({
type = "fuel",
recipe = "default:acacia_bush_stem",
burntime = 8,
})
minetest.register_craft({
type = "fuel",
recipe = "default:junglegrass",
burntime = 2,
})
minetest.register_craft({
type = "fuel",
recipe = "group:leaves",
burntime = 1,
})
minetest.register_craft({
type = "fuel",
recipe = "default:cactus",
burntime = 15,
})
minetest.register_craft({
type = "fuel",
recipe = "default:papyrus",
burntime = 1,
})
minetest.register_craft({
type = "fuel",
recipe = "default:bookshelf",
burntime = 30,
})
minetest.register_craft({
type = "fuel",
recipe = "default:ladder_wood",
burntime = 5,
})
minetest.register_craft({
type = "fuel",
recipe = "default:lava_source",
burntime = 60,
})
minetest.register_craft({
type = "fuel",
recipe = "default:torch",
burntime = 4,
})
minetest.register_craft({
type = "fuel",
recipe = "default:sign_wall_wood",
burntime = 10,
})
minetest.register_craft({
type = "fuel",
recipe = "default:chest",
burntime = 30,
})
minetest.register_craft({
type = "fuel",
recipe = "default:chest_locked",
burntime = 30,
})
minetest.register_craft({
type = "fuel",
recipe = "default:apple",
burntime = 3,
})
minetest.register_craft({
type = "fuel",
recipe = "default:coal_lump",
burntime = 40,
})
minetest.register_craft({
type = "fuel",
recipe = "default:coalblock",
burntime = 370,
})
minetest.register_craft({
type = "fuel",
recipe = "default:grass_1",
burntime = 2,
})
minetest.register_craft({
type = "fuel",
recipe = "default:dry_grass_1",
burntime = 2,
})
| lgpl-2.1 |
delram/seed3 | bot/seedbot.lua | 2 | 10658 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '1.0'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
-- mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"download_media",
"plugins",
"invite",
"all",
"leave_ban"
},
sudo_users = {94477327,94389886},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[🔥 ħʍď ąɲţɨ-şpąʍʍ€ŕ 🔥 V3.8
Manager: @Farzadhmd1 & Developer: @GenerousMan_Bot
]],
help_text_realm = [[
Realm Commands:
!creategroup [Name]
Create a group
!createrealm [Name]
Create a realm
!setname [Name]
Set realm name
!setabout [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
!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
!log
Grt a logfile of current group or realm
!broadcast [text]
!broadcast Hello !
Send text to all groups
Only sudo users can run this command
!br [group_id] [text]
!br 123456789 Hello !
This command will send text to [group_id]
**U can use both "/" and "!"
*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 = [[
⚜لیست دستورات⚜
1=sik
برای حذف کردن از گروه با
(id)و(username)و(reply)
انجام دهید
2=ban
برای حذف غیرقابل برگشت
بن رامیتوانیدبا
(id)و(username)و(reply)
انجام دهید
3=unban
برای در اوردن از حذف غیرقابل برگشت
این دستور را میتوانیدبا
(id)و(username)و(reply)
انجام دهید
4=who
لیست افراد گروه
5=modlist
لیست ادمین های گپ
6=promote
اضافه کردن ادمین به گپ
7=demote
حذف کردن ادمین از گپ
8=sikme
لفت دادن از گروه
9=setphoto
تعویض عکس گروه بعد از ارسال این دستور عکس را ارسال کنید
10=setname
تعویض اسم ابتدا دستور را نوشته سپس یک فاصله گزاشته و بعد اسم جدید را تایپ کنید
11=id
گرفتن ایدی فقط با رپلی روی پیام شخص
12=lock
name_member_bots_arabic_photo_flood
برای قفل کردن اسم و عکس و ربات و ادد و زبان فارسی و اسپم به کار میرود
13=unlock
name_member_bots_arabic_photo_flood
برای حذف قفل اسم و عکس و ربات و ادد و زبان فارسی و اسپم به کار میرود
14=newlink
برای تعویض لینک به کار میرود
15=link
برای گرفتن لینک به کار میرود
16=setflood 5_20
برای تنظیم تعداد پیام اسپم برای کیک کردن خودکار
17_clean
member_modlist_rulesبرای پاک کردن دسته جمعی:اعضا و ادمین ها و قانون
18=res @username
برای گرفتن ایدی از طریق یوزر نیم
19=banlist
اسامی افراد بن شده از گپ
20=settings
مشاهده تنظیمات گروه
🔷🔷🔷🔷🔷🔷🔷🔷🔷🔷🔷🔷
توجه
1⃣ شما میتوانید اول دستورات
!_/_#_@_$_خالی
بگزارید
2⃣ادمین ها میتوانند
کیک+بن+آن بن+تعویض لینک+گرفتن لینک+عوض کردن اسم+عوض کردن عکس+تمامی قفل ها+حذف تمامی قفل ها+گزاشتن قانون
3⃣اونر ها میتوانند کل کار های ادمین هارا انجام دهند+ادمین کردن+حذف ادمین
🔥 ħʍď ąɲţɨ-şpąʍʍ€ŕ 🔥
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
mrbangi/mr-bangi | plugins/welcome.lua | 1 | 3485 | local add_user_cfg = load_from_file('data/add_user_cfg.lua')
local function template_add_user(base, to_username, from_username, chat_name, chat_id)
base = base or ''
to_username = '@' .. (to_username or '')
from_username = '@' .. (from_username or '')
chat_name = string.gsub(chat_name, '_', ' ') or ''
chat_id = "chat#id" .. (chat_id or '')
if to_username == "@" then
to_username = ''
end
if from_username == "@" then
from_username = ''
end
base = string.gsub(base, "{to_username}", to_username)
base = string.gsub(base, "{from_username}", from_username)
base = string.gsub(base, "{chat_name}", chat_name)
base = string.gsub(base, "{chat_id}", chat_id)
return base
end
function chat_new_user_link(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.from.username
local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')'
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
function chat_new_user(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.action.user.username
local from_username = msg.from.username
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
local function description_rules(msg, nama)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
local about = ""
local rules = ""
if data[tostring(msg.to.id)]["description"] then
about = data[tostring(msg.to.id)]["description"]
about = "\nAbout :\n"..about.."\n"
end
if data[tostring(msg.to.id)]["rules"] then
rules = data[tostring(msg.to.id)]["rules"]
rules = "\nRules :\n"..rules.."\n"
end
local sambutan = "Hi "..nama.."\nWelcome'"..string.gsub(msg.to.print_name, "_", " ").."'\n"
local text = sambutan..about..rules.."\n"
local receiver = get_receiver(msg)
send_large_msg(receiver, text, ok_cb, false)
end
end
local function run(msg, matches)
if not msg.service then
return "Are you trying to troll me?"
end
--vardump(msg)
if matches[1] == "chat_add_user" then
if not msg.action.user.username then
nama = string.gsub(msg.action.user.print_name, "_", " ")
else
nama = "@"..msg.action.user.username
end
chat_new_user(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_add_user_link" then
if not msg.from.username then
nama = string.gsub(msg.from.print_name, "_", " ")
else
nama = "@"..msg.from.username
end
chat_new_user_link(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_del_user" then
local bye_name = msg.action.user.first_name
return 'Sikout '..bye_name
end
end
return {
description = "Welcoming Message",
usage = "send message to new member",
patterns = {
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_add_user_link)$",
"^!!tgservice (chat_del_user)$",
},
run = run
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.