content
stringlengths 5
1.05M
|
---|
local skynet = require "skynet.manager"
local codecache = require "skynet.codecache"
local cluster = require "skynet.cluster"
local json = require("cjson")
local sprotoloader = require "sprotoloader"
local queue = require "skynet.queue"
local clusterMonitor = require "utils/clusterMonitor"
local TAG = "GateServiceMgr"
local GateServiceMgr = {}
function GateServiceMgr:init(pGameCode, pIdentify)
local pServerConfig = require(onGetServerConfigFile(pGameCode))
self.m_pGameCode = pGameCode
self.m_pHallServiceMgr = nil
self.m_pWatchDogs = {}
self.m_pAgentMap = {}
for k, v in pairs(pServerConfig.iGateServerConfig or {}) do
-- 监听玩家的登陆
local watchdog = skynet.newservice("watchdog")
local pRet = skynet.call(watchdog, "lua", "init",{
port = v.port,
maxclient = 1024,
nodelay = true,
})
table.insert(self.m_pWatchDogs, watchdog)
end
local host = sprotoloader.load(1):host("package")
self.m_pSendPackage = host:attach(sprotoloader.load(2))
-- 启动计时器
self.m_pScheduleMgr = require('utils/schedulerMgr')
self.m_pScheduleMgr:init()
local pCallback = self.onCheckTooTimeNotActive
self.m_pCheckActiveTimer = self.m_pScheduleMgr:register(pCallback, 5 * 60 * 1000, -1, 10 * 1000, self)
-- 确保自身数据初始化完毕再开启结点间链接
clusterMonitor:onSubscribeNode(self.onConnectChange)
clusterMonitor:onStart(pServerConfig.iClusterConfig)
self.m_pClusterId = clusterMonitor:onGetCurrentNodename()
clusterMonitor:onOpen()
end
function GateServiceMgr:onPrint()
Log.dump(TAG, self.m_pAgentMap, "self.m_pAgentMap")
end
function GateServiceMgr:onRegisterAgent(pAgent)
table.insert(self.m_pAgentMap, pAgent)
-- self:onPrint()
if not self.m_pHallServiceMgr then
Log.e(TAG, "hallservice disconnect error ")
return
end
local data = {}
data.iAgent = pAgent
data.iClusterId = self.m_pClusterId
pcall(skynet.call, self.m_pHallServiceMgr, "lua", "onUpdateGateServerData", string.format("%s_%s", self.m_pClusterId, pAgent), data)
end
function GateServiceMgr:ClientUserHeartbeat(pAgent, name, request)
local resName = "ServerUserHeartbeat"
local info = {}
local pRet = skynet.call(pAgent, "lua", "onSendPackage", resName, info)
end
function GateServiceMgr:onReceivePackage(pAgent, name, request )
if self[name] then
self[name](self, pAgent, name, request)
else
if self.m_pHallServiceMgr then
Log.d(TAG, "onReceivePackage[%s] self.m_pHallServiceMgr[%s]", name, self.m_pHallServiceMgr)
pcall(skynet.call, self.m_pHallServiceMgr, "lua", "onReceivePackage", string.format("%s_%s", self.m_pClusterId, pAgent), name, request)
else
Log.e(TAG, "hallservice disconnect error ")
end
end
end
function GateServiceMgr:onDisConnect(pAgent, pClearRedis)
for k, v in ipairs(self.m_pAgentMap) do
if v == pAgent then
table.remove(self.m_pAgentMap, k)
break
end
end
self:onPrint()
if self.m_pHallServiceMgr then
pcall(skynet.call, self.m_pHallServiceMgr, "lua", "onDisConnect", string.format("%s_%s", self.m_pClusterId, pAgent), pClearRedis)
else
Log.e(TAG, "hallservice disconnect error ")
end
end
function GateServiceMgr:onCheckTooTimeNotActive()
Log.d(TAG, "onCheckTooTimeNotActive")
for k, v in pairs(self.m_pAgentMap) do
local pRet = skynet.call(v, "lua", "onCheckTooTimeNotActive")
end
end
function GateServiceMgr:onPackLookbackTable(pLookbackTable)
--写入回看数据
local pIsAllOk = true
local pLookbackDataTable = {}
for _, kLookback in pairs(pLookbackTable) do
local pIsOk, pack = pcall(self.m_pSendPackage, kLookback.iName, kLookback.iInfo)
if not pIsOk then
Log.e(TAG, "kLookback.iName[%s]", kLookback.iName)
pIsAllOk = false
break
else
local package = string.pack(">s2", pack)
table.insert(pLookbackDataTable, package)
end
end
return pIsAllOk, json.encode(pLookbackDataTable)
end
function GateServiceMgr:onConnectChange( conf )
Log.dump(TAG,conf,"onConnectChange")
if conf.isonline == 1 then
self.m_pHallServiceMgr = cluster.proxy(conf.nodename, conf.clustername)
for k,v in pairs(self.m_pWatchDogs) do
local pRet = skynet.call(v, "lua", "start") -- 开启监听
end
else
for k,v in pairs(self.m_pWatchDogs) do
local pRet = skynet.call(v, "lua", "stop") -- 关闭监听
end
for k,v in ipairs(self.m_pAgentMap) do
local pRet = skynet.call(v, "lua", "close") -- 关闭所有agent
end
self.m_pHallServiceMgr = nil
end
end
function GateServiceMgr:onMonitorNodeChange(conf)
if not conf then return end
if not conf.nodename then return end
local callback = clusterMonitor:onGetSubcribeCallback()
if not callback then
return
end
return callback(GateServiceMgr,conf)
end
function GateServiceMgr:onReLoad()
local modulename = onGetServerConfigFile(self.m_pGameCode)
package.loaded[modulename] = nil
codecache.clear()
local pServerConfig = require(modulename)
clusterMonitor:onReLoad(pServerConfig.iClusterConfig)
end
-- 热更新协议
function GateServiceMgr:onUpdateProto(pProto)
-- local pProtoService = skynet.localname(".ProtoLoader")
local pProtoService = skynet.queryservice("protoLoader")
Log.e(TAG, "更新pProto,pProtoService[%s]", pProtoService)
pcall(skynet.call, pProtoService, "lua", "onUpdateProto", pProto)
end
skynet.start(function()
skynet.dispatch("lua", function(_, _, command, ...)
skynet.ret(skynet.pack(GateServiceMgr[command](GateServiceMgr, ...)))
end)
end)
|
-- Kong, the biggest ape in town
--
-- /\ ____
-- <> ( oo )
-- <>_| ^^ |_
-- <> @ \
-- /~~\ . . _ |
-- /~~~~\ | |
-- /~~~~~~\/ _| |
-- |[][][]/ / [m]
-- |[][][[m]
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[|--|]|
-- |[| |]|
-- ========
-- ==========
-- |[[ ]]|
-- ==========
--加载luarock.loader包以使用luarock
pcall(require, "luarocks.loader")
-- 检查resty.core包是否加载成功
assert(package.loaded["resty.core"], "lua-resty-core must be loaded; make " ..
"sure 'lua_load_resty_core' is not "..
"disabled.")
-- 引用constants.lua文件
local constants = require "kong.constants"
do
-- let's ensure the required shared dictionaries are
-- declared via lua_shared_dict in the Nginx conf
-- 遍历DICTS,
-- DICTS = {
-- "kong", 5m
-- "kong_locks", 8m
-- "kong_db_cache", 128m
-- "kong_db_cache_miss", 12m
-- "kong_process_events", 5m
-- "kong_cluster_events", 5m
-- "kong_healthchecks", 5m
-- "kong_rate_limiting_counters", 12m
-- }
for _, dict in ipairs(constants.DICTS) do
if not ngx.shared[dict] then
return error("missing shared dict '" .. dict .. "' in Nginx " ..
"configuration, are you using a custom template? " ..
"Make sure the 'lua_shared_dict " .. dict .. " [SIZE];' " ..
"directive is defined.")
end
end
-- if we're running `nginx -t` then don't initialize
-- 检查nginx配置文件的语法
-- 返回当前进程的环境变量的值,如果没有返回nil
if os.getenv("KONG_NGINX_CONF_CHECK") then
return {
init = function() end,
}
end
end
require("kong.globalpatches")()
local kong_global = require "kong.global"
local PHASES = kong_global.phases
_G.kong = kong_global.new() -- no versioned PDK for plugins for now
local DB = require "kong.db"
local dns = require "kong.tools.dns"
local utils = require "kong.tools.utils"
local lapis = require "lapis"
local pl_utils = require "pl.utils"
local http_tls = require "http.tls"
local openssl_ssl = require "openssl.ssl"
local openssl_pkey = require "openssl.pkey"
local openssl_x509 = require "openssl.x509"
local runloop = require "kong.runloop.handler"
local mesh = require "kong.runloop.mesh"
local singletons = require "kong.singletons"
local declarative = require "kong.db.declarative"
local ngx_balancer = require "ngx.balancer"
local kong_resty_ctx = require "kong.resty.ctx"
local certificate = require "kong.runloop.certificate"
local concurrency = require "kong.concurrency"
local cache_warmup = require "kong.cache_warmup"
local balancer_execute = require("kong.runloop.balancer").execute
local kong_error_handlers = require "kong.error_handlers"
local migrations_utils = require "kong.cmd.utils.migrations"
local kong = kong
local ngx = ngx
local now = ngx.now
local update_time = ngx.update_time
local var = ngx.var
local arg = ngx.arg
local header = ngx.header
local ngx_log = ngx.log
-- 日志级别
local ngx_ALERT = ngx.ALERT -- 报警
local ngx_CRIT = ngx.CRIT -- 严重,系统故障, 触发运维告警系统
local ngx_ERR = ngx.ERR -- 错误,业务不可恢复性错误
local ngx_WARN = ngx.WARN -- 提醒,业务中可忽略错误
local ngx_INFO = ngx.INFO -- 信息,业务琐碎日志信息,包含不同情况判断等
local ngx_DEBUG = ngx.DEBUG
local subsystem = ngx.config.subsystem
local type = type
local error = error
local ipairs = ipairs
local assert = assert
local tostring = tostring
local coroutine = coroutine
local getmetatable = getmetatable
local registry = debug.getregistry()
local get_last_failure = ngx_balancer.get_last_failure
local set_current_peer = ngx_balancer.set_current_peer
local set_ssl_ctx = ngx_balancer.set_ssl_ctx
local set_timeouts = ngx_balancer.set_timeouts
local set_more_tries = ngx_balancer.set_more_tries
local ffi = require "ffi"
local cast = ffi.cast
local voidpp = ffi.typeof("void**")
local TLS_SCHEMES = {
https = true,
tls = true,
}
local declarative_entities
local schema_state
local stash_init_worker_error
local log_init_worker_errors
-- 初始化worker错误并隐藏暂存
do
local init_worker_errors
local init_worker_errors_str
local ctx_k = {}
stash_init_worker_error = function(err)
if err == nil then
return
end
err = tostring(err)
if not init_worker_errors then
init_worker_errors = {}
end
table.insert(init_worker_errors, err)
init_worker_errors_str = table.concat(init_worker_errors, ", ")
return ngx_log(ngx_CRIT, "worker initialization error: ", err,
"; this node must be restarted")
end
log_init_worker_errors = function(ctx)
if not init_worker_errors_str or ctx[ctx_k] then
return
end
ctx[ctx_k] = true
return ngx_log(ngx_ALERT, "unsafe request processing due to earlier ",
"initialization errors; this node must be ",
"restarted (", init_worker_errors_str, ")")
end
end
-- 此代码块初始化kong的共享空间字典
local reset_kong_shm
do
local preserve_keys = {
"events:requests",
"kong:node_id",
}
reset_kong_shm = function()
local preserved = {}
for _, key in ipairs(preserve_keys) do
-- ignore errors
preserved[key] = ngx.shared.kong:get(key)
end
ngx.shared.kong:flush_all()
ngx.shared.kong:flush_expired(0)
for _, key in ipairs(preserve_keys) do
ngx.shared.kong:set(key, preserved[key])
end
end
end
local function execute_plugins_iterator(plugins_iterator, phase, ctx)
for plugin, configuration in plugins_iterator:iterate(phase, ctx) do
if ctx then
kong_global.set_named_ctx(kong, "plugin", configuration)
end
kong_global.set_namespaced_log(kong, plugin.name)
plugin.handler[phase](plugin.handler, configuration)
kong_global.reset_log(kong)
end
end
----------------------------------------------------------------
--- name: execute_cache_warmup
--- function: 执行缓存查找
--- param: kong_config string kong的配置文件 M
--- return: true 返回命中的值
--- nil 表示未命中
----------------------------------------------------------------
local function execute_cache_warmup(kong_config)
if kong_config.database == "off" then
return true
end
-- ngx.worker.id是openresty的一个接口,返回当前 Nginx 工作进程的一个顺序数字(从 0 开始)
-- 此处即判断是否刚刚启动worker进程
if ngx.worker.id() == 0 then
local ok, err = cache_warmup.execute(kong_config.db_cache_warmup_entities)
if not ok then
return nil, err
end
end
return true
end
local function get_now_ms()
update_time()
return now() * 1000 -- time is kept in seconds with millisecond resolution.
end
local function flush_delayed_response(ctx)
ctx.delay_response = false
if type(ctx.delayed_response_callback) == "function" then
ctx.delayed_response_callback(ctx)
return -- avoid tail call
end
kong.response.exit(ctx.delayed_response.status_code,
ctx.delayed_response.content,
ctx.delayed_response.headers)
end
local function parse_declarative_config(kong_config)
if kong_config.database ~= "off" then
return {}
end
if not kong_config.declarative_config then
return {}
end
local dc = declarative.new_config(kong_config)
local entities, err = dc:parse_file(kong_config.declarative_config)
if not entities then
return nil, "error parsing declarative config file " ..
kong_config.declarative_config .. ":\n" .. err
end
return entities
end
local function load_declarative_config(kong_config, entities)
if kong_config.database ~= "off" then
return true
end
if not kong_config.declarative_config then
-- no configuration yet, just build empty plugins iterator
local ok, err = runloop.build_plugins_iterator(utils.uuid())
if not ok then
error("error building initial plugins iterator: " .. err)
end
return true
end
local opts = {
name = "declarative_config",
}
return concurrency.with_worker_mutex(opts, function()
local value = ngx.shared.kong:get("declarative_config:loaded")
if value then
return true
end
local ok, err = declarative.load_into_cache(entities)
if not ok then
return nil, err
end
kong.log.notice("declarative config loaded from ",
kong_config.declarative_config)
ok, err = runloop.build_plugins_iterator(utils.uuid())
if not ok then
error("error building initial plugins iterator: " .. err)
end
assert(runloop.build_router("init"))
if kong_config.service_mesh then
mesh.init()
end
ok, err = ngx.shared.kong:safe_set("declarative_config:loaded", true)
if not ok then
kong.log.warn("failed marking declarative_config as loaded: ", err)
end
return true
end)
end
local function list_migrations(migtable)
local list = {}
for _, t in ipairs(migtable) do
local mignames = {}
for _, mig in ipairs(t.migrations) do
table.insert(mignames, mig.name)
end
table.insert(list, string.format("%s (%s)", t.subsystem,
table.concat(mignames, ", ")))
end
return table.concat(list, " ")
end
-- Kong public context handlers.
-- @section kong_handlers
local Kong = {}
-- 发生在master进程启动阶段。这里会对数据访问层进行初始化,加载插件的代码,构造路由规则表。
function Kong.init()
--初始化kong的共享空间
reset_kong_shm()
-- special math.randomseed from kong.globalpatches not taking any argument.
-- Must only be called in the init or init_worker phases, to avoid
-- duplicated seeds.
math.randomseed()
-- 引用pl.path库
local pl_path = require "pl.path"
-- 应用conf_loader文件
local conf_loader = require "kong.conf_loader"
-- check if kong global is the correct one
if not kong.version then
error("configuration error: make sure your template is not setting a " ..
"global named 'kong' (please use 'Kong' instead)")
end
-- retrieve kong_config
local conf_path = pl_path.join(ngx.config.prefix(), ".kong_env")
-- 读取config,利用assert可以打印错误信息
local config = assert(conf_loader(conf_path, nil, { from_kong_env = true }))
-- Set up default ssl client context
local default_client_ssl_ctx
-- service_mesh在config中的设置在下个版本删除
if config.service_mesh then
if set_ssl_ctx then
default_client_ssl_ctx = http_tls.new_client_context()
default_client_ssl_ctx:setVerify(openssl_ssl.VERIFY_NONE)
default_client_ssl_ctx:setAlpnProtos { "http/1.1" }
-- TODO: copy proxy_ssl_* flags?
if config.client_ssl then
local pem_key = assert(pl_utils.readfile(config.client_ssl_cert_key))
default_client_ssl_ctx:setPrivateKey(openssl_pkey.new(pem_key))
-- XXX: intermediary certs are NYI https://github.com/wahern/luaossl/issues/123
local pem_cert = assert(pl_utils.readfile(config.client_ssl_cert))
default_client_ssl_ctx:setCertificate(openssl_x509.new(pem_cert))
end
else
ngx_log(ngx_WARN, "missing \"ngx.balancer\".set_ssl_ctx API. ",
"Dynamic client SSL_CTX* will be unavailable")
end
end
-- 初始化pdk
kong_global.init_pdk(kong, config, nil) -- nil: latest PDK
local db = assert(DB.new(config))
assert(db:init_connector())
schema_state = assert(db:schema_state())
migrations_utils.check_state(schema_state, db)
if schema_state.missing_migrations or schema_state.pending_migrations then
if schema_state.missing_migrations then
ngx_log(ngx_WARN, "database is missing some migrations:\n",
schema_state.missing_migrations)
end
if schema_state.pending_migrations then
ngx_log(ngx_WARN, "database has pending migrations:\n",
schema_state.pending_migrations)
end
end
assert(db:connect())
assert(db.plugins:check_db_against_config(config.loaded_plugins))
-- LEGACY
singletons.dns = dns(config)
singletons.configuration = config
singletons.db = db
-- /LEGACY
do
local origins = {}
for _, v in ipairs(config.origins) do
-- Validated in conf_loader
local from_scheme, from_authority, to_scheme, to_authority =
v:match("^(%a[%w+.-]*)://([^=]+:[%d]+)=(%a[%w+.-]*)://(.+)$")
local from = assert(utils.normalize_ip(from_authority))
local to = assert(utils.normalize_ip(to_authority))
local from_origin = from_scheme:lower() .. "://" .. utils.format_host(from)
to.scheme = to_scheme
if to.port == nil then
if to_scheme == "http" then
to.port = 80
elseif to_scheme == "https" then
to.port = 443
else
error("scheme has unknown default port")
end
end
origins[from_origin] = to
end
singletons.origins = origins
end
kong.db = db
kong.dns = singletons.dns
if config.service_mesh then
kong.default_client_ssl_ctx = default_client_ssl_ctx
end
if subsystem == "stream" or config.proxy_ssl_enabled then
certificate.init()
end
if config.service_mesh and kong.configuration.database ~= "off" then
mesh.init()
end
-- Load plugins as late as possible so that everything is set up
assert(db.plugins:load_plugin_schemas(config.loaded_plugins))
if kong.configuration.database == "off" then
local err
declarative_entities, err = parse_declarative_config(kong.configuration)
if not declarative_entities then
error(err)
end
else
local ok, err = runloop.build_plugins_iterator("init")
if not ok then
error("error building initial plugins: " .. tostring(err))
end
assert(runloop.build_router("init"))
end
db:close()
end
function Kong.init_worker()
kong_global.set_phase(kong, PHASES.init_worker)
-- special math.randomseed from kong.globalpatches not taking any argument.
-- Must only be called in the init or init_worker phases, to avoid
-- duplicated seeds.
math.randomseed()
-- init DB
local ok, err = kong.db:init_worker()
if not ok then
stash_init_worker_error("failed to instantiate 'kong.db' module: " .. err)
return
end
if ngx.worker.id() == 0 then
if schema_state.missing_migrations then
ngx_log(ngx_WARN, "missing migrations: ",
list_migrations(schema_state.missing_migrations))
end
if schema_state.pending_migrations then
ngx_log(ngx_INFO, "starting with pending migrations: ",
list_migrations(schema_state.pending_migrations))
end
end
local worker_events, err = kong_global.init_worker_events()
if not worker_events then
stash_init_worker_error("failed to instantiate 'kong.worker_events' " ..
"module: " .. err)
return
end
kong.worker_events = worker_events
local cluster_events, err = kong_global.init_cluster_events(kong.configuration, kong.db)
if not cluster_events then
stash_init_worker_error("failed to instantiate 'kong.cluster_events' " ..
"module: " .. err)
return
end
kong.cluster_events = cluster_events
local cache, err = kong_global.init_cache(kong.configuration, cluster_events, worker_events)
if not cache then
stash_init_worker_error("failed to instantiate 'kong.cache' module: " ..
err)
return
end
kong.cache = cache
ok, err = runloop.set_init_versions_in_cache()
if not ok then
stash_init_worker_error(err) -- 'err' fully formatted
return
end
-- LEGACY
singletons.cache = cache
singletons.worker_events = worker_events
singletons.cluster_events = cluster_events
-- /LEGACY
kong.db:set_events_handler(worker_events)
ok, err = load_declarative_config(kong.configuration, declarative_entities)
if not ok then
stash_init_worker_error("failed to load declarative config file: " .. err)
return
end
ok, err = execute_cache_warmup(kong.configuration)
if not ok then
ngx_log(ngx_ERR, "failed to warm up the DB cache: " .. err)
end
runloop.init_worker.before()
-- run plugins init_worker context
ok, err = runloop.update_plugins_iterator()
if not ok then
stash_init_worker_error("failed to build the plugins iterator: " .. err)
return
end
local plugins_iterator = runloop.get_plugins_iterator()
execute_plugins_iterator(plugins_iterator, "init_worker")
end
function Kong.preread()
local ctx = ngx.ctx
if not ctx.KONG_PROCESSING_START then
ctx.KONG_PROCESSING_START = get_now_ms()
end
if not ctx.KONG_PREREAD_START then
ctx.KONG_PREREAD_START = ctx.KONG_PROCESSING_START
end
kong_global.set_phase(kong, PHASES.preread)
log_init_worker_errors(ctx)
runloop.preread.before(ctx)
local plugins_iterator = runloop.get_updated_plugins_iterator()
execute_plugins_iterator(plugins_iterator, "preread", ctx)
runloop.preread.after(ctx)
ctx.KONG_PREREAD_ENDED_AT = get_now_ms()
ctx.KONG_PREREAD_TIME = ctx.KONG_PREREAD_ENDED_AT - ctx.KONG_PREREAD_START
-- we intent to proxy, though balancer may fail on that
ctx.KONG_PROXIED = true
end
function Kong.ssl_certificate()
kong_global.set_phase(kong, PHASES.certificate)
-- this doesn't really work across the phases currently (OpenResty 1.13.6.2),
-- but it returns a table (rewrite phase clears it)
local ctx = ngx.ctx
log_init_worker_errors(ctx)
runloop.certificate.before(ctx)
local plugins_iterator = runloop.get_updated_plugins_iterator()
execute_plugins_iterator(plugins_iterator, "certificate", ctx)
end
function Kong.rewrite()
if var.kong_proxy_mode == "grpc" then
kong_resty_ctx.apply_ref() -- if kong_proxy_mode is gRPC, this is executing
kong_resty_ctx.stash_ref() -- after an internal redirect. Restore (and restash)
-- context to avoid re-executing phases
local ctx = ngx.ctx
ctx.KONG_REWRITE_ENDED_AT = get_now_ms()
ctx.KONG_REWRITE_TIME = ctx.KONG_REWRITE_ENDED_AT - ctx.KONG_REWRITE_START
return
end
local ctx = ngx.ctx
if not ctx.KONG_PROCESSING_START then
ctx.KONG_PROCESSING_START = ngx.req.start_time() * 1000
end
if not ctx.KONG_REWRITE_START then
ctx.KONG_REWRITE_START = get_now_ms()
end
kong_global.set_phase(kong, PHASES.rewrite)
kong_resty_ctx.stash_ref()
local is_https = var.https == "on"
if not is_https then
log_init_worker_errors(ctx)
end
runloop.rewrite.before(ctx)
-- On HTTPS requests, the plugins iterator is already updated in the ssl_certificate phase
local plugins_iterator
if is_https then
plugins_iterator = runloop.get_plugins_iterator()
else
plugins_iterator = runloop.get_updated_plugins_iterator()
end
execute_plugins_iterator(plugins_iterator, "rewrite", ctx)
ctx.KONG_REWRITE_ENDED_AT = get_now_ms()
ctx.KONG_REWRITE_TIME = ctx.KONG_REWRITE_ENDED_AT - ctx.KONG_REWRITE_START
end
function Kong.access()
local ctx = ngx.ctx
if not ctx.KONG_ACCESS_START then
ctx.KONG_ACCESS_START = get_now_ms()
if ctx.KONG_REWRITE_START and not ctx.KONG_REWRITE_ENDED_AT then
ctx.KONG_REWRITE_ENDED_AT = ctx.KONG_ACCESS_START
ctx.KONG_REWRITE_TIME = ctx.KONG_REWRITE_ENDED_AT - ctx.KONG_REWRITE_START
end
end
kong_global.set_phase(kong, PHASES.access)
runloop.access.before(ctx)
ctx.delay_response = true
local plugins_iterator = runloop.get_plugins_iterator()
for plugin, plugin_conf in plugins_iterator:iterate("access", ctx) do
if not ctx.delayed_response then
kong_global.set_named_ctx(kong, "plugin", plugin_conf)
kong_global.set_namespaced_log(kong, plugin.name)
local err = coroutine.wrap(plugin.handler.access)(plugin.handler, plugin_conf)
kong_global.reset_log(kong)
if err then
ctx.delay_response = false
kong.log.err(err)
ctx.KONG_ACCESS_ENDED_AT = get_now_ms()
ctx.KONG_ACCESS_TIME = ctx.KONG_ACCESS_ENDED_AT - ctx.KONG_ACCESS_START
ctx.KONG_RESPONSE_LATENCY = ctx.KONG_ACCESS_ENDED_AT - ctx.KONG_PROCESSING_START
return kong.response.exit(500, { message = "An unexpected error occurred" })
end
end
end
if ctx.delayed_response then
ctx.KONG_ACCESS_ENDED_AT = get_now_ms()
ctx.KONG_ACCESS_TIME = ctx.KONG_ACCESS_ENDED_AT - ctx.KONG_ACCESS_START
ctx.KONG_RESPONSE_LATENCY = ctx.KONG_ACCESS_ENDED_AT - ctx.KONG_PROCESSING_START
return flush_delayed_response(ctx)
end
ctx.delay_response = false
runloop.access.after(ctx)
ctx.KONG_ACCESS_ENDED_AT = get_now_ms()
ctx.KONG_ACCESS_TIME = ctx.KONG_ACCESS_ENDED_AT - ctx.KONG_ACCESS_START
-- we intent to proxy, though balancer may fail on that
ctx.KONG_PROXIED = true
end
function Kong.balancer()
-- This may be called multiple times, and no yielding here!
local now_ms = get_now_ms()
local ctx = ngx.ctx
if not ctx.KONG_BALANCER_START then
ctx.KONG_BALANCER_START = now_ms
if subsystem == "stream" then
if ctx.KONG_PREREAD_START and not ctx.KONG_PREREAD_ENDED_AT then
ctx.KONG_PREREAD_ENDED_AT = ctx.KONG_BALANCER_START
ctx.KONG_PREREAD_TIME = ctx.KONG_PREREAD_ENDED_AT -
ctx.KONG_PREREAD_START
end
else
if ctx.KONG_REWRITE_START and not ctx.KONG_REWRITE_ENDED_AT then
ctx.KONG_REWRITE_ENDED_AT = ctx.KONG_ACCESS_START or
ctx.KONG_BALANCER_START
ctx.KONG_REWRITE_TIME = ctx.KONG_REWRITE_ENDED_AT -
ctx.KONG_REWRITE_START
end
if ctx.KONG_ACCESS_START and not ctx.KONG_ACCESS_ENDED_AT then
ctx.KONG_ACCESS_ENDED_AT = ctx.KONG_BALANCER_START
ctx.KONG_ACCESS_TIME = ctx.KONG_ACCESS_ENDED_AT -
ctx.KONG_ACCESS_START
end
end
end
kong_global.set_phase(kong, PHASES.balancer)
local balancer_data = ctx.balancer_data
local tries = balancer_data.tries
local current_try = {}
balancer_data.try_count = balancer_data.try_count + 1
tries[balancer_data.try_count] = current_try
current_try.balancer_start = now_ms
if balancer_data.try_count > 1 then
-- only call balancer on retry, first one is done in `runloop.access.after`
-- which runs in the ACCESS context and hence has less limitations than
-- this BALANCER context where the retries are executed
-- record failure data
local previous_try = tries[balancer_data.try_count - 1]
previous_try.state, previous_try.code = get_last_failure()
-- Report HTTP status for health checks
local balancer = balancer_data.balancer
if balancer then
if previous_try.state == "failed" then
if previous_try.code == 504 then
balancer.report_timeout(balancer_data.balancer_handle)
else
balancer.report_tcp_failure(balancer_data.balancer_handle)
end
else
balancer.report_http_status(balancer_data.balancer_handle,
previous_try.code)
end
end
local ok, err, errcode = balancer_execute(balancer_data)
if not ok then
ngx_log(ngx_ERR, "failed to retry the dns/balancer resolver for ",
tostring(balancer_data.host), "' with: ", tostring(err))
ctx.KONG_BALANCER_ENDED_AT = get_now_ms()
ctx.KONG_BALANCER_TIME = ctx.KONG_BALANCER_ENDED_AT - ctx.KONG_BALANCER_START
ctx.KONG_PROXY_LATENCY = ctx.KONG_BALANCER_ENDED_AT - ctx.KONG_PROCESSING_START
return ngx.exit(errcode)
end
else
-- first try, so set the max number of retries
local retries = balancer_data.retries
if retries > 0 then
set_more_tries(retries)
end
end
local ssl_ctx = balancer_data.ssl_ctx
if TLS_SCHEMES[balancer_data.scheme] and ssl_ctx ~= nil then
if not set_ssl_ctx then
-- this API depends on an OpenResty patch
ngx_log(ngx_ERR, "failed to set the upstream SSL_CTX*: missing ",
"\"ngx.balancer\".set_ssl_ctx API")
ctx.KONG_BALANCER_ENDED_AT = get_now_ms()
ctx.KONG_BALANCER_TIME = ctx.KONG_BALANCER_ENDED_AT - ctx.KONG_BALANCER_START
ctx.KONG_PROXY_LATENCY = ctx.KONG_BALANCER_ENDED_AT - ctx.KONG_PROCESSING_START
return ngx.exit(500)
end
-- ensure a third-party (e.g. plugin) did not set an invalid type for
-- this value as such mistakes could cause segfaults
assert(getmetatable(ssl_ctx) == registry["SSL_CTX*"],
"unknown userdata type, expected SSL_CTX*")
local ok, err = set_ssl_ctx(cast(voidpp, ssl_ctx)[0])
if not ok then
ngx_log(ngx_ERR, "failed to set the upstream SSL_CTX*: ", err)
ctx.KONG_BALANCER_ENDED_AT = get_now_ms()
ctx.KONG_BALANCER_TIME = ctx.KONG_BALANCER_ENDED_AT - ctx.KONG_BALANCER_START
ctx.KONG_PROXY_LATENCY = ctx.KONG_BALANCER_ENDED_AT - ctx.KONG_PROCESSING_START
return ngx.exit(500)
end
end
current_try.ip = balancer_data.ip
current_try.port = balancer_data.port
-- set the targets as resolved
ngx_log(ngx_DEBUG, "setting address (try ", balancer_data.try_count, "): ",
balancer_data.ip, ":", balancer_data.port)
local ok, err = set_current_peer(balancer_data.ip, balancer_data.port)
if not ok then
ngx_log(ngx_ERR, "failed to set the current peer (address: ",
tostring(balancer_data.ip), " port: ", tostring(balancer_data.port),
"): ", tostring(err))
ctx.KONG_BALANCER_ENDED_AT = get_now_ms()
ctx.KONG_BALANCER_TIME = ctx.KONG_BALANCER_ENDED_AT - ctx.KONG_BALANCER_START
ctx.KONG_PROXY_LATENCY = ctx.KONG_BALANCER_ENDED_AT - ctx.KONG_PROCESSING_START
return ngx.exit(500)
end
ok, err = set_timeouts(balancer_data.connect_timeout / 1000,
balancer_data.send_timeout / 1000,
balancer_data.read_timeout / 1000)
if not ok then
ngx_log(ngx_ERR, "could not set upstream timeouts: ", err)
end
-- record overall latency
ctx.KONG_BALANCER_ENDED_AT = get_now_ms()
ctx.KONG_BALANCER_TIME = ctx.KONG_BALANCER_ENDED_AT - ctx.KONG_BALANCER_START
-- record try-latency
local try_latency = ctx.KONG_BALANCER_ENDED_AT - current_try.balancer_start
current_try.balancer_latency = try_latency
-- time spent in Kong before sending the request to upstream
-- start_time() is kept in seconds with millisecond resolution.
ctx.KONG_PROXY_LATENCY = ctx.KONG_BALANCER_ENDED_AT - ctx.KONG_PROCESSING_START
end
function Kong.header_filter()
local ctx = ngx.ctx
if not ctx.KONG_PROCESSING_START then
ctx.KONG_PROCESSING_START = ngx.req.start_time() * 1000
end
if not ctx.KONG_HEADER_FILTER_START then
ctx.KONG_HEADER_FILTER_START = get_now_ms()
if ctx.KONG_REWRITE_START and not ctx.KONG_REWRITE_ENDED_AT then
ctx.KONG_REWRITE_ENDED_AT = ctx.KONG_BALANCER_START or
ctx.KONG_ACCESS_START or
ctx.KONG_HEADER_FILTER_START
ctx.KONG_REWRITE_TIME = ctx.KONG_REWRITE_ENDED_AT -
ctx.KONG_REWRITE_START
end
if ctx.KONG_ACCESS_START and not ctx.KONG_ACCESS_ENDED_AT then
ctx.KONG_ACCESS_ENDED_AT = ctx.KONG_BALANCER_START or
ctx.KONG_HEADER_FILTER_START
ctx.KONG_ACCESS_TIME = ctx.KONG_ACCESS_ENDED_AT -
ctx.KONG_ACCESS_START
end
if ctx.KONG_BALANCER_START and not ctx.KONG_BALANCER_ENDED_AT then
ctx.KONG_BALANCER_ENDED_AT = ctx.KONG_HEADER_FILTER_START
ctx.KONG_BALANCER_TIME = ctx.KONG_BALANCER_ENDED_AT -
ctx.KONG_BALANCER_START
end
end
if ctx.KONG_PROXIED then
ctx.KONG_WAITING_TIME = ctx.KONG_HEADER_FILTER_START -
(ctx.KONG_BALANCER_ENDED_AT or ctx.KONG_ACCESS_ENDED_AT)
if not ctx.KONG_PROXY_LATENCY then
ctx.KONG_PROXY_LATENCY = ctx.KONG_HEADER_FILTER_START - ctx.KONG_PROCESSING_START
end
elseif not ctx.KONG_RESPONSE_LATENCY then
ctx.KONG_RESPONSE_LATENCY = ctx.KONG_HEADER_FILTER_START - ctx.KONG_PROCESSING_START
end
kong_global.set_phase(kong, PHASES.header_filter)
runloop.header_filter.before(ctx)
local plugins_iterator = runloop.get_plugins_iterator()
execute_plugins_iterator(plugins_iterator, "header_filter", ctx)
runloop.header_filter.after(ctx)
ctx.KONG_HEADER_FILTER_ENDED_AT = get_now_ms()
ctx.KONG_HEADER_FILTER_TIME = ctx.KONG_HEADER_FILTER_ENDED_AT - ctx.KONG_HEADER_FILTER_START
end
function Kong.body_filter()
local ctx = ngx.ctx
if not ctx.KONG_BODY_FILTER_START then
ctx.KONG_BODY_FILTER_START = get_now_ms()
if ctx.KONG_REWRITE_START and not ctx.KONG_REWRITE_ENDED_AT then
ctx.KONG_REWRITE_ENDED_AT = ctx.KONG_ACCESS_START or
ctx.KONG_BALANCER_START or
ctx.KONG_HEADER_FILTER_START or
ctx.KONG_BODY_FILTER_START
ctx.KONG_REWRITE_TIME = ctx.KONG_REWRITE_ENDED_AT -
ctx.KONG_REWRITE_START
end
if ctx.KONG_ACCESS_START and not ctx.KONG_ACCESS_ENDED_AT then
ctx.KONG_ACCESS_ENDED_AT = ctx.KONG_BALANCER_START or
ctx.KONG_HEADER_FILTER_START or
ctx.KONG_BODY_FILTER_START
ctx.KONG_ACCESS_TIME = ctx.KONG_ACCESS_ENDED_AT -
ctx.KONG_ACCESS_START
end
if ctx.KONG_BALANCER_START and not ctx.KONG_BALANCER_ENDED_AT then
ctx.KONG_BALANCER_ENDED_AT = ctx.KONG_HEADER_FILTER_START or
ctx.KONG_BODY_FILTER_START
ctx.KONG_BALANCER_TIME = ctx.KONG_BALANCER_ENDED_AT -
ctx.KONG_BALANCER_START
end
if ctx.KONG_HEADER_FILTER_START and not ctx.KONG_HEADER_FILTER_ENDED_AT then
ctx.KONG_HEADER_FILTER_ENDED_AT = ctx.KONG_BODY_FILTER_START
ctx.KONG_HEADER_FILTER_TIME = ctx.KONG_HEADER_FILTER_ENDED_AT -
ctx.KONG_HEADER_FILTER_START
end
end
kong_global.set_phase(kong, PHASES.body_filter)
local plugins_iterator = runloop.get_plugins_iterator()
execute_plugins_iterator(plugins_iterator, "body_filter", ctx)
if not arg[2] then
return
end
ctx.KONG_BODY_FILTER_ENDED_AT = get_now_ms()
ctx.KONG_BODY_FILTER_TIME = ctx.KONG_BODY_FILTER_ENDED_AT - ctx.KONG_BODY_FILTER_START
if ctx.KONG_PROXIED then
-- time spent receiving the response (header_filter + body_filter)
-- we could use $upstream_response_time but we need to distinguish the waiting time
-- from the receiving time in our logging plugins (especially ALF serializer).
ctx.KONG_RECEIVE_TIME = ctx.KONG_BODY_FILTER_ENDED_AT - (ctx.KONG_HEADER_FILTER_START or
ctx.KONG_BALANCER_ENDED_AT or
ctx.KONG_BALANCER_START or
ctx.KONG_ACCESS_ENDED_AT)
end
end
function Kong.log()
local ctx = ngx.ctx
if not ctx.KONG_LOG_START then
ctx.KONG_LOG_START = get_now_ms()
if subsystem == "stream" then
if ctx.KONG_PREREAD_START and not ctx.KONG_PREREAD_ENDED_AT then
ctx.KONG_PREREAD_ENDED_AT = ctx.KONG_LOG_START
ctx.KONG_PREREAD_TIME = ctx.KONG_PREREAD_ENDED_AT -
ctx.KONG_PREREAD_START
end
if ctx.KONG_BALANCER_START and not ctx.KONG_BALANCER_ENDED_AT then
ctx.KONG_BALANCER_ENDED_AT = ctx.KONG_LOG_START
ctx.KONG_BALANCER_TIME = ctx.KONG_BALANCER_ENDED_AT -
ctx.KONG_BALANCER_START
end
else
if ctx.KONG_BODY_FILTER_START and not ctx.KONG_BODY_FILTER_ENDED_AT then
ctx.KONG_BODY_FILTER_ENDED_AT = ctx.KONG_LOG_START
ctx.KONG_BODY_FILTER_TIME = ctx.KONG_BODY_FILTER_ENDED_AT -
ctx.KONG_BODY_FILTER_START
end
if ctx.KONG_REWRITE_START and not ctx.KONG_REWRITE_ENDED_AT then
ctx.KONG_REWRITE_ENDED_AT = ctx.KONG_ACCESS_START or
ctx.KONG_BALANCER_START or
ctx.KONG_HEADER_FILTER_START or
ctx.BODY_FILTER_START or
ctx.KONG_LOG_START
ctx.KONG_REWRITE_TIME = ctx.KONG_REWRITE_ENDED_AT -
ctx.KONG_REWRITE_START
end
if ctx.KONG_ACCESS_START and not ctx.KONG_ACCESS_ENDED_AT then
ctx.KONG_ACCESS_ENDED_AT = ctx.KONG_BALANCER_START or
ctx.KONG_HEADER_FILTER_START or
ctx.BODY_FILTER_START or
ctx.KONG_LOG_START
ctx.KONG_ACCESS_TIME = ctx.KONG_ACCESS_ENDED_AT -
ctx.KONG_ACCESS_START
end
if ctx.KONG_BALANCER_START and not ctx.KONG_BALANCER_ENDED_AT then
ctx.KONG_BALANCER_ENDED_AT = ctx.KONG_HEADER_FILTER_START or
ctx.BODY_FILTER_START or
ctx.KONG_LOG_START
ctx.KONG_BALANCER_TIME = ctx.KONG_BALANCER_ENDED_AT -
ctx.KONG_BALANCER_START
end
if ctx.KONG_HEADER_FILTER_START and not ctx.KONG_HEADER_FILTER_ENDED_AT then
ctx.KONG_HEADER_FILTER_ENDED_AT = ctx.BODY_FILTER_START or
ctx.KONG_LOG_START
ctx.KONG_HEADER_FILTER_TIME = ctx.KONG_HEADER_FILTER_ENDED_AT -
ctx.KONG_HEADER_FILTER_START
end
end
end
kong_global.set_phase(kong, PHASES.log)
local ctx = ngx.ctx
local plugins_iterator = runloop.get_plugins_iterator()
execute_plugins_iterator(plugins_iterator, "log", ctx)
runloop.log.after(ctx)
-- this is not used for now, but perhaps we need it later?
--ctx.KONG_LOG_ENDED_AT = get_now_ms()
--ctx.KONG_LOG_TIME = ctx.KONG_LOG_ENDED_AT - ctx.KONG_LOG_START
end
function Kong.handle_error()
kong_resty_ctx.apply_ref()
local ctx = ngx.ctx
ctx.KONG_UNEXPECTED = true
log_init_worker_errors(ctx)
if not ctx.plugins then
local plugins_iterator = runloop.get_updated_plugins_iterator()
for _ in plugins_iterator:iterate("content", ctx) do
-- just build list of plugins
end
end
return kong_error_handlers(ngx)
end
local function serve_content(module, options)
kong_global.set_phase(kong, PHASES.admin_api)
local ctx = ngx.ctx
ctx.KONG_PROCESSING_START = ngx.req.start_time() * 1000
ctx.KONG_ADMIN_CONTENT_START = ctx.KONG_ADMIN_CONTENT_START or get_now_ms()
log_init_worker_errors(ctx)
options = options or {}
header["Access-Control-Allow-Origin"] = options.allow_origin or "*"
if ngx.req.get_method() == "OPTIONS" then
header["Access-Control-Allow-Methods"] = "GET, HEAD, PUT, PATCH, POST, DELETE"
header["Access-Control-Allow-Headers"] = "Content-Type"
ctx.KONG_ADMIN_CONTENT_ENDED_AT = get_now_ms()
ctx.KONG_ADMIN_CONTENT_TIME = ctx.KONG_ADMIN_CONTENT_ENDED_AT - ctx.KONG_ADMIN_CONTENT_START
ctx.KONG_ADMIN_LATENCY = ctx.KONG_ADMIN_CONTENT_ENDED_AT - ctx.KONG_PROCESSING_START
return ngx.exit(204)
end
lapis.serve(module)
ctx.KONG_ADMIN_CONTENT_ENDED_AT = get_now_ms()
ctx.KONG_ADMIN_CONTENT_TIME = ctx.KONG_ADMIN_CONTENT_ENDED_AT - ctx.KONG_ADMIN_CONTENT_START
ctx.KONG_ADMIN_LATENCY = ctx.KONG_ADMIN_CONTENT_ENDED_AT - ctx.KONG_PROCESSING_START
end
function Kong.admin_content(options)
return serve_content("kong.api", options)
end
-- TODO: deprecate the following alias
Kong.serve_admin_api = Kong.admin_content
function Kong.admin_header_filter()
local ctx = ngx.ctx
if not ctx.KONG_PROCESSING_START then
ctx.KONG_PROCESSING_START = ngx.req.start_time() * 1000
end
if not ctx.KONG_ADMIN_HEADER_FILTER_START then
ctx.KONG_ADMIN_HEADER_FILTER_START = get_now_ms()
if ctx.KONG_ADMIN_CONTENT_START and not ctx.KONG_ADMIN_CONTENT_ENDED_AT then
ctx.KONG_ADMIN_CONTENT_ENDED_AT = ctx.KONG_ADMIN_HEADER_FILTER_START
ctx.KONG_ADMIN_CONTENT_TIME = ctx.KONG_ADMIN_CONTENT_ENDED_AT - ctx.KONG_ADMIN_CONTENT_START
end
if not ctx.KONG_ADMIN_LATENCY then
ctx.KONG_ADMIN_LATENCY = ctx.KONG_ADMIN_HEADER_FILTER_START - ctx.KONG_PROCESSING_START
end
end
if kong.configuration.enabled_headers[constants.HEADERS.ADMIN_LATENCY] then
header[constants.HEADERS.ADMIN_LATENCY] = ctx.KONG_ADMIN_LATENCY
end
-- this is not used for now, but perhaps we need it later?
--ctx.KONG_ADMIN_HEADER_FILTER_ENDED_AT = get_now_ms()
--ctx.KONG_ADMIN_HEADER_FILTER_TIME = ctx.KONG_ADMIN_HEADER_FILTER_ENDED_AT - ctx.KONG_ADMIN_HEADER_FILTER_START
end
function Kong.status_content()
return serve_content("kong.status")
end
Kong.status_header_filter = Kong.admin_header_filter
return Kong
|
require("config")
local lightoros_engine_thread
local screen
local lightoros_engine_channel
local screen_width, screen_height, flags = love.window.getMode()
local dot_w = screen_width / v_width
local dot_h = screen_height / v_height
function love.load()
lightoros_engine_thread = love.thread.newThread("lightoros-dummy.lua")
lightoros_engine_channel = love.thread.getChannel("engine")
lightoros_engine_thread:start(effect, v_width, v_height, args)
end
love.draw = function()
local new_screen = lightoros_engine_channel:pop()
if new_screen then
screen = new_screen
end
if screen then
for x = 1, v_width do
for y = 1, v_height do
dot = screen[x][y]
love.graphics.setColor(dot[1] / 255, dot[2] / 255, dot[3] / 255, 1)
love.graphics.rectangle("fill", (x - 1) * dot_w, (y - 1) * dot_h, dot_w, dot_h)
end
end
end
end
|
------------------------------------------------------------------------------------------------------------------------
-- Mount Manager Client
-- Author Morticai - (https://www.coregames.com/user/d1073dbcc404405cbef8ce728e53d380)
-- Date: 2021/3/26
-- Version 0.1.0
------------------------------------------------------------------------------------------------------------------------
-- Require
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
-- Objects
------------------------------------------------------------------------------------------------------------------------
local MOUNT_LEVELS = script:GetCustomProperty("MountLevels"):WaitForObject()
------------------------------------------------------------------------------------------------------------------------
-- Global Table Setup
------------------------------------------------------------------------------------------------------------------------
local API = {}
_G.MOUNT_SPEED = API
------------------------------------------------------------------------------------------------------------------------
-- Local Variables
------------------------------------------------------------------------------------------------------------------------
local MOUNT_LEVELS = MOUNT_LEVELS:GetChildren()
local MAX_MOUNT_LEVEL = #MOUNT_LEVELS
------------------------------------------------------------------------------------------------------------------------
-- Local Functions
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
-- Public API
------------------------------------------------------------------------------------------------------------------------
--@params object player
--@return string mountSpeed
function API.GetSpeed(player)
return tostring(player:GetResource("MOUNT_LEVEL"))
end
|
print "enter a number:"
n = io.read("*number")
if not n then
error("invalid input")
else
print("you entered: " .. n)
end
|
--[[
Carbon for Lua
#class Collections.Set
#description {
Provides operations for operating on unordered sets.
The @Set type Differs from the primtive @set type by adding methods to it.
It is possible to use these methods with a plain @set, just call them in a non-object oriented way:
```lua
Set.ToList(set)
```
}
#alias List Collections.List
]]
local Carbon, self = ...
local List = Carbon.Collections.List
local Set = {}
Set.__object_metatable = {
__index = Set
}
Set.Is = {
[Set] = true
}
--[[#method 1 {
class public @Set Set:New([@table data])
optional data: The data of the set. Empty if not given.
Turns the given object into a Set.
Allows method-style syntax.
}]]
function Set:New(object)
return setmetatable(object or {}, self.__object_metatable)
end
function Set:Serialize()
return nil, Carbon.Exceptions.NotImplementedException("Set:Serialize")
end
function Set.DeserializeInPlace(source)
return self.Deserialize(source, self)
end
function Set.Deserialize(source, out)
return nil, Carbon.Exceptions.NotImplementedException("Set:Deserialize")
end
--[[#method {
class public @List Set.ToList(@table self, [@table out])
-alias: object public @List Set:ToList([@table out])
required self: The set to collect members for.
optional out: Where to put the resulting data. Put into a new @List by default.
Collects all members of the set and puts them in a list.
}]]
function Set.ToList(self, out)
out = out or List:New({})
for key, value in pairs(self) do
if (value) then
table.insert(out, key)
end
end
return out
end
Carbon.Metadata:RegisterMethods(Set, self)
return Set |
------------------------------------------------------
-- Screen identifier
------------------------------------------------------
SCREEN_ATTRACT_IDENTIFIER = "attract"
------------------------------------------------------
-- Digital input states
------------------------------------------------------
SCREEN_ATTRACT_DI_SELECT_NEXT = 0
SCREEN_ATTRACT_DI_SELECT_PREV = 1
SCREEN_ATTRACT_DI_SELECTION_CONFIRMED = 2
SCREEN_ATTRACT_DI_EXIT_APPLICATION = 3
SCREEN_ATTRACT_DI_OPERATOR_SCREEN = 4
SCREEN_ATTRACT_DI_DEBUG_0 = 5
SCREEN_ATTRACT_DI_DEBUG_1 = 6
SCREEN_ATTRACT_DI_DEBUG_2 = 7
SCREEN_ATTRACT_DI_DEBUG_3 = 8
SCREEN_ATTRACT_DI_DEBUG_4 = 9
SCREEN_ATTRACT_DI_DEBUG_5 = 10
SCREEN_ATTRACT_DI_DEBUG_6 = 11
SCREEN_ATTRACT_DI_DEBUG_7 = 12
------------------------------------------------------
-- Digital output states
------------------------------------------------------
SCREEN_ATTRACT_DO_NEW_ENTRY_SELECTED = 0
SCREEN_ATTRACT_DO_ENTRY_SELECTION_CONFIRMED = 1
SCREEN_ATTRACT_DO_EXIT_SCREEN = 2
------------------------------------------------------
-- Text output states
------------------------------------------------------
SCREEN_ATTRACT_TO_GAME_NAME_SELECTED = 0 |
local log = require("PremakeConsoleLog")
local defaultSettings = require("PremakeSettings")
-- Create a new module for premake and get it.
premake.modules.exeliusGeneratorClass = {}
local exeliusGenerator = premake.modules.exeliusGeneratorClass
function GenerateWindowsWorkspace()
filter {"system:windows"}
-- Generate the different build configurations for Visual Studio.
configurations
{
"Debug", -- Contains no compiler optimized code and no packaged assets. (Slow and Heavy)
"ASan", -- Same as Debug, with Address Sanitizer.(EXTREMELY Slow and Heavy)
"Test", -- Contains compiler optimized code and no packaged assets. (Fast and Heavy)
"Release" -- Contains compiler optimized code and packaged assets. (Fast and Light)
}
platforms
{
"x64",
"x86"
}
-- Set the compilation process to be multithreaded, this only effects MSVC... not sure how to speed up Linux.
flags
{
"MultiProcessorCompile"
}
-- Reset filters
filter {}
end
function GenerateLinuxWorkspace()
filter {"system:linux"}
-- Set the configuration based on the command line argument supplied from Setup.py.
configurations
{
_OPTIONS["configuration"]
}
-- Set the architecture based on the command line argument supplied from Setup.py.
platforms
{
_OPTIONS["architecture"]
}
-- Reset filters
filter {}
end
function SetWindowsPostBuildCommands()
filter {"system:windows"}
postbuildcommands
{
[[copy "%{wks.location}tools\templates\engine_config.ini" "%{cfg.targetdir}\engine_config.ini" /y /a]], -- Copy the ini into the final build directory.
[[copy "%{wks.location}tools\templates\engine_config.ini" "engine_config.ini" /y /a]], -- Copy the ini into the debuggers directory.
[[xcopy "assets" "%{cfg.targetdir}\assets\" /y /q /e]] -- Copy assets into final build directory.
}
end
function SetLinuxPostBuildCommands()
-- TODO: This will need to be tested and worked on.
filter {"system:linux"}
postbuildcommands
{
[[cp -f %{wks.location}/tools/templates/engine_config.ini %{cfg.targetdir}/engine_config.ini]],
[[cp -r assets %{cfg.targetdir}/assets]]
}
end
function exeliusGenerator.GenerateEngineWorkspace()
workspace(defaultSettings.workspaceName)
startproject(defaultSettings.startProjectName)
local workspacePath = os.realpath("../")
location(workspacePath)
GenerateWindowsWorkspace()
GenerateLinuxWorkspace()
end
function exeliusGenerator.GenerateEngineProject()
project(defaultSettings.engineProjectName)
defaultSettings.SetGlobalProjectDefaultSettings()
local enginePath = os.realpath("../" .. defaultSettings.engineProjectName)
-- Use a relative path here only because it logs nicer. Totally unnessesary.
local pathToLog = os.realpath("../" .. defaultSettings.engineProjectName)
log.Log("[Premake] Generating Engine at Path: " .. pathToLog)
location(enginePath)
kind(defaultSettings.defaultkind)
pchheader("EXEPCH.h")
pchsource("../%{prj.name}/source/precompilation/EXEPCH.cpp")
--pchsource("%{prj.location}/Source/Precompilation/EXEPCH.cpp") -- Doesn't work. %{prj.location} or %{wks.location} will not correctly expand when used in pchsource.
files
{
"../%{prj.name}/**.h",
"../%{prj.name}/**.cpp"
}
includedirs
{
"../%{prj.name}/",
"../%{prj.name}/source/precompilation/"
}
end
function exeliusGenerator.GenerateEditorProject()
project(defaultSettings.exeliusEditorName)
defaultSettings.SetGlobalProjectDefaultSettings()
local editorPath = os.realpath("../" .. defaultSettings.exeliusEditorName)
-- Use a relative path here only because it logs nicer. Totally unnessesary.
local pathToLog = os.realpath("../" .. defaultSettings.exeliusEditorName)
log.Log("[Premake] Generating Editor at Path: " .. pathToLog)
location(editorPath)
kind("ConsoleApp")
files
{
"../%{prj.name}/source/**.h",
"../%{prj.name}/source/**.cpp"
}
includedirs
{
"../%{prj.name}/source/"
}
end
function exeliusGenerator.LinkEngineToProject()
local engineIncludePath = os.realpath("../" .. defaultSettings.engineProjectName)
-- Use a relative path here only because it logs nicer. Totally unnessesary.
local pathToLog = os.realpath("../" .. defaultSettings.engineProjectName)
log.Log("[Premake] Linking Engine From Path: " .. pathToLog)
links
{
defaultSettings.engineProjectName
}
includedirs
{
engineIncludePath
}
SetWindowsPostBuildCommands()
SetLinuxPostBuildCommands()
end
return exeliusGenerator |
local constant = require 'constant'
local expand = require 'expand'
local gui = {}
function gui.show_dialog()
local factor = 2
local should_adjust_beat_sync = true
local should_adjust_lpb = true
local vb = renoise.ViewBuilder()
local show_pattern_warning, show_beat_sync_warning, show_lpb_warning, show_warnings
local function update_warnings()
show_pattern_warning = not expand.can_expand_all_patterns(factor)
show_beat_sync_warning = should_adjust_beat_sync and not expand.can_adjust_beat_sync(factor)
show_lpb_warning = should_adjust_lpb and not expand.can_adjust_lpb(factor)
show_warnings = show_pattern_warning or show_beat_sync_warning or show_lpb_warning
end
local function update_warning_text()
vb.views.pattern_warning.visible = show_pattern_warning
vb.views.beat_sync_warning.visible = show_beat_sync_warning
vb.views.lpb_warning.visible = show_lpb_warning
vb.views.warnings.visible = show_warnings
end
update_warnings()
renoise.app():show_custom_dialog('Expand song',
vb:column {
id = 'dialog',
margin = renoise.ViewBuilder.DEFAULT_DIALOG_MARGIN,
spacing = renoise.ViewBuilder.DEFAULT_DIALOG_SPACING,
uniform = true,
vb:column {
style = 'panel',
margin = renoise.ViewBuilder.DEFAULT_CONTROL_MARGIN,
spacing = renoise.ViewBuilder.DEFAULT_CONTROL_SPACING,
vb:text {
text = 'Options',
font = 'bold',
width = '100%',
align = 'center',
},
vb:horizontal_aligner {
spacing = renoise.ViewBuilder.DEFAULT_CONTROL_SPACING,
mode = 'justify',
vb:text {
text = 'Factor'
},
vb:valuebox {
min = 2,
value = factor,
notifier = function(value)
factor = value
update_warnings()
update_warning_text()
end,
},
},
vb:row {
id = 'beat_sync_option',
vb:checkbox {
value = should_adjust_beat_sync,
notifier = function(value)
should_adjust_beat_sync = value
update_warnings()
update_warning_text()
end,
},
vb:text {text = 'Adjust sample beat sync values'}
},
vb:row {
vb:checkbox {
value = should_adjust_lpb,
notifier = function(value)
should_adjust_lpb = value
update_warnings()
update_warning_text()
end,
},
vb:text {text = 'Adjust lines per beat'}
},
},
vb:column {
id = 'warnings',
visible = show_pattern_warning or show_beat_sync_warning or show_lpb_warning,
style = 'panel',
margin = renoise.ViewBuilder.DEFAULT_CONTROL_MARGIN,
spacing = renoise.ViewBuilder.DEFAULT_CONTROL_SPACING,
vb:text {
text = 'Warnings',
font = 'bold',
width = '100%',
align = 'center',
},
vb:multiline_text {
id = 'pattern_warning',
visible = show_pattern_warning,
text = 'Some patterns will be truncated. Patterns have a max length of '
.. renoise.Pattern.MAX_NUMBER_OF_LINES .. ' lines.',
width = '100%',
height = 48,
},
vb:multiline_text {
id = 'beat_sync_warning',
visible = show_beat_sync_warning,
text = 'Some samples will have improperly adjusted beat sync values. Samples have a max beat sync value of '
.. constant.max_sample_beat_sync_lines .. ' lines.',
width = '100%',
height = 64,
},
vb:multiline_text {
id = 'lpb_warning',
visible = show_lpb_warning,
text = 'Some LPB values will be improperly adjusted. The max LPB value is '
.. constant.max_lpb .. ' lines.',
width = '100%',
height = 48,
},
},
vb:button {
id = 'expand_song_button',
text = 'Expand song',
height = renoise.ViewBuilder.DEFAULT_DIALOG_BUTTON_HEIGHT,
notifier = function()
expand.expand_song(factor, should_adjust_beat_sync, should_adjust_lpb)
end,
},
}
)
end
return gui
|
local textureInt = 0
--local ringMat = Material("effects/select_ring")
-- local redlaser_mat = Material( "cable/redlaser" )
--local blue_mat = Material( "cable/blue_elec" )
-- local hydr_mat = Material( "cable/hydra" )
-- local beam1_mat = Material( "cable/crystal_beam1" )
local Vector, render = Vector, render
function render.DrawBoundingBox( pos1, pos2, color, mat, thick )
--mat = mat or blue_mat
thick = thick or 1
color = color or color_white
local a1 = Vector( pos1.x, pos2.y, pos1.z )
local a2 = Vector(pos2.x, pos1.y, pos1.z)
local a3 = Vector(pos1.x, pos1.y, pos2.z)
local b1 = Vector( pos2.x, pos2.y, pos1.z )
local b2 = Vector( pos2.x, pos1.y, pos2.z )
local b3 = Vector( pos1.x, pos2.y, pos2.z )
if (mat) then
render.SetMaterial( mat )
else
render.SetColorMaterial()
end
render.DrawBeam( pos1, a1, thick, textureInt, textureInt, color )
render.DrawBeam( pos1, a2, thick, textureInt, textureInt, color )
render.DrawBeam( pos1, a3, thick, textureInt, textureInt, color )
render.DrawBeam( pos2, b1, thick, textureInt, textureInt, color )
render.DrawBeam( pos2, b2, thick, textureInt, textureInt, color )
render.DrawBeam( pos2, b3, thick, textureInt, textureInt, color )
render.DrawBeam( a3, b3, thick, textureInt, textureInt, color )
render.DrawBeam( a3, b2, thick, textureInt, textureInt, color )
render.DrawBeam( b2, a2, thick, textureInt, textureInt, color )
render.DrawBeam( b3, a1, thick, textureInt, textureInt, color )
render.DrawBeam( b1, a1, thick, textureInt, textureInt, color )
render.DrawBeam( b1, a2, thick, textureInt, textureInt, color )
end
-- render.SetMaterial(ringMat)
-- render.DrawQuadEasy(center, vector_up, sizeRing, sizeRing, Color(50, 200, 50)) |
local Network = require "Network"
---@class Relay
local Relay = {
---@type Network
src=nil,
---@type Network
dst=nil
}
---@class Map
local Map = {}
Map.__index = Map
---@return Map
function Map.new()
local self = setmetatable({
---@type table<string, Network>
networks={},
---@type Relay[]
relays={} -- Not used yet
}, Map)
return self
end
function Map.deserialize(save)
local self = Map.new()
for _, networkSave in pairs(save.networks) do
self.networks[networkSave.name] = Network.deserialize(self, networkSave)
end
for _, relay in ipairs(save.relays) do
self.relays[#self.relays+1] = {
src=relay.src,
dst=relay.dst
}
end
return self
end
---@return string
function Map:serialize()
local networks = {}
for _, network in pairs(self.networks) do
networks[#networks+1] = network:serialize()
end
local relays = {}
for _, relay in pairs(self.relays) do
relays[#relays+1] = relay
end
return setmetatable({
networks=setmetatable(networks, {__yaml_mapping=false}),
relays=setmetatable(relays, {__yaml_mapping=false})
}, {__yaml_order={networks=1}})
end
function Map:update(dt)
for _, network in pairs(self.networks) do
network:update(dt)
end
end
function Map:removeNetwork(network)
self.networks[network.name] = nil
end
function Map:addNetwork(network)
if self.networks[network.name] ~= nil then
error("Attempt to override existing network with name " .. network.name)
end
self.networks[network.name] = network
end
---@param x number
---@param y number
---@return Device|nil
function Map:getObjectAt(x, y)
for _, network in pairs(self.networks) do
if network:withinBounds(x, y) then
local obj = network:getObjectAt(x, y)
if obj ~= nil then
return obj
end
end
end
end
---@param x number
---@param y number
---@return Network|nil
function Map:getNetworkAt(x, y)
for _, network in pairs(self.networks) do
if network:withinBounds(x, y) then
return network
end
end
end
---@param x number
---@param y number
---@return Network|nil
function Map:getNetworksAt(x, y)
local networks = {}
for _, network in pairs(self.networks) do
if network:withinBounds(x, y) then
table.insert(networks, network)
end
end
return networks
end
return Map
|
local xpnn_const = {}
xpnn_const.CD_TYPE = {
}
xpnn_const.GAME_STATE = {
ready_begin = 0,
qiang_banker = 1,
bet = 2,
open_card = 3,
game_end = 4,
}
xpnn_const.MAX_QIANG_BANKER_TIMES = 4
xpnn_const.MAX_BET_TIMES = 5
return xpnn_const |
pg = pg or {}
pg.chapter_defense = {
[1250001] = {
id = 1250001,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1240002,
1240005,
1240008
},
damage_by_id = {
{
1240221,
3
}
},
evaluation_display_s = {
2,
59134,
5
},
evaluation_display_a = {
2,
59134,
2
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1250002] = {
id = 1250002,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1240102,
1240105,
1240108
},
damage_by_id = {
{
1240231,
3
},
{
1240232,
3
}
},
evaluation_display_s = {
2,
59134,
5
},
evaluation_display_a = {
2,
59134,
2
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1250003] = {
id = 1250003,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1240202,
1240205,
1240208
},
damage_by_id = {
{
1240241,
3
},
{
1240242,
3
},
{
1240243,
3
}
},
evaluation_display_s = {
2,
59134,
5
},
evaluation_display_a = {
2,
59134,
2
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1250011] = {
id = 1250011,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1240602,
1240605,
1240608
},
damage_by_id = {
{
1240821,
3
},
{
1240822,
3
}
},
evaluation_display_s = {
2,
59134,
15
},
evaluation_display_a = {
2,
59134,
6
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1250012] = {
id = 1250012,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1240702,
1240705,
1240708
},
damage_by_id = {
{
1240831,
3
},
{
1240832,
3
},
{
1240833,
3
}
},
evaluation_display_s = {
2,
59134,
15
},
evaluation_display_a = {
2,
59134,
6
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1250013] = {
id = 1250013,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1240802,
1240805,
1240808
},
damage_by_id = {
{
1240841,
3
},
{
1240842,
3
},
{
1240843,
3
},
{
1240844,
3
}
},
evaluation_display_s = {
2,
59134,
15
},
evaluation_display_a = {
2,
59134,
6
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1250017] = {
id = 1250017,
port_hp = 12,
bonus_time = 0,
port_refresh = 1,
score = {
10,
6,
1
},
reinforce_expedition_list = {
1241202,
1241205,
1241208
},
damage_by_id = {
{
1241255,
5
},
{
1241251,
3
},
{
1241252,
3
},
{
1241253,
3
},
{
1241254,
3
}
},
evaluation_display_s = {
2,
59134,
800
},
evaluation_display_a = {
2,
59134,
785
},
evaluation_display_b = {
2,
59134,
760
},
strategy_list = {
{
12,
1
}
}
},
[1260002] = {
id = 1260002,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1250231
},
damage_by_id = {
{
1250231,
3
}
},
evaluation_display_s = {
2,
59137,
5
},
evaluation_display_a = {
2,
59137,
2
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1260003] = {
id = 1260003,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1250241
},
damage_by_id = {
{
1250241,
3
}
},
evaluation_display_s = {
2,
59137,
5
},
evaluation_display_a = {
2,
59137,
2
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1260022] = {
id = 1260022,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1250831
},
damage_by_id = {
{
1250831,
3
}
},
evaluation_display_s = {
2,
59137,
15
},
evaluation_display_a = {
2,
59137,
6
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1260023] = {
id = 1260023,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1250841
},
damage_by_id = {
{
1250841,
3
}
},
evaluation_display_s = {
2,
59137,
15
},
evaluation_display_a = {
2,
59137,
6
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1470002] = {
id = 1470002,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1250231
},
damage_by_id = {
{
1250231,
3
}
},
evaluation_display_s = {
2,
59196,
5
},
evaluation_display_a = {
2,
59196,
2
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1470003] = {
id = 1470003,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1250241
},
damage_by_id = {
{
1250241,
3
}
},
evaluation_display_s = {
2,
59196,
5
},
evaluation_display_a = {
2,
59196,
2
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1470022] = {
id = 1470022,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1250831
},
damage_by_id = {
{
1250831,
3
}
},
evaluation_display_s = {
2,
59196,
15
},
evaluation_display_a = {
2,
59196,
6
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1470023] = {
id = 1470023,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1250841
},
damage_by_id = {
{
1250841,
3
}
},
evaluation_display_s = {
2,
59196,
15
},
evaluation_display_a = {
2,
59196,
6
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1490001] = {
id = 1490001,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1240002,
1240005,
1240008
},
damage_by_id = {
{
1240221,
3
}
},
evaluation_display_s = {
2,
59207,
5
},
evaluation_display_a = {
2,
59207,
2
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1490002] = {
id = 1490002,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1240102,
1240105,
1240108
},
damage_by_id = {
{
1240231,
3
},
{
1240232,
3
}
},
evaluation_display_s = {
2,
59207,
5
},
evaluation_display_a = {
2,
59207,
2
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1490003] = {
id = 1490003,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1240202,
1240205,
1240208
},
damage_by_id = {
{
1240241,
3
},
{
1240242,
3
},
{
1240243,
3
}
},
evaluation_display_s = {
2,
59207,
5
},
evaluation_display_a = {
2,
59207,
2
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1490011] = {
id = 1490011,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1240602,
1240605,
1240608
},
damage_by_id = {
{
1240821,
3
},
{
1240822,
3
}
},
evaluation_display_s = {
2,
59207,
15
},
evaluation_display_a = {
2,
59207,
6
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1490012] = {
id = 1490012,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1240702,
1240705,
1240708
},
damage_by_id = {
{
1240831,
3
},
{
1240832,
3
},
{
1240833,
3
}
},
evaluation_display_s = {
2,
59207,
15
},
evaluation_display_a = {
2,
59207,
6
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1490013] = {
id = 1490013,
port_hp = 8,
bonus_time = 0,
port_refresh = 1,
score = {
8,
4,
1
},
reinforce_expedition_list = {
1240802,
1240805,
1240808
},
damage_by_id = {
{
1240841,
3
},
{
1240842,
3
},
{
1240843,
3
},
{
1240844,
3
}
},
evaluation_display_s = {
2,
59207,
15
},
evaluation_display_a = {
2,
59207,
6
},
evaluation_display_b = {},
strategy_list = {
{
12,
1
}
}
},
[1490017] = {
id = 1490017,
port_hp = 12,
bonus_time = 0,
port_refresh = 1,
score = {
10,
6,
1
},
reinforce_expedition_list = {
1241202,
1241205,
1241208
},
damage_by_id = {
{
1241255,
5
},
{
1241251,
3
},
{
1241252,
3
},
{
1241253,
3
},
{
1241254,
3
}
},
evaluation_display_s = {
2,
59207,
800
},
evaluation_display_a = {
2,
59207,
785
},
evaluation_display_b = {
2,
59207,
760
},
strategy_list = {
{
12,
1
}
}
},
all = {
1250001,
1250002,
1250003,
1250011,
1250012,
1250013,
1250017,
1260002,
1260003,
1260022,
1260023,
1470002,
1470003,
1470022,
1470023,
1490001,
1490002,
1490003,
1490011,
1490012,
1490013,
1490017
}
}
return
|
local core = require "sys.core"
local zproto = require "zproto"
local rpc = require "cluster.rpc"
local pairs = pairs
local assert = assert
local error = error
local format = string.format
local proto, server, master
local M = {}
local mepoch
local router = {}
local handler = {}
local type_to_workers = {}
local join_r = {
self = nil,
workers = nil
}
local function clone(src, dst)
dst = dst or {}
for k, v in pairs(src) do
dst[k] = v
end
end
local function formatworker(w)
return format(
[[{type="%s",epoch=%s,status="%s",listen="%s",slot=%s}]],
w.type, w.epoch, w.status, w.listen,w.slot)
end
local function transition_until_success(status)
local x = {}
local req = {
self = x,
workers = join_r.workers
}
clone(join_r.self, x)
x.status = status
while true do
core.log("[worker] join try type:", x.type,
"listen:", x.listen, "status:", status)
local ack, err = master:call("join_r", req)
if ack and not ack.result then
assert(ack.epoch)
assert(ack.slot)
assert(ack.status == status, ack.status)
local self = join_r.self
self.epoch = ack.epoch
self.slot = ack.slot
self.status = status
core.log("[worker] join successfully type:", x.type,
"listen:", x.listen,
"mepoch:", ack.mepoch,
"self:", formatworker(self))
return ack.mepoch, ack.capacity
end
if not ack then
core.log("[worker] join timeout type:",
x.type, "listen:", x.listen)
else
local res = ack.result
if res == 1 then
core.log("[worker] join retry type:",
x.type, "listen:", x.listen)
else
core.log("[worker] join error type:", x.type,
"listen:", x.listen,
"status:", ack.status)
core.exit(1)
end
end
core.sleep(500)
end
end
local function create_rpc_for_worker(w)
if w.rpc then
w.rpc:close()
end
core.log("[worker] rpc connect to", w.listen)
w.rpc = rpc.connect {
addr = w.listen,
proto = proto,
timeout = 5000,
close = function(fd, errno)
core.log("[worker] worker close", w.listen)
end
}
end
local function worker_join(w, conns_of_type)
local typ = w.type
local workers = type_to_workers[typ]
if not workers then
return
end
local conns = conns_of_type[typ]
if not conns then
conns = {}
conns_of_type[typ] = conns
end
local slot = w.slot
local ww = workers[slot]
if not ww then
workers[slot] = w
if w.status == "run" then
conns[w.slot] = w
end
core.log("[worker] worker_join add", formatworker(w))
return
end
assert(w.epoch >= ww.epoch)
if w.epoch > ww.epoch then
if ww.rpc then
ww.rpc:close()
end
clone(w, ww)
if ww.status == "run" then
conns[ww.slot] = ww
end
elseif w.status ~= ww.status then
assert(w.status == "run")
assert(ww.status == "up")
assert(ww.epoch == w.epoch)
assert(ww.slot == w.slot)
assert(ww.listen == w.listen)
ww.status = w.status
conns[ww.slot] = ww
else
return
end
core.log("[worker] worker_join update", formatworker(w))
end
function handler.cluster_r(msg, cmd, fd)
local conns_of_type = {}
local workers = msg.workers
join_r.workers = workers
core.log("[worker] cluster_r join_r.workers", #workers)
for _, w in pairs(workers) do
worker_join(w, conns_of_type)
end
for typ, conns in pairs(conns_of_type) do
for k, v in pairs(conns) do
create_rpc_for_worker(v)
conns[k] = v.rpc
end
local workers = type_to_workers[typ]
workers.agent.join(conns, #workers, typ)
end
return "cluster_a", {}
end
function handler.status_r(msg, cmd, fd)
local sys, usr = core.cpuinfo()
local mused = core.memused()
local mrss = core.memrss()
local status = {
pid = core.getpid(),
cpu_sys = format("%.2fs", sys),
cpu_user = format("%.2fs", usr),
memory_used = mused,
memory_rss = mrss,
memory_fragmentation_ratio = mrss / mused,
memory_allocator = core.allocator,
version = core.version,
multiplexing_api = core.pollapi,
uptime_in_seconds = core.monotonicsec(),
message_pending = core.msgsize(),
timer_resolution = core.timerrs,
}
return "status_a", status
end
local function heartbeat()
local ack, err = master:call("heartbeat_r", {})
if not ack then
core.log("[worker] master heartbeat timeout")
return
end
if not ack.mepoch or mepoch and mepoch ~= ack.mepoch then
local status = join_r.self.status
assert(status == "up" or status == "run")
core.log("[worker] master down report to new master")
mepoch = transition_until_success("run")
end
end
local function timer()
local ok, err = core.pcall(heartbeat)
if not ok then
core.log("[worker] timer", err)
end
core.timeout(1000, timer)
end
function M.more(funcs, __index)
for k, v in pairs(funcs) do
local cmd = assert(proto:tag(k), k)
router[cmd] = v
end
if __index then
setmetatable(router, {__index = __index})
else
setmetatable(router, nil)
end
end
function M.run(funcs, __index)
M.more(funcs, __index)
mepoch = transition_until_success("run")
end
function M.up(conf)
local errno
local str = require "cluster.proto"
proto = assert(zproto:parse(str .. conf.proto))
for k, v in pairs(handler) do
local cmd = assert(proto:tag(k), k)
router[cmd] = v
end
server, errno = rpc.listen {
proto = proto,
addr = conf.listen,
type = conf.type,
accept = function(fd, addr)
core.log("[worker] accept", fd, addr)
end,
call = function(msg, cmd, fd)
local cb = router[cmd]
if cb then
return cb(msg, cmd, fd)
end
error(format("[worker] call %s %s none", fd, cmd))
end,
close = function(fd, errno)
core.log("[worker] close", fd, errno)
end
}
assert(server, errno)
master = rpc.connect {
addr = conf.master,
proto = proto,
timeout = 5000,
close = function(fd, errno)
core.log("[worker] master close", fd, errno)
end
}
join_r.self = {
epoch = nil,
slot = nil,
type = conf.type,
status = "start",
listen = conf.listen,
}
for typ, agent in pairs(conf.agents) do
type_to_workers[typ] = {
agent = agent
}
end
local _, capacity = transition_until_success("up")
timer()
return join_r.self.slot, capacity
end
return M
|
ROOKI = ROOKI or {}
draw = draw or {}
function ROOKI:getFontSize(fontname, txt)
surface.SetFont(fontname)
return {surface.GetTextSize(txt)}
end
function draw.SimpleTextShadow(text, font, x, y, color, xalign, yalign, shadowcolor, size)
if (not shadowcolor) then
shadowcolor = Color(0, 0, 0)
end
draw.SimpleText(text, font, x, y, color, xalign, yalign)
draw.SimpleText(text, font, x + size, y + size, shadowcolor, xalign, yalign)
end |
-- Global configuration
fields = {
sitename = "Wercstyle",
}
-- Store global variables as Lua code in the database.
-- Any other Lua file may load them with: CodeLib():import("globals")
OnReady(function()
-- Prepare a CodeLib object and clear the "globals" key
codelib = CodeLib()
-- Store the configuration strings as Lua code under the key "globals".
local first = true
for k, v in pairs(fields) do
luaCode = k .. "=\"" .. v .. "\""
if first then
codelib:set("globals", luaCode)
first = false
else
codelib:add("globals", luaCode)
end
end
end)
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf/protobuf"
module('RoleConfig_pb')
ROLECONFIG = protobuf.Descriptor();
local ROLECONFIG_TYPE_FIELD = protobuf.FieldDescriptor();
local ROLECONFIG_VALUE_FIELD = protobuf.FieldDescriptor();
ROLECONFIG_TYPE_FIELD.name = "type"
ROLECONFIG_TYPE_FIELD.full_name = ".KKSG.RoleConfig.type"
ROLECONFIG_TYPE_FIELD.number = 1
ROLECONFIG_TYPE_FIELD.index = 0
ROLECONFIG_TYPE_FIELD.label = 3
ROLECONFIG_TYPE_FIELD.has_default_value = false
ROLECONFIG_TYPE_FIELD.default_value = {}
ROLECONFIG_TYPE_FIELD.type = 9
ROLECONFIG_TYPE_FIELD.cpp_type = 9
ROLECONFIG_VALUE_FIELD.name = "value"
ROLECONFIG_VALUE_FIELD.full_name = ".KKSG.RoleConfig.value"
ROLECONFIG_VALUE_FIELD.number = 2
ROLECONFIG_VALUE_FIELD.index = 1
ROLECONFIG_VALUE_FIELD.label = 3
ROLECONFIG_VALUE_FIELD.has_default_value = false
ROLECONFIG_VALUE_FIELD.default_value = {}
ROLECONFIG_VALUE_FIELD.type = 9
ROLECONFIG_VALUE_FIELD.cpp_type = 9
ROLECONFIG.name = "RoleConfig"
ROLECONFIG.full_name = ".KKSG.RoleConfig"
ROLECONFIG.nested_types = {}
ROLECONFIG.enum_types = {}
ROLECONFIG.fields = {ROLECONFIG_TYPE_FIELD, ROLECONFIG_VALUE_FIELD}
ROLECONFIG.is_extendable = false
ROLECONFIG.extensions = {}
RoleConfig = protobuf.Message(ROLECONFIG)
|
constants = require 'constants'
log = require 'log'
Player = {
chassis = nil,
frontTyre = nil,
rearTyre = nil,
jFrontTyre = nil,
jRearTyre = nil,
}
function Player:init(world)
local x, y = 300, 300
self.chassis:init(world, x, y)
local frontTyreOffset = -self.chassis.length / 2
local rearTyreOffset = self.chassis.length / 2
self.frontTyre:init(world, x, y + frontTyreOffset)
self.rearTyre:init(world, x, y + rearTyreOffset)
self.jFrontTyre = love.physics.newRevoluteJoint(self.chassis.body, self.frontTyre.body, x, y + frontTyreOffset, false)
-- self.jFrontTyre:setLimits(0, 0)
-- self.jFrontTyre:setLimitsEnabled(true)
self.jRearTyre = love.physics.newRevoluteJoint(self.chassis.body, self.rearTyre.body, x, y + rearTyreOffset, false)
self.jRearTyre:setLimits(0, 0)
self.jRearTyre:setLimitsEnabled(true)
-- TODO destroy
end
function Player:update(dt)
self.frontTyre:update(dt)
self.rearTyre:update(dt)
end
-- function Player:keypressed(key, collider)
-- if self.control:isChangeDirectionKey(key) then
-- self:_changeDirection(collider)
-- end
-- end
-- function Player:touchpressed(x, y, collider)
-- if self.control:isChangeDirectionTouch(x, y) then
-- self:_changeDirection(collider)
-- end
-- end
function Player:control()
self.frontTyre:control()
end
function Player:draw()
self.frontTyre:draw()
self.rearTyre:draw()
self.chassis:draw()
end
function Player:new (o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
return Player
|
local htmlTags = require "HtmlTags"
local markdown = require "http.markdown"
local searchMgr = {}
local json = require"sys.json"
local CodeMgr = require "CodeMgr"
local SpecialSearchMgr = require "SpecialSearchMgr"
local keywordTbl = require "KeywordTbl"
local codeConfig = SAConfig.CodeConfig
function searchMgr:ParseKeywordPlain(tbl)
for k,v in pairs (tbl) do
tbl[k] = {richTxt = v, priority = 0}
end
return tbl
end
function searchMgr:ParseKeywordByRule(keywordInfoTbl)
local defaultTextType = "code"
local tbl = {}
local keywordsSubTbl,extra = keywordInfoTbl[1], keywordInfoTbl[2]
if not extra or not extra.parseRule then
for k,v in pairs (keywordsSubTbl or {}) do
local longKey = k
if extra and extra.title then
longKey = extra.title.."-"..longKey
end
tbl[longKey] = {richTxt = v, priority = extra.priority or 0, title = extra.title, key = k, textType = defaultTextType}
end
elseif extra.parseRule == 1 then
for _,kvPair in ipairs (keywordsSubTbl or {}) do
local longKey = kvPair[1]
if extra and extra.title then
longKey = extra.title.."-"..longKey
end
tbl[longKey] = {richTxt = kvPair[2], priority = kvPair[3] or 0, title = extra.title, key = kvPair[1], textType = defaultTextType}
end
elseif extra.parseRule == 2 then
for _,kvPair in ipairs(keywordsSubTbl or {}) do
local longKey = kvPair.key
if extra and extra.title then
longKey = extra.title.."-"..longKey
end
tbl[longKey] = {richTxt = kvPair.richTxt, priority = kvPair.priority or 0, title = extra.title, key = kvPair.key, textType = kvPair.textType or defaultTextType}
end
end
return tbl
end
function searchMgr:Init(bReload)
self:ParseKeywordPlain(keywordTbl)
local keywordsDir = "keywords/"
local allAlias = SAConfig.CodeConfig.Alias
local toLoadKeywords = {}
for idx,aliasTbl in pairs(allAlias) do
if string.find(aliasTbl[1], "keyword") then
local baseFileName = string.match(aliasTbl[2], "([%w_]+).lua")
print(baseFileName)
table.insert(toLoadKeywords, baseFileName)
end
end
for _,fileName in pairs(global.__extraDownload or {}) do
table.insert(toLoadKeywords, fileName)
end
for _, fileBaseName in pairs (toLoadKeywords) do
local moduleName = keywordsDir..fileBaseName
print("loading module for search "..moduleName)
local keywordInfoTbl
if not bReload then
keywordInfoTbl = require (moduleName)
else
keywordInfoTbl = dofile("process/one/"..moduleName..".lua")
end
local parsedTbl = self:ParseKeywordByRule(keywordInfoTbl)
for k,v in pairs (parsedTbl) do
keywordTbl[k] = v
end
end
end
function searchMgr:OnRefreshTick()
global.__extraDownload = {}
CodeMgr:DownLoadCode()
self:Init(true)
end
function searchMgr:IsAllKeywordMatch(toSearchTbl, keywordFromTbl)
local totalCount = #toSearchTbl or 1
local matchedCount = 0
for _,toSearchKey in ipairs(toSearchTbl) do
if string.find(string.lower(keywordFromTbl), string.lower(toSearchKey)) then
matchedCount = matchedCount + 1
-- return false
end
end
if matchedCount >= 1 then
return true, matchedCount * 10000 / totalCount
end
return false, 0
end
function searchMgr:GetSearchTblByInput(content)
local tosearchTbl = {}
for key in string.gmatch(content, "([^%+]+)") do
table.insert(tosearchTbl, key)
end
return tosearchTbl
end
function searchMgr:ConvetToRichTitle(key ,title, toSearchTbl)
local plainShowTxt = key.." - "..(title or "")
local ret = plainShowTxt
for _,toSearchKey in ipairs(toSearchTbl) do
local ignoreCasePattern = string.gsub(toSearchKey, "(%a)", function(c)
return string.format("[%s%s]", string.lower(c), string.upper(c))
end)
ret = string.gsub(ret, ignoreCasePattern, "<em>".."%1".."</em>")
end
return ret
end
-- 这是入口
function searchMgr:GetAnswer(content)
print("search text is: "..content.." lenth is "..#content)
local tosearchTbl = self:GetSearchTblByInput(content)
local ret = {}
local matchCount = 0
-- 检查是否能匹配特殊规则
local bMatched, specialResult = SpecialSearchMgr:GetSpecialResult(tosearchTbl)
if bMatched and specialResult then
table.insert(ret, specialResult)
matchCount = matchCount + 1
end
local candidate = {}
for keyword,item in pairs(keywordTbl) do
local bMatch, matchFactor = self:IsAllKeywordMatch(tosearchTbl, keyword)
if bMatch then
-- local showTitle = (item.key or keyword).." - " .. item.title
local showTitle = self:ConvetToRichTitle(item.key or keyword, item.title, tosearchTbl)
local showTxt = self:ConvertToReadbleSearchItem(keyword, item, showTitle)
table.insert(candidate, {showTxt, item.priority * matchFactor or 0})
matchCount = matchCount + 1
end
end
table.sort(candidate, function (a,b)
if a[2] > b[2] then return true end
end
)
for _,result in ipairs(candidate) do
table.insert(ret, result[1])
end
table.insert(ret, self:GetSummary(matchCount))
print("search hit count is "..matchCount)
local res = table.concat( ret, "" )
return res
end
function searchMgr:GetDetail(content)
print("search text is: "..content.." lenth is "..#content)
local ret = {}
local matchCount = 0
for keyword,item in pairs(keywordTbl) do
if keyword == content then
matchCount = matchCount + 1
local showTxt = self:ConvertToReadbleDetailTxt(keyword, item)
table.insert(ret, showTxt)
end
end
local res = table.concat( ret, global.httpMultiLineTag )
return res
end
function searchMgr:GetSummary(resultCount)
if resultCount > 0 then
return global.httpMultiLineTag..global.httpBoldTagBegin..global.summaryOkText..resultCount..global.httpBoldTagEnd
end
return global.summaryFailText
end
function searchMgr:GetDetailTips(count)
return global.httpBoldTagBegin..global.detialOkText..count..global.httpBoldTagEnd
end
function searchMgr:ConvertToReadbleSearchItem(keyword, item, showTitle)
local richTxt = item.richTxt
local firstWordIdx = string.find(richTxt, "[%\n%S]")
richTxt = string.sub(richTxt, firstWordIdx or 1)
richTxt = string.gsub(richTxt, "\n", "<br>")
richTxt = htmlTags.SearchItemContentBegin..richTxt..htmlTags.SearchItemContentEnd
return htmlTags.SearchItemBegin..keyword..htmlTags.SearchItemMiddle..showTitle..htmlTags.SearchItemEnd..richTxt
end
function searchMgr:PreHandleJsonTbl(tbl)
local toExchange = {}
for k,v in pairs(tbl) do
if type(v) == "string" and type(k) == "number" then
toExchange[k] = v
end
if type(v) == "table" then
self:PreHandleJsonTbl(v)
end
end
for k,v in pairs(toExchange) do
tbl[k] = nil
tbl[v] = k
end
end
function searchMgr:RecoverAliasTblKey(tbl)
if not self._keyAlias then return tbl end
local toReplace = {}
for k,v in pairs(tbl) do
local aliasCorresponding = self._keyAlias[k]
if aliasCorresponding then
toReplace[k] = aliasCorresponding
end
end
for k,v in pairs(toReplace) do
tbl[v] = tbl[k]
tbl[k] = nil
end
for k,v in pairs(tbl) do
if type(v) == "table" then
self:RecoverAliasTblKey(v)
end
end
end
function searchMgr:RecoverColorTblKey(tbl)
if not self._colorAlias then return tbl end
local toReplace = {}
for k,v in pairs(tbl) do
if k == self._colorAlias then
toReplace[k] = ".level"
end
end
for k,v in pairs(toReplace) do
tbl[v] = tbl[k]
tbl[k] = nil
end
for k,v in pairs(tbl) do
if type(v) == "table" then
self:RecoverColorTblKey(v)
end
end
end
function searchMgr:HandlePredifinedKeyWord(tbl)
for k,v in pairs(tbl) do
if type(v) == "table" then
self:HandlePredifinedKeyWord(v)
end
end
for k,v in pairs(tbl) do
if k == "URL" then
tbl[".url"] = v
break
end
end
for k,v in pairs(tbl) do
if k == "NOTE" then
tbl[".note"] = v
break
end
end
for k,v in pairs(tbl) do
if k == "UNFOLD" then
tbl[".noExpand"] = v
break
end
end
tbl["URL"] = nil
tbl["NOTE"] = nil
tbl["UNFOLD"] = nil
end
function searchMgr:GenerateMindMapFile(textTbl)
local mindMapConfig = SAConfig.CodeConfig.MindMapConfig
local dynamicJsFileName = mindMapConfig.GenDynamicFilePath..mindMapConfig.GenDynamicFileName
local f = io.open(dynamicJsFileName, "w")
local head = htmlTags.mindmapBundleDynamicBegin
local tail = htmlTags.mindmapBundleDynamicEnd
f:write(head)
f:write("\n")
self:PreHandleJsonTbl(textTbl)
self:RecoverAliasTblKey(textTbl)
self:GetColorKeyword(textTbl)
self:RecoverColorTblKey(textTbl)
self:HandlePredifinedKeyWord(textTbl)
f:write(json.encode(textTbl))
f:write(tail)
f:close()
local htmlFileName = "dynamic.html" -- nothing to be changed.
return htmlFileName
end
-- 替换括号(table初始化语句)中的key为非中文的字符,避免中文导致报错
function searchMgr:ReplaceTblKeyInBracketsToASC(str)
self._keyAlias = {}
local idx = 1
local ret = string.gsub(str, "{(.-)}", function(c)
local new = string.gsub(c, "([^%s]+)%s+=", function(d)
idx = idx + 1
local cachedIdx ="c_"..idx
self._keyAlias[cachedIdx] = d
return cachedIdx.." ="
end)
return "{"..new.."}"
end)
return ret
end
function searchMgr:GetColorKeyword(tbl)
local kw = tbl.colorKeyword
if kw then
self._colorAlias = kw
end
end
function searchMgr:ConvertToReadbleDetailTxt(keyword, item)
local richTxt = item.richTxt
if item.textType == "code" then
return htmlTags.CodeBegin..richTxt..htmlTags.CodeEnd
elseif item.textType == "markdown" then
return markdown(richTxt)
elseif item.textType == "mindmap" then
richTxt = self:ReplaceTblKeyInBracketsToASC(richTxt)
local textTbl = assert(load(richTxt))()
self:GetColorKeyword(textTbl)
local newIdx = self:GenerateMindMapFile(textTbl)
local newHref = "http://"..codeConfig.PublicHttpHost..":"..codeConfig.PublicHttpPort.."/"..codeConfig.LocalMindMapDir..newIdx
return htmlTags.httpRedirectScriptBegin..newHref..htmlTags.httpRedirectScriptEnd
end
return htmlTags.CodeBegin..richTxt..htmlTags.CodeEnd
end
searchMgr:Init()
registertick(function()
searchMgr:OnRefreshTick()
end, 1000 * 60 * 10 )
return searchMgr
|
----------------------------------------
--------------- Perkshop ---------------
----------------------------------------
------- Created by my_hat_stinks -------
----------------------------------------
-- cl_init.lua CLIENT --
-- --
-- Clientside intialisation stuff. --
----------------------------------------
// Hooks //
hook.Add( "PlayerBindPress", "PerkShop_Bind_Open", function( ply, bind, pressed )
if bind=="gm_showspare1" and pressed then
PerkShop:Open()
end
end)
local shopCommands = {
["!shop"]=true, ["!perk"]=true, ["!perks"]=true, ["!perkshop"]=true,
["/shop"]=true, ["/perk"]=true, ["/perks"]=true, ["/perkshop"]=true,
}
hook.Add( "OnPlayerChat", "PerkShop_Chat_Open", function( ply, msg )
if shopCommands[ msg:lower() ] then
if ply==LocalPlayer() then
PerkShop:Open()
end
return true
end
end)
|
local ABGS = require(script:GetCustomProperty("APIBasicGameState"))
-----------------------------------------------------------|
--[[
Loot Box animator
Moves the roulette wheel
]]
-----------------------------------------------------------|
local LOCAL_PLAYER = Game.GetLocalPlayer()
local RollEvent = script:GetCustomProperty("RollEvent")
local MovementSpeed = script:GetCustomProperty("MovementSpeed")
local NumberOfLoops = script:GetCustomProperty("NumberOfLoops")
local DefaultSpawn = script:GetCustomProperty("DefaultSpawn")
local SelectedWeapon = script:GetCustomProperty("SelectedWeapon"):WaitForObject()
local OtherWeapons = script:GetCustomProperty("OtherWeapons"):WaitForObject()
local WeaponRackSpinner = script:GetCustomProperty("WeaponRackSpinner"):WaitForObject()
local WeaponRackHolders = script:GetCustomProperty("WeaponRackHolders"):WaitForObject()
local RackSFX = script:GetCustomProperty("RackSFX"):WaitForObject()
local Door1 = script:GetCustomProperty("Door1"):WaitForObject()
local Door2 = script:GetCustomProperty("Doo2"):WaitForObject()
local DoorOpenSFX = script:GetCustomProperty("DoorOpenSFX")
local ArmMoveSFX = script:GetCustomProperty("ArmMoveSFX")
local WEAPON_TEXT = script:GetCustomProperty("WEAPON_TEXT"):WaitForObject()
local LootBoxCamera = script:GetCustomProperty("LootBoxCamera"):WaitForObject()
local DestinationPoint = script:GetCustomProperty("DestinationPoint"):WaitForObject()
local ReloadPoint = script:GetCustomProperty("ReloadPoint"):WaitForObject()
local Ease3D = require(script:GetCustomProperty("Ease3D"))
local ChuggSFX = script:GetCustomProperty("ChuggSFX"):WaitForObject()
local defaultCamera = nil
local holderEntry = {}
local numberOfHolders = 0
local animationTask = nil
local passToTask = {}
--Initilizes lootbox
function InitializeLootBox()
local isDestination = false
local isReload = false
for id, holder in ipairs(WeaponRackHolders:GetChildren()) do
if holder:GetWorldPosition() == DestinationPoint:GetWorldPosition() then
isDestination = true
elseif holder:GetWorldPosition() == ReloadPoint:GetWorldPosition() then
isReload = true
end
holderEntry[id] = {
holder = holder,
weaponPosition = holder:FindDescendantByName("WeaponPosition"),
atDestination = isDestination,
atReload = isReload,
hasSelected = false
}
isDestination = false
isReload = false
end
numberOfHolders = #WeaponRackHolders:GetChildren()
end
--does introduction for lootbox
function IntroAnimation()
--Door1:MoveTo(Vector3.New(0, 100, 0), 1, true)
--Door2:MoveTo(Vector3.New(0, -100, 0), 1, true)
--Ease3D.EasePosition(LootBoxCamera, Vector3.New(320, 0, 30), 4, Ease3D.EasingEquation.CUBIC, Ease3D.EasingDirection.INOUT)
--Ease3D.EaseRotation(LootBoxCamera, Rotation.New(0, -5, 180), 2, Ease3D.EasingEquation.SINE, Ease3D.EasingDirection.INOUT)
WEAPON_TEXT.visibility = Visibility.FORCE_OFF
Ease3D.EasePosition(
LootBoxCamera,
Vector3.New(320, 0, 50),
8,
Ease3D.EasingEquation.SINE,
Ease3D.EasingDirection.INOUT
)
Ease3D.EaseRotation(
LootBoxCamera,
Rotation.New(0, -15, 180),
8,
Ease3D.EasingEquation.SINE,
Ease3D.EasingDirection.INOUT
)
--Task.Wait(1)
World.SpawnAsset(DoorOpenSFX)
Ease3D.EasePosition(Door1, Vector3.New(0, 25, 0), .3, Ease3D.EasingEquation.ELASTIC, Ease3D.EasingDirection.INOUT)
Ease3D.EasePosition(Door2, Vector3.New(0, -25, 0), .3, Ease3D.EasingEquation.ELASTIC, Ease3D.EasingDirection.INOUT)
Task.Wait(.3)
Ease3D.EasePosition(Door1, Vector3.New(0, 125, 0), 1, Ease3D.EasingEquation.ELASTIC, Ease3D.EasingDirection.INOUT)
Ease3D.EasePosition(Door2, Vector3.New(0, -125, 0), 1, Ease3D.EasingEquation.ELASTIC, Ease3D.EasingDirection.INOUT)
if not LOCAL_PLAYER.clientUserData.shouldSkip then
RackSFX:Play()
end
--Task.Wait(1.5)
end
--Moves holders to the proper position
function MoveHolders(movementPercentage)
local next = 0
local firstReload = holderEntry[1].atReload
local firstDestination = holderEntry[1].atDestination
for id, entry in pairs(holderEntry) do
if id >= numberOfHolders then
next = 1
else
next = id + 1
end
entry.holder:MoveTo(holderEntry[next].holder:GetPosition(), MovementSpeed * movementPercentage, true)
entry.holder:RotateTo(holderEntry[next].holder:GetRotation(), MovementSpeed * movementPercentage, true)
if next == 1 then
entry.atDestination = firstDestination
entry.atReload = firstReload
else
entry.atDestination = holderEntry[next].atDestination
entry.atReload = holderEntry[next].atReload
end
end
Task.Wait(MovementSpeed * movementPercentage)
end
--Attaches items to the wheel
function LoadHolder(selectedHolderEntry, weaponToLoad)
local currentWeapon = selectedHolderEntry.weaponPosition:GetChildren()
if #currentWeapon > 0 then
currentWeapon[1].parent = OtherWeapons
currentWeapon[1]:SetPosition(Vector3.ZERO)
end
if weaponToLoad and Object.IsValid(weaponToLoad) then
weaponToLoad.parent = selectedHolderEntry.weaponPosition
weaponToLoad:SetPosition(Vector3.New(0, 0, -15))
end
end
--Animates the winning item
function AnimateSelection(selectedHolderEntry, player, Main)
-- setup
local originalPosition = selectedHolderEntry.holder:GetPosition()
local originalRotation = selectedHolderEntry.holder:GetRotation()
local originalWeaponPostion = selectedHolderEntry.weaponPosition:GetPosition()
local originalWeaponRotation = selectedHolderEntry.weaponPosition:GetRotation()
-- reveal animation
--selectedHolderEntry.holder:MoveTo(selectedHolderEntry.holder:GetPosition() + Vector3.New(40, 0, -30), 2, true)
--selectedHolderEntry.holder:RotateTo(selectedHolderEntry.holder:GetRotation() + Rotation.New(0, 90, 0), 3, true)
RackSFX:Stop()
World.SpawnAsset(ArmMoveSFX)
Ease3D.EaseRotation(
selectedHolderEntry.holder,
selectedHolderEntry.holder:GetRotation() + Rotation.New(0, 30, 0),
1.5,
Ease3D.EasingEquation.ELASTIC,
Ease3D.EasingDirection.INOUT
)
Task.Wait(.5)
Ease3D.EasePosition(
selectedHolderEntry.holder,
selectedHolderEntry.holder:GetPosition() + Vector3.New(40, 0, -50),
.5,
Ease3D.EasingEquation.BACK,
Ease3D.EasingDirection.INOUT
)
Task.Wait(1.5)
--selectedHolderEntry.weaponPosition:MoveTo(selectedHolderEntry.weaponPosition:GetPosition() + Vector3.UP * -70 + Vector3.FORWARD * 15, 1, true)
--selectedHolderEntry.weaponPosition:RotateContinuous(Rotation.New(100, 0, 0), 1, true)
if not LOCAL_PLAYER.clientUserData.shouldSkip then
ChuggSFX:Play()
end
--Main["object"]:RotateTo(Rotation.ZERO, 1, false)
Ease3D.EasePosition(
selectedHolderEntry.weaponPosition,
Vector3.New(100, -20, 0),
2,
Ease3D.EasingEquation.BACK,
Ease3D.EasingDirection.OUT
)
Ease3D.EaseRotation(
selectedHolderEntry.weaponPosition,
Rotation.New(0, 0, 0),
1,
Ease3D.EasingEquation.BACK,
Ease3D.EasingDirection.OUT
)
Ease3D.EaseRotation(
Main["object"],
Main["item"].data.Rotation_Offset + Rotation.New(0, 30, 90),
1,
Ease3D.EasingEquation.BACK,
Ease3D.EasingDirection.OUT
)
Task.Wait(1)
if not LOCAL_PLAYER.clientUserData.shouldSkip then
WEAPON_TEXT.visibility = Visibility.FORCE_ON
end
local slot = Main["item"]:GetSlot()
if slot == "Perks" then
slot = "Passive"
end
if slot ~= "Special" then
WEAPON_TEXT.text = string.format("You unlocked a new %s \n %s ", slot, Main["item"]:GetName())
else
WEAPON_TEXT.text = string.format("You have gained %s", Main["item"]:GetName())
end
--selectedHolderEntry.weaponPosition:RotateContinuous(Rotation.New(60, 0, 0), 1, true)
Task.Wait(7)
-- reset
Events.Broadcast("FinishedLoot")
Events.Broadcast("HideSkipButton")
WEAPON_TEXT.visibility = Visibility.FORCE_OFF
player:ClearOverrideCamera()
Events.Broadcast("VictoryUI.ForceCamera")
Events.Broadcast("ShowPlayerPanels",true)
selectedHolderEntry.weaponPosition:StopRotate()
selectedHolderEntry.weaponPosition:SetPosition(originalWeaponPostion)
selectedHolderEntry.weaponPosition:SetRotation(originalWeaponRotation)
selectedHolderEntry.holder:SetPosition(originalPosition)
selectedHolderEntry.holder:SetRotation(originalRotation)
end
--Skips the animation
function Skip()
if not animationTask:GetStatus() == TaskStatus.RUNNING then return end
-- reset
WEAPON_TEXT.visibility = Visibility.FORCE_ON
Events.Broadcast("FinishedLoot")
LOCAL_PLAYER:ClearOverrideCamera()
local slot = LOCAL_PLAYER.clientUserData.selectedWeapon:GetSlot()
if slot == "Perks" then
slot = "Passive"
end
if slot ~= "Special" then
WEAPON_TEXT.text =
string.format("You unlocked a new %s \n %s ", slot, LOCAL_PLAYER.clientUserData.selectedWeapon:GetName())
else
WEAPON_TEXT.text = string.format("You have gained %s", LOCAL_PLAYER.clientUserData.selectedWeapon:GetName())
end
Task.Spawn(
function()
WEAPON_TEXT.visibility = Visibility.FORCE_OFF
end,
3
)
if animationTask then
animationTask:Cancel()
animationTask = nil
end
RackSFX:Stop()
CleanLootBox()
Events.Broadcast("HideSkipButton")
end
--Empties the lootbox holders
function CleanLootBox()
local currentWeapon = nil
for _, w in pairs(OtherWeapons:GetChildren()) do
w:Destroy()
end
for _, h in pairs(holderEntry) do
currentWeapon = h.weaponPosition:GetChildren()
if #currentWeapon > 0 then
currentWeapon[1]:Destroy()
end
end
Door1:SetPosition(Vector3.ZERO)
Door2:SetPosition(Vector3.ZERO)
LootBoxCamera:SetPosition(Vector3.New(500, 0, -80))
LootBoxCamera:SetRotation(Rotation.New(0, 15, 180))
end
--Animates the Roll
function RollAnimation(player, Main)
passToTask[1] = player
passToTask[2] = Main
animationTask = Task.Spawn(function()
local player = passToTask[1]
local Main = passToTask[2]
defaultCamera = player:GetActiveCamera()
player:SetOverrideCamera(LootBoxCamera)
local weaponTable = OtherWeapons:GetChildren()
local selected = SelectedWeapon:GetChildren()[1]
print(selected.name)
local selectedHolder = nil
local slowdown = 1
Task.Wait(1)
print("performing intro")
IntroAnimation()
print("performing loops")
for i = 1, NumberOfLoops do
for i, w in pairs(weaponTable) do
MoveHolders(1)
for _, h in ipairs(holderEntry) do
if h.atReload == true then
LoadHolder(h, weaponTable[i])
break
end
end
end
end
print("setting selected")
for _, h in ipairs(holderEntry) do
if h.atReload == true then
selectedHolder = h
LoadHolder(h, selected)
break
end
end
print("slowing down")
for i, w in pairs(weaponTable) do
slowdown = slowdown + 0.1
MoveHolders(slowdown)
for _, h in ipairs(holderEntry) do
if h.atReload == true then
LoadHolder(h, weaponTable[i])
break
end
end
if slowdown >= 1.5 then
break
end
end
print("presenting selected")
while not selectedHolder.atDestination do
MoveHolders(slowdown)
end
AnimateSelection(selectedHolder, player, Main)
CleanLootBox()
end, 0)
end
--Calls the inisilization of the lootbox
function Roll(MainWeapon, others)
for _, v in pairs(others) do
local weapon = v:SpawnSkin()
if not weapon then
weapon = World.SpawnAsset(DefaultSpawn)
end
if v:GetSlot() == ("Primary" or "Secondary" or "Melee") then
weapon:SetRotation(v.data.Rotation_Offset + Rotation.New(0, 90, 0))
else
--weapon:SetRotation(v.data.Rotation_Offset + Rotation.New(0, 0, 0))
end
weapon.parent = OtherWeapons
end
local Main = MainWeapon:SpawnSkin()
if not Main then
Main = World.SpawnAsset(DefaultSpawn)
end
Main.parent = SelectedWeapon
if MainWeapon:GetSlot() == ("Primary" or "Secondary" or "Melee") then
Main:SetRotation(MainWeapon.data.Rotation_Offset + Rotation.New(0, 90, 0))
end
LOCAL_PLAYER.clientUserData.selectedWeapon = MainWeapon
RollAnimation(Game.GetLocalPlayer(), {["item"] = MainWeapon, ["object"] = Main})
end
InitializeLootBox()
function OnGameStateChanged(oldState, newState, hasDuration, time)
if newState == ABGS.GAME_STATE_LOBBY and oldState ~= ABGS.GAME_STATE_LOBBY then
if animationTask then
Skip()
end
end
end
Events.Connect("GameStateChanged", OnGameStateChanged)
Events.Connect("LootboxRoll", Roll)
Events.Connect("Lootbox.SkipAnimation", Skip)
Events.Connect(RollEvent, RollAnimation)
|
--[[
Delete key with match the repr.
Accepted parameters:
Keys:
key_name - repr
Return value:
delete number
--]]
redis.replicate_commands()
local cursor = '0'
local delete_count = 0
repeat
local result = redis.call('scan', cursor, 'MATCH', KEYS[1], 'COUNT', 100)
cursor = result[1]
local list = result[2]
delete_count = delete_count + #list
redis.call('del', unpack(list))
until (cursor == '0')
return delete_count
|
local st = GS.new()
local W, H
local title, title_width, title_height
local image, next_state
function st:enter(_, t, ns)
W = love.graphics.getWidth()
H = love.graphics.getHeight()
title = t
image = Image[t]
title_width = Font.slkscr[70]:getWidth(title)
title_height = Font.slkscr[70]:getHeight(title)
next_state = ns
end
function st:keypressed(key, code)
if key == ' ' or key == 'return' then
GS.transition(next_state, .5)
end
end
local t = 0
function st:update(dt)
t = t + dt
end
function st:draw()
love.graphics.setColor(255,255,255)
love.graphics.setFont(Font.slkscr[70])
love.graphics.rectangle('fill', 20,40, W-40, title_height)
love.graphics.setColor(0,0,0)
love.graphics.print(title, (W-title_width)/2, 40)
love.graphics.setColor(255,255,255)
love.graphics.draw(image, W/2,H/2+30,0,2,2, image:getWidth()/2,image:getHeight()/2)
love.graphics.setColor(255,255,255,(math.sin(t)*.5+.5) * 100 + 155)
love.graphics.setFont(Font.slkscr[40])
love.graphics.printf("Press [space] to continue", 0,H-70,W, 'center')
end
return st
|
vim.opt.termguicolors = true
require("bufferline").setup{
diagnostics = "nvim_lsp"
}
|
---
-- Get the total item count in the turtle's inventory.
-- @return the amount of items.
function getItemCount()
logger.debug("Getting item count...")
local count = 0
for i = 1, 16 do
local items = turtle.getItemCount(i)
logger.debug("Found " .. items .. " items in slot " .. i .. ".")
count = count + items
end
logger.debug("Found " .. count .. " items.")
return count
end
---
-- Check if the turtle's inventory is full.
-- @return false if at least one slot has 0 items in it.
function isInventoryFull()
logger.debug("Finding empty slot...")
for i = 1, 16 do
if turtle.getItemCount(i) == 0 then
logger.debug("Found empty slot: " .. i .. ".")
return false
end
end
logger.debug("Found no empty slot.")
return true
end
---
-- Refuel the turtle using items from the turtle's inventory.
-- The turtle's cursor position is returned to its previous slot.
function refuel()
logger.debug("Refueling from turtle inventory...")
local slot = turtle.getSelectedSlot()
for i = 1, 16 do
turtle.select(i)
turtle.refuel()
end
turtle.select(slot)
end
---
-- Grab as many items as we can from in front of the turtle.
function suckForward()
local before = getItemCount()
repeat
before = getItemCount()
turtle.suck()
until before == getItemCount()
end
---
-- Grab as many items as we can from above the turtle.
function suckUp()
local before = getItemCount()
repeat
before = getItemCount()
turtle.suckUp()
until before == getItemCount()
end
---
-- Grab as many items as we can from below the turtle.
function suckDown()
local before = getItemCount()
repeat
before = getItemCount()
turtle.suckDown()
until before == getItemCount()
end
---
-- Try to drop all items in front of the turtle.
-- @return true if all items could be dropped successfully.
function dropAll()
logger.debug("Dropping items...")
local slot = turtle.getSelectedSlot()
local success = true
for i = 1, 16 do
turtle.select(i)
if not turtle.drop() and turtle.getItemCount() ~= 0 then
logger.debug("Could not drop item in slot " .. i .. ".")
success = false
end
end
turtle.select(slot)
return success
end
---
-- Try to drop all items above the turtle.
-- @return true if all items could be dropped successfully
function dropAllUp()
logger.debug("Dropping items above turtle...")
local slot = turtle.getSelectedSlot()
local success = true
for i = 1, 16 do
turtle.select(i)
if not turtle.dropUp() and turtle.getItemCount() ~= 0 then
logger.debug("Could not drop item in slot " .. i .. ".")
success = false
end
end
turtle.select(slot)
return success
end
---
-- Try to drop all items below the turtle.
-- @return true if all items could be dropped successfully
function dropAllDown()
logger.debug("Dropping items below turtle...")
local slot = turtle.getSelectedSlot()
local success = true
for i = 1, 16 do
turtle.select(i)
if not turtle.dropDown() and turtle.getItemCount() ~= 0 then
logger.debug("Could not drop item in slot " .. i .. ".")
success = false
end
end
turtle.select(slot)
return success
end |
--[[
Copyright 2014-2015 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.
--]]
local spawn = require('coro-spawn')
local split = require('coro-split')
return function (command, ...)
local child = spawn(command, {
args = {...},
-- Tell spawn to create coroutine pipes for stdout and stderr only
stdio = {nil, true, true}
})
local stdout, stderr, code, signal
-- Split the coroutine into three sub-coroutines and wait for all three.
split(function ()
local parts = {}
for data in child.stdout.read do
parts[#parts + 1] = data
end
stdout = table.concat(parts)
end, function ()
local parts = {}
for data in child.stderr.read do
parts[#parts + 1] = data
end
stderr = table.concat(parts)
end, function ()
code, signal = child.waitExit()
end)
return stdout, stderr, code, signal
end |
local LIFX = require "lifx.types"
local builder = {}
local function build_header(mac, msg_size, msg_type)
local flags = 0
flags = flags | (LIFX.PROTOCOL_NUMBER << LIFX.HEADER_FLAGS_PROTOCOL_BITS_SHIFT)
flags = flags | (1 << LIFX.HEADER_FLAGS_ADDRESSABLE_BITS_SHIFT)
local target = {}
if mac == nil then -- No provided MAC will default to setting header to broadcast
flags = flags | (1 << LIFX.HEADER_FLAGS_TAGGED_BITS_SHIFT)
for i = 1, 8 do
target[i] = 0
end
else
target[1] = mac[1]
target[2] = mac[2]
target[3] = mac[3]
target[4] = mac[4]
target[5] = mac[5]
target[6] = mac[6]
target[7] = 0 -- byte 7 always 0
target[8] = 0 -- byte 8 always 0
end
local requiredFlags = 0
-- requiredFlags = requiredFlags | (1 << HEADER_ACK_REQUIRED_BITS_SHIFT) BA: Do not require ACK until we can properly handle it
requiredFlags = requiredFlags | (1 << LIFX.HEADER_RES_REQUIRED_BITS_SHIFT)
-- set a source value so target device sends a unicast response, not broadcast
-- TODO: If we want to generate attribute change events on ACKS, generate a unique source id for every message to correlate request and response. Setting an arbitrary source id of 99 for now.
return string.pack(
"<I2I2I4I1I1I1I1I1I1I1I1I6I1xI8I2xx",
msg_size,
flags,
99,
target[1],
target[2],
target[3],
target[4],
target[5],
target[6],
target[7],
target[8],
0,
requiredFlags,
0,
msg_type
)
end
local function build_set_power_payload(on)
local level = 0
if on then
level = LIFX.POWER_ON
end
return string.pack("<I2I4", level, LIFX.DEFAULT_TRANSITION_TIME)
end
local function build_set_waveform_optional_payload(hue, sat, bri, kel)
return string.pack(
"<I1I1I2I2I2I2I4fi2I1I1I1I1I1",
0,
0,
hue or 0,
sat or 0,
bri or 0,
kel or 0,
LIFX.DEFAULT_TRANSITION_TIME,
1,
0,
2,
hue and 1 or 0,
sat and 1 or 0,
bri and 1 or 0,
kel and 1 or 0
)
end
function builder.build_get_message(mac)
return build_header(mac, LIFX.HEADER_SIZE, LIFX.MSG_TYPE_GET)
end
function builder.build_getversion(mac)
return build_header(mac, LIFX.HEADER_SIZE, LIFX.MSG_TYPE_GETVERSION)
end
function builder.build_getlabel(mac)
return build_header(mac, LIFX.HEADER_SIZE, LIFX.MSG_TYPE_GETLABEL)
end
function builder.build_set_power_message(mac, power)
local hdr = build_header(mac, LIFX.HEADER_SIZE + LIFX.SETPOWER_PAYLOAD_SIZE, LIFX.MSG_TYPE_SETPOWER)
local payload = build_set_power_payload(power)
return string.pack("c" .. LIFX.HEADER_SIZE .. "c" .. LIFX.SETPOWER_PAYLOAD_SIZE, hdr, payload)
end
function builder.build_set_waveform_optional_message(mac, hue, sat, bri, kel)
local hdr =
build_header(mac, LIFX.HEADER_SIZE + LIFX.SETWAVEFORMOPTIONAL_PAYLOAD_SIZE, LIFX.MSG_TYPE_SETWAVEFORMOPTIONAL)
local payload = build_set_waveform_optional_payload(hue, sat, bri, kel)
return string.pack("c" .. LIFX.HEADER_SIZE .. "c" .. LIFX.SETWAVEFORMOPTIONAL_PAYLOAD_SIZE, hdr, payload)
end
return builder
|
DOORS_STATIC_MESHES = {}
SPAWNS_UNLOCKED = {}
ROOMS_UNLOCKED = {}
BARRICADES = {}
SM_MysteryBoxes = {}
Active_MysteryBox_ID = nil
OpenedMysteryBox_Data = nil
MAP_POWER_SM = nil
MAP_POWER_SM_HANDLE = nil
MAP_PAP_SM = nil
SM_Wunderfizzes = {}
Active_Wunderfizz_ID = nil
local Wunderfizz_Bought_Timeout
local Wunderfizz_Finished_Waiting_Timeout
local Wunderfizz_Fake_Bottles_Interval
local Wunderfizz_Particle_Ref
function DestroyMapDoors()
for k, v in pairs(StaticMesh.GetAll()) do
if v:GetValue("DoorID") then
v:Destroy()
end
end
end
function SpawnMapDoors()
for i, v in ipairs(MAP_DOORS) do
local SM = StaticMesh(
v.location,
v.rotation,
v.model
)
SM:SetScale(v.scale)
SM:SetValue("DoorID", i, true)
table.insert(DOORS_STATIC_MESHES, SM)
end
end
function GetMapDoorFromID(door_id)
for k, v in pairs(StaticMesh.GetPairs()) do
if v:GetValue("DoorID") == door_id then
return v
end
end
return false
end
function CreatePackAPunch(location, rotation)
local SM = StaticMesh(
location,
rotation,
"vzombies-assets::pack_a_punch"
)
SM:SetScale(Vector(0.01, 0.01, 0.01))
SM:SetValue("IsPackAPunch", true, true)
SM:SetValue("CanBuyPackAPunch", true, true)
MAP_PAP_SM = SM
end
if MAP_PACK_A_PUNCH then
CreatePackAPunch(MAP_PACK_A_PUNCH.location, MAP_PACK_A_PUNCH.rotation)
end
if MAP_POWER then
local SM = StaticMesh(
MAP_POWER.location,
MAP_POWER.rotation,
"vzombies-assets::power_base"
)
SM:SetScale(Vector(0.01, 0.01, 0.01))
SM:SetValue("MapPower", true, true)
MAP_POWER_SM = SM
local SM_Handle = StaticMesh(
MAP_POWER.handle_location,
MAP_POWER.handle_rotation,
"vzombies-assets::power_handle"
)
SM_Handle:SetScale(Vector(0.01, 0.01, 0.01))
SM_Handle:SetCollision(CollisionType.NoCollision)
SM_Handle:SetValue("MapPowerHANDLE", true, true)
MAP_POWER_SM_HANDLE = SM_Handle
else
POWER_ON = true
end
function ResetMapPower()
if MAP_POWER then
POWER_ON = false
Events.BroadcastRemote("SetClientPowerON", false)
MAP_POWER_SM_HANDLE:SetRotation(MAP_POWER.handle_rotation)
end
end
function PlayerTurnPowerON(ply, power_sm)
--print(ply, power_sm)
if not POWER_ON then
if power_sm:IsValid() then
if power_sm == MAP_POWER_SM then
if ply:GetValue("ZMoney") ~= -666 then -- Means that they shouldn't do anything
local char = ply:GetControlledCharacter()
if char then
if not char:GetValue("PlayerDown") then
POWER_ON = true
ROOMS_UNLOCKED[-1] = true
MAP_POWER_SM_HANDLE:RotateTo(MAP_POWER.rotation, 2, 0)
Events.BroadcastRemote("PowerONSound")
for i, v in ipairs(MAP_DOORS) do
if v.price == 0 then
local good_needed_power = false
for i2, v2 in ipairs(v.required_rooms) do
if v2 == -1 then
good_needed_power = true
break
end
end
if good_needed_power then
local good_required_all = true
for i2, v2 in ipairs(v.required_rooms) do
if not ROOMS_UNLOCKED[v2] then
good_required_all = false
break
end
end
if good_required_all then
local map_door = GetMapDoorFromID(i)
if map_door then
map_door:Destroy()
for i2, v2 in ipairs(v.between_rooms) do
UnlockRoom(v2)
end
end
end
end
end
end
end
end
end
end
end
end
end
VZ_EVENT_SUBSCRIBE("Events", "TurnPowerON", PlayerTurnPowerON)
function DestroyMapPerks()
for k, v in pairs(StaticMesh.GetAll()) do
if v:GetValue("MapPerk") then
v:Destroy()
end
end
end
function SpawnPerk(perk_name, location, rotation)
local SM = StaticMesh(
location,
rotation,
PERKS_CONFIG[perk_name].Asset
)
SM:SetScale(PERKS_CONFIG[perk_name].scale)
SM:SetValue("MapPerk", perk_name, true)
SM:SetValue("ProneMoney", true, false)
return SM
end
Package.Export("SpawnPerk", SpawnPerk)
function SpawnMapPerks()
if MAP_PERKS then
for k, v in pairs(MAP_PERKS) do
SpawnPerk(k, v.location, v.rotation)
end
end
end
function SpawnBearForMBOX(SM)
local Bear_SM = StaticMesh(
Vector(0, 0, 0),
Rotator(0, 0, 0),
"vzombies-assets::mystery_box_fake_bear"
)
Bear_SM:SetScale(Vector(0.01, 0.01, 0.01))
Bear_SM:AttachTo(SM, AttachmentRule.SnapToTarget, "")
Bear_SM:SetRelativeLocation(Vector(0, 0, 5000))
Bear_SM:SetRelativeRotation(Rotator(0, 0, 0))
Bear_SM:SetCollision(CollisionType.NoCollision)
return Bear_SM
end
if MAP_MYSTERY_BOXES then
for i, v in ipairs(MAP_MYSTERY_BOXES) do
local SM = StaticMesh(
v.location,
v.rotation,
"vzombies-assets::mystery_box"
)
SM:SetScale(Vector(0.01, 0.01, 0.01))
table.insert(SM_MysteryBoxes, {
mbox = SM,
bear = SpawnBearForMBOX(SM),
})
end
end
function OpenedMBOXResetStage1()
Timer.ClearTimeout(OpenedMysteryBox_Data.MoveTimeout)
Timer.ClearInterval(OpenedMysteryBox_Data.FakeInterval)
OpenedMysteryBox_Data.MoveTimeout = nil
OpenedMysteryBox_Data.FakeInterval = nil
if OpenedMysteryBox_Data.fweap then
OpenedMysteryBox_Data.fweap:Destroy()
OpenedMysteryBox_Data.fweap = nil
end
end
function OpenedMBOXResetStage2()
Timer.ClearTimeout(OpenedMysteryBox_Data.MoveTimeout)
OpenedMysteryBox_Data.realweap:Destroy()
OpenedMysteryBox_Data.SM_Attach:Destroy()
end
function OpenedMBOXResetStage3(real_reset)
OpenedMysteryBox_Data.SM_Attach:Destroy()
OpenedMysteryBox_Data.bear:Destroy()
if real_reset then
Timer.ClearTimeout(OpenedMysteryBox_Data.bearTimeout)
end
end
function ResetMBOX(id)
if OpenedMysteryBox_Data then
if OpenedMysteryBox_Data.FakeInterval then
OpenedMBOXResetStage1()
elseif OpenedMysteryBox_Data.realweap then
OpenedMBOXResetStage2()
elseif OpenedMysteryBox_Data.bear then
OpenedMBOXResetStage3(true)
end
OpenedMysteryBox_Data = nil
end
SM_MysteryBoxes[id].mbox:SetValue("CanBuyMysteryBox", nil, true)
SM_MysteryBoxes[id].bear = SpawnBearForMBOX(SM_MysteryBoxes[id].mbox)
if (SM_MysteryBoxes[id].active_particle and SM_MysteryBoxes[id].active_particle:IsValid()) then
SM_MysteryBoxes[id].active_particle:Destroy()
end
Active_MysteryBox_ID = nil
end
function ResetMysteryBoxes()
if Active_MysteryBox_ID then
ResetMBOX(Active_MysteryBox_ID)
end
end
function PickNewMysteryBox()
local pick_tbl = {}
for i, v in ipairs(SM_MysteryBoxes) do
if v.bear then
table.insert(pick_tbl, i)
end
end
if table_count(pick_tbl) > 0 then -- If theres more than 1 box on the map
local random_pick_id = math.random(table_count(pick_tbl))
local random_pick = SM_MysteryBoxes[pick_tbl[random_pick_id]]
if Active_MysteryBox_ID then
ResetMBOX(Active_MysteryBox_ID)
end
random_pick.bear:Destroy()
random_pick.bear = nil
random_pick.mbox:SetValue("CanBuyMysteryBox", true, true)
random_pick.active_particle = Particle(
Vector(0, 0, 0),
Rotator(0, 0, 0),
Active_MysteryBox_Particle.path,
false,
true
)
random_pick.active_particle:SetScale(Active_MysteryBox_Particle.scale)
random_pick.active_particle:AttachTo(random_pick.mbox, AttachmentRule.SnapToTarget, "", 0)
random_pick.active_particle:SetRelativeLocation(Active_MysteryBox_Particle.relative_location)
random_pick.active_particle:SetRotation(Rotator(0, random_pick.active_particle:GetRotation().Yaw, 0))
Active_MysteryBox_ID = pick_tbl[random_pick_id]
end
end
function OpenedMBoxNewFakeWeapon()
if OpenedMysteryBox_Data.fweap then
OpenedMysteryBox_Data.fweap:Destroy()
end
local random_weap = Mystery_box_weapons[math.random(table_count(Mystery_box_weapons))]
--print(random_weap.weapon_name)
OpenedMysteryBox_Data.fweap = NanosWorldWeapons[random_weap.weapon_name](Vector(0, 0, 0), Rotator(0, 0, 0))
OpenedMysteryBox_Data.fweap:SetCollision(CollisionType.NoCollision)
OpenedMysteryBox_Data.fweap:SetGravityEnabled(false)
OpenedMysteryBox_Data.fweap:SetValue("MBOXFakeWeapon", true, false)
OpenedMysteryBox_Data.fweap:AttachTo(OpenedMysteryBox_Data.SM_Attach, AttachmentRule.SnapToTarget, "")
end
function OpenActiveMysteryBox(char)
SM_MysteryBoxes[Active_MysteryBox_ID].mbox:SetValue("CanBuyMysteryBox", false, true)
local SM = StaticMesh(
Vector(0, 0, 0),
Rotator(0, 0, 0),
"nanos-world::SM_None"
)
SM:SetCollision(CollisionType.NoCollision)
SM:AttachTo(SM_MysteryBoxes[Active_MysteryBox_ID].mbox, AttachmentRule.SnapToTarget, "")
SM:Detach()
SM:SetLocation(SM:GetLocation() + Vector(0, 0, Mystery_box_weapon_spawn_offset_z))
local targetTranslateTo = SM:GetLocation() + Vector(0, 0, Mystery_box_weapon_target_offset_z)
SM:TranslateTo(targetTranslateTo, Mystery_box_weapon_time, Mystery_box_translate_exp)
OpenedMysteryBox_Data = {
SM_Attach = SM,
FakeInterval = Timer.SetInterval(function()
OpenedMBoxNewFakeWeapon()
end, Mystery_box_fake_weapon_interval_ms),
MoveTimeout = Timer.SetTimeout(function()
OpenedMBOXResetStage1()
local mbox_weapons_count = table_count(Mystery_box_weapons)
local random_weap_id = math.random(mbox_weapons_count + 1)
if table_count(MAP_MYSTERY_BOXES) == 1 then
random_weap_id = math.random(mbox_weapons_count)
end
if random_weap_id <= mbox_weapons_count then
if char:IsValid() then
local random_weap = Mystery_box_weapons[random_weap_id]
OpenedMysteryBox_Data.realweap = NanosWorldWeapons[random_weap.weapon_name](Vector(0, 0, 0), Rotator(0, 0, 0))
OpenedMysteryBox_Data.realweap:SetCollision(CollisionType.NoCollision)
OpenedMysteryBox_Data.realweap:SetGravityEnabled(false)
OpenedMysteryBox_Data.realweap:SetValue("MBOXFinalWeaponForCharacterID", {char:GetID(), random_weap}, false)
OpenedMysteryBox_Data.realweap:AttachTo(OpenedMysteryBox_Data.SM_Attach, AttachmentRule.SnapToTarget, "")
OpenedMysteryBox_Data.SM_Attach:TranslateTo(SM_MysteryBoxes[Active_MysteryBox_ID].mbox:GetLocation() + Vector(0, 0, Mystery_box_weapon_spawn_offset_z), Mystery_box_weapon_time_reverse, Mystery_box_translate_exp)
OpenedMysteryBox_Data.MoveTimeout = Timer.SetTimeout(function()
OpenedMBOXResetStage2()
OpenedMysteryBox_Data = nil
SM_MysteryBoxes[Active_MysteryBox_ID].mbox:SetValue("CanBuyMysteryBox", true, true)
end, Mystery_box_weapon_time_reverse * 1000)
end
else
local Bear_SM = StaticMesh(
Vector(0, 0, 0),
Rotator(0, 0, 0),
"vzombies-assets::mystery_box_fake_bear"
)
Bear_SM:SetScale(Vector(0.01, 0.01, 0.01))
Bear_SM:AttachTo(OpenedMysteryBox_Data.SM_Attach, AttachmentRule.SnapToTarget, "")
Bear_SM:SetCollision(CollisionType.NoCollision)
OpenedMysteryBox_Data.bear = Bear_SM
OpenedMysteryBox_Data.bearTimeout = Timer.SetTimeout(function()
OpenedMBOXResetStage3()
OpenedMysteryBox_Data = nil
PickNewMysteryBox()
end, NewMysteryBox_Timeout_ms)
Events.BroadcastRemote("MBOXChangedSound")
end
end, Mystery_box_weapon_time * 1000),
}
OpenedMBoxNewFakeWeapon()
Events.BroadcastRemote("OpenMBOXSound", SM_MysteryBoxes[Active_MysteryBox_ID].mbox:GetLocation())
end
function UnlockRoom(id)
if not ROOMS_UNLOCKED[id] then
ROOMS_UNLOCKED[id] = true
for k, v in pairs(MAP_ROOMS[id]) do
if v.type == "ground" then
table.insert(SPAWNS_UNLOCKED, {
location = v.location,
rotation = v.rotation,
zspawnid = v.zspawnid
})
else
for k2, v2 in pairs(v.z_spawns) do
table.insert(SPAWNS_UNLOCKED, v2)
end
end
end
Events.Call("VZ_RoomUnlocked", id)
end
end
function DestroyBarricades()
for i, v in ipairs(BARRICADES) do
for k2, v2 in pairs(v.top.barricades) do
v2:Destroy()
end
for k2, v2 in pairs(v.ground.barricades) do
v2:Destroy()
end
v.top.root:Destroy()
v.ground.root:Destroy()
end
BARRICADES = {}
end
function ApplySMBarricadeOptions(SM)
SM:SetScale(Vector(2, 0.1, 0.025))
SM:SetCollision(CollisionType.NoCollision)
SM:SetMaterial("vzombies-assets::M_Plank")
end
function SpawnBarricade(zspawn, zspawnid)
local SM_Root = StaticMesh(
zspawn.barricade_location,
zspawn.barricade_rotation,
"nanos-world::SM_None"
)
SM_Root:SetValue("BarricadeSpawnID", zspawnid, true)
SM_Root:SetValue("BarricadeLife", 5, true)
SM_Root:SetCollision(CollisionType.NoCollision)
local SM_Root_Ground = StaticMesh(
zspawn.z_ground_debris_location,
Rotator(0, 0, 0),
"nanos-world::SM_None"
)
SM_Root_Ground:AttachTo(SM_Root, AttachmentRule.KeepWorld, "")
SM_Root_Ground:SetRelativeRotation(Barricades_Config.ground_root.rrotation)
SM_Root_Ground:SetCollision(CollisionType.NoCollision)
local SM_Barricade_1 = StaticMesh(
Vector(0, 0, 0),
Rotator(0, 0, 0),
"nanos-world::SM_Cube"
)
SM_Barricade_1:AttachTo(SM_Root, AttachmentRule.KeepWorld, "")
SM_Barricade_1:SetRelativeLocation(Barricades_Config.top[1].rlocation)
SM_Barricade_1:SetRelativeRotation(Barricades_Config.top[1].rrotation)
local SM_Barricade_2 = StaticMesh(
Vector(0, 0, 0),
Rotator(0, 0, 0),
"nanos-world::SM_Cube"
)
SM_Barricade_2:AttachTo(SM_Root, AttachmentRule.KeepWorld, "")
SM_Barricade_2:SetRelativeLocation(Barricades_Config.top[2].rlocation)
SM_Barricade_2:SetRelativeRotation(Barricades_Config.top[2].rrotation)
local SM_Barricade_3 = StaticMesh(
Vector(0, 0, 0),
Rotator(0, 0, 0),
"nanos-world::SM_Cube"
)
SM_Barricade_3:AttachTo(SM_Root, AttachmentRule.KeepWorld, "")
SM_Barricade_3:SetRelativeLocation(Barricades_Config.top[3].rlocation)
SM_Barricade_3:SetRelativeRotation(Barricades_Config.top[3].rrotation)
local SM_Barricade_4 = StaticMesh(
Vector(0, 0, 0),
Rotator(0, 0, 0),
"nanos-world::SM_Cube"
)
SM_Barricade_4:AttachTo(SM_Root, AttachmentRule.KeepWorld, "")
SM_Barricade_4:SetRelativeLocation(Barricades_Config.top[4].rlocation)
SM_Barricade_4:SetRelativeRotation(Barricades_Config.top[4].rrotation)
local SM_Barricade_5 = StaticMesh(
Vector(0, 0, 0),
Rotator(0, 0, 0),
"nanos-world::SM_Cube"
)
SM_Barricade_5:AttachTo(SM_Root, AttachmentRule.KeepWorld, "")
SM_Barricade_5:SetRelativeLocation(Barricades_Config.top[5].rlocation)
SM_Barricade_5:SetRelativeRotation(Barricades_Config.top[5].rrotation)
table.insert(BARRICADES, {
zspawnid = zspawnid,
top = {
root = SM_Root,
barricades = {
SM_Barricade_1,
SM_Barricade_2,
SM_Barricade_3,
SM_Barricade_4,
SM_Barricade_5,
},
},
ground = {
root = SM_Root_Ground,
barricades = {},
}
})
for k, v in pairs(BARRICADES) do
if v.top.root == SM_Root then
for i2, v2 in ipairs(v.top.barricades) do
ApplySMBarricadeOptions(v2)
end
end
end
end
function DamageBarricade(barricade, zombie)
local top_barricades = table_count(barricade.top.barricades)
local ground_barricades = table_count(barricade.ground.barricades)
if top_barricades > 0 then
local destroyed_loc = barricade.top.barricades[top_barricades]:GetLocation()
barricade.top.barricades[top_barricades]:Destroy()
barricade.top.barricades[top_barricades] = nil
barricade.top.root:SetValue("BarricadeLife", top_barricades - 1, true)
local SM_Barricade = StaticMesh(
Vector(0, 0, 0),
Rotator(0, 0, 0),
"nanos-world::SM_Cube"
)
SM_Barricade:AttachTo(barricade.ground.root, AttachmentRule.KeepWorld, "")
SM_Barricade:SetRelativeLocation(Barricades_Config.ground[ground_barricades + 1].rlocation)
SM_Barricade:SetRelativeRotation(Barricades_Config.ground[ground_barricades + 1].rrotation)
local play_sound_for_players = GetPlayersInRadius(destroyed_loc, RANDOM_SOUNDS.barricade_break.falloff_distance)
for i, v in ipairs(play_sound_for_players) do
Events.CallRemote("DamageBarricadeSound", v, VZ_RandomSound(RANDOM_SOUNDS.barricade_break), destroyed_loc)
end
ApplySMBarricadeOptions(SM_Barricade)
table.insert(barricade.ground.barricades, SM_Barricade)
end
end
function RepairBarricade(barricade)
local top_barricades = table_count(barricade.top.barricades)
local ground_barricades = table_count(barricade.ground.barricades)
if ground_barricades > 0 then
barricade.ground.barricades[ground_barricades]:Destroy()
barricade.ground.barricades[ground_barricades] = nil
barricade.top.root:SetValue("BarricadeLife", top_barricades + 1, true)
local SM_Barricade = StaticMesh(
Vector(0, 0, 0),
Rotator(0, 0, 0),
"nanos-world::SM_Cube"
)
SM_Barricade:AttachTo(barricade.top.root, AttachmentRule.KeepWorld, "")
SM_Barricade:SetRelativeLocation(Barricades_Config.top[top_barricades + 1].rlocation)
SM_Barricade:SetRelativeRotation(Barricades_Config.top[top_barricades + 1].rrotation)
local repaired_loc = barricade.top.root:GetLocation()
local play_sound_for_players = GetPlayersInRadius(repaired_loc, RANDOM_SOUNDS.barricade_slam.falloff_distance)
for i, v in ipairs(play_sound_for_players) do
Events.CallRemote("RepairBarricadeSound", v, VZ_RandomSound(RANDOM_SOUNDS.barricade_slam), repaired_loc)
end
ApplySMBarricadeOptions(SM_Barricade)
table.insert(barricade.top.barricades, SM_Barricade)
end
end
function SpawnMapBarricades()
for i, v in ipairs(MAP_ROOMS) do
for k2, v2 in pairs(v) do
if v2.type == "barricade" then
SpawnBarricade(MAP_ROOMS[i][k2], v2.zspawnid)
end
end
end
end
local curspawn_id = 1
for i, v in ipairs(MAP_ROOMS) do
for k2, v2 in pairs(v) do
MAP_ROOMS[i][k2].zspawnid = curspawn_id
if v2.z_spawns then
for k3, v3 in pairs(v2.z_spawns) do
v3.zspawnid = curspawn_id
end
end
curspawn_id = curspawn_id + 1
end
end
function GetBarricadeFromZSpawnID(zspawnid)
for k, v in pairs(BARRICADES) do
if v.zspawnid == zspawnid then
return k, v
end
end
end
function GetSpawnTargetFromZSpawnID(zspawnid)
for k, v in pairs(MAP_ROOMS) do
for k2, v2 in pairs(v) do
if v2.zspawnid == zspawnid then
return v2
end
end
end
end
function GetSpawnFromZSpawnID(zspawnid)
for k, v in pairs(SPAWNS_UNLOCKED) do
if v.zspawnid == zspawnid then
return v
end
end
end
VZ_EVENT_SUBSCRIBE("Events", "RepairBarricade", function(ply, zspawnid)
if ply:GetValue("ZMoney") ~= -666 then
local char = ply:GetControlledCharacter()
if char then
if not char:GetValue("PlayerDown") then
local bid, barricade = GetBarricadeFromZSpawnID(zspawnid)
if bid then
if barricade.top.root:GetValue("BarricadeLife") < 5 then
RepairBarricade(barricade)
AddMoney(ply, Player_Repair_Barricade_Money)
end
end
end
end
end
end)
for i, v in ipairs(MAP_WEAPONS) do
if NanosWorldWeapons[v.weapon_name] then
local weapon = NanosWorldWeapons[v.weapon_name](v.location, v.rotation)
weapon:SetValue("MapWeaponID", i, true)
weapon:SetGravityEnabled(false)
weapon:SetCollision(CollisionType.NoCollision)
else
Package.Error("vzombies : Invalid weapon name '" .. v.weapon_name .. "' in zombie map config (MAP_WEAPONS[" .. tostring(i) .. "])")
end
end
if MAP_WUNDERFIZZ then
for k, v in pairs(MAP_WUNDERFIZZ) do
local Wunder_SM = StaticMesh(
v.location,
v.rotation,
"vzombies-assets::wunderfizz_body"
)
table.insert(SM_Wunderfizzes, {body = Wunder_SM})
end
end
function ResetRunningWunderfizzStage1()
if SM_Wunderfizzes[Active_Wunderfizz_ID].fake_bottle then
SM_Wunderfizzes[Active_Wunderfizz_ID].fake_bottle:Destroy()
SM_Wunderfizzes[Active_Wunderfizz_ID].fake_bottle = nil
end
if (Wunderfizz_Particle_Ref and Wunderfizz_Particle_Ref:IsValid()) then
Wunderfizz_Particle_Ref:Destroy()
end
Wunderfizz_Particle_Ref = nil
Timer.ClearTimeout(Wunderfizz_Bought_Timeout)
Wunderfizz_Bought_Timeout = nil
Timer.ClearInterval(Wunderfizz_Fake_Bottles_Interval)
Wunderfizz_Fake_Bottles_Interval = nil
end
function ResetRunningWunderfizzStage2()
if SM_Wunderfizzes[Active_Wunderfizz_ID].real_bottle then
SM_Wunderfizzes[Active_Wunderfizz_ID].real_bottle:Destroy()
SM_Wunderfizzes[Active_Wunderfizz_ID].real_bottle = nil
end
SM_Wunderfizzes[Active_Wunderfizz_ID].body:SetValue("CanBuyWunder", true, true)
Timer.ClearTimeout(Wunderfizz_Finished_Waiting_Timeout)
Wunderfizz_Finished_Waiting_Timeout = nil
end
function ResetWunderfizz(id)
SM_Wunderfizzes[id].body:SetValue("CanBuyWunder", nil, true)
SM_Wunderfizzes[id].ball:Destroy()
SM_Wunderfizzes[id].ball = nil
if Wunderfizz_Bought_Timeout then
ResetRunningWunderfizzStage1()
elseif Wunderfizz_Finished_Waiting_Timeout then
ResetRunningWunderfizzStage2()
end
Active_Wunderfizz_ID = nil
end
function ResetWunderfizzes()
if Active_Wunderfizz_ID then
ResetWunderfizz(Active_Wunderfizz_ID)
end
end
function PickNewWunderfizz()
local pick_tbl = {}
for i, v in ipairs(SM_Wunderfizzes) do
if not v.ball then
table.insert(pick_tbl, i)
end
end
if table_count(pick_tbl) > 0 then -- If theres more than 1 wunder on the map
local random_pick_id = math.random(table_count(pick_tbl))
local random_pick = SM_Wunderfizzes[pick_tbl[random_pick_id]]
if Active_Wunderfizz_ID then
ResetWunderfizz(Active_Wunderfizz_ID)
end
random_pick.ball = StaticMesh(
random_pick.body:GetLocation(),
random_pick.body:GetRotation(),
"vzombies-assets::wunderfizz_ball"
)
random_pick.ball:SetCollision(CollisionType.NoCollision)
random_pick.body:SetValue("CanBuyWunder", true, true)
Active_Wunderfizz_ID = pick_tbl[random_pick_id]
end
end
function FakeBottleInterval()
if SM_Wunderfizzes[Active_Wunderfizz_ID].fake_bottle then
SM_Wunderfizzes[Active_Wunderfizz_ID].fake_bottle:Destroy()
end
local random_pick_id = math.random(table_count(PERKS_CONFIG))
local random_pick
local count = 0
for k, v in pairs(PERKS_CONFIG) do
count = count + 1
if random_pick_id == count then
random_pick = v
break
end
end
SM_Wunderfizzes[Active_Wunderfizz_ID].fake_bottle = StaticMesh(
SM_Wunderfizzes[Active_Wunderfizz_ID].body:GetLocation() + Wonderfizz_Bottles_Offset,
SM_Wunderfizzes[Active_Wunderfizz_ID].body:GetRotation(),
random_pick.bottle_asset
)
SM_Wunderfizzes[Active_Wunderfizz_ID].fake_bottle:SetCollision(CollisionType.NoCollision)
SM_Wunderfizzes[Active_Wunderfizz_ID].fake_bottle:SetScale(Vector(0.01, 0.01, 0.01))
end
function OpenActiveWunderfizz(char)
SM_Wunderfizzes[Active_Wunderfizz_ID].body:SetValue("CanBuyWunder", false, true)
Wunderfizz_Particle_Ref = Particle(
SM_Wunderfizzes[Active_Wunderfizz_ID].body:GetLocation() + Wonderfizz_Particle_Offset,
SM_Wunderfizzes[Active_Wunderfizz_ID].body:GetRotation(),
Wonderfizz_Particle,
false,
true -- Auto Activate?
)
Wunderfizz_Bought_Timeout = Timer.SetTimeout(function()
ResetRunningWunderfizzStage1()
local random_move = math.random(100)
if (random_move <= Wonderfizz_Move_Percentage and table_count(SM_Wunderfizzes) > 1) then
local players_sound = GetPlayersInRadius(SM_Wunderfizzes[Active_Wunderfizz_ID].body:GetLocation() + Wonderfizz_Bottles_Offset, Wunderfizz_leave_Sound.falloff_distance)
for k, v in pairs(players_sound) do
Events.CallRemote("PlayWunderLeaveSound", v, SM_Wunderfizzes[Active_Wunderfizz_ID].body:GetLocation() + Wonderfizz_Bottles_Offset)
end
PickNewWunderfizz()
else
local pick_tbl = {}
local char_perks = char:GetValue("OwnedPerks")
for k, v in pairs(PERKS_CONFIG) do
if not char_perks[k] then
table.insert(pick_tbl, k)
end
end
if table_count(pick_tbl) > 0 then
local perk_selected = pick_tbl[math.random(table_count(pick_tbl))]
SM_Wunderfizzes[Active_Wunderfizz_ID].real_bottle = Prop(
SM_Wunderfizzes[Active_Wunderfizz_ID].body:GetLocation() + Wonderfizz_Bottles_Offset,
SM_Wunderfizzes[Active_Wunderfizz_ID].body:GetRotation(),
PERKS_CONFIG[perk_selected].bottle_asset
)
SM_Wunderfizzes[Active_Wunderfizz_ID].real_bottle:SetCollision(CollisionType.NoCollision)
SM_Wunderfizzes[Active_Wunderfizz_ID].real_bottle:SetScale(Vector(0.01, 0.01, 0.01))
SM_Wunderfizzes[Active_Wunderfizz_ID].real_bottle:SetGravityEnabled(false)
SM_Wunderfizzes[Active_Wunderfizz_ID].real_bottle:SetGrabbable(false)
SM_Wunderfizzes[Active_Wunderfizz_ID].real_bottle:SetValue("RealBottleData", {char:GetID(), perk_selected}, true)
Wunderfizz_Finished_Waiting_Timeout = Timer.SetTimeout(function()
ResetRunningWunderfizzStage2()
end, Wonderfizz_Real_Bottle_Destroyed_After_ms)
end
end
end, Wonderfizz_Real_Bottle_After_ms)
Wunderfizz_Fake_Bottles_Interval = Timer.SetInterval(function()
FakeBottleInterval()
end, Wonderfizz_Fake_Bottle_Interval_ms)
FakeBottleInterval()
end
VZ_EVENT_SUBSCRIBE("Events", "TakeWunderfizzPerk", function(ply, bottle)
if ply:IsValid() then
local char = ply:GetControlledCharacter()
if char then
if not char:GetValue("PlayerDown") then
if bottle then
if bottle:IsValid() then
local wunder_bottle = bottle:GetValue("RealBottleData")
if wunder_bottle then
if wunder_bottle[1] == char:GetID() then
local char_perks = char:GetValue("OwnedPerks")
if not char_perks[wunder_bottle[2]] then
ResetRunningWunderfizzStage2()
GiveCharacterPerk(char, wunder_bottle[2])
end
end
end
end
end
end
end
end
end)
function DestroyMapTeleporters()
for k, v in pairs(StaticMesh.GetAll()) do
if v:GetValue("TeleporterID") then
v:Destroy()
end
end
end
function CreateMapTeleporters()
if MAP_TELEPORTERS then
for i, v in ipairs(MAP_TELEPORTERS) do
--print(i, v.price)
local teleporter = StaticMesh(
v.location,
Rotator(0, 0, 0),
"nanos-world::SM_None"
)
teleporter:SetCollision(CollisionType.NoCollision)
teleporter:SetValue("TeleporterID", i, true)
teleporter:SetValue("CanTeleport", true, true)
end
end
end
if MAP_LIGHT_ZONES then
for i, v in ipairs(MAP_LIGHT_ZONES) do
--print(ZDEV_IsModeEnabled("ZDEV_DEBUG_TRIGGERS"))
local trigger = Trigger(v.location, v.rotation, v.scale * 31.5, TriggerType.Box, ZDEV_IsModeEnabled("ZDEV_DEBUG_TRIGGERS"), Color.RED)
VZ_ENT_EVENT_SUBSCRIBE(trigger, "BeginOverlap", function(self, triggered_by)
if NanosUtils.IsA(triggered_by, Character) then
local ply = triggered_by:GetPlayer()
if ply then
--print("FL Zone BeginOverlap")
local FLZones = triggered_by:GetValue("InFlashlightZones")
table.insert(FLZones, i)
triggered_by:SetValue("InFlashlightZones", FLZones, false)
if table_count(FLZones) == 1 then
AttachFlashLightToCurWeapon(triggered_by)
end
end
end
end)
VZ_ENT_EVENT_SUBSCRIBE(trigger, "EndOverlap", function(self, triggered_by)
if NanosUtils.IsA(triggered_by, Character) then
local ply = triggered_by:GetPlayer()
if ply then
--print("FL Zone EndOverlap")
local Was_in_zone
local FLZones = triggered_by:GetValue("InFlashlightZones")
for i2, v2 in ipairs(FLZones) do
if v2 == i then
table.remove(FLZones, i2)
Was_in_zone = true
break
end
end
if Was_in_zone then
triggered_by:SetValue("InFlashlightZones", FLZones, false)
if table_count(FLZones) == 0 then
local picked_thing = triggered_by:GetPicked()
if picked_thing then
if NanosUtils.IsA(picked_thing, Weapon) then
DetachFlashLightFromWeapon(picked_thing)
end
end
end
end
end
end
end)
end
end
if MAP_STATIC_MESHES then
for i, v in ipairs(MAP_STATIC_MESHES) do
local SM = StaticMesh(
v.location,
v.rotation,
v.model
)
SM:SetScale(v.scale)
SM:SetValue("MapSMID", i, false)
end
end |
-- Copyright (c) 2021 Kirazy
-- Part of Artisanal Reskins: Bob's Mods
--
-- See LICENSE in the project directory for license information.
-- Check to see if reskinning needs to be done.
if not (reskins.bobs and reskins.bobs.triggers.logistics.entities) then return end
-- Set input parameters
local inputs = {
type = "construction-robot",
icon_name = "construction-robot",
base_entity = "construction-robot",
mod = "bobs",
group = "logistics",
particles = {["medium"] = 2},
}
local tier_map = {
["construction-robot"] = {1, 2},
["bob-construction-robot-2"] = {2, 3},
["bob-construction-robot-3"] = {3, 4},
["bob-construction-robot-4"] = {4, 5},
["bob-construction-robot-5"] = {5, 5, util.color(reskins.lib.setting("reskins-bobs-fusion-robot-color"))},
}
-- Animations
local function generate_robot_animations(tint)
return
{
idle = {
layers = {
-- Base
{
filename = "__base__/graphics/entity/construction-robot/construction-robot.png",
priority = "high",
line_length = 16,
width = 32,
height = 36,
frame_count = 1,
shift = util.by_pixel(0,-4.5),
direction_count = 16,
hr_version = {
filename = "__base__/graphics/entity/construction-robot/hr-construction-robot.png",
priority = "high",
line_length = 16,
width = 66,
height = 76,
frame_count = 1,
shift = util.by_pixel(0,-4.5),
direction_count = 16,
scale = 0.5
}
},
-- Mask
{
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/construction-robot-mask.png",
priority = "high",
line_length = 16,
width = 32,
height = 36,
frame_count = 1,
shift = util.by_pixel(0,-4.5),
tint = tint,
direction_count = 16,
hr_version = {
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/hr-construction-robot-mask.png",
priority = "high",
line_length = 16,
width = 66,
height = 76,
frame_count = 1,
shift = util.by_pixel(0,-4.5),
tint = tint,
direction_count = 16,
scale = 0.5
}
},
-- Highlights
{
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/construction-robot-highlights.png",
priority = "high",
line_length = 16,
width = 32,
height = 36,
frame_count = 1,
shift = util.by_pixel(0,-4.5),
blend_mode = reskins.lib.blend_mode, -- "additive",
direction_count = 16,
hr_version = {
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/hr-construction-robot-highlights.png",
priority = "high",
line_length = 16,
width = 66,
height = 76,
frame_count = 1,
shift = util.by_pixel(0,-4.5),
blend_mode = reskins.lib.blend_mode, -- "additive",
direction_count = 16,
scale = 0.5
}
}
}
},
in_motion = {
layers = {
-- Base
{
filename = "__base__/graphics/entity/construction-robot/construction-robot.png",
priority = "high",
line_length = 16,
width = 32,
height = 36,
frame_count = 1,
shift = util.by_pixel(0, -4.5),
direction_count = 16,
y = 36,
hr_version = {
filename = "__base__/graphics/entity/construction-robot/hr-construction-robot.png",
priority = "high",
line_length = 16,
width = 66,
height = 76,
frame_count = 1,
shift = util.by_pixel(0, -4.5),
direction_count = 16,
y = 76,
scale = 0.5
}
},
-- Mask
{
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/construction-robot-mask.png",
priority = "high",
line_length = 16,
width = 32,
height = 36,
frame_count = 1,
shift = util.by_pixel(0, -4.5),
tint = tint,
direction_count = 16,
y = 36,
hr_version = {
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/hr-construction-robot-mask.png",
priority = "high",
line_length = 16,
width = 66,
height = 76,
frame_count = 1,
shift = util.by_pixel(0, -4.5),
tint = tint,
direction_count = 16,
y = 76,
scale = 0.5
}
},
-- Highlights
{
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/construction-robot-highlights.png",
priority = "high",
line_length = 16,
width = 32,
height = 36,
frame_count = 1,
shift = util.by_pixel(0, -4.5),
blend_mode = reskins.lib.blend_mode, -- "additive",
direction_count = 16,
y = 36,
hr_version = {
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/hr-construction-robot-highlights.png",
priority = "high",
line_length = 16,
width = 66,
height = 76,
frame_count = 1,
shift = util.by_pixel(0, -4.5),
blend_mode = reskins.lib.blend_mode, -- "additive",
direction_count = 16,
y = 76,
scale = 0.5
}
}
}
},
working = {
layers = {
-- Base
{
filename = "__base__/graphics/entity/construction-robot/construction-robot-working.png",
priority = "high",
line_length = 2,
width = 28,
height = 36,
frame_count = 2,
shift = util.by_pixel(-0.25, -5),
direction_count = 16,
animation_speed = 0.3,
hr_version = {
filename = "__base__/graphics/entity/construction-robot/hr-construction-robot-working.png",
priority = "high",
line_length = 2,
width = 57,
height = 74,
frame_count = 2,
shift = util.by_pixel(-0.25, -5),
direction_count = 16,
animation_speed = 0.3,
scale = 0.5
}
},
-- Mask
{
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/construction-robot-working-mask.png",
priority = "high",
line_length = 2,
width = 28,
height = 36,
frame_count = 2,
shift = util.by_pixel(-0.25, -5),
tint = tint,
direction_count = 16,
animation_speed = 0.3,
hr_version = {
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/hr-construction-robot-working-mask.png",
priority = "high",
line_length = 2,
width = 57,
height = 74,
frame_count = 2,
shift = util.by_pixel(-0.25, -5),
tint = tint,
direction_count = 16,
animation_speed = 0.3,
scale = 0.5
}
},
-- Highlights
{
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/construction-robot-working-highlights.png",
priority = "high",
line_length = 2,
width = 28,
height = 36,
frame_count = 2,
shift = util.by_pixel(-0.25, -5),
blend_mode = reskins.lib.blend_mode, -- "additive",
direction_count = 16,
animation_speed = 0.3,
hr_version = {
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/hr-construction-robot-working-highlights.png",
priority = "high",
line_length = 2,
width = 57,
height = 74,
frame_count = 2,
shift = util.by_pixel(-0.25, -5),
blend_mode = reskins.lib.blend_mode, -- "additive",
direction_count = 16,
animation_speed = 0.3,
scale = 0.5
}
}
}
},
shadow_idle = {
filename = "__base__/graphics/entity/construction-robot/construction-robot-shadow.png",
priority = "high",
line_length = 16,
width = 53,
height = 25,
frame_count = 1,
shift = util.by_pixel(33.5, 18.5),
direction_count = 16,
draw_as_shadow = true,
hr_version = {
filename = "__base__/graphics/entity/construction-robot/hr-construction-robot-shadow.png",
priority = "high",
line_length = 16,
width = 104,
height = 49,
frame_count = 1,
shift = util.by_pixel(33.5, 18.75),
direction_count = 16,
scale = 0.5,
draw_as_shadow = true
}
},
shadow_in_motion = {
filename = "__base__/graphics/entity/construction-robot/construction-robot-shadow.png",
priority = "high",
line_length = 16,
width = 53,
height = 25,
frame_count = 1,
shift = util.by_pixel(33.5, 18.5),
direction_count = 16,
draw_as_shadow = true,
hr_version = {
filename = "__base__/graphics/entity/construction-robot/hr-construction-robot-shadow.png",
priority = "high",
line_length = 16,
width = 104,
height = 49,
frame_count = 1,
shift = util.by_pixel(33.5, 18.75),
direction_count = 16,
scale = 0.5,
draw_as_shadow = true
}
},
shadow_working = {
filename = "__base__/graphics/entity/construction-robot/construction-robot-shadow.png",
priority = "high",
line_length = 16,
width = 53,
height = 25,
frame_count = 1,
repeat_count = 2,
shift = util.by_pixel(33.5, 18.5),
direction_count = 16,
draw_as_shadow = true,
hr_version = {
filename = "__base__/graphics/entity/construction-robot/hr-construction-robot-shadow.png",
priority = "high",
line_length = 16,
width = 104,
height = 49,
frame_count = 1,
repeat_count = 2,
shift = util.by_pixel(33.5, 18.75),
direction_count = 16,
scale = 0.5,
draw_as_shadow = true
}
}
}
end
-- Reskin entities, create and assign extra details
for name, map in pairs(tier_map) do
-- Fetch entity
local entity = data.raw[inputs.type][name]
-- Check if entity exists, if not, skip this iteration
if not entity then goto continue end
-- Parse map
local tier = map[1]
local fusion_robot_color
if (reskins.lib.setting("reskins-lib-tier-mapping") == "progression-map" and reskins.lib.setting("reskins-bobs-do-progression-based-robots")) then
tier = map[2]
fusion_robot_color = map[3]
end
-- Determine what tint we're using
inputs.tint = fusion_robot_color or reskins.lib.tint_index[tier]
reskins.lib.setup_standard_entity(name, tier, inputs)
-- Generate robot animations
local animations = generate_robot_animations(inputs.tint)
-- Fetch remnant
local remnant = data.raw["corpse"][name.."-remnants"]
-- Reskin remnants
remnant.animation = make_rotated_animation_variations_from_sheet (3, {
layers = {
-- Base
{
filename = "__base__/graphics/entity/construction-robot/remnants/construction-robot-remnants.png",
line_length = 1,
width = 60,
height = 58,
frame_count = 1,
variation_count = 1,
axially_symmetrical = false,
direction_count = 1,
shift = util.by_pixel(2, 1),
hr_version = {
filename = "__base__/graphics/entity/construction-robot/remnants/hr-construction-robot-remnants.png",
line_length = 1,
width = 120,
height = 114,
frame_count = 1,
variation_count = 1,
axially_symmetrical = false,
direction_count = 1,
shift = util.by_pixel(2, 1),
scale = 0.5,
}
},
-- Mask
{
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/remnants/construction-robot-remnants-mask.png",
line_length = 1,
width = 60,
height = 58,
frame_count = 1,
variation_count = 1,
axially_symmetrical = false,
direction_count = 1,
shift = util.by_pixel(2, 1),
tint = inputs.tint,
hr_version = {
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/remnants/hr-construction-robot-remnants-mask.png",
line_length = 1,
width = 120,
height = 114,
frame_count = 1,
variation_count = 1,
axially_symmetrical = false,
direction_count = 1,
shift = util.by_pixel(2, 1),
tint = inputs.tint,
scale = 0.5,
}
},
-- Highlights
{
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/remnants/construction-robot-remnants-highlights.png",
line_length = 1,
width = 60,
height = 58,
frame_count = 1,
variation_count = 1,
axially_symmetrical = false,
direction_count = 1,
shift = util.by_pixel(2, 1),
blend_mode = reskins.lib.blend_mode, -- "additive",
hr_version = {
filename = reskins.bobs.directory.."/graphics/entity/logistics/construction-robot/remnants/hr-construction-robot-remnants-highlights.png",
line_length = 1,
width = 120,
height = 114,
frame_count = 1,
variation_count = 1,
axially_symmetrical = false,
direction_count = 1,
shift = util.by_pixel(2, 1),
blend_mode = reskins.lib.blend_mode, -- "additive",
scale = 0.5,
}
}
}
})
-- Clear this, construction robots do not generate the corpse directly
entity.corpse = nil
-- Reskin entities
entity.idle = animations.idle
entity.in_motion = animations.in_motion
entity.working = animations.working
entity.shadow_idle = animations.shadow_idle
entity.shadow_in_motion = animations.shadow_in_motion
entity.shadow_working = animations.shadow_working
-- Setup remnants and destruction animation
reskins.bobs.make_robot_particle(entity)
-- Label to skip to next iteration
::continue::
end |
-- Copyright (c) 2021 StefanT <[email protected]>
-- See LICENSE.md in the project directory for license information.
--
-- Calculate the distance of two LuaControl objects to each other
--
-- @param obj1 The first LuaControl object
-- @param obj2 The second LuaControl object
-- @return The distance between the objects
--
function distance(obj1, obj2)
return ((obj1.position.x - obj2.position.x) ^ 2 + (obj1.position.y - obj2.position.y) ^ 2) ^ 0.5
end
--
-- Get the localized name for the signal.
--
-- @param id The signal ID to process
-- @return The localized name of the signal
--
function signalIdToLocalName(id)
if not id or not id.type then return nil end
if id.type == 'item' then
return game.item_prototypes[id.name].localised_name
elseif id.type == 'fluid' then
return game.fluid_prototypes[id.name].localised_name
elseif id.type == 'virtual' then
return game.virtual_signal_prototypes[id.name].localised_name
end
end
--
-- Convert a SignalID to a string.
--
-- @param id The signal ID to convert
-- @return A string representing the signal
--
function signalIdToStr(id)
if not id or not id.type then return nil end
return string.sub(id.type, 1, 1)..'-'..id.name
end
--
-- Convert a signal string to a SignalID.
--
-- @param sigstr The signal string to convert
-- @return The corresponding signal ID
--
function strToSignalId(sigstr)
if not sigstr then return nil end
local type = string.sub(sigstr, 1, 1)
local name = string.sub(sigstr, 3)
if type == 'i' then
return { type = 'item', name = name }
elseif type == 'f' then
return { type = 'fluid', name = name }
elseif type == 'v' then
return { type = 'virtual', name = name }
end
log("unknown signal string type '"..type.."'")
return nil
end
--
-- Convert a signal to a sprite path.
--
-- @param signal The signal to convert
-- @return The sprite path for the signal
--
function signalToSpritePath(signal)
if not signal then return nil end
if signal.type == "virtual" then
return 'virtual-signal/'..signal.name
else
return signal.type..'/'..signal.name
end
end
--
-- A pairs function that iterates over a table using the comparator function.
--
-- If no comparator function is given then the table is sorted by it's keys using
-- LUA's builtin comparator.
--
-- @param t The table to iterate
-- @param comp The function to compare two table entries, optional
-- @return The iterator for the table
--
function sortedPairs(t, comp)
-- collect the keys
local keys = {}
for k in pairs(t) do keys[#keys+1] = k end
-- if comparator function given, sort by it by passing the table and keys a, b,
-- otherwise just sort the keys
if comp then
table.sort(keys, comp)
else
table.sort(keys)
end
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
--
-- Split a string.
--
-- @param str The string to split
-- @param sep The separator character
-- @return A table with the splitted parts
--
function strSplit(str, sep)
local sep, result = sep or ":", {}
for s in string.gmatch(str, "([^"..sep.."]+)") do
table.insert(result, s)
end
return result
end
|
--======================================================================--
--== Coronium GS Corona SDK Client
--== @copyright Chris Byerley @develephant
--== @year 2014
--== @version 1.04
--== @license 2-clause BSD
--======================================================================--
require( 'gs.30logglobal' ) --== http://yonaba.github.io/30log/
local crypto = require( 'crypto' )
local socketlib = require( 'socket' )
local json = require( 'json' )
local utils = require( 'gs.utils' )
--== https://github.com/daveyang/EventDispatcher
local dispatcher = require( 'gs.EventDispatcher' )
--======================================================================--
--== GS Utils
--======================================================================--
local p = function( tbl )
if tbl then
if type( tbl ) == "table" then
utils:printTable( tbl )
else
print( tbl )
end
end
end
local function line( str )
return str .. "\r\n"
end
local function uuid( index )
--Object UUID generator
local index = index or 0
local salt = os.time() .. "coronium" .. ( math.random( os.time() ) + index )
local genId = crypto.digest( crypto.md5, salt )
local uuid = genId:sub( 1, 6 ) .. genId:sub( -4 )
return uuid
end
---Coronium GS Client
-- @author Chris Byerley
-- @copyright 2014 develephant
-- @license 2-clause BSD
-- @module CoroniumGSClient
local CoroniumGSClient = class()
---Create a new game client instance.
-- @function new
-- @tparam[opt=false] boolean asGlobal Automatically 'globalize' the module.
-- This includes the Pretty Printer 'p' method as well.
-- @treturn Client The newly created client.
-- @usage local gs = require( 'gs.CoroniumGSClient' ):new()
function CoroniumGSClient:__init( asGlobal )
--==Connections
self.host = nil
self.port = 7173
--== Event dispatcher
self.events = dispatcher()
--== Timers
self.process_timer = 0
self.ping_timer = 0
self.use_ping = false
--== Client socket
self.socket = nil
self.socket_closed = true
self.sendQ = {}
--== Connection Key
self.connection_key = nil
--== Game
self.game_id = nil
self.game_players_info = {} --==from server
--== Player
self.player_num = 0
self.player_handle = nil
self.player_data = nil
--== Globalize
if asGlobal then
_G.gs = self
_G.p = p
end
end
---Pretty print table data.
-- @tparam table tbl The table data to print.
-- @usage gs.p( some_table_data )
function CoroniumGSClient.p( tbl )
p( tbl )
end
--======================================================================--
--== Code
--======================================================================--
---Send table data to the server.
-- @tparam table data_tbl A table of data to send.
-- @usage gs:send( { move_done = 1 } )
function CoroniumGSClient:send( data_tbl )
table.insert( self.sendQ, data_tbl )
end
---Connect to a listening game server instance.
-- @param connection_table See @{connection_table}
function CoroniumGSClient:connect( connection_table )
self.host = connection_table.host or nil
self.port = connection_table.port or 7173
self.player_handle = connection_table.handle or nil
if not connection_table.data then
connection_table.data = {}
end
connection_table.data.device = self:_getPlatform()
self.player_data = connection_table.data or nil
--== Key to pair with Server
self.connection_key = connection_table.key or 'abc'
self.use_ping = connection_table.ping or false
p( "connecting to " .. self.host )
--== Initial clean up
if self.socket then
self.socket:close()
self.socket = nil
end
--== Init socket
self.socket = socketlib.tcp()
--== Connect to server
local success, msg = self.socket:connect( self.host, self.port )
if success then
self.socket_closed = false
self.client_id = uuid( os.time() )
self.socket:settimeout( 0 )
self.socket:setoption( "tcp-nodelay", true )
--== Socket connection event
self.events:emit( { name = "SocketConnect", data = "connected" } )
--== Pingu functionality
if self.use_ping then
self:_startPingu()
end
--==Send Queue
local function checkSendQ( client )
if #self.sendQ > 0 then
local data_tbl = table.remove( self.sendQ, 1 )
local len, err = client:send( line( json.encode( data_tbl ) ) )
end
end
local function tick()
local input, output = socketlib.select( { self.socket }, { self.socket }, 0 )
for _, client in ipairs( input ) do
local data, err, partial = client:receive('*l')
if data and not err then --== Incoming data
local data = json.decode( data )
if type( data ) ~= "table" then data = {} end
--======================================================================--
--== Handshake
--======================================================================--
if data._handshake then
self:send( { _handshook = 1, key = self.connection_key,
handle = self.player_handle, data = self.player_data } )
--======================================================================--
--== Client Confirmed
--======================================================================--
elseif data._client_confirmed then
self.events:emit( { name = "ClientConnect", data = "connected" } )
--======================================================================--
--== Pong
--======================================================================--
elseif data._pong then --== Pongu
self.events:emit( { name = "ClientPing", data = data.ts } )
--======================================================================--
--== Game Create
--======================================================================--
elseif data._game_create then
self.game_id = data.game_id
self.events:emit( { name = "GameCreate", data = data } )
--======================================================================--
--== Game Start
--======================================================================--
elseif data._game_start then
self.player_num = data.player_num
self.player_handle = data.player_handle
self.game_id = data.game_id
self.events:emit( { name = "GameStart", data = data } )
--======================================================================--
--== Game Cancel
--======================================================================--
elseif data._game_cancel then
self.game_id = nil
self.player_num = 0
self.events:emit( { name = "GameCancel", data = "canceled" } )
--======================================================================--
--== Game Join
--======================================================================--
elseif data._game_join then
self.events:emit( { name = "GameJoin", data = data } )
--======================================================================--
--== Game Leave
--======================================================================--
elseif data._game_leave then
self.events:emit( { name = "GameLeave", data = data } )
--======================================================================--
--== Game Data
--======================================================================--
elseif data._game_data then
self.events:emit( { name = "GameData", data = data } )
--======================================================================--
--== Game Closed
--======================================================================--
elseif data._game_done then
self.game_id = nil
self.player_num = 0
self.events:emit( { name = "GameDone", data = data } )
--======================================================================--
--== Game Players Meta
--======================================================================--
elseif data._players_info then
self.game_players_info = data.info --== Cache it
--======================================================================--
--== Client Data
--======================================================================--
else
self.events:emit( { name = "ClientData", data = data } )
end
else
--======================================================================--
--== Closed
--======================================================================--
if err == "closed" then
self:disconnect()
--======================================================================--
--== Error
--======================================================================--
elseif err == "timeout" then
self.events:emit( { name = "ClientTimeout", data = err } )
else
self.events:emit( { name = "ClientError", data = err } )
self:disconnect()
end
end
end
--==Send message from Queue
for _, client in ipairs( output ) do
checkSendQ( client )
end
end
--tick timer
self.process_timer = timer.performWithDelay( 50, function() tick(); end, -1 ) -- -1
else
self.events:emit( { name = "ClientError", data = msg } )
end
end
---The connection table used for the `connect` method.
-- A __key__ can be set on the server to help limit unwanted connections.
-- You must pass a matching key in the __key__ parameter to
-- successfully pair the client to the server.
-- By enabling the __ping__ parameter, you keep the client alive and connected.
-- This basically disables any client timeout settings on the server-side.
-- The __handle__ parameter can be used as a username, player name, or any other
-- identifier. Additional starting data can be sent as a simple table in
-- the __data__ parameter. You can retrieve this data with the
-- __client:getPlayerData()__ method. See [Client](http://coronium.gs/server/modules/Client.html).
-- @field host string The host address.
-- @field[opt=7173] port int The host port.
-- @field[opt=server assigned] handle string String based identifier for the client.
-- @field[opt=nil] data table A simple starting data table for the client.
-- @field[opt='abc'] key string The server pairing key.
-- @field[opt=false] ping bool The ping flag.
-- @table connection_table
-- @usage local conn_tbl =
-- {
-- host = 'ping.coronium.gs',
-- port = '7173',
-- handle = 'Chris',
-- data = { color = "blue", fun = "Yes!" },
-- key = 'abc',
-- ping = true
-- }
--gs:connect( conn_tbl )
---Create a fresh connection to the server. Useful after
-- a game has ended and you want to reconnect.
-- @tparam[opt=3000] int reconnect_delay Milliseconds delay before reconnecting.
-- @usage gs:reconnect( 5000 )
function CoroniumGSClient:reconnect( reconnect_delay )
local reconnect_delay = reconnect_delay or 3000
self:disconnect()
timer.performWithDelay( reconnect_delay , function( e )
local connection_table =
{
host = self.host,
port = self.port,
handle = self.player_handle,
data = self.player_data,
key = self.connection_key,
ping = self.use_ping
}
self:connect( connection_table )
end )
end
--======================================================================--
--== Player / Game
--======================================================================--
--- Get current stored game data from server.
-- Returned as table via the `GameData` event.
-- @usage gs.events:on( "GameData", function( event )
-- gs.p( event.data.game_data )
-- end )
-- gs:getData()
function CoroniumGSClient:getData()
self:send( { _game_data = 1 } )
end
--- Get the client players connection handle.
-- @treturn string The players handle.
-- @usage local player_handle = gs:getPlayerHandle()
function CoroniumGSClient:getPlayerHandle()
return self.player_handle
end
---Get the client player position.
-- @treturn int The player position.
-- @usage local player_num = gs:getPlayerNum()
function CoroniumGSClient:getPlayerNum()
return self.player_num
end
---Get the client game id.
-- @treturn[1] string The current game ID
-- @treturn[2] nil No game id found.
-- @usage local game_id = gs:getGameId()
function CoroniumGSClient:getGameId()
return self.game_id
end
---Get the game players info data table.
-- This method can only be called after the `GameCreate`
-- or `GameJoin` client-side event.
-- @treturn table A table of game players meta data.
-- @usage function onGameJoin( event )
-- local info_table = gs:getPlayersInfo()
-- for key, value in pairs( info_table ) do
-- p( value )
-- end
-- end
function CoroniumGSClient:getPlayersInfo()
return self.game_players_info
end
---Check if the client is connected to the server
-- @treturn bool The client connection state.
-- @usage local is_connected = gs:isConnected()
function CoroniumGSClient:isConnected()
return not self.socket_closed
end
---Check if the game is running and socket connected.
-- @treturn bool The current state as boolean.
-- @usage local state = gs:isGameRunning()
function CoroniumGSClient:isGameRunning()
if self.game_id and not self.socket_closed then
return true
end
return false
end
---Closes the client connection.
-- @usage gs:disconnect()
function CoroniumGSClient:disconnect()
self.game_id = nil
self.player_num = 0
if self.process_timer ~= 0 then
timer.cancel( self.process_timer )
end
if self.ping_timer ~= 0 then
timer.cancel( self.ping_timer )
end
if self.socket then
self.socket:close()
end
self.socket_closed = true
self.events:emit( { name = "ClientClose", data = "Player Left" } )
end
--======================================================================--
--== Games
--======================================================================--
--- Create a new game for other players to connect to.
-- You can only use this method after the `ClientConnect` client-side
-- event. Only call `createGame` OR `joinGame` once in each client, not both.
-- @tparam int players_max The maximal amount players
-- needed to start this game.
-- @tparam table game_criteria Special criteria for other players to find the game with.
-- This is useful for private, friend to friend, or matchmaking games. The game_criteria
-- table supports a 'tag' table key that will be matched up with the `joinGame` method.
-- This creates a way to direct clients to specific rooms. See also `joinGame`.
-- @usage function onClientConnect( event )
-- --== Create a 2 player game for others to join.
-- gs:createGame( 2 )
-- --== Create a 2 player game with a custom 'tag' for the other players to join with.
-- gs:createGame( 2, { tag = 'custom_str' } )
-- end
function CoroniumGSClient:createGame( players_max, game_criteria )
local players_max = players_max or 1
self:send( { _create_game = 1, players_max = players_max, game_criteria = game_criteria or nil } )
end
--- Join a game that was created with the `createGame` method.
-- You can only use this method after the `ClientConnect` client-side event.
-- Only call `createGame` OR `joinGame` once in each client, but not both.
-- @tparam int players_max Join a game with `players_max` players.
-- @tparam table game_criteria Special criteria to find game by. This table
-- supports a 'tag' key which you can use to find specifically created games.
-- See also `createGame`.
-- @usage function onClientConnect( event )
-- --== Find a 2 player game to join.
-- gs:joinGame( 2 )
-- --== Find a 2 player game with a custom 'tag' to join.
-- gs:joinGame( 2, { tag = 'custom_str' } )
-- end
function CoroniumGSClient:joinGame( players_max, game_criteria )
local players_max = players_max or 1
self:send( { _join_game = 1, players_max = players_max, game_criteria = game_criteria or nil } )
end
--- Cancel a `Game` in a waiting state. Useful when no games found.
-- You will revieve `GameCancel` when the game has been canceled.
-- @usage gs:cancelGame()
function CoroniumGSClient:cancelGame()
self:send( { _game_cancel = self:getGameId() } )
end
function CoroniumGSClient:_getPlatform()
local platformName = system.getInfo( "platformName" )
if platformName == "Android" then
return "android"
elseif platformName == "iPhone OS" then
return "ios"
else
return "unknown" --devin' 'unknown' is default
end
end
--======================================================================--
--== Pingu
--======================================================================--
--- Start pinging the server.
-- @local
function CoroniumGSClient:_startPingu()
self.ping_timer = timer.performWithDelay( 5000, function()
self:send( { _ping = 1, ts = os.time() } )
end, -1 )
end
--- Stop pinging the server.
-- @local
function CoroniumGSClient:_stopPingu()
timer.cancel( self.ping_timer )
end
--======================================================================--
--== Return class
--======================================================================--
return CoroniumGSClient
--- Game Events.
-- You can listen for the following __Game__ events.
-- @section Events
--[[--
A game has been created. __This event will only
be received by the client/player calling it__.
@field GameCreate
@usage
gs.events:on( "GameCreate", function( event )
print( event.data )
end )
]]
--[[--
The game has been canceled. State reset.
@field GameCancel
@usage
gs.events:on( "GameCancel", function( event )
print( "game canceled" )
end )
]]
--[[--
The game has started. All players present.
@field GameStart
@usage
gs.events:on( "GameStart", function( event )
print( event.data )
end )
]]
--[[--
A player has joined the game.
@field GameJoin
@usage
gs.events:on( "GameJoin", function( event )
print( event.data )
end )
]]
--[[--
A player has left the game.
@field GameLeave
@usage
gs.events:on( "GameLeave", function( event )
print( event.data )
end )
]]
--[[--
The game is finished. See the server-side call [publishGameDone](http://coronium.gs/server/modules/Game.html#publishGameDone) as well.
@field GameDone
@usage
gs.events:on( "GameDone", function( event )
print( event.data )
end )
]]
--[[--
Game data has been received.
@field GameData
@usage
gs.events:on( "GameData", function( event )
p( event.data.game_data )
end )
]]
--- Client Events.
-- You can listen for the following __Client__ events.
-- @section Events
--[[--
Incoming Client data.
@field ClientData
@usage
gs.events:on( "ClientData", function( event )
print( event.data.some_table_key )
end )
]]
--[[--
Client has thrown an error.
@field ClientError
@usage
gs.events:on( "ClientError", function( event )
print( "error: " .. event.data )
end )
]]
--[[--
Client has closed.
@field ClientClose
@usage
gs.events:on( "ClientClose", function( event )
print( "client closed" )
end )
]]
--[[--
Client has connected to server.
@field ClientConnect
@usage
gs.events:on( "ClientConnect", function( event )
print( "client connected" )
end )
]]
--[[--
Client has received a ping.
@field ClientPing
@usage
gs.events:on( "ClientPing", function( event )
print( "timestamp: " .. event.data )
end )
]]
|
project "zziplib"
SetupNativeDependencyProject()
kind "StaticLib"
files { "src/*.c" }
includedirs { "include", "../zlib/include" } |
-- Real train scroller: 96 x 16 px
local function createRects(w,h)
local rects = {}
local xw, yh = w/10, h/10
for i = 1, xw-1 do
for j = 1, yh-1 do
local x,y = i/xw*w,j/yh*h
table.insert(rects,{x=x,y=y,w=w/xw,h=h/yh,c=color(img:get(math.floor(x),math.floor(y))):blend(color(75,60,35))})
end
end
return rects
end
local function drawText()
fill(255,130,0)
text(Text,0,0)
end
function createImage()
local tw,th = textSize(Text)
img = image(tw+20,th)
setContext(img)
drawText()
setContext()
grid = createRects(tw+20,th)
end
function setup()
parameter.boolean("ShowOriginal",false)
parameter.text("Text","Sample Text",createImage)
ellipseMode(CORNER)
textMode(CORNER)
font("HelveticaNeue-Bold")
textWrapWidth(WIDTH)
fontSize(120)
createImage()
end
function draw()
background(40,30,25)
local _,th = textSize(Text)
local lazy = HEIGHT-th
translate(0,lazy)
if ShowOriginal then
drawText()
else
for k,v in ipairs(grid) do
fill(v.c)
ellipse(v.x,v.y,v.w,v.h)
end
end
translate(0,-lazy)
end |
local ITEM = Clockwork.item:New();
ITEM.name = "Scrap Metal";
ITEM.model = "models/props_debris/metal_panelchunk02d.mdl";
ITEM.weight = 0.8;
ITEM.category = "Materials";
ITEM.description = "A bent and dirty piece of metal.";
-- Called when a player drops the item.
function ITEM:OnDrop(player, position) end;
ITEM:Register(); |
local xx = 520;
local yy = 451;
local xx2 = 820;
local yy2 = 451;
local ofs = 60;
local followchars = true;
local del = 0;
local del2 = 0;
function onCreate()
debugPrint('Please disable "Flashing Effects" and "Camera Shake" in options if you are at risk of seizures')
debugPrint('This song contains "Flashing Lights" and "Camera Shake".')
debugPrint('Epilepsy / Photosensitivity Warning:')
if not lowQuality then -- If Low Quality is disabled, allow the precaching of assets
if flashingLights then -- If Flashing Lights are enabled, allow the precaching of assets
precacheImage('stages/stagecurtains-erect-left')
precacheImage('stages/stagecurtains-erect-down')
precacheImage('stages/stagecurtains-erect-up')
precacheImage('stages/stagecurtains-erect-right')
precacheImage('stages/stagefront-beatglow')
end
end
end
function onBeatHit(id, noteData, isSustainNote)
if not lowQuality then -- If Low Quality is disabled, allow the code to run
if flashingLights then -- If Flashing Lights are enabled, allow the code to run
makeLuaSprite('beatglow', 'stages/stagefront-erect-beatglow', -675, 600);
scaleObject('beatglow', 1.1, 1.1)
addLuaSprite('beatglow', false);
runTimer('wait', 0.1);
end
end
end
function opponentNoteHit(id, noteData, isSustainNote)
if not lowQuality then -- If Low Quality is disabled, allow the code to run
if flashingLights then -- If Flashing Lights are enabled, allow the code to run
if noteData == 0 then -- Left Note
-- Stage lights
makeLuaSprite('stagelight-left', 'stages/stagecurtains-erect-left', -800, -525);
setScrollFactor('stagelight-left', 1.3, 1.3);
scaleObject('stagelight-left', 1.2, 1.2);
addLuaSprite('stagelight-left', false);
setObjectCamera('stagelight-left', 'camGame');
elseif noteData == 1 then -- Down Note
-- Stage lights
makeLuaSprite('stagelight-down', 'stages/stagecurtains-erect-down', -800, -525);
setScrollFactor('stagelight-down', 1.3, 1.3);
scaleObject('stagelight-down', 1.2, 1.2);
addLuaSprite('stagelight-down', false);
setObjectCamera('stagelight-down', 'camGame');
elseif noteData == 2 then -- Up Note
-- Stage lights
makeLuaSprite('stagelight-up', 'stages/stagecurtains-erect-up', -800, -525);
setScrollFactor('stagelight-up', 1.3, 1.3);
scaleObject('stagelight-up', 1.2, 1.2);
addLuaSprite('stagelight-up', false);
setObjectCamera('stagelight-up', 'camGame');
elseif noteData == 3 then -- Right Note
-- Stage lights
makeLuaSprite('stagelight-right', 'stages/stagecurtains-erect-right', -800, -525);
setScrollFactor('stagelight-right', 1.3, 1.3);
scaleObject('stagelight-right', 1.2, 1.2);
addLuaSprite('stagelight-right', false);
setObjectCamera('stagelight-right', 'camGame');
end
end
end
end
function goodNoteHit(id, noteData, isSustainNote)
if not lowQuality then -- If Low Quality is disabled, allow the code to run
if flashingLights then -- If Flashing Lights are enabled, allow the code to run
if noteData == 0 then -- Left Note
-- Stage lights
makeLuaSprite('stagelight-left', 'stages/stagecurtains-erect-left', -800, -525);
setScrollFactor('stagelight-left', 1.3, 1.3);
scaleObject('stagelight-left', 1.2, 1.2);
addLuaSprite('stagelight-left', false);
setObjectCamera('stagelight-left', 'camGame');
elseif noteData == 1 then -- Down Note
-- Stage lights
makeLuaSprite('stagelight-down', 'stages/stagecurtains-erect-down', -800, -525);
setScrollFactor('stagelight-down', 1.3, 1.3);
scaleObject('stagelight-down', 1.2, 1.2);
addLuaSprite('stagelight-down', false);
setObjectCamera('stagelight-down', 'camGame');
elseif noteData == 2 then -- Up Note
-- Stage lights
makeLuaSprite('stagelight-up', 'stages/stagecurtains-erect-up', -800, -525);
setScrollFactor('stagelight-up', 1.3, 1.3);
scaleObject('stagelight-up', 1.2, 1.2);
addLuaSprite('stagelight-up', false);
setObjectCamera('stagelight-up', 'camGame');
elseif noteData == 3 then -- Right Note
-- Stage lights
makeLuaSprite('stagelight-right', 'stages/stagecurtains-erect-right', -800, -525);
setScrollFactor('stagelight-right', 1.3, 1.3);
scaleObject('stagelight-right', 1.2, 1.2);
addLuaSprite('stagelight-right', false);
setObjectCamera('stagelight-right', 'camGame');
end
end
end
end
function onTimerCompleted(tag, loops, loopsleft)
if not lowQuality then -- If Low Quality is disabled, allow the code to run
if flashingLights then -- If Flashing Lights are enabled, allow the code to run
if tag == 'wait' then
doTweenAlpha('byebye', 'beatglow', 0, 0.2, 'linear');
end
end
end
end
function onTweenCompleted(tag)
if not lowQuality then -- If Low Quality is disabled, allow the code to run
if flashingLights then -- If Flashing Lights are enabled, allow the code to run
if tag == 'byebye' then
doTweenAlpha('beatglow', 0.1, 1.2, 'linear');
removeLuaSprite('beatglow', true);
end
end
end
end
function onUpdate(elapsed)
if cameraZoomOnBeat then -- If Camera Effects are enabled, allow the code to run
if del > 0 then
del = del - 1
end
if del2 > 0 then
del2 = del2 - 1
end
if followchars == true then
if mustHitSection == false then
if getProperty('dad.animation.curAnim.name') == 'singLEFT' then
triggerEvent('Camera Follow Pos',xx-ofs,yy)
end
if getProperty('dad.animation.curAnim.name') == 'singRIGHT' then
triggerEvent('Camera Follow Pos',xx+ofs,yy)
end
if getProperty('dad.animation.curAnim.name') == 'singUP' then
triggerEvent('Camera Follow Pos',xx,yy-ofs)
end
if getProperty('dad.animation.curAnim.name') == 'singDOWN' then
triggerEvent('Camera Follow Pos',xx,yy+ofs)
end
if getProperty('dad.animation.curAnim.name') == 'singLEFT-alt' then
triggerEvent('Camera Follow Pos',xx-ofs,yy)
end
if getProperty('dad.animation.curAnim.name') == 'singRIGHT-alt' then
triggerEvent('Camera Follow Pos',xx+ofs,yy)
end
if getProperty('dad.animation.curAnim.name') == 'singUP-alt' then
triggerEvent('Camera Follow Pos',xx,yy-ofs)
end
if getProperty('dad.animation.curAnim.name') == 'singDOWN-alt' then
triggerEvent('Camera Follow Pos',xx,yy+ofs)
end
if getProperty('dad.animation.curAnim.name') == 'idle-alt' then
triggerEvent('Camera Follow Pos',xx,yy)
end
if getProperty('dad.animation.curAnim.name') == 'idle' then
triggerEvent('Camera Follow Pos',xx,yy)
end
else
if getProperty('boyfriend.animation.curAnim.name') == 'singLEFT' then
triggerEvent('Camera Follow Pos',xx2-ofs,yy2)
end
if getProperty('boyfriend.animation.curAnim.name') == 'singRIGHT' then
triggerEvent('Camera Follow Pos',xx2+ofs,yy2)
end
if getProperty('boyfriend.animation.curAnim.name') == 'singUP' then
triggerEvent('Camera Follow Pos',xx2,yy2-ofs)
end
if getProperty('boyfriend.animation.curAnim.name') == 'singDOWN' then
triggerEvent('Camera Follow Pos',xx2,yy2+ofs)
end
if getProperty('boyfriend.animation.curAnim.name') == 'idle' then
triggerEvent('Camera Follow Pos',xx2,yy2)
end
end
else
triggerEvent('Camera Follow Pos','','')
end
end
end |
local _M = {
unset = 0,
ok = 1,
error = 2,
}
-- returns a valid span status code
function _M.validate(code)
if not code or code < 0 or code > 2 then
-- default unset
return 0
end
return code
end
return _M
|
local t = Def.ActorFrame { }
t[#t + 1] =
Def.Actor {
CodeMessageCommand = function(self, params)
if params.Name == "AvatarShow" and not SCREENMAN:get_input_redirected(PLAYER_1) then
SCREENMAN:SetNewScreen("ScreenAssetSettings")
end
end,
OnCommand = function(self)
inScreenSelectMusic = true
end,
EndCommand = function(self)
inScreenSelectMusic = nil
end
}
t[#t + 1] = LoadActor("../_frame")
t[#t + 1] = LoadActor("../_PlayerInfo")
t[#t + 1] = LoadActor("currentsort")
t[#t + 1] =
LoadFont("Common Large") ..
{
InitCommand = function(self)
self:xy(5, 32):halign(0):valign(1):zoom(0.55):diffuse(getMainColor("positive"))
self:settext(THEME:GetString("ScreenNetRoom", "Title"))
end
}
t[#t + 1] = LoadActor("../_cursor")
t[#t + 1] = LoadActor("../_mousewheelscroll")
t[#t + 1] = LoadActor("../_halppls")
--t[#t + 1] = LoadActor("../_userlist")
t[#t + 1] = LoadActor("../_lobbyuserlist")
return t
|
----------------------------------------
-- Attempt to connect to MySQL Database to store match results.
if CL_MYSQL_NAME then
ok, msg = pcall(require, "luasql.mysql")
if not ok then
print("Could not load mysql. If you want to use MySQL logging, make sure the lua extension luasql is installed! Otherwise, ignore this warning.")
else
print("MYSQL driver loaded.")
MYSQL = true
luasql = msg
end
end
function chooseNewAIfromDB_filename()
print("Looking for AIs in DB!")
if MYSQL then
-- open MYSQL environment:
env = luasql.mysql()
if env then
conn = env:connect(MYSQL_DATABASE, CL_MYSQL_NAME, CL_MYSQL_PASS, CL_MYQSL_HOST, CL_MYSQL_PORT)
if conn then
print("Connected to DB.")
result = false
exists = false
cursor,err = conn:execute("SELECT name,owner,matches FROM ais ORDER BY matches;")
local row, fileNames = {}, {}
local i = 1
local probability = 0
local totalMatches = 0
if cursor then
row[i] = cursor:fetch ({}, "a")
while row[i] do
totalMatches = totalMatches + row[i].matches -- count all matches
i = i + 1
row[i] = cursor:fetch ({}, "a")
end
end
for i = 1,#row do
local p = (totalMatches/math.max(1,row[i].matches))
probability = probability + p*p
row[i].probability = probability
print("1. Found in Database", row[i].name, row[i].owner, row[i].matches, row[i].probability, p, totalMatches)
end
toChoose = math.min(4, #row)
print("Choosing " .. toChoose .. " AIs.")
while toChoose > 0 do
local chosen = math.random(probability)
print("Choosing probability:", chosen)
local i = #row
local found = false
while i > 0 do
print("i",i, row[i].name, row[i].probability, row[i-1], chosen <= row[i].probability)
if row[i] then
if chosen <= row[i].probability then
found = true
end
if not row[i].chosen and found and (not row[i-1] or chosen > row[i-1].probability) then
row[i].chosen = true
toChoose = toChoose - 1
break
end
end
i = i - 1
end
if i == 0 then -- none found. Go back through the list and choose the first possible one.
i = 1
while i < #row do
if not row[i].chosen then
row[i].chosen = true
toChoose = toChoose - 1
break
end
i = i + 1
end
end
end
for i = 1,#row do
if row[i].chosen then
table.insert( fileNames, CL_DIRECTORY .. "/" .. row[i].owner .. "/" .. row[i].name .. ".lua" )
end
end
for i = 1, #fileNames do
print(i, fileNames[i])
end
return fileNames
end
end
else
return nil
end
end
function chooseNewAIfromDB_table()
if MYSQL then
-- open MYSQL environment:
env = luasql.mysql()
if env then
conn = env:connect(MYSQL_DATABASE, CL_MYSQL_NAME, CL_MYSQL_PASS, CL_MYQSL_HOST, CL_MYSQL_PORT)
if conn then
result = false
exists = false
cursor,err = conn:execute("SELECT name,owner,matches FROM ais ORDER BY matches;")
local row, fileNames = {}, {}
local i = 1
local probability = 0
local totalMatches = 0
if cursor then
row[i] = cursor:fetch ({}, "a")
while row[i] do
totalMatches = totalMatches + row[i].matches -- count all matches
i = i + 1
row[i] = cursor:fetch ({}, "a")
end
end
for i = 1,#row do
local p = (totalMatches/math.max(1,row[i].matches))
probability = probability + p*p
row[i].probability = probability
end
toChoose = math.min(4, #row)
local firstChosen = false
while toChoose > 0 do
local found = false
local chosen = 1
local i = #row
if firstChosen == false then
chosen = math.random(math.max(probability, 1))
while i > 0 do
if row[i] then
if chosen <= row[i].probability then
found = true
end
if not row[i].chosen and found and (not row[i-1] or chosen > row[i-1].probability) then
row[i].chosen = true
toChoose = toChoose - 1
break
end
end
i = i - 1
end
else
chosen = math.random(#row)
while i > 0 do
if row[chosen] and not row[chosen].chosen then
row[chosen].chosen = true
toChoose = toChoose - 1
break
end
i = i - 1
end
end
if i == 0 then -- none found. Go back through the list and choose the first possible one.
i = 1
while i <= #row do
if not row[i].chosen then
row[i].chosen = true
toChoose = toChoose - 1
break
end
i = i + 1
end
end
firstChosen = true
end
for i = 1,#row do
if row[i].chosen then
table.insert( fileNames, {owner=row[i].owner, name=row[i].name} )
end
end
return fileNames
end
end
else
return nil
end
end
-- Check if there's AIs stages for a match. If so, return them, the list of staged Matches.
-- Also, make sure to add new AIs to the list.
function chooseAIfromDB(numMatches)
returnAIs = {}
numMatches = numMatches or 1
if MYSQL then
-- open MYSQL environment:
env = luasql.mysql()
local found = false
if env then
conn = env:connect(MYSQL_DATABASE, CL_MYSQL_NAME, CL_MYSQL_PASS, CL_MYQSL_HOST, CL_MYSQL_PORT)
if conn then
-- first, check if the "nextMatch" table exists. If not, create it:
cursor,err = conn:execute("SELECT * FROM nextMatch")
if not cursor then
cursor,err = conn:execute("CREATE TABLE nextMatch (name VARCHAR(30), owner VARCHAR(30), matchNum INT);")
if err then
print("Could not create 'nextMatch' table in " .. MYSQL_DATABASE .. ":", err)
else
print("Created new 'nextMatch' table.")
end
end
cursor,err = conn:execute("SELECT * FROM nextMatchTime")
if not cursor then
cursor,err = conn:execute("CREATE TABLE nextMatchTime (time DATETIME);")
if err then
print("Could not create 'nextMatchTime' table in " .. MYSQL_DATABASE .. ":", err)
else
print("Created new 'nextMatchTime' table.")
end
else
cursor,err = conn:execute("DELETE FROM nextMatchTime")
end
-- check if enough entries exist in nextMatch. If not, add them.
print("Checking if there's " .. numMatches + 1 .. " matches in the 'nextMatch' table:")
for count = 1, numMatches + 1 do
cursor,err = conn:execute("SELECT name,owner FROM nextMatch WHERE matchNum=" .. count .. ";")
if cursor and type(cursor) ~= "number" then
row = cursor:fetch ({}, "a")
end
print(cursor, err, row)
if not cursor or cursor == 0 or not row then
newAIs = chooseNewAIfromDB_table()
conn:setautocommit(false)
for k, a in pairs(newAIs) do
cursor,err = conn:execute("INSERT INTO nextMatch VALUES('" .. a.name .. "', '" .. a.owner .. "', " .. count .. ");")
end
conn:commit() --send all at once.
conn:setautocommit(true)
print(nil, "-> not found " .. count .. ", adding!")
else
print(nil, "-> found " .. count)
end
end
print("done")
cursor,err = conn:execute("SELECT name,owner FROM nextMatch WHERE matchNum=1;")
if cursor then
row = cursor:fetch ({}, "a")
while row do
found = true
table.insert(returnAIs, CL_DIRECTORY .. "/" .. row.owner .. "/" .. row.name .. ".lua")
print("Found: " .. CL_DIRECTORY .. "/" .. row.owner .. "/" .. row.name .. ".lua")
row = cursor:fetch ({}, "a")
end
end
--move all entries up:
conn:setautocommit(false)
cursor,err = conn:execute("UPDATE nextMatch SET matchNum=matchNum-1;")
cursor,err = conn:execute("DELETE FROM nextMatch WHERE matchNum<0;")
q = "INSERT INTO nextMatchTime VALUES(NOW() + INTERVAL " .. (CL_ROUND_TIME or FALLBACK_ROUND_TIME) + TIME_BETWEEN_MATCHES .. " SECOND);"
cursor,err = conn:execute(q)
print(q)
conn:commit() --send all at once.
conn:setautocommit(true)
end
end
end
if found then
while #returnAIs > 4 do
returnAIs[#returnAIs] = nil
end
print("returning AIs:", #returnAIs)
return returnAIs
else
return nil
end
end
log = {}
function log.matchResults()
print("attempting to log match")
if MYSQL then
print("mysql found")
-- open MYSQL environment:
env = luasql.mysql()
if env then
print("loaded mysql driver!")
conn = env:connect(MYSQL_DATABASE, CL_MYSQL_NAME, CL_MYSQL_PASS, CL_MYQSL_HOST, CL_MYSQL_PORT)
if conn then
print("connection successful!")
querry = "UPDATE ais SET matches=matches+1"
first = true
for i = 1,#aiList do
result = false
exists = false
cursor,err = conn:execute("SELECT name FROM ais WHERE name LIKE '" .. aiList[i].name .. "' AND owner LIKE '" .. aiList[i].owner .. "';")
if not cursor then
print(err)
else
result = cursor:fetch()
cursor:close()
end
if result then
print("Found " .. aiList[i].name .. " in Database!")
exists = true
cursor,err = conn:execute("UPDATE ais SET points=points+" .. aiList[i].points .. " WHERE name LIKE '" .. aiList[i].name .. "' AND owner LIKE '" .. aiList[i].owner .. "';")
if cursor then
if type(cursor) == "table" then
cursor:close()
end
end
--[[else
print("Didn't find " .. aiList[i].name .. " in Database. Attempting to add.")
cursor, err = conn:execute("INSERT INTO ais VALUE('" .. aiList[i].name .. "','" .. aiList[i].owner .. "',0,0,0,'" .. aiList[i].name .. ".lua', NULL);")
if not cursor then
print(err)
elseif type(cursor) == "table" then
cursor:close()
exists = true
end]]--
end
if exists then
if first then
first = false
querry = querry .. " WHERE (name LIKE '" .. aiList[i].name .. "' AND owner LIKE '" .. aiList[i].owner .. "')"
else
querry = querry .. " OR (name LIKE '" .. aiList[i].name .. "' AND owner LIKE '" .. aiList[i].owner .. "')"
end
end
end
querry = querry .. ";"
print("Querry:", querry)
cursor,err = conn:execute(querry)
if not cursor then
print(err)
elseif type(cursor) == "table" then
print("result:")
printTable(cursor)
cursor:close()
else
print("result",cursor)
end
if winnerID and aiList[winnerID] then
querry = "UPDATE ais SET wins=wins+1 WHERE name LIKE '" .. aiList[winnerID].name .. "' AND owner LIKE '" .. aiList[winnerID].owner .. "';"
cursor,err = conn:execute(querry)
if not cursor then
print(err)
elseif type(cursor) == "table" then
cursor:close()
else
print("result",cursor)
end
end
-- add a table holding the last match:
-- drop previous one:
querry = "DROP TABLE lastMatch;"
cursor,err = conn:execute(querry)
if not cursor then
print(err)
end
print( conn:setautocommit(false) )
-- create a new one:
querry = "CREATE TABLE lastMatch (name VARCHAR(30), owner VARCHAR(30), pTransported INT, points INT, timeEnded DATETIME);"
cursor,err = conn:execute(querry)
if not cursor then
print(err)
elseif type(cursor) == "table" then
cursor:close()
else
print("result",cursor)
end
-- fill the table:
for i = 1,#aiList do
querry = "INSERT INTO lastMatch VALUE('" .. aiList[i].name .. "','" .. aiList[i].owner .. "'," .. stats.getPassengersTransported(i) .. "," .. aiList[i].points ..", NOW());"
print(querry)
cursor, err = conn:execute(querry)
end
conn:commit()
conn:close()
else
print("Error connecting to MySQL. Does the database exist?")
end
env:close()
else
print("Error opening MySQL environment.")
end
end
end
function log.findTable()
if MYSQL then
env = luasql.mysql()
if env then
conn = env:connect(MYSQL_DATABASE, CL_MYSQL_NAME, CL_MYSQL_PASS, CL_MYQSL_HOST, CL_MYSQL_PORT)
if conn then
cursor = conn:execute("SHOW TABLES LIKE 'ais';") -- see if the "ais" table exists. if not, attempt to create it:
result = nil
if cursor then
result = cursor:fetch()
cursor:close()
end
if result then
found = true
print("Found table 'ais'. Success!")
else
cursor = conn:execute("CREATE TABLE ais (name VARCHAR(30), owner VARCHAR(30), matches INT, wins INT, cash INT, scriptName VARCHAR(40), timeCreated DATETIME);") -- see if the "ais" table exists. if not, attempt to create it:
if cursor then
found = true
print("Created table 'ais' in " .. MYSQL_DATABASE .. ".")
if type(cursor) == "table" then
cursor:close()
end
end
end
conn:close()
else
print("Error connecting to MySQL. Does the database exist?")
end
end
if not found then
MYSQL = false
print("Could not find nor create table 'ais' in '" .. MYSQL_DATABASE .. "'... disabling MySQL logging.")
end
end
end
return log
|
TrinketPatches = {
mod = RegisterMod("TrinketPatches", 1),
debug = false,
util = require("utils.lua"),
game = Game(),
config = require("config.lua")
}
-- Register load/save
TrinketPatches.mod:AddCallback(ModCallbacks.MC_POST_GAME_STARTED, function() TrinketPatches.config:load() end)
TrinketPatches.mod:AddCallback(ModCallbacks.MC_PRE_GAME_EXIT, function() TrinketPatches.config:save() end)
-- Load EID entries
pcall(require, "eid.lua")
local files = {
"bloody_crown.lua",
"bobs_bladder.lua",
"burnt_match.lua",
"cancer.lua",
"equality.lua",
"match_stick.lua",
"moms_locket.lua",
"silver_dollar.lua",
"stem_cell.lua",
"tick.lua"
}
-- Load all trinket effects
for _, file in pairs(files) do
pcall(require, "trinkets/"..file)
end
|
-- mod-version:2 -- lite-xl 2.0
local core = require "core"
local common = require "core.common"
local command = require "core.command"
local keymap = require "core.keymap"
local Doc = require "core.doc"
local DocView = require "core.docview"
local navigate = {
list = {},
current = nil,
index = 0
}
--
-- Private functions
--
local function get_active_view()
if getmetatable(core.active_view) == DocView then
return core.active_view
end
return nil
end
-- Solution to safely remove elements from array table:
-- found at https://stackoverflow.com/a/53038524
local function array_remove(t, fnKeep)
local j, n = 1, #t;
for i=1, n do
if (fnKeep(t, i, j)) then
if (i ~= j) then
t[j] = t[i];
t[i] = nil;
end
j = j + 1;
else
t[i] = nil;
end
end
return t;
end
local function add(doc)
-- Make new navigation point last in list
if navigate.index > 0 and navigate.index < #navigate.list then
local remove_start = navigate.index + 1
local remove_end = #navigate.list
array_remove(navigate.list, function(_, i)
if i >= remove_start and i <= remove_end then
return false
end
return true
end)
end
local line, col = doc:get_selection()
table.insert(navigate.list, {
filename = doc.filename,
line = line,
col = col
})
navigate.current = navigate.list[#navigate.list]
navigate.index = #navigate.list
end
local function open_doc(doc)
core.root_view:open_doc(
core.open_doc(
common.home_expand(
doc.filename
)
)
)
local av_doc = get_active_view().doc
local line, col = av_doc:get_selection()
if doc.line ~= line or doc.col ~= col then
av_doc:set_selection(doc.line, doc.col, doc.line, doc.col)
end
end
--
-- Public functions
--
function navigate.next()
if navigate.index < #navigate.list then
navigate.index = navigate.index + 1
navigate.current = navigate.list[navigate.index]
open_doc(navigate.current)
end
end
function navigate.prev()
if navigate.index > 1 then
navigate.index = navigate.index - 1
navigate.current = navigate.list[navigate.index]
open_doc(navigate.current)
end
end
--
-- Thread
--
core.add_thread(function()
while true do
local av = get_active_view()
if av and av.doc and av.doc.filename then
local doc = av.doc
local line, col = doc:get_selection()
local current = navigate.current
if
not current
or
current.filename ~= doc.filename
or
current.line ~= line
then
add(doc)
else
current.col = col
end
end
coroutine.yield(0.5)
end
end)
--
-- Patching
--
local doc_on_close = Doc.on_close
function Doc:on_close()
local filename = self.filename
-- remove all positions referencing closed file
array_remove(navigate.list, function(t, i)
if t[i].filename == filename then
return false
end
return true
end)
doc_on_close(self)
end
--
-- Commands
--
command.add("core.docview", {
["navigate:previous"] = function()
navigate.prev()
end,
["navigate:next"] = function()
navigate.next()
end,
})
--
-- Default Keybindings
--
keymap.add {
["alt+left"] = "navigate:previous",
["alt+right"] = "navigate:next",
}
return navigate
|
--- Makes monolithic Factorio GUI events more manageable.
-- @module Event.Gui
-- @usage local Gui = require('__stdlib__/stdlib/event/gui')
local Event = require('__stdlib__/stdlib/event/event')
local Gui = {
__class = 'Gui',
__index = require('__stdlib__/stdlib/core')
}
setmetatable(Gui, Gui)
--- Registers a function for a given gui element name or pattern when the element is clicked.
-- @tparam string gui_element_pattern the name or string regular expression to match the gui element
-- @tparam function handler the function to call when gui element is clicked
-- @return (<span class="types">@{Gui}</span>)
function Gui.on_click(gui_element_pattern, handler)
Event.register(defines.events.on_gui_click, handler, Event.Filters.gui, gui_element_pattern)
return Gui
end
--- Registers a function for a given GUI element name or pattern when the element checked state changes.
-- @tparam string gui_element_pattern the name or string regular expression to match the GUI element
-- @tparam function handler the function to call when GUI element checked state changes
-- @return (<span class="types">@{Gui}</span>)
function Gui.on_checked_state_changed(gui_element_pattern, handler)
Event.register(defines.events.on_gui_checked_state_changed, handler, Event.Filters.gui, gui_element_pattern)
return Gui
end
--- Registers a function for a given GUI element name or pattern when the element text changes.
-- @tparam string gui_element_pattern the name or string regular expression to match the GUI element
-- @tparam function handler the function to call when GUI element text changes
-- @return (<span class="types">@{Gui}</span>)
function Gui.on_text_changed(gui_element_pattern, handler)
Event.register(defines.events.on_gui_text_changed, handler, Event.Filters.gui, gui_element_pattern)
return Gui
end
--- Registers a function for a given GUI element name or pattern when the element selection changes.
-- @tparam string gui_element_pattern the name or string regular expression to match the GUI element
-- @tparam function handler the function to call when GUI element selection changes
-- @return (<span class="types">@{Gui}</span>)
function Gui.on_elem_changed(gui_element_pattern, handler)
Event.register(defines.events.on_gui_elem_changed, handler, Event.Filters.gui, gui_element_pattern)
return Gui
end
--- Registers a function for a given GUI element name or pattern when the element state changes (drop down).
-- @tparam string gui_element_pattern the name or string regular expression to match the GUI element
-- @tparam function handler the function to call when GUI element state changes
-- @return (<span class="types">@{Gui}</span>)
function Gui.on_selection_state_changed(gui_element_pattern, handler)
Event.register(defines.events.on_gui_selection_state_changed, handler, Event.Filters.gui, gui_element_pattern)
return Gui
end
--- Registers a function for a given GUI element name or pattern when the element value changes (slider).
-- @tparam string gui_element_pattern the name or string regular expression to match the GUI element
-- @tparam function handler the function to call when GUI element state changes
-- @return (<span class="types">@{Gui}</span>)
function Gui.on_value_changed(gui_element_pattern, handler)
Event.register(defines.events.on_gui_value_changed, handler, Event.Filters.gui, gui_element_pattern)
return Gui
end
--- Registers a function for a given GUI element name or pattern when the element is confirmed.
-- @tparam string gui_element_pattern the name or string regular expression to match the GUI element
-- @tparam function handler the function to call when GUI element state changes
-- @return (<span class="types">@{Gui}</span>)
function Gui.on_confirmed(gui_element_pattern, handler)
Event.register(defines.events.on_gui_confirmed, handler, Event.Filters.gui, gui_element_pattern)
return Gui
end
Event.Gui = Gui
return Gui
|
TOOL.Category = "SCars"
TOOL.Name = "#tool.carsuspension.title"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.LiveEnt = NULL
TOOL.UpdateHeight = CurTime()
TOOL.UpdateDelay = 0.25
TOOL.ClientConVar = {
SoftnesFront = "0",
SoftnesRear = "0",
liveAction = "0",
liveAction2 = "0",
HeightFront = "0",
HeightRear = "0",
}
TOOL.OldSoftnesFront = 0
TOOL.OldSoftnesRear = 0
TOOL.OldHeightFront = 0
TOOL.OldHeightRear = 0
if CLIENT then
end
function TOOL:LeftClick( trace )
if !trace.Entity:IsValid() or !trace.Entity.Base or trace.Entity.Base != "sent_sakarias_scar_base" then return false end
if (CLIENT) then return true end
local ply = self:GetOwner()
if !CanUseSCarTool("scar_carsuspension", ply) then return false end
trace.Entity:EmitSound("carStools/hydraulic.wav",100,math.random(80,150))
local SoftnesFront = self:GetClientNumber( "SoftnesFront" )
local SoftnesRear = self:GetClientNumber( "SoftnesRear" )
local HeightFront = self:GetClientNumber( "HeightFront" )
local HeightRear = self:GetClientNumber( "HeightRear" )
local NewHeightFront = HeightFront * -1
local NewHeightRear = HeightRear * -1
self.OldHeightFront = HeightFront
self.OldHeightRear = HeightRear
self.OldSoftnesFront = SoftnesFront
self.OldSoftnesRear = SoftnesRear
--A weird bug makes the car disappear if a wheel is damaged for some reason
if trace.Entity:WheelsAreDamaged() then
trace.Entity:Repair()
end
trace.Entity:SetSoftnesFront( SoftnesFront )
trace.Entity:SetSoftnesRear( SoftnesRear )
trace.Entity:SetHeightFront( NewHeightFront )
trace.Entity:SetHeightRear( NewHeightRear )
self.LiveEnt = trace.Entity
return true
end
function TOOL:RightClick( trace )
if !trace.Entity:IsValid() or !trace.Entity.Base or trace.Entity.Base != "sent_sakarias_scar_base" then return false end
if (CLIENT) then return true end
local ply = self:GetOwner()
self.LiveEnt = NULL
local SoftnesFront = trace.Entity.SoftnesFront
local SoftnesRear = trace.Entity.SoftnesRear
local HeightFront = trace.Entity.HeightFront * -1
local HeightRear = trace.Entity.HeightRear * -1
self:GetOwner():ConCommand("carsuspension_SoftnesFront "..SoftnesFront)
self:GetOwner():ConCommand("carsuspension_SoftnesRear "..SoftnesRear)
self:GetOwner():ConCommand("carsuspension_HeightFront "..HeightFront)
self:GetOwner():ConCommand("carsuspension_HeightRear "..HeightRear)
self.OldHeightFront = HeightFront
self.OldHeightRear = HeightRear
self.OldSoftnesFront = SoftnesFront
self.OldSoftnesRear = SoftnesRear
self.LiveEnt = trace.Entity
return true
end
function TOOL:ValChange( sofF, sofR, heiF, heiR)
if self.OldSoftnesFront != sofF then return true end
if self.OldSoftnesRear != sofR then return true end
if self.OldHeightFront != heiF then return true end
if self.OldHeightRear != heiR then return true end
return false
end
function TOOL:Think()
if (CLIENT) then return true end
if self.LiveEnt != NULL && self.LiveEnt != nil && self.LiveEnt:IsValid() && self.LiveEnt.Base == "sent_sakarias_scar_base" && self.UpdateHeight < CurTime() then
self.UpdateHeight = CurTime() + self.UpdateDelay
self.LiveEnt:GetPhysicsObject():Wake()
local SoftnesFront = self:GetClientNumber( "SoftnesFront" )
local SoftnesRear = self:GetClientNumber( "SoftnesRear" )
local HeightFront = self:GetClientNumber( "HeightFront" )
local HeightRear = self:GetClientNumber( "HeightRear" )
if self:ValChange(SoftnesFront, SoftnesRear, HeightFront, HeightRear) then
self.OldHeightFront = HeightFront
self.OldHeightRear = HeightRear
self.OldSoftnesFront = SoftnesFront
self.OldSoftnesRear = SoftnesRear
local live = self:GetClientNumber( "liveAction" )
local live2 = self:GetClientNumber( "liveAction2" )
if live2 == 1 or live == 1 then
self.LiveEnt:ForceRemoveHandBrake()
end
if live2 == 1 then
self.LiveEnt:SetSoftnesFront( SoftnesFront )
self.LiveEnt.SoftnesFront = SoftnesFront
self.LiveEnt:SetSoftnesRear( SoftnesRear )
self.LiveEnt.SoftnesRear = SoftnesRear
end
if live == 1 then
self.LiveEnt:SetHeightFront( HeightFront * -1 )
self.LiveEnt.HeightFront = HeightFront
self.LiveEnt:SetHeightRear( HeightRear * -1 )
self.LiveEnt.HeightRear = HeightRear
end
end
end
end
function TOOL.BuildCPanel( CPanel )
// HEADER
CPanel:AddControl( "Slider", { Label = "#tool_car_softnesfront",
Description = "",
Type = "float",
Min = -30,
Max = 30,
Command = "carsuspension_SoftnesFront" } )
CPanel:AddControl( "Slider", { Label = "#tool_car_softnesrear",
Description = "",
Type = "float",
Min = -30,
Max = 30,
Command = "carsuspension_SoftnesRear" } )
CPanel:AddControl( "CheckBox", { Label = "#tool_car_liveaction",
Description = "#tool_car_liveaction_desc",
Command = "carsuspension_liveAction2" } )
CPanel:AddControl( "Label", { Text = "________________________________________", Description = "" } )
CPanel:AddControl( "Slider", { Label = "#tool_car_heightfront",
Description = "",
Type = "float",
Min = -30,
Max = 30,
Command = "carsuspension_HeightFront" } )
CPanel:AddControl( "Slider", { Label = "#tool_car_heightrear",
Description = "",
Type = "float",
Min = -30,
Max = 30,
Command = "carsuspension_HeightRear" } )
CPanel:AddControl( "CheckBox", { Label = "#tool_car_liveaction",
Description = "#tool_car_liveaction_desc",
Command = "carsuspension_liveAction" } )
end
|
------------------------------------------------------------------------
--[[ Perplexity ]]--
-- Feedback
-- Computes perplexity for language models
-- For now, only works with SoftmaxTree
------------------------------------------------------------------------
local Perplexity, parent = torch.class("dp.Perplexity", "dp.Feedback")
Perplexity.isPerplexity = true
function Perplexity:__init(config)
config = config or {}
assert(torch.type(config) == 'table' and not config[1],
"Constructor requires key-value arguments")
local args, ignore_list, name = xlua.unpack(
{config},
'Perplexity',
'Computes perplexity for language models',
{arg='ignore_list', type='table', default={},
help='array of tokens to be ignored'},
{arg='name', type='string', default='perplexity',
help='name identifying Feedback in reports'}
)
self._ignore_set = {}
for k,v in ipairs(ignore_list) do self._ignore_set[v] = true end
config.name = name
parent.__init(self, config)
self._nll = 0
end
function Perplexity:setup(config)
parent.setup(self, config)
self._mediator:subscribe("doneEpoch", self, "doneEpoch")
end
function Perplexity:perplexity()
-- exponential of the mean NLL
return math.exp(self._nll / self._n_sample)
end
function Perplexity:doneEpoch(report)
if self._n_sample > 0 and self._verbose then
print(self._id:toString().." perplexity = "..self:perplexity())
end
end
function Perplexity:_add(batch, output, carry, report)
if output:input():dim() == 2 then
-- assume output originates from LogSoftMax
local act = output:forward('bf')
if act ~= 'torch.DoubleTensor' and act ~= 'torch.FloatTensor' then
act = output:forward('bf', 'torch.FloatTensor')
end
local targets = batch:targets():forward('b')
local sum = 0
for i=1,targets:size(1) do
if self._ignore_set[targets[i]] then
self._n_sample = self._n_sample - 1
else
sum = sum + act[i][targets[i]]
end
end
self._nll = self._nll - sum
else
-- assume output originates from SoftMaxTree
local act = output:forward('b')
if act ~= 'torch.DoubleTensor' and act ~= 'torch.FloatTensor' then
act = output:forward('b', 'torch.FloatTensor')
end
-- accumulate the sum of negative log likelihoods
self._nll = self._nll - act:sum()
end
end
function Perplexity:_reset()
self._nll = 0
end
function Perplexity:report()
return {
[self:name()] = {
perplexity = self._n_sample > 0 and self:perplexity() or 0
},
n_sample = self._n_sample
}
end
|
--------------------------------
-- @module AsyncTaskPool
-- @parent_module cc
---@class cc.AsyncTaskPool
local AsyncTaskPool = {}
cc.AsyncTaskPool = AsyncTaskPool
--------------------------------
--- Enqueue a asynchronous task.<br>
-- param type task type is io task, network task or others, each type of task has a thread to deal with it.<br>
-- param task: task can be lambda function to be performed off thread.<br>
-- lua NA
---@param type number
---@param callback fun()
---@param callbackParam void
---@param task fun()
---@return cc.AsyncTaskPool
---@overload fun(self:cc.AsyncTaskPool, type:number, task:function):cc.AsyncTaskPool
function AsyncTaskPool:enqueue(type, callback, callbackParam, task)
end
--------------------------------
--- Stop tasks.
--- param type Task type you want to stop.
---@param type number
---@return cc.AsyncTaskPool
function AsyncTaskPool:stopTasks(type)
end
--------------------------------
--- Destroys the async task pool.
---@return cc.AsyncTaskPool
function AsyncTaskPool:destroyInstance()
end
--------------------------------
--- Returns the shared instance of the async task pool.
---@return cc.AsyncTaskPool
function AsyncTaskPool:getInstance()
end
--------------------------------
---
---@return cc.AsyncTaskPool
function AsyncTaskPool:AsyncTaskPool()
end
return nil
|
include("terms")
factor = math.random(9);
name = array_decname[factor]
index = math.random(2);
choice = array_izbor[index];
fact = factor * 100;
if (index == 1) then
min = fact + 2;
max = fact + 100;
else
min = fact + 1;
max = fact + 99;
end
|
local skynet = require "skynet"
local snax = require "snax"
skynet.start(function()
local ps = snax.newservice("pingserver", "hello world")
end) |
local _, Addon = ...; -- Namespace
local Module = Addon.ModuleManager:GetModuleWorkspace("morph");
--------------------------------------
-- Module
--------------------------------------
local UIFrame;
local MorphModelId = 0;
function Module:GetDescription()
return "User interface for .morph command";
end
function Module:Enable()
local ui = UIFrame or Module:CreateUIFrame();
ui:Show();
end
function Module:Disable()
local ui = UIFrame or Module:CreateUIFrame();
ui:Hide();
end
function Module.OnConfigChange(propertyName, propertyValue)
if propertyName == "x" or propertyName == "y" then
UIFrame:SetPoint("LEFT", UIParent, "LEFT", Module.config.x, Module.config.y);
end
end
--------------------------------------
-- UI
--------------------------------------
function Module:CreateUIFrame()
-- Wrapper
UIFrame = CreateFrame("Frame", "AT_MORPH");
UIFrame:SetPoint("LEFT", UIParent, "LEFT", Module.config.x, Module.config.y);
UIFrame:SetSize(48, 128);
-- Model Id input
UIFrame.Input = CreateFrame("EditBox", "AT_INPUT", UIFrame, "InputBoxTemplate");
UIFrame.Input:SetPoint("CENTER", UIFrame, "CENTER");
UIFrame.Input:SetWidth(48);
UIFrame.Input:SetHeight(24);
UIFrame.Input:SetNumeric(true);
UIFrame.Input:SetNumber(MorphModelId);
UIFrame.Input:SetScript("OnEnterPressed", function(self)
Module:ExecMorph(UIFrame.Input:GetNumber());
end);
-- Controls
UIFrame.ButtonPlus = Module:CreateUIControl(UIFrame, 0, 25, "+");
UIFrame.ButtonPlus:SetScript("OnMouseUp", function(self, button)
Module:ExecMorph(MorphModelId + (button == "LeftButton" and Module.config.step or Module.config.jump));
end);
UIFrame.ButtonMinus = Module:CreateUIControl(UIFrame, 0, -24, "-");
UIFrame.ButtonMinus:SetScript("OnMouseUp", function(self, button)
Module:ExecMorph(MorphModelId - (button == "LeftButton" and Module.config.step or Module.config.jump));
end);
UIFrame:Hide();
return UIFrame;
end
function Module:CreateUIControl(parent, x, y, text)
local control = CreateFrame("Button", "AT_CONTROL_" .. text, parent, "UIPanelButtonTemplate");
control:SetPoint("CENTER", parent, "CENTER", x, y);
control:SetWidth(32);
control:SetHeight(24);
control:SetText(text);
control:RegisterForClicks("LeftButtonUp, RightButtonUp");
return control;
end
--------------------------------------
-- Logic
--------------------------------------
function Module:ExecMorph(id)
if id < 0 then
id = 0;
end
if MorphModelId ~= id then
MorphModelId = id;
UIFrame.Input:SetNumber(id);
UIFrame.Input:ClearFocus();
SendChatMessage(".morph " .. id);
end
end
|
CuiVersion = "1.5.5"
LastUpdate = "2020-06-07"
VersionDetail = "Concise UI - " .. CuiVersion .. "[NEWLINE]" .. "Last Update: " .. LastUpdate
|
Require("ProjectDir","../../Common/IngenUtils.lua");
Require("ProjectDir","../../Common/Easing.lua","Easing");
Require("ProjectDir","../../Common/LuaGen.lua","LG");
Require("ProjectDir","Marionette3.lua");
Require("ProjectDir","GpuParticleSystemCurl.lua","GPUPS");
PROFILING = true;
-- Okay, how to do the choreography...
-- 1. More than one tweened camera movement should be possible per shot
-- 2. Should be able to jump to any specific shot through the console
-- 3. Should be able to cue actions within a shot using one or more 'magic buttons'
-- 4. Should be able to trigger restrings, special effects, physics properties etc.
-- Functions?
function store(name)
return function(value)
_G[name] = value;
end
end
function ResetPerformanceCamera()
SetCameraPosition(performanceCamera,-0.5,0.5,2);
SetCameraTarget(performanceCamera,0,-0.5,0);
SetCameraClipFov(performanceCamera,0.01,200,0.78539);
end
setupCS1 = true;
function CS1(progress)
if setupCS1 then
PlaySound(waterLily);
SetLightColor(light,0,0,0);
setupCS1 = false;
end
local cameraPos1 = CreateVector(-0.21, 0.05,-0.55, 1);
local cameraTgt1 = CreateVector(-0.46, 0.14,-1.48, 1);
local cameraPos2 = CreateVector( 0.47,-0.09, 0.95, 1);
local cameraTgt2 = CreateVector(-0.32,-0.32,-0.69, 1);
if progress >= 12.5 then Cutscene(csPanAcrossTable) end
local cameraPos = Easing.linear(progress, cameraPos1, cameraPos2 - cameraPos1, 12.2);
local cameraTgt = Easing.linear(progress, cameraTgt1, cameraTgt2 - cameraTgt1, 12.2);
SetCameraPosition(performanceCamera, cameraPos.x, cameraPos.y, cameraPos.z);
SetCameraTarget(performanceCamera, cameraTgt.x, cameraTgt.y, cameraTgt.z);
if progress > 4 then
local lightColor = Easing.linear(progress-4, 0, 1, 8.2);
SetLightColor(light, lightColor,lightColor,lightColor);
end
end
function csPanAcrossTable(progress)
cameraPos1 = CreateVector(0.911497669614,-0.087275455240438,0.83127248782394, 1);
cameraTgt1 = CreateVector(0.70341969155019,-0.364396330297,-0.12952861900218, 1);
cameraPos2 = CreateVector(-2.2794403279456,-0.21917106436887,0.62660954712759, 1);
cameraTgt2 = CreateVector(-1.8509603484754,-0.4088118956667,-0.25681631976669, 1);
if progress >= 10 then Cutscene(csDownFromSky) end
local cameraPos = Easing.linear(progress, cameraPos1, cameraPos2 - cameraPos1, 10);
local cameraTgt = Easing.linear(progress, cameraTgt1, cameraTgt2 - cameraTgt1, 10);
SetCameraPosition(performanceCamera, cameraPos.x, cameraPos.y, cameraPos.z);
SetCameraTarget(performanceCamera, cameraTgt.x, cameraTgt.y, cameraTgt.z);
end
function csDownFromSky(progress)
cameraPos1 = CreateVector(1.5827534542447,1.214914791749,0.84395068446955,1)
cameraTgt1 = CreateVector(1.2603276908486,0.43734207299804,0.30411525199706,1)
cameraPos2 = CreateVector(-1.5789526447216,-0.89242552215229,0.72446486428968,1)
cameraTgt2 = CreateVector(-1.37401389805484,-1.0228492308904,-0.21987705600876,1)
if progress >= 12 then progress = 12 end
local cameraPos = Easing.linear(progress, cameraPos1, cameraPos2 - cameraPos1, 12);
local cameraTgt = Easing.linear(progress, cameraTgt1, cameraTgt2 - cameraTgt1, 12);
SetCameraPosition(performanceCamera, cameraPos.x, cameraPos.y, cameraPos.z);
SetCameraTarget(performanceCamera, cameraTgt.x, cameraTgt.y, cameraTgt.z);
SetCameraClipFov(performanceCamera, 0.01, 20, 0.985);
end
function csLookAroundRoom(progress)
end
function csRevealCar(progress)
drawCar = true;
if progress > 8 then progress = 8 end;
local revealVal = Easing.linear(progress, -1, 2, 8);
SetEffectParam(revealEffect,5,revealVal+1);
SetEffectParam(revealEffect,8,revealVal-1);
end
function Cutscene(cutsceneFunc)
cutsceneTimer = 0;
cutsceneFunction = cutsceneFunc;
end
function UpdateLeapHand()
for i = 1,GetLeapNumBones(leapHelper) do
visible, length, radius = GetLeapBoneDetails(leapHelper, i-1);
leapVisibilities[i] = visible;
if visible then
if leapModels[i] == nil then
local vtx, idx = CreateCapsule(length / (radius * 2.0));
local boneModel = CreateModel("PosNor",vtx,idx);
SetMeshScale(boneModel, 0, radius * 2.0);
leapModels[i] = boneModel;
print("Created Leap Model " .. i-1);
end
local leapBoneMatrix = GetLeapBoneMatrix(leapHelper, i-1);
SetModelMatrix(leapModels[i], leapBoneMatrix);
end
end
end
function DrawLeapHand()
for i,leapModel in pairs(leapModels) do
if leapModel and leapVisibilities[i] then
DrawComplexModel(leapModel,camera,light);
end
end
end
function Begin()
local appPathArg, puppeteerArg = GetCommandLineArgs();
if puppeteerArg and puppeteerArg == "puppeteer" then
puppeteer = true;
end
assetTicket = LoadAssets(
{"FrameworkDir","SkyShader.xml","Shader","skyshader"},
{"FrameworkDir","ShadowLit.xml","Shader","shadowShader"},
{"FrameworkDir","NoiseReveal.xml","Shader","noiseReveal"},
{"ProjectDir","Stars2.dds","CubeMap","skymap"},
{"ProjectDir","stonefloor.bmp","Texture","floortex"},
{"ProjectDir","Noise2D.dds","Texture","noiseTex"},
{"ProjectDir","Models/room/roomModel.inm","IngenuityModel","roomModel"},
{"ProjectDir","Models/tools/toolsModel.inm","IngenuityModel","toolsModel"},
{"ProjectDir","Models/car/carModel2.inm","IngenuityModel","carModel"},
{"ProjectDir","Music/Water Lily.wav","WavAudio","waterLily"}
);
camera = CreateCamera();
SetCameraClipFov(camera,0.01,200,0.78539);
SetupFlyCamera(camera, 0, 0,-2, 0.01, 1);
floorModel = CreateModel("PosNorTex",CreateCube());
SetModelScale(floorModel,1.0,0.5,1.0);
SetModelPosition(floorModel,0,-1,-0.5);
--SetMeshColor(floorModel,0,0.0,1.0,0.0);
skyModel = CreateSkyCube();
physicsWorld = CreatePhysicsWorld();
physicsFloor = CreatePhysicsCuboid(2,1,2,false);
AddToPhysicsWorld(physicsWorld,physicsFloor,true);
SetPhysicsPosition(physicsFloor,0,-1,-0.5);
SetPhysicsRotation(physicsFloor,0,0,0);
physicsRagdoll = CreateMarionette(physicsWorld);
leapModels = {};
leapVisibilities = {};
--leapPhysicals = {};
leapHelper = CreateLeapHelper();
SetLeapPosition(leapHelper,0,-0.5,0);
SetLeapScale(leapHelper,0.0025);
pickModel = CreateModel("PosNor",CreateSphere());
SetModelScale(pickModel,0.01);
SetMeshColor(pickModel,0,1,0,0);
debugFont = GetFont(40,"Arial");
SetFontColor(debugFont,1,1,1);
lightPosX = -math.sin(2.5);
lightPosY = 0.75;
lightPosZ = -math.cos(2.5);
light = CreateLight("spot");
SetLightPosition(light,lightPosX,lightPosY,lightPosZ)
SetLightDirection(light,-lightPosX,-lightPosY,-lightPosZ);
SetLightSpotPower(light,12);
shadowSurface = CreateSurface(2048,2048,false,"typeless");
shadowCamera = CreateCamera();
SetCameraPosition(shadowCamera,lightPosX,lightPosY,lightPosZ);
SetCameraClipFov(shadowCamera,0.01,20,0.785);
--performanceWindow = CreateWindow();
--SetWindowProps(performanceWindow,nil,nil,true); -- Set performance window undecorated!
performanceCamera = CreateCamera();
ResetPerformanceCamera();
spriteCamera = CreateSpriteCamera(true,false,true);
performanceSurface = CreateSurface(1.0,1.0,GetMainWindow());
performanceQuad = CreateSpriteModel(GetSurfaceTexture(performanceSurface));
cutsceneTimer = 0;
drawCar = false;
end
function Update(delta)
if PROFILING then BeginTimestamp("Update",true,false) end
if IsLoaded(assetTicket) then
skyEffect = CreateEffect("skyshader");
shadowEffect = CreateEffect("shadowShader");
revealEffect = CreateEffect("noiseReveal");
skyMap = GetAsset("skymap");
floorTex = GetAsset("floortex");
noiseTex = GetAsset("noiseTex");
roomModel = GetAsset("roomModel");
toolsModel = GetAsset("toolsModel");
carModel = GetAsset("carModel");
waterLily = GetAsset("waterLily");
if skyEffect then
SetMeshCubeMap(skyModel,0,skyMap);
SetMeshEffect(skyModel,0,skyEffect);
end
if carModel then
SetModelScale(carModel,0.3)
SetModelPosition(carModel,0,-0.6,0)
SetModelRotation(carModel,0,-PI_2,0)
end
if revealEffect then
SetEffectParam(revealEffect,0,noiseTex);
SetEffectParam(revealEffect,5,-2);
SetEffectParam(revealEffect,6,0);
SetEffectParam(revealEffect,8,-1);
end
SetMeshTexture(floorModel,0,floorTex);
assetTicket = -1;
end
UpdateLeapHand();
UpdatePhysicsWorld(physicsWorld,delta);
UpdateMarionette(delta);
--down,pressed,released = GetMouseLeft();
--if pickedObject and down then
-- DragPhysicsObject(physicsWorld,camera,x/sWidth,y/sHeight);
--else
UpdateFlyCamera(delta);
--end
local sWidth, sHeight = GetBackbufferSize();
local mouseX, mouseY = GetMousePosition();
--down,pressed,released = GetKeyState('p');
--if pressed then
pickedObject, pickedPos = PickPhysicsObject(physicsWorld,
CreateVector(flyCamX,flyCamY,flyCamZ,1),
GetCameraRay(camera,mouseX/sWidth,mouseY/sHeight));
if pickedObject then
SetModelPosition(pickModel,pickedPos.x,pickedPos.y,pickedPos.z);
end
--end
UpdateFrameTime(delta);
--local fDown, fPressed, fReleased = GetKeyState('f');
--if fPressed then
-- if currentlyFullscreen then
-- SetWindowProps(performanceWindow, previousWidth, previousHeight, false);
-- currentlyFullscreen = false;
-- else
-- previousWidth, previousHeight = GetBackbufferSize();
-- newWidth, newHeight = GetMonitorSize(performanceWindow);
-- print("Resizing window to " .. newWidth .. ", " .. newHeight);
-- SetWindowProps(performanceWindow, newWidth, newHeight, true);
-- currentlyFullscreen = true;
-- end
--end
if roomModel and toolsModel then
SetModelPosition(roomModel,0,-1.59,-0.95);
SetModelPosition(toolsModel,0,-1.59,-0.95);
SetModelScale(roomModel,0.285);
SetModelScale(toolsModel,0.285);
end
ResetPerformanceCamera();
lightPosX = -math.sin(2.5) * 1.2;
lightPosY = 1.0;
lightPosZ = -math.cos(2.5) * 1.2;
SetLightPosition(light,lightPosX,lightPosY,lightPosZ)
SetLightDirection(light,-lightPosX,-lightPosY,-lightPosZ);
SetCameraPosition(shadowCamera,lightPosX,lightPosY,lightPosZ);
SetCameraClipFov(shadowCamera,0.01,20,1.185);
UpdatePixelCamera(spriteCamera,nil,false,true,1,5000);
cutsceneTimer = cutsceneTimer + delta;
if cutsceneFunction then
cutsceneFunction(cutsceneTimer);
end
if PROFILING then EndTimestamp("Update",true,false) end
end
function PrintCamera()
local dirX = (math.sin(flyCamYAngle) * math.cos(flyCamUpAngle));
local dirY = (math.sin(flyCamUpAngle));
local dirZ = (math.cos(flyCamYAngle) * math.cos(flyCamUpAngle));
print(LG.Assign(LG.Call("CreateVector",flyCamX,flyCamY,flyCamZ,1),"cameraPos"));
print(LG.Assign(LG.Call("CreateVector",flyCamX+dirX,flyCamY+dirY,flyCamZ+dirZ,1),"cameraTgt"));
end
function SyncCameras()
local dirX = (math.sin(flyCamYAngle) * math.cos(flyCamUpAngle));
local dirY = (math.sin(flyCamUpAngle));
local dirZ = (math.cos(flyCamYAngle) * math.cos(flyCamUpAngle));
SetCameraPosition(performanceCamera,flyCamX,flyCamY,flyCamZ);
SetCameraTarget(performanceCamera,flyCamX+dirX,flyCamY+dirY,flyCamZ+dirZ);
end
function Draw()
if PROFILING then BeginTimestamp("Draw",true,true) end
if puppeteer then
-- Draw all objects to the main window
if PROFILING then BeginTimestamp("DrawControl",false,true) end
DrawComplexModel(floorModel,camera,light);
if roomModel and toolsModel then
--DrawComplexModel(roomModel,camera,light,nil,nil,shadowEffect);
--DrawComplexModel(toolsModel,camera,light,nil,nil,shadowEffect);
end
if pickedObject then
DrawComplexModel(pickModel,camera,light);
end
DrawLeapHand();
DrawMarionette(camera,nil,nil);
DrawMarionetteWires(camera,nil,nil);
if PROFILING then EndTimestamp("DrawControl",false,true) end
-- This skybox looks absolute crap, I might have to ditch it...
--DrawComplexModel(skyModel,camera,nil);
else -- not puppeteer
-- Draw shadows to the shadow map
if PROFILING then BeginTimestamp("DrawShadows",false,true) end
ClearSurface(shadowSurface);
if toolsModel then
DrawComplexModel(roomModel,shadowCamera,nil,shadowSurface);
DrawComplexModel(toolsModel,shadowCamera,nil,shadowSurface);
end
DrawMarionette(shadowCamera,shadowSurface,nil,false);
if PROFILING then EndTimestamp("DrawShadows",false,true) end
-- Draw objects to the performance surface
if PROFILING then BeginTimestamp("DrawPerformance",false,true) end
if performanceSurface then
ClearSurface(performanceSurface);
if shadowEffect then
local cameraMatrix = GetCameraProjMatrix(shadowCamera,shadowSurface,true) * GetCameraViewMatrix(shadowCamera);
cameraMatrixFloats = CreateFloatArray(cameraMatrix);
SetEffectParam(shadowEffect,0,cameraMatrixFloats);
SetEffectParam(shadowEffect,1,GetSurfaceTexture(shadowSurface));
SetEffectParam(shadowEffect,2,0.00005);
end
--DrawComplexModel(floorModel,performanceCamera,light,performanceSurface,nil,shadowEffect);
if roomModel and toolsModel then
DrawComplexModel(roomModel,performanceCamera,light,performanceSurface,nil,shadowEffect);
DrawComplexModel(toolsModel,performanceCamera,light,performanceSurface,nil,shadowEffect);
end
DrawMarionette(performanceCamera,performanceSurface,shadowEffect);
if skyEffect then
DrawComplexModel(skyModel,performanceCamera,nil,performanceSurface);
end
if drawCar then
DrawComplexModel(carModel,performanceCamera,light,performanceSurface,nil,revealEffect);
end
end
if PROFILING then EndTimestamp("DrawPerformance",false,true) end
-- Draw the performance surface
if PROFILING then BeginTimestamp("DrawViewports",false,true) end
--local performanceWindowSurface = GetWindowSurface(performanceWindow);
--if performanceWindowSurface then
DrawSurface(performanceSurface,nil,performanceWindowSurface);
--end
--local performanceWidth, performanceHeight = GetBackbufferSize(performanceWindow);
--local mainWidth, mainHeight = GetBackbufferSize();
--SetMeshTexture(performanceQuad,0,GetSurfaceTexture(performanceSurface));
--local quadWidth = (performanceWidth/performanceHeight) * 250;
--SetMeshScale(performanceQuad,0, quadWidth, 250, 1);
--SetModelPosition(performanceQuad,mainWidth - quadWidth,0,0);
--DrawComplexModel(performanceQuad,spriteCamera);
if PROFILING then EndTimestamp("DrawViewports",false,true) end
end -- not puppeteer
if PROFILING then EndTimestamp("Draw",true,true) end
if PROFILING then
DrawText(debugFont,frameTimeText,0,0);
timestampText = string.format("Update CPU: %2.2fms, Draw CPU: %2.2fms, Draw Gpu: %2.2fms",
GetTimestampData("Update",true) * 1000,
GetTimestampData("Draw",true) * 1000,
GetTimestampData("Draw",false) * 1000);
drawTimeText = string.format("CTRL: %2.2fms, SHDW: %2.2fms, PRFM: %2.2fms, VIEW: %2.2fms",
GetTimestampData("DrawControl",false) * 1000,
GetTimestampData("DrawShadows",false) * 1000,
GetTimestampData("DrawPerformance",false) * 1000,
GetTimestampData("DrawViewports",false) * 1000);
DrawText(debugFont,timestampText,0,50);
DrawText(debugFont,drawTimeText,0,100);
end
end
function End()
end
|
explosions = {}
genericEnemyExplosion = nil
fps = 18
function newAnimation(anim, x, y)
return {
anim = anim,
x = x,
y = y,
time = 0,
maxTime = anim.frames / fps
}
end
function initAnimations()
simpleBulletExplosion = loadAnimation(love.graphics.newImage("assets/img/bulletexpl.png"), 15, 15)
rocketExplosion = loadAnimation(love.graphics.newImage("assets/img/missileexpl.png"), 39, 39)
stargunExplosion = loadAnimation(love.graphics.newImage("assets/img/starexpl.png"), 27, 27)
blackHoleImplosion = loadAnimation(love.graphics.newImage("assets/img/blackholeexpl.png"), 33, 39)
genericEnemyExplosion = loadAnimation(love.graphics.newImage("assets/img/genericenemyexpl.png"), 54, 54)
weapons.params.machinegun.explosion = simpleBulletExplosion
enemyParams.params.simpleBullet.explosion = simpleBulletExplosion
weapons.params.rockets.explosion = rocketExplosion
weapons.params.stars.explosion = stargunExplosion
blackHoleParams.explosion = blackHoleImplosion
end
function loadAnimation(image, width, height)
anim = {}
anim.img = image
anim.quads = {}
anim.frames = 0
anim.width = width
anim.height = height
for y = 0, image:getHeight() - height, height do
for x = 0, image:getWidth() - width, width do
table.insert(anim.quads, love.graphics.newQuad(x, 0, width, height, image:getDimensions()))
anim.frames = anim.frames + 1
end
end
return anim
end
function explosionsProcess(dt)
for i, anim in ipairs(explosions) do
anim.time = anim.time + dt
anim.y = anim.y + bgV*dt
if anim.time >= anim.maxTime then
table.remove(explosions, i)
end
end
end
function explosionsDraw(dt)
for i, anim in ipairs(explosions) do
frame = math.floor(anim.time*fps)+1
love.graphics.draw(anim.anim.img, anim.anim.quads[frame], gridPos(anim.x - anim.anim.width/2),
gridPos(anim.y - anim.anim.height/2))
end
end
|
local PANEL = {}
PANEL.permission_value = PERM_NO
PANEL.permission = {}
function PANEL:rebuild()
if IsValid(self.container) then
self.container:safe_remove()
end
local width, height = self:GetWide(), self:GetTall()
local font = Font.size(Theme.get_font('text_normal_smaller'), math.scale(18))
local font_size = draw.GetFontHeight(font)
local permission = self:get_permission()
local quarter = width * 0.25
self.container = vgui.Create('fl_base_panel', self)
self.container:SetSize(width, height)
self.container:SetPos(0, 0)
self.title = vgui.Create('DLabel', self.container)
self.title:SetPos(0, height * 0.5 - font_size * 0.5)
self.title:SetFont(font)
self.title:SetText(permission.name or 'No Permission')
self.title:SetSize(quarter, height)
if permission.description then
self.title:SetTooltip(permission.description)
end
self.button_allow = vgui.Create('DButton', self.container)
self.button_allow:SetPos(quarter, 0)
self.button_allow:SetSize(quarter * 0.9, height)
self.button_allow:SetText('')
self.button_allow.perm_value = PERM_ALLOW
self.button_allow.Paint = function(btn, w, h) Theme.call('PaintPermissionButton', self, btn, w, h) end
self.button_allow.DoClick = function(btn)
if btn.is_selected then return end
surface.PlaySound('buttons/button14.wav')
self:select_button(btn)
end
self.button_allow.DoRightClick = function(btn)
surface.PlaySound('buttons/button14.wav')
Derma_StringRequest(t'ui.admin.temp_permission.title',
t'ui.admin.temp_permission.message',
'',
function(text)
local duration = Bolt:interpret_ban_time(text)
local perm_id = self:get_permission().id
local perm_value = btn.perm_value
if text == '' then
Cable.send('fl_delete_temp_permission', self:get_player(), perm_id)
self:set_temporary(perm_value, 0)
return
end
if duration then
Cable.send('fl_temp_permission', self:get_player(), perm_id, perm_value, duration)
self:set_temporary(perm_value, os.time() + duration)
end
end)
end
self.button_no = vgui.Create('DButton', self.container)
self.button_no:SetPos(quarter * 2, 0)
self.button_no:SetSize(quarter * 0.9, height)
self.button_no:SetText('')
self.button_no.perm_value = PERM_NO
self.button_no.Paint = function(btn, w, h) Theme.call('PaintPermissionButton', self, btn, w, h) end
self.button_no.DoClick = function(btn)
if btn.is_selected then return end
surface.PlaySound('ui/buttonclick.wav')
self:select_button(btn)
end
self.button_no.DoRightClick = function(btn)
surface.PlaySound('buttons/button14.wav')
Derma_StringRequest(t'ui.admin.temp_permission.title',
t'ui.admin.temp_permission.message',
'',
function(text)
local duration = Bolt:interpret_ban_time(text)
local perm_id = self:get_permission().id
local perm_value = btn.perm_value
if text == '' then
Cable.send('fl_delete_temp_permission', self:get_player(), perm_id)
self:set_temporary(perm_value, 0)
return
end
if duration then
Cable.send('fl_temp_permission', self:get_player(), perm_id, perm_value, duration)
self:set_temporary(perm_value, os.time() + duration)
end
end)
end
self.button_never = vgui.Create('DButton', self.container)
self.button_never:SetPos(quarter * 3, 0)
self.button_never:SetSize(quarter * 0.9, height)
self.button_never:SetText('')
self.button_never.perm_value = PERM_NEVER
self.button_never.Paint = function(btn, w, h) Theme.call('PaintPermissionButton', self, btn, w, h) end
self.button_never.DoClick = function(btn)
if btn.is_selected then return end
surface.PlaySound('buttons/button10.wav')
self:select_button(btn)
end
self.button_never.DoRightClick = function(btn)
surface.PlaySound('buttons/button14.wav')
Derma_StringRequest(t'ui.admin.temp_permission.title',
t'ui.admin.temp_permission.message',
'',
function(text)
local duration = Bolt:interpret_ban_time(text)
local perm_id = self:get_permission().id
local perm_value = btn.perm_value
if text == '' then
Cable.send('fl_delete_temp_permission', self:get_player(), perm_id)
self:set_temporary(perm_value, 0)
return
end
if duration then
Cable.send('fl_temp_permission', self:get_player(), perm_id, perm_value, duration)
self:set_temporary(perm_value, os.time() + duration)
end
end)
end
end
function PANEL:select_button(button)
local value = button.perm_value or PERM_NO
local perm = self:get_permission()
self.permission_value = value
button.is_selected = true
local player = self:get_player()
if IsValid(player) and (value != player:get_permission(perm.id)) then
Cable.send('fl_bolt_set_permission', player, perm.id, value)
end
if IsValid(self.prev_button) and self.prev_button != button then
self.prev_button.is_selected = false
end
self.prev_button = button
end
function PANEL:set_player(player)
self.active_player = player
end
function PANEL:get_player()
return self.active_player
end
function PANEL:set_permission(perm)
self.permission = perm or {}
self:rebuild()
end
function PANEL:get_permission()
return self.permission
end
function PANEL:get_value()
return self.permission_value
end
function PANEL:get_button(perm)
if perm == PERM_ALLOW then
return self.button_allow
elseif perm == PERM_NEVER then
return self.button_never
else
return self.button_no
end
end
function PANEL:set_value(perm)
self:select_button(self:get_button(perm))
end
function PANEL:set_temporary(perm, expires)
local button = self:get_button(perm)
button.is_temp = expires != 0 and true or nil
button:SetTooltip(expires != 0 and t'ui.admin.expires'..' '..Flux.Lang:nice_time(expires - os.time()) or false)
if IsValid(self.prev_temp) and self.prev_temp != button then
self.prev_temp.is_temp = nil
self.prev_temp:SetTooltip(false)
end
self.prev_temp = button
end
vgui.Register('fl_permission', PANEL, 'fl_base_panel')
local PANEL = {}
function PANEL:Init()
self.permissions = {}
self:rebuild()
end
function PANEL:Paint(w, h)
Theme.call('PaintPermissionEditor', self, w, h)
end
function PANEL:get_permissions()
local perm_list = {}
for k, v in pairs(self.permissions) do
if v:get_value() != PERM_NO then
perm_list[v:get_permission()] = v:get_value()
end
end
return perm_list
end
function PANEL:set_permissions(perm_list, temp_perm_list)
for k, v in pairs(perm_list) do
self.permissions[k]:set_value(tonumber(v))
end
if temp_perm_list then
for k, v in pairs(temp_perm_list) do
if v.expires > os.time() then
self.permissions[k]:set_temporary(tonumber(v.value), v.expires)
end
end
end
end
function PANEL:set_player(player)
self.active_player = player
self:rebuild()
self:set_permissions(player:get_permissions(), player:get_temp_permissions())
end
function PANEL:get_player()
return self.active_player
end
function PANEL:rebuild()
if IsValid(self.list_layout) then
self.list_layout:safe_remove()
end
local permissions = Bolt:get_permissions()
local width, height = self:GetWide(), self:GetTall()
self.scroll_panel = vgui.Create('DScrollPanel', self)
self.scroll_panel:SetSize(width, height)
self.list_layout = vgui.Create('DListLayout', self.scroll_panel)
self.list_layout:SetSize(width, height)
for category, perms in SortedPairs(permissions) do
local collapsible_category = vgui.Create('DCollapsibleCategory', self.list_layout)
collapsible_category:SetLabel(t(category))
collapsible_category:SetSize(width, 21)
local list = vgui.Create('DListLayout', self.list_layout)
collapsible_category:SetContents(list)
if table.count(perms) > 1 then
local panel = vgui.create('fl_base_panel')
local category_buttons = {
t'ui.admin.allow_all',
t'ui.admin.no_all',
t'ui.admin.never_all'
}
local quarter = width / 4
for k, v in pairs(category_buttons) do
local button = vgui.create('fl_button', panel)
button:SetSize(quarter * 0.9, 20)
button:SetPos(quarter * k, 2)
button:SetFont(Theme.get_font('text_small'))
button:set_text(v)
button:set_centered(true)
button.DoClick = function(btn)
local can_click = false
for k1, v1 in pairs(perms) do
if self.permissions[v1.id]:get_value() != k - 1 then
can_click = true
break
end
end
if !can_click then return end
surface.PlaySound('buttons/button4.wav')
for k1, v1 in pairs(perms) do
self.permissions[v1.id]:set_value(k - 1)
end
end
end
list:Add(panel)
end
local cur_y = 0
for k, v in SortedPairs(perms) do
local button = vgui.Create('fl_permission', self)
button:SetSize(width, 20)
button:set_permission(v)
button:set_value(PERM_NO)
button:set_player(self:get_player())
list:Add(button)
self.permissions[v.id] = button
end
end
end
vgui.Register('fl_permissions_editor', PANEL, 'fl_base_panel')
|
local cjson = require "cjson"
local ocsp = require "ngx.ocsp"
local ssl = require "ngx.ssl"
local resty_lock = require "resty.lock"
local resty_http = require "resty.http"
local resty_lrucache = require "resty.lrucache"
-- alias functions and variables
local ngx_log = ngx.log
local ngx_exit = ngx.exit
local ngx_time = ngx.time
local ngx_now = ngx.now
local ngx_encode_base64 = ngx.encode_base64
local ngx_decode_base64 = ngx.decode_base64
local ngx_NOTICE = ngx.NOTICE
local ngx_WARN = ngx.WARN
local ngx_ERR = ngx.ERR
local string_find = string.find
local string_sub = string.sub
local table_insert = table.insert
local err_204_no_content = "204 no content"
local _M = { _VERSION = '0.4.2' }
-- We need to initialize the cache on the lua module level so that
-- it can be shared by all the requests served by each nginx worker process.
local lru_cache = nil
function _M.new(options)
local opts = options or {}
local host, port
if not opts.backend then
opts.backend = "127.0.0.1:8999"
else
host, port = opts.backend:match("([^:]+):(%d+)")
if not host then
host = opts.backend:match("^%d[%d%.]+%d$")
if not host then
ngx_log(ngx_ERR, "invalid backend IP address, using default 127.0.0.1:8999")
opts.backend = "127.0.0.1:8999"
else
opts.backend = host .. ":80"
end
end
end
host, port = opts.backend:match("([^:]+):(%d+)")
opts.backend_host = host
opts.backend_port = tonumber(port or 80)
if not opts.allow_domain then
opts.allow_domain = function(domain)
return false
end
end
local err = nil
opts.lru_maxitems = tonumber(opts.lru_maxitems or 100)
lru_cache, err = resty_lrucache.new(opts.lru_maxitems)
if err then
ngx_log(ngx_ERR, "failed to create lru cache")
end
ngx_log(ngx_NOTICE, "initialized ssl-cert-server with backend ", opts.backend)
return setmetatable({ opts = opts }, { __index = _M })
end
local function _split_string(buf, length)
local sep = "|"
local result = {}
local from, sep_idx = 1, 0
for _ = 1, length - 1 do
sep_idx = string_find(buf, sep, from)
if sep_idx == from then
table_insert(result, "")
else
table_insert(result, string_sub(buf, from, sep_idx - 1))
end
from = sep_idx + 1
end
table_insert(result, string_sub(buf, from))
return result
end
local cachecert = {
cert_pem = nil,
pkey_pem = nil,
cert_type = 0,
fingerprint = "",
expire_at = 0,
refresh_at = 0,
cert_cdata = nil,
pkey_cdata = nil,
}
function cachecert:new(obj)
obj = obj or {}
setmetatable(obj, self)
self.__index = self
return obj
end
function cachecert:serialize()
local sep = "|"
return self.cert_type .. sep .. self.fingerprint .. sep .. self.expire_at .. sep .. self.refresh_at .. sep .. self.cert_pem .. sep .. self.pkey_pem
end
function cachecert:deserialize(buf)
-- see cachecert:serialize
local result = _split_string(buf, 6)
self.cert_type = tonumber(result[1]) or 0
self.fingerprint = result[2] or ""
self.expire_at = tonumber(result[3]) or 0
self.refresh_at = tonumber(result[4]) or 0
self.cert_pem = result[5]
self.pkey_pem = result[6]
return self
end
function cachecert:parse_cert_and_priv_key()
local cert_cdata, pkey_cdata, err
cert_cdata, err = ssl.parse_pem_cert(self.cert_pem)
if err then
return "failed to parse certificate: " .. err
end
pkey_cdata, err = ssl.parse_pem_priv_key(self.pkey_pem)
if err then
return "failed to parse private key: " .. err
end
self.cert_cdata = cert_cdata
self.pkey_cdata = pkey_cdata
return nil
end
local cachestapling = {
stapling = nil,
expire_at = 0,
refresh_at = 0,
}
function cachestapling:new(obj)
obj = obj or {}
setmetatable(obj, self)
self.__index = self
return obj
end
function cachestapling:serialize()
local sep = "|"
return self.expire_at .. sep .. self.refresh_at .. sep .. self.stapling
end
function cachestapling:deserialize(buf)
-- see cachestapling:serialize
local result = _split_string(buf, 3)
self.expire_at = tonumber(result[1]) or 0
self.refresh_at = tonumber(result[2]) or 0
self.stapling = result[3]
return self
end
local function _log_unlock(lock)
local ok, lock_err = lock:unlock()
if not ok then
ngx_log(ngx_ERR, "failed to unlock: " .. lock_err)
return false
end
return true
end
local function _lock(key, opts)
local lock, lock_err = resty_lock:new("ssl_certs_cache", opts)
if not lock then
return nil, "failed to create lock: " .. lock_err
end
local elapsed, lock_err = lock:lock(key)
if not elapsed then
return nil, "failed to acquire lock: " .. lock_err
end
return lock
end
local function safe_connect(self)
local lock_key = "lock:backend:connect"
local failure_key = "backend:failure"
local cache = ngx.shared.ssl_certs_cache
local failure, cache_err = cache:get(failure_key)
if cache_err then
return nil, "failed to get backend failure status: " .. cache_err
end
local sleep, previous
if failure then
local data = cjson.decode(failure)
sleep, previous = data['sleep'], data['previous']
if ngx_now() - previous < sleep then
return nil, "backend is in unhealthy state"
end
end
local lock, lock_err = _lock(lock_key, { exptime = 1, timeout = 1 })
if not lock then
return nil, lock_err
end
-- Check again after holding lock.
failure, cache_err = cache:get(failure_key)
if cache_err then
_log_unlock(lock)
return nil, "failed to get backend failure status: " .. cache_err
end
if failure then
local data = cjson.decode(failure)
sleep, previous = data['sleep'], data['previous']
if ngx_now() - previous < sleep then
_log_unlock(lock, lock_key)
return nil, "backend is in unhealthy state"
end
end
-- Backend looks all right, try it.
local httpc = resty_http.new()
httpc:set_timeout(500)
local ok, conn_err = httpc:connect(self.opts.backend_host, self.opts.backend_port)
if not ok then
-- Block further connections to avoid slowing down nginx too much for busy website.
-- Connect to backend as soon as possible, no more than 2 minutes.
if not sleep then
sleep = 1
else
sleep = sleep * 2
if sleep > 120 then
sleep = 120
end
end
ngx_log(ngx_ERR, "backend in unhealthy state, block for ", sleep, " seconds")
local ok, cache_err = cache:set(failure_key, cjson.encode({ sleep = sleep, previous = ngx_now() }))
if not ok then
ngx_log(ngx_ERR, "failed to set backend failure status: ", cache_err)
end
_log_unlock(lock)
return nil, conn_err
end
-- Connect backend success, clear failure status if exists.
if failure then
local ok, cache_err = cache:delete(failure_key)
if not ok then
ngx_log(ngx_ERR, "failed to delete backend failure status: ", cache_err)
end
end
_log_unlock(lock)
return httpc
end
local function make_request(self, opts, timeout, decode_json)
local httpc, conn_err = safe_connect(self)
if conn_err ~= nil then
return nil, nil, conn_err
end
httpc:set_timeout((timeout or 5) * 1000)
local res, req_err = httpc:request(opts)
local body, headers
if res then
if res.status == 204 then
req_err = err_204_no_content
elseif res.status ~= 200 then
req_err = "bad http status " .. res.status
else
headers = res.headers
body, req_err = res:read_body()
if body and decode_json then
local suc
suc, body = pcall(cjson.decode, body)
if not suc then
req_err = "invalid json data from server"
end
end
end
end
if req_err then
return nil, nil, req_err
end
httpc:set_keepalive()
return body, headers
end
local function request_cert(self, domain, timeout)
-- Get the certificate from backend cert server.
local cert_json, headers, req_err = make_request(self, { path = "/cert/" .. domain }, timeout, true)
if not (cert_json and headers) or req_err then
return nil, req_err
end
local cert = cachecert:new({
cert_pem = cert_json["cert"],
pkey_pem = cert_json["pkey"],
cert_type = cert_json["type"],
fingerprint = cert_json["fingerprint"],
expire_at = cert_json["expire_at"],
refresh_at = ngx_time() + cert_json["ttl"],
})
return cert
end
local function get_cert(self, domain)
local cache = ngx.shared.ssl_certs_cache
local cert_key = "cert:" .. domain
local lock_key = "lock:cert:" .. domain
local lock_exptime = 120 -- seconds
local is_expired = false
local cert_buf, cache_err = cache:get(cert_key)
if cache_err then
return nil, nil, "failed to get certificate cache: " .. cache_err
end
local cert
if cert_buf then
cert = cachecert:new():deserialize(cert_buf)
-- the cached certificate is within TTL, use it
if cert.refresh_at > ngx_time() then
return cert
end
end
-- TTL expired, refresh it
-- lock to prevent multiple requests for same domain.
local lock, lock_err = _lock(lock_key, { exptime = lock_exptime, timeout = lock_exptime })
if not lock then
return nil, nil, lock_err
end
-- check the cache again after holding the lock.
cert_buf, cache_err = cache:get(cert_key)
if cache_err then
_log_unlock(lock)
return nil, nil, "failed to get certificate cache: " .. cache_err
end
-- Someone may already done the work.
if cert_buf then
cert = cachecert:new():deserialize(cert_buf)
if cert.refresh_at > ngx_time() then
_log_unlock(lock)
return cert, is_expired
end
end
-- We are the first, request or refresh certificate from backend server.
local new_cert, req_err
new_cert, req_err = request_cert(self, domain, lock_exptime - 10)
if new_cert then
-- Cache the newly requested certificate.
ngx_log(ngx_NOTICE, "requested certificate from backend server: " .. domain
.. " fingerprint= " .. new_cert["fingerprint"]
.. " expire_at= " .. new_cert["expire_at"]
.. " refresh_at= " .. new_cert["refresh_at"])
cert = new_cert
cert_buf = cert:serialize()
local ok, cache_err, forcible = cache:set(cert_key, cert_buf)
if forcible then
ngx_log(ngx_ERR, "lua shared dict 'ssl_certs_cache' might be too small - consider increasing its size (old entries were removed while adding certificate for " .. domain .. ")")
end
if not ok then
ngx_log(ngx_ERR, domain, ": failed to set certificate cache: ", cache_err)
end
else
-- Since certificate renewal happens far before expired on backend server,
-- most probably the previous certificate is valid, we use it if it is available.
-- This avoids further requests within next cache period triggering certificate
-- requests to backend, which may slow down nginx and rise up pressure on busy site.
-- Also we consider an recently-expired certificate is more friendly to our users
-- than fallback to self-signed certificate.
if cert and cert.expire_at <= ngx_time() then
is_expired = true
ngx_log(ngx_WARN, domain, ": fallback to expired certificate")
end
end
-- Now we can release the lock.
_log_unlock(lock)
return cert, is_expired, nil
end
local function set_cert(self, cert_cdata, pkey_cdata)
local ok, err
-- Clear the default fallback certificates (defined in the hard-coded nginx configuration).
ok, err = ssl.clear_certs()
if not ok then
return false, "failed to clear existing (fallback) certificates: " .. err
end
-- Set the public certificate chain.
ok, err = ssl.set_cert(cert_cdata)
if not ok then
return false, "failed to set certificate: " .. err
end
-- Set the private key.
ok, err = ssl.set_priv_key(pkey_cdata)
if not ok then
return false, "failed to set private key: " .. err
end
return true
end
local function request_stapling(self, domain, fingerprint, timeout)
-- Get OCSP stapling from backend cert server.
local path = "/ocsp/" .. domain .. "?fp=" .. fingerprint
local resp_stapling, headers, req_err = make_request(self, { path = path }, timeout, false)
if req_err then
return nil, req_err
end
-- Parse TTL from response header, default 10 minutes if absent for any reason.
local ttl = tonumber(headers["X-TTL"] or 600)
local expire_at = tonumber(headers["X-Expire-At"] or 600)
local stapling = cachestapling:new({
stapling = resp_stapling,
expire_at = expire_at,
refresh_at = ngx_time() + ttl,
})
return stapling
end
local function get_stapling(self, domain, fingerprint)
local shm_cache = ngx.shared.ssl_certs_cache
local stapling_key = "stapling:" .. domain .. ":" .. fingerprint
local lock_key = "lock:stapling:" .. domain
local lock_exptime = 10 -- seconds
local stapling_buf, cache_err = shm_cache:get(stapling_key)
if cache_err then
return nil, "failed to get OCSP stapling cache: " .. cache_err
end
local stapling
if stapling_buf then
stapling = cachestapling:new():deserialize(stapling_buf)
-- the cached stapling is within TTL, use it
if stapling.refresh_at > ngx_time() then
return stapling
end
end
-- TTL expired, refresh it
-- Lock to prevent multiple requests for same domain.
local lock, lock_err = _lock(lock_key, { exptime = lock_exptime, timeout = lock_exptime })
if not lock then
return nil, lock_err
end
-- Check the cache again after holding the lock.
stapling_buf, cache_err = shm_cache:get(stapling_key)
if cache_err then
_log_unlock(lock)
return nil, "failed to get OCSP stapling cache: " .. cache_err
end
if stapling_buf then
stapling = cachestapling:new():deserialize(stapling_buf)
if stapling.refresh_at > ngx_time() then
_log_unlock(lock)
return stapling
end
end
-- We are the first, request and cache OCSP stapling from backend server.
local new_stapling, req_err
new_stapling, req_err = request_stapling(self, domain, fingerprint, lock_exptime - 2)
if new_stapling then
-- Cache the newly requested stapling.
-- Consider time deviation, expire the backup 10 seconds before expiration.
ngx_log(ngx.NOTICE, "requested stapling from backend server: " .. domain
.. " fingerprint= " .. fingerprint
.. " expire_at= " .. new_stapling["expire_at"]
.. " refresh_at= " .. new_stapling["refresh_at"])
stapling = new_stapling
stapling_buf = stapling:serialize()
local expire_ttl = stapling.expire_at - ngx_time() - 10
if expire_ttl > 0 then
local ok, cache_err, forcible = shm_cache:set(stapling_key, stapling_buf, expire_ttl)
if forcible then
ngx_log(ngx_ERR, "lua shared dict 'ssl_certs_cache' might be too small - consider increasing its size (old entries were removed while adding OCSP stapling for " .. domain .. ")")
end
if not ok then
ngx_log(ngx_ERR, "failed to set OCSP stapling cache: ", cache_err)
end
end
else
-- In case of backend failure, use cached response if not expired.
if stapling and stapling.expire_at < ngx_time() then
stapling = nil
end
end
-- Release the lock.
_log_unlock(lock)
if not stapling then
return nil, req_err
end
return stapling
end
local function set_stapling(self, stapling)
-- Set the OCSP stapling response.
local ok, err = ocsp.set_ocsp_status_resp(stapling)
if not ok then
return false, "failed to set OCSP stapling: " .. err
end
return true
end
local function get_cert_from_lru_cache(domain)
local cert_key = "cert:" .. domain
return lru_cache:get(cert_key)
end
local function set_cert_to_lru_cache(domain, cert)
local ttl = cert.refresh_at - ngx_time()
if ttl > 0 then
local cert_key = "cert:" .. domain
lru_cache:set(cert_key, cert, ttl)
end
end
function _M.ssl_certificate(self)
local domain, domain_err = ssl.server_name()
if not domain or domain_err then
ngx_log(ngx_WARN, "could not determine domain for request (SNI not supported?): ", (domain_err or ""))
return
end
-- Check the domain is one we allow for handling SSL.
if not self.opts.allow_domain(domain) then
ngx_log(ngx_NOTICE, domain, ": domain not allowed")
return
end
local cert = get_cert_from_lru_cache(domain)
local has_stapling, is_expired
local err
if not cert then
cert, is_expired, err = get_cert(self, domain)
end
-- Missed from LRU cache, and got from shared memory or backend.
if cert and (not cert.cert_cdata) then
err = cert:parse_cert_and_priv_key()
if err then
ngx_log(ngx_ERR, domain, ": ", err)
return
end
-- From now on, the certificate and private key PEM are not needed
-- anymore, drop them to save some memory space for LRU cache.
cert.cert_pem = nil
cert.pkey_pem = nil
-- Cache the parsed cdata to LRU cache.
if not is_expired then
set_cert_to_lru_cache(domain, cert)
end
end
-- Got from LRU cache, the certificate may be expired.
if cert then
if (not is_expired) and cert.cert_type < 100 then
has_stapling = true
end
local ok, set_err = set_cert(self, cert.cert_cdata, cert.pkey_cdata)
if not ok then
ngx_log(ngx_ERR, domain, ": ", set_err)
return
end
else
-- No cached certificate is available, fallback to the default
-- certificate configured in the configuration file.
if err then
ngx_log(ngx_ERR, domain, ": ", err)
end
ngx_log(ngx_WARN, domain, ": fallback to configured default certificate")
return
end
if self.opts.disable_stapling or (not has_stapling) then
return
end
-- Since the ocsp library supports only DER format, it doesn't make much
-- sense to use LRU cache here, so we don't use it for OCSP stapling.
local stapling
stapling, err = get_stapling(self, domain, cert.fingerprint)
if stapling then
local ok, set_err = set_stapling(self, stapling.stapling)
if not ok then
ngx_log(ngx_ERR, domain, ": ", set_err)
return
end
else
ngx_log(ngx_NOTICE, domain, ": ", err)
return
end
end
function _M.challenge_server(self)
local domain, domain_err = ssl.server_name()
if domain_err then
ngx_log(ngx_WARN, "failed to get ssl.server_name (SNI not supported?): ", domain_err)
end
if not domain or domain == "" then
domain = ngx.var.host
if not domain or domain == "" then
ngx_log(ngx_ERR, "could not determine domain from either ssl.server_name nor ngx.var.host")
ngx_exit(ngx.HTTP_BAD_REQUEST)
end
end
if not self.opts.allow_domain(domain) then
ngx_log(ngx_NOTICE, domain, ": domain not allowed")
ngx_exit(ngx.HTTP_NOT_FOUND)
end
-- Proxy challenge request to backend cert server.
local httpc = resty_http.new()
httpc:set_timeout(500)
local ok, conn_err = httpc:connect(self.opts.backend_host, self.opts.backend_port)
if not ok then
ngx_log(ngx_ERR, domain, ": failed to connect backend server to proxy challenge request: ", conn_err)
ngx_exit(ngx.HTTP_BAD_GATEWAY)
end
httpc:set_timeout(2000)
httpc:proxy_response(httpc:proxy_request())
httpc:set_keepalive()
end
return _M
|
local skynet = require "skynet"
local function main()
skynet.newservice("debug_console", 8081)
-- 登陆服务
local login = skynet.newservice("login")
skynet.call(login, "lua", "start", {
port = 8080,
maxclient = 1000,
nodelay = true,
})
-- base_app_mgr
skynet.uniqueservice("base_app_mgr")
skynet.call("base_app_mgr", "lua", "start")
-- area_mgr
skynet.uniqueservice("area_mgr")
skynet.call("area_mgr", "lua", "start")
-- room_mgr
skynet.uniqueservice("room_mgr")
skynet.exit()
end
skynet.start(main)
|
local HttpService = game:GetService("HttpService")
local Action = require(script.Parent.Action)
return Action("BrushObjectNew", function(rbxObject, guid)
if not guid then
guid = HttpService:GenerateGUID()
end
assert(rbxObject.Archivable)
return {
guid = guid,
rbxObject = rbxObject:Clone()
}
end) |
Tremualin.Configuration.RandomBreakthroughChoices = 4
local configuration = Tremualin.Configuration
local function GetRandomUnregisteredBreakthroughs(first_breakthrough)
local colony = UIColony
local choices = configuration.RandomBreakthroughChoices
local unregistered_breakthroughs = colony:GetUnregisteredBreakthroughs()
local random_breakthroughts = {}
if first_breakthrough and not colony:IsTechDiscovered(first_breakthrough.id) and colony:TechAvailableCondition(first_breakthrough) then
table.insert(random_breakthroughts, first_breakthrough)
for i = 1, #unregistered_breakthroughs do
if unregistered_breakthroughs[i] == first_breakthrough.id then
table.remove(unregistered_breakthroughs, i)
choices = choices - 1
break
end
end
end
StableShuffle(unregistered_breakthroughs, AsyncRand, 100)
for i = 1, choices do
table.insert(random_breakthroughts, TechDef[unregistered_breakthroughs[i]])
end
return random_breakthroughts
end
local function ShowCherryPickingPopup(first_breakthrough, map_id, notification_type, research_instead_of_discover)
local colony = UIColony
local unregistered_breakthroughs = colony:GetUnregisteredBreakthroughs()
if #unregistered_breakthroughs > 0 then
CreateRealTimeThread(function()
local params = {
id = GetUUID(),
title = Untranslated("Available Breakthroughs"),
text = Untranslated("Our scientists believe that the recent findings will reveal never before seen technologies. But the experts can't agree on which path to pursue. Would you kindly help them choose a possible practical application of the discovery?"),
minimized_notification_priority = "CriticalBlue",
image = "UI/Messages/Events/03_discussion.tga",
start_minimized = false,
dismissable = false
}
local choices = {}
local random_breakthroughts = GetRandomUnregisteredBreakthroughs(first_breakthrough)
for i, breakthrought in ipairs(random_breakthroughts) do
choices[i] = breakthrought
params["choice" .. i] = breakthrought.display_name
end
if #random_breakthroughts > 0 then
local choice = choices[WaitPopupNotification(false, params)]
-- Is the chosen tech is already choice we had a bit of a race condition; try again
if colony:IsTechResearched(choice.id) then
ShowCherryPickingPopup(first_breakthrough, map_id, notification_type, research_instead_of_discover)
return
end
-- Omega telescope will research instead of discover
if research_instead_of_discover then colony:SetTechResearched(choice.id) else colony:SetTechDiscovered(choice.id) end
if map_id then
AddOnScreenNotification(notification_type, OpenResearchDialog, {
name = choice.display_name,
context = choice,
rollover_title = choice.display_name,
rollover_text = choice.description
}, nil, map_id)
else
AddOnScreenNotification(notification_type, OpenResearchDialog, {
name = choice.display_name,
context = choice,
rollover_title = choice.display_name,
rollover_text = choice.description
})
end
end
end) -- CreateRealTimeThread
return true
else
return false
end
end
local orig_SubsurfaceAnomaly_ScanCompleted = SubsurfaceAnomaly.ScanCompleted
function SubsurfaceAnomaly:ScanCompleted(scanner, ...)
local research = scanner and scanner.city and scanner.city.colony or UIColony
local tech_action = self.tech_action
local map_id = self:GetMapID()
if tech_action == "breakthrough" then
local first_breakthrough = TechDef[self.breakthrough_tech]
if ShowCherryPickingPopup(first_breakthrough, map_id, "BreakthroughDiscovered") then
-- proceeds with the original method but doesn't unlock anything extra
self.tech_action = "none"
else
-- if no breakthroughs are found, unlock new technologies
self.tech_action = "unlock"
end
end
return orig_SubsurfaceAnomaly_ScanCompleted(self, scanner, ...)
end
local orig_PlanetaryAnomaly_Scan = PlanetaryAnomaly.Scan
function PlanetaryAnomaly:Scan(rocket)
local reward = self.reward
if reward == "breakthrough" then
local first_breakthrough = TechDef[self.breakthrough_tech]
if ShowCherryPickingPopup(first_breakthrough, nil, "PlanetaryAnomaly_BreakthroughDiscovered") then
self.reward = false
else
self.reward = "tech unlock"
end
end
orig_PlanetaryAnomaly_Scan(self, rocket)
end
function OmegaTelescope:UnlockBreakthroughs(count)
CreateGameTimeThread(function()
local unlocked = 0
while count > unlocked do
ShowCherryPickingPopup(nil, nil, "BreakthroughDiscovered", true)
unlocked = unlocked + 1
Sleep(100)
end
end)
end
|
local j1 = mk_assumption_justification(1)
local j2 = mk_assumption_justification(2)
assert(is_justification(j1))
assert(j1:depends_on(j1))
assert(not j1:depends_on(j2))
for c in j1:children() do
assert(false)
end
assert(not j2:has_children())
print(j1)
assert(not j1:get_main_expr())
|
--shameless copy-pasta of SkyLight's 3p8_time which was a copy-pasta of SkyLight's micro_gamecoob which was a copy-pasta of SkyLight's micro_item_salainen_radio which was a copy-pasta of SkyLight's micro_item_salainen_saha which was a copy-pasta of SkyLight's micro_item_salainen_kanto which was a copy-pasta of SkyLight's micro_item_salainen_puulle which was a copy-pasta of SkyLight's micro_item_salainen_kookospahkina_puu7 which was a copy-pasta of SkyLight's micro_item_salainen_kookospahkina_puu6 which was a copy-pasta of SkyLight's micro_item_salainen_kookospahkina_puu5 which was a copy-pasta of SkyLight's micro_item_salainen_kookospahkina_puu4 which was a copy-pasta of SkyLight's micro_item_salainen_kookospahkina_puu3 which was a copy-pasta of SkyLight's micro_item_salainen_kookospahkina_puu2 which was a copy-pasta of SkyLight's micro_item_salainen_kookospahkina_puu1 which was a copy-pasta of SkyLight's micro_item_salainen_kookospahkina_puu which was a copy-pasta of SkyLight's micro_item_secrete_hd which was a copy-pasta of SkyLight's micro_collectable_food which was a copy-pasta of SkyLight's micro_item_armorkit.lua which was a copy-pasta of Parakeet's micro_item_medkit.lua
--gottem
--gravity for spheres ay lamo
--3p8_planet
--I think the sphere will repulse you sometimes because the center of mass is not the origin... xD
AddCSLuaFile()
ENT.Type = "anim"
ENT.ItemName = "3P8 Homeworld"
ENT.ItemModel = "models/hunter/misc/sphere375x375.mdl"
function ENT:Initialize()
self:SetModel(self.ItemModel)
self:PhysicsInitStandard()
--self:PhysicsInit(SOLID_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
--stop movement
self:SetMoveType(MOVETYPE_VPHYSICS)
local phys = self:GetPhysicsObject()
if (phys:IsValid()) then
phys:EnableMotion(false)
end
self.meme = Vector(0,0,0)
--g = (6.674×10^−11 N(m/kg)2) --it's a constant, might need to make my own for gmod to make it dank, thanks wikipedia
self.g = 6.674/10^(11)
--m1 = player mass = ? PhysObj:GetMass() ? = 128 --because I said so, bitch
self.me = 128
--m2 = planet mass = ur mom = M⊕ = (5.9722±0.0006)×10^24 kg --wikipedia
self.meplanet = (5.9722)*10^(15)
--r = |(planet center - player center)|
self.raddude = 1
--F = g(m1)(m2)/r^2 = the magnitude of the vector I want to set the player's velocity to
self.mag = 0
self.delta = Vector(0,0,0)
self.vect = Vector(0,0,0)
--print("initialized planet")
end
if SERVER then
function ENT:Think()
--set ply velocity based on newtonian physics F = -g(m1)(m2)/r^2
--F = g(m1)(m2)/r^2 = the magnitude of the vector I want to set the player's velocity to
--self.mag = self.g*self.me*self.meplanet/(self.raddude^2)
--local dank = ents.GetAll()
for i,ent in pairs(ents.GetAll()) do
local phys = ent:GetPhysicsObject()
if ( IsValid( phys ) ) then -- Always check with IsValid! The ent might not have physics!
self.me = phys:GetMass()
self.raddude = math.abs(self.meme:Distance(phys:GetPos()))
self.mag = self.g*self.me*self.meplanet/(self.raddude^2)
self.meme = phys:LocalToWorld( phys:GetMassCenter() )
--largest number should be 1, smallest should be -1?
--divide by |largest| number :P
self.delta = (phys:GetPos() - self.meme)
if self.delta != Vector(0,0,0) then --ignores itself
if math.abs(self.delta.x) > math.abs(self.delta.y) && math.abs(self.delta.x) > math.abs(self.delta.z) then
self.vect = self.delta / self.delta.x
elseif math.abs(self.delta.y) > math.abs(self.delta.x) && math.abs(self.delta.y) > math.abs(self.delta.z) then
self.vect = self.delta / self.delta.y
elseif math.abs(self.delta.z) > math.abs(self.delta.y) && math.abs(self.delta.z) > math.abs(self.delta.x) then
self.vect = self.delta / self.delta.z
else
print("ERROR: 3p8_planet resultant gravity vector... non-existant?")
print(self.vect.x ..", ".. self.vect.y ..", ".. self.vect.z .. " vect " .. self.delta.x ..", ".. self.delta.y ..", ".. self.delta.z .. " delta")
end
--print(dank[1].ClassName .. " ************************************************")
print(self.vect.x ..", ".. self.vect.y ..", ".. self.vect.z .. " vect " .. self.delta.x ..", ".. self.delta.y ..", ".. self.delta.z .. " delta")
ent:SetVelocity(self.mag*self.vect) --has to be a vector, not a number...
end
end
end
--set player angle (rotate them like we in portal)
--get the normal relative to the center of the planet and the player
--ply:SetAngle()
--nahmeen?
--print("ply: "..self.ply.." mag: "..self.mag.." velo: "..self.meme.." angel: "..self.meme)
end
end |
hook.Add( "OnPlayerChat", "YouTubeMSG", function( ply, text, team, dead )
if ply ~= LocalPlayer() then return end
if string.sub( text, 1, 8 ) == "/playnow" then
local frame = vgui.Create( "DFrame" )
frame:SetTitle( "YouTube" )
frame:SetSize( ScrW() * 0.75, ScrH() * 0.75 )
frame:Center()
frame:MakePopup()
local html = vgui.Create( "HTML", frame )
html:Dock( FILL )
html:OpenURL( string.sub( text, 10 ) )
return true
end
end )
|
-- Variables
g_Me = getLocalPlayer()
g_Resource = getThisResource()
g_Root = getRootElement()
g_ResourceRoot = getResourceRootElement(g_Resource)
local screenX, screenY = guiGetScreenSize()
local g_Spawnpoints = {}
local g_Pickups = {}
local g_VisiblePickups = {}
local g_DeathListRec = {}
local deathListPositions = 10
local plrDeathListPos = -1
local deathListAdded = false
local g_PrevVehicleHeight = nil
local pickupAngle = 0
local survivorDynY = 0
local wonCamZ = 0
local wonPosX = 0
local wonPosY = 0
local wonPosZ = 0
local wonCY = 0
local wonName = nil
local cdTimer = nil
local heliTimer = nil
local countState = nil
local countTXT = nil
local endTime = 0
local startTime = 0
local lastTick = 0
local cImageGO = dxCreateTexture("images/count_go.png")
local cImage1 = dxCreateTexture("images/count_1.png")
local cImage2 = dxCreateTexture("images/count_2.png")
local cImage3 = dxCreateTexture("images/count_3.png")
local imgSurvivor = dxCreateTexture("images/last_survivor.png")
local cMapName = "None"
local nextMapName = "Random"
countImages = {
[0] = cImageGO,
[1] = cImage1,
[2] = cImage2,
[3] = cImage3
}
local g_WaterCraftIDs = table.create({ 539, 460, 417, 447, 472, 473, 493, 595, 484, 430, 453, 452, 446, 454 }, true)
addEventHandler("onClientFilesAreAllDownloaded",g_ResourceRoot,
function ()
setBlurLevel(0)
g_ModelForPickupType = { nitro = 2221, repair = 2222, vehiclechange = 2223 }
engineImportTXD(engineLoadTXD('models/nitro.txd'), 2221)
engineReplaceModel(engineLoadDFF('models/nitro.dff', 2221), 2221)
engineSetModelLODDistance(2221, 60 )
engineImportTXD(engineLoadTXD('models/repair.txd'), 2222)
engineReplaceModel(engineLoadDFF('models/repair.dff', 2222), 2222)
engineSetModelLODDistance(2222, 60 )
engineImportTXD(engineLoadTXD('models/vehiclechange.txd'), 2223)
engineReplaceModel(engineLoadDFF('models/vehiclechange.dff', 2223), 2223)
engineSetModelLODDistance(2223, 60 )
setCameraClip ( true, false )
setPedCanBeKnockedOffBike(localPlayer, false)
exports.BB_Rooms:loadRoomMap(localPlayer,getElementData(localPlayer,"bb.room"))
end
)
addEvent("onMapElement",true)
addEventHandler("onMapElement",g_Root,
function (name,element)
if(name == "spawnpoint") then
table.insert(g_Spawnpoints,{
vehicle = (element.vehicle or 0),
posX = (element.posX or 0.0),
posY = (element.posY or 0.0),
posZ = (element.posZ or 0.0),
rotX = (element.rotX or 0.0),
rotY = (element.rotY or 0.0),
rotZ = (element.rotZ or 0.0)
})
end
if(name == "racepickup") then
pType = (element.type or "nitro")
vehicle = (element.vehicle or 0)
posX = (element.posX or 0.0)
posY = (element.posY or 0.0)
posZ = (element.posZ or 0.0)
respawn = (element.respawn or 0)
if(pType == "nitro") then
racePickup = createObject(2221,posX,posY,posZ)
end
if(pType == "repair") then
racePickup = createObject(2222,posX,posY,posZ)
end
if(pType == "vehiclechange") then
racePickup = createObject(2223,posX,posY,posZ)
end
setElementCollisionsEnabled(racePickup, false)
setElementDimension(racePickup,getElementData(localPlayer,"bb.room"))
colShape = createColSphere(posX,posY,posZ, 3.5)
table.insert(g_Pickups,{
pType = pType,
vehicle = vehicle,
element = racePickup,
colshape = colShape,
respawn = respawn
})
end
end
)
addEvent("setCurrentMatrix",true)
addEventHandler("setCurrentMatrix",g_Root,
function()
local x,y,z,camX,camY,camZ = getCameraMatrix()
setCameraMatrix(x,y,z,camX,camY,camZ)
setElementDimension(localPlayer,getElementData(localPlayer,"bb.room"))
end
)
addEventHandler('onClientElementStreamIn', g_Root,
function()
for _,v in ipairs(g_Pickups) do
if(v.element == source) then
table.insert(g_VisiblePickups,{ element = v.element, vehicle = v.vehicle, pType = v.pType })
break
end
end
end
)
addEventHandler('onClientElementStreamOut', g_Root,
function()
for i,v in ipairs(g_VisiblePickups) do
if(v.element == source) then
table.remove(g_VisiblePickups,i)
break
end
end
end
)
function checkWater()
if(getElementData(localPlayer,"state") ~= "alive") then return end
if isPedInVehicle(localPlayer) then
if g_WaterCraftIDs[getElementModel(getPedOccupiedVehicle(localPlayer))] then
return
end
local x, y, z = getElementPosition(localPlayer)
local waterZ = getWaterLevel(x, y, z)
if waterZ and z < waterZ - 0.5 then
triggerServerEvent("onKillPlayer",localPlayer)
end
end
end
setTimer(checkWater,1000,0)
function performSuicide(player)
if not isPedInVehicle(localPlayer) then return end
if not isElementFrozen(getPedOccupiedVehicle(localPlayer)) then
triggerServerEvent("onKillPlayer",localPlayer)
end
end
addCommandHandler("kill",performSuicide)
bindKey(next(getBoundKeys"enter_exit"), "down", "kill")
function spectatePrevious()
if (getElementData(localPlayer,"state") ~= "spectating") then return end
triggerServerEvent("onSpectatePrevious",localPlayer)
end
addCommandHandler("spectate previous",spectatePrevious)
function spectateNext()
if (getElementData(localPlayer,"state") ~= "spectating") then return end
triggerServerEvent("onSpectateNext",localPlayer)
end
addCommandHandler("spectate next",spectateNext)
bindKey("arrow_l", "down", "spectate previous")
bindKey("arrow_r", "down", "spectate next")
function renderTimeLeft()
local roomState = getElementData(getElementByID("room_"..tostring(getElementData(localPlayer,"bb.room"))),"room.state")
if(roomState ~= "playing") then
return
end
dxDrawImage(((screenX/2)-(conv(150)/2)), 0, conv(150), conv(50), 'images/timeleft.png', 0, 0, 0)
local distLeft = endTime-(getTickCount())
if(distLeft < 0) then
distLeft = 0
local length = dxGetTextWidth("Time is up!",conv(2),"default-bold")
local height = dxGetFontHeight(conv(2),"default-bold")
dxDrawText("Time is up!", ((screenX/2)-(length/2)), ((screenY-conv((230))+conv(75))-(height/2)), (((screenX/2)-(length/2))+50), screenY-conv(150), tocolor(255,0,0,255), conv(2), "default-bold" )
local x,y,z,camX,camY,camZ = getCameraMatrix()
setCameraMatrix(x,y,z,camX,camY,camZ)
else
if(distLeft < 10000) then
local length = dxGetTextWidth("Hurry up!!!",conv(2),"default-bold")
local height = dxGetFontHeight(conv(2),"default-bold")
dxDrawText("Hurry up!!!", ((screenX/2)-(length/2)), ((screenY-conv((230))+conv(75))-(height/2)), (((screenX/2)-(length/2))+50), screenY-conv(150), tocolor(255,0,0,255), conv(2), "default-bold" )
end
end
local timeLeft = formatTime(distLeft)
local timePlayed = 0
if(lastTick ~= 0) then
if(getElementData(localPlayer,"state") == "alive" and distLeft > 0) then
lastTick = getTickCount()
end
timePlayed = formatTime((lastTick-startTime))
else
timePlayed = formatTime(0)
end
local width = dxGetTextWidth(timeLeft,conv(0.9),"default-bold")
dxDrawText(timeLeft, ((screenX/2)-conv(35)-conv(width/2)), conv(27), 0, 0, tocolor(255,255,255,200), conv(0.9), "default-bold","left","top",false,false,false,true)
local width = dxGetTextWidth(timePlayed,conv(0.9),"default-bold")
dxDrawText(timePlayed, ((screenX/2)+conv(35)-conv(width/2)), conv(27), 0, 0, tocolor(255,255,255,200), conv(0.9), "default-bold","left","top",false,false,false,true)
end
addEventHandler("onClientRender",g_Root,renderTimeLeft)
function renderStats()
local state = getElementData(localPlayer,"state")
if(state == "alive" or state == "spectating") then
local roomState = getElementData(getElementByID("room_"..tostring(getElementData(localPlayer,"bb.room"))),"room.state")
if(roomState == "loading" or roomState == "unloading" or roomState == "winning") then
return
end
if(getElementData(localPlayer,"UAG.MenuShown") == true) then
return
end
dxDrawText("FPS:",conv(10), screenY-conv(65), conv(50), screenY-conv(20), tocolor(27,161,226,200), conv(1.2), "default-bold")
dxDrawText(getElementData(localPlayer,"fps"),conv(50), screenY-conv(64), conv(50), screenY-conv(20), tocolor(255,255,255,200), conv(1.1), "default")
dxDrawText("Next Map:",conv(10), screenY-conv(45), conv(50), screenY-conv(20), tocolor(27,161,226,200), conv(1.2), "default-bold")
dxDrawText(nextMapName,conv(90), screenY-conv(44), conv(50), screenY-conv(20), tocolor(255,255,255,200), conv(1.1), "default")
dxDrawText("Map:",conv(10), screenY-conv(25), conv(50), screenY-conv(20), tocolor(27,161,226,200), conv(1.2), "default-bold")
dxDrawText(cMapName,conv(50), screenY-conv(24), conv(50), screenY-conv(20), tocolor(255,255,255,200), conv(1.1), "default")
end
end
addEventHandler('onClientRender', g_Root, renderStats)
addEvent("updateDeathList",true)
addEventHandler("updateDeathList",g_Root,
function(deathlist)
local cCount = 1
table.sort(deathlist, function(a,b) return a.pos<b.pos end)
for _,v in ipairs(deathlist) do
if(cCount >= deathListPositions) then break end
if(#g_DeathListRec <= deathListPositions) then
if(cCount == 1 and #g_DeathListRec >= 1) then
g_DeathListRec[1].pos = v.pos
g_DeathListRec[1].player = v.player
g_DeathListRec[1].name = v.name
g_DeathListRec[1].recX = 0
elseif(cCount == 1 and #g_DeathListRec == 0) then
table.insert(g_DeathListRec,cCount,{pos=v.pos,player=v.player,name=v.name,recX=0})
elseif(cCount > 1 and cCount <= #g_DeathListRec) then
g_DeathListRec[cCount].pos = v.pos
g_DeathListRec[cCount].player = v.player
g_DeathListRec[cCount].name = v.name
elseif(cCount > #g_DeathListRec) then
table.insert(g_DeathListRec,cCount,{pos=v.pos,player=v.player,name=v.name,recX=150})
end
else
if(cCount < deathListPositions) then
g_DeathListRec[cCount].pos = g_DeathListRec[cCount+1].pos
g_DeathListRec[cCount].player = g_DeathListRec[cCount+1].player
g_DeathListRec[cCount].name = g_DeathListRec[cCount+1].name
else
g_DeathListRec[cCount].pos = v.pos
g_DeathListRec[cCount].player = v.player
g_DeathListRec[cCount].name = v.name
end
end
if(v.player == localPlayer) then
plrDeathListPos = v.pos
deathListAdded = true
end
cCount = cCount + 1
end
end
)
function renderDeathlist()
if(#g_DeathListRec == 0) then return end
local roomState = getElementData(getElementByID("room_"..tostring(getElementData(localPlayer,"bb.room"))),"room.state")
if(roomState == "loading" or roomState == "unloading") then
return
end
if(getElementData(localPlayer,"UAG.MenuShown") == true) then
return
end
local recPos = conv(15)+(conv(30)*(deathListPositions/2))
local fontHeight = dxGetFontHeight(conv(1.2),"default-bold")
local plrFound = false
for _,v in ipairs(g_DeathListRec) do
local camTarget = getCameraTarget()
if(camTarget == false) then
r,g,b = 0,0,0
alpha = 100
elseif(getVehicleOccupant(camTarget) == false) then
r,g,b = 0,0,0
alpha = 100
elseif(getVehicleOccupant(camTarget) == getElementData(v.player,"spectating")) then
r,g,b = 27,161,226
alpha = 40
else
r,g,b = 0,0,0
alpha = 100
end
if(v.player == localPlayer) then
dxDrawRectangle((screenX-v.recX), ((screenY/2)-recPos), conv(200), conv(30), tocolor(0,0,0,200))
plrFound = true
else
dxDrawRectangle((screenX-v.recX), ((screenY/2)-recPos), conv(200), conv(30), tocolor(r,g,b,alpha))
end
dxDrawText(v.pos..". "..v.name,(screenX-(v.recX-conv(10))), ((((screenY/2)-recPos)+conv(15))-(fontHeight/2)), conv(200), conv(30), tocolor(255,255,255,150), conv(1.2), "default-bold","left","top",false,false,false,true)
recPos = recPos - conv(30)
if(v.recX < conv(200)) then
v.recX = v.recX + conv(2)
end
if(v.recX > conv(200)) then
v.recX = conv(200)
end
end
if((getElementData(localPlayer,"state") ~= "alive") and (plrFound == false) and (deathListAdded == true)) then
dxDrawRectangle((screenX-conv(200)), ((screenY/2)+conv(105)), conv(200), conv(30), tocolor(0,0,0,200))
dxDrawText(plrDeathListPos..". "..getPlayerName(localPlayer),(screenX-(conv(190))), ((((screenY/2)+conv(135))-conv(15))-(fontHeight/2)), conv(200), conv(30), tocolor(255,255,255,150), conv(1.2), "default-bold","left","top",false,false,false,true)
end
end
addEventHandler('onClientRender', g_Root, renderDeathlist)
function updatePickups()
local cx, cy, cz = getCameraMatrix()
for i,v in ipairs(g_VisiblePickups) do
if (v.pType == "vehiclechange") then
local x,y,z = getElementPosition(v.element)
local distance = getDistanceBetweenPoints3D(cx,cy,cz,x,y,z)
if distance < 60 then
local sx,sy = getScreenFromWorldPosition (x,y,z+1,0.08)
if sx then
if isLineOfSightClear(cx,cy,cz,x,y,z,true, false, false, true, false) then
local scale = (60/distance)*0.5
dxDrawText(getVehicleNameFromModel(v.vehicle), sx, sy, sx, sy, tocolor(27,161,226,200), (scale/3.5), "bankgothic", "center", "bottom", false, false, false )
end
end
end
end
setElementRotation(v.element,0,0,pickupAngle)
end
if((pickupAngle + 5) > 360) then
pickupAngle = 0
else
pickupAngle = pickupAngle + 5
end
end
addEventHandler('onClientRender', g_Root, updatePickups)
function renderLastSurvivor()
if(survivorDynY < conv(200)) then
survivorDynY = survivorDynY + 2
if(survivorDynY > conv(200)) then
survivorDynY = conv(200)
end
end
dxDrawImage((screenX-(conv(200))), survivorDynY-conv(240), conv(240), conv(240), imgSurvivor, 0)
end
addEvent("onWonScreen",true)
addEventHandler("onWonScreen",g_Root,
function(plrName,camX,camY,camZ)
removeEventHandler('onClientRender', g_Root, renderLastSurvivor)
setCameraMatrix(camX+20,camY,camZ+100,camX,camY,camZ)
wonPosX = tonumber(camX)
wonPosY = tonumber(camY)
wonPosZ = tonumber(camZ)
wonCamZ = tonumber(camZ+100)
wonName = plrName
wonCY = conv(200)
setTimer(function()
fadeCamera(true)
removeEventHandler('onClientRender', g_Root, moveWonCamera)
addEventHandler('onClientRender', g_Root, moveWonCamera)
end,1000,1)
end
)
function moveWonCamera()
local roomState = getElementData(getElementByID("room_"..tostring(getElementData(localPlayer,"bb.room"))),"room.state")
if(roomState == "loading" or roomState == "unloading") then
return
end
if(getElementData(getElementByID("room_"..tostring(getElementData(localPlayer,"bb.room"))),"room.state") ~= "winning") then
return
end
if(wonCamZ > wonPosZ) then
wonCamZ = wonCamZ - 1
end
if(wonCY > 0) then
wonCY = wonCY - 2
end
if(wonCY < 0) then
wonCY = 0
end
setCameraMatrix(wonPosX+10,wonPosY,wonPosZ+((wonCamZ-wonPosZ)+3),wonPosX,wonPosY,wonPosZ)
if(getElementData(localPlayer,"UAG.MenuShown") == true) then
return
end
dxDrawRectangle(0,((screenY-conv(200))+wonCY),screenX,conv(200),tocolor(0,0,0,150))
local height = dxGetFontHeight(conv(5),"default-bold")
local width = dxGetTextWidth(removeColorCoding(wonName),conv(5),"default-bold")
dxDrawText(wonName, ((screenX/2)-(width/2)),(((screenY-conv(125))-(height/2))+wonCY), ((screenX/2)-(width/2)),((screenY-conv(125))-(height/2)), tocolor(255,255,255,255), conv(5), "default-bold","left","top",false,false,false,true)
local height = dxGetFontHeight(conv(3),"default-bold")
local width = dxGetTextWidth("Won the map!",conv(3),"default-bold")
dxDrawText("Won the map!", ((screenX/2)-(width/2)),(((screenY-conv(50))-(height/2))+wonCY), ((screenX/2)-(width/2)),((screenY-conv(50))-(height/2)), tocolor(255,255,255,255), conv(3), "default-bold","left","top",false,false,false,true)
end
addEvent("onLastSurvivor",true)
addEventHandler("onLastSurvivor",g_Root,
function()
survivorDynY = 0
addEventHandler('onClientRender', g_Root, renderLastSurvivor)
end
)
addEvent("onMapIsLoaded",true)
addEventHandler("onMapIsLoaded",g_Root,
function ()
removeEventHandler('onClientRender', g_Root, moveWonCamera)
setCameraTarget(localPlayer,localPlayer)
local pID = getElementData(localPlayer,"UAG.pIDroom")
setCloudsEnabled(false)
startTime = 0
endTime = 0
if(pID <= #g_Spawnpoints) then
spawnClientOnPoint(pID)
elseif(pID <= (#g_Spawnpoints*2)) then
spawnClientOnPoint(pID-#g_Spawnpoints)
else
local pPos = math.random(1,#g_Spawnpoints)
spawnClientOnPoint(pPos)
end
g_DeathListRec = {}
deathListAdded = false
heliTimer = setTimer(checkHelicopter,500,0)
end
)
addEvent("setGhostMode",true)
addEventHandler("setGhostMode",g_Root,
function (aliveTable,ghostmode)
if(ghostmode) then
state = false
else
state = true
end
for i,plr in ipairs(aliveTable) do
for i,veh in ipairs(getElementsByType("vehicle")) do
setElementCollidableWith(getPedOccupiedVehicle(plr), veh, state)
setElementCollidableWith(veh, getPedOccupiedVehicle(plr), state)
end
end
end
)
addEvent("onMapStopping",true)
addEventHandler("onMapStopping",g_Root,
function ()
removeEventHandler('onClientRender', g_Root, moveWonCamera)
for _,v in ipairs(g_Pickups) do
destroyElement(v.element)
end
removeEventHandler('onClientRender', g_Root, renderLastSurvivor)
triggerServerEvent("destroyPlayerVehicle",localPlayer)
g_Pickups = {}
g_Spawnpoints = {}
g_VisiblePickups = {}
g_DeathListRec = {}
deathListAdded = false
if(isTimer(cdTimer)) then killTimer(cdTimer) end
if(isTimer(heliTimer)) then killTimer(heliTimer) end
end
)
addEvent("setCurrentMap",true)
addEventHandler("setCurrentMap",getRootElement(),
function (mapname)
cMapName = mapname
end
)
addEvent("setNextMap",true)
addEventHandler("setNextMap",getRootElement(),
function (mapname)
nextMapName = mapname
end
)
function vehicleEnter()
local plrVehicle = getPedOccupiedVehicle(localPlayer)
if(source == localPlayer) then
setCameraBehindVehicle(plrVehicle)
end
end
addEventHandler("onClientPlayerVehicleEnter",getRootElement(),vehicleEnter)
function doCountdown(count)
if(count == 1) then
local tickCount = getTickCount()
endTime = (tickCount+600000)
startTime = tickCount
lastTick = tickCount
end
if(count >= 1) then
cdTimer = setTimer(doCountdown,1000,1,(count-1))
if(count == 3) then
exports.BB_Maps:closeLoader()
addEventHandler("onClientRender",getRootElement(),renderCount)
end
playSound("audio/count_"..count..".mp3",false)
countState = count
else
countState = 0
setTimer(function()
removeEventHandler("onClientRender",getRootElement(),renderCount)
end,1000,1)
local goSound = playSound("audio/count_go.mp3",false)
setSoundVolume(goSound,60)
cdTimer = nil
end
end
addEvent("doCountdown",true)
addEventHandler("doCountdown",g_Root,doCountdown)
function doSetTimeLeft(dif)
endTime = getTickCount() + dif
end
addEvent("setTimeLeft",true)
addEventHandler("setTimeLeft",g_Root,doSetTimeLeft)
function renderCount()
if(getElementData(getElementByID("room_"..tostring(getElementData(localPlayer,"bb.room"))),"room.state") ~= "countdown") then
return
end
dxDrawImage(((screenX/2)-(conv(270)/2)), ((screenY/2)-(conv(300)/2)), conv(300), conv(300), countImages[countState], 0)
end
addEventHandler("onClientColShapeHit", g_Root,
function (player, matchingDimension)
if(player == localPlayer) then
for _,v in ipairs(g_Pickups) do
if(v.colshape == source) then
g_PrevVehicleHeight = getElementDistanceFromCentreOfMassToBaseOfModel(getPedOccupiedVehicle(localPlayer))
triggerServerEvent("onRacePickupTrigger",localPlayer,v)
break
end
end
end
end
)
addEvent("alignVehicleWithUp",true)
addEventHandler("alignVehicleWithUp",g_Root,
function ()
local vehicle = getPedOccupiedVehicle(localPlayer)
if not vehicle then return end
local matrix = getElementMatrix(vehicle)
local Right = Vector3D:new(matrix[1][1], matrix[1][2], matrix[1][3])
local Fwd = Vector3D:new(matrix[2][1], matrix[2][2], matrix[2][3])
local Up = Vector3D:new(matrix[3][1], matrix[3][2], matrix[3][3])
local Velocity = Vector3D:new( getElementVelocity( vehicle ) )
local rz
if Velocity:Length() > 0.05 and Up.z < 0.001 then
rz = directionToRotation2D( Velocity.x, Velocity.y)
else
rz = directionToRotation2D(Fwd.x, Fwd.y)
end
setElementRotation(vehicle, 0, 0, rz)
local newVehicleHeight = getElementDistanceFromCentreOfMassToBaseOfModel(vehicle)
local x, y, z = getElementPosition(vehicle)
if g_PrevVehicleHeight and newVehicleHeight > g_PrevVehicleHeight then
z = z - g_PrevVehicleHeight + newVehicleHeight
end
if changez then
z = z + 1
end
setElementPosition(vehicle, x, y, z)
g_PrevVehicleHeight = nil
checkHelicopter()
end
)
function checkHelicopter()
local vehicle = getPedOccupiedVehicle(localPlayer)
if not isPedInVehicle(localPlayer) then return end
local vehID = getElementModel(vehicle)
if vehID == 417 or vehID == 425 or vehID == 447 or vehID == 465 or vehID == 469 or vehID == 487 or vehID == 488 or vehID == 497 or vehID == 501 or vehID == 548 or vehID == 563 then
setHelicopterRotorSpeed (vehicle, 0.2)
end
end
function spawnClientOnPoint(pos)
triggerServerEvent("onMapSpawn",localPlayer,g_Spawnpoints[pos])
end |
-- huangxin <[email protected]>
local db = KEYS[1];
local client_ip = KEYS[2];
--
redis.call('SELECT', db);
--
return 'OK';
|
function draw()
imgui.Begin("BatchRemove")
state.IsWindowHovered = imgui.IsWindowHovered()
if imgui.Button("Remove") then
actions.RemoveHitObjectBatch(state.SelectedHitObjects)
end
imgui.End()
end
|
local AddonName, AddonTable = ...
-- Auchenai Crypts
AddonTable.crypts = {
-- Shirrak the Dead Watcher
27846,
25964,
27410,
27408,
27409,
27866,
27847,
27865,
27493,
27845,
26055,
-- Exarch Maladaar
27412,
27872,
27415,
27414,
27871,
29354,
29257,
29244,
27870,
27867,
27411,
27523,
27413,
27869,
27416,
-- Quest Rewards
29341,
}
|
-- manages trades
-- author: Polymorphic
local module = {}
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local HttpService = game:GetService("HttpService")
local network
local configuration
local itemLookup = require(ReplicatedStorage.itemData)
--[[
playerTradeSessionData {}
instance player
string state
int gold
{inventoryTransferData} inventoryTransferDataCollection
tradeSessionData {}
string guid
string state
playerTradeSessionData playerTradeSessionData_player1
playerTradeSessionData playerTradeSessionData_player2
--]]
-- contains tradeSessionData
local tradeSessionDataCollection = {}
local pendingTrade_guids = {}
-- if IFFIsActiveTrade is set, the trade must be ongoing to return the sessionData
local function getTradeSessionDataByPlayer(player)
for i, tradeSessionData in pairs(tradeSessionDataCollection) do
if tradeSessionData.playerTradeSessionData_player1.player == player or tradeSessionData.playerTradeSessionData_player2.player == player then
return tradeSessionData
end
end
return nil
end
local function propogateTradeDataUpdate(tradeSessionData)
network:fireClient("signal_tradeSessionChanged", tradeSessionData.playerTradeSessionData_player1.player, tradeSessionData)
network:fireClient("signal_tradeSessionChanged", tradeSessionData.playerTradeSessionData_player2.player, tradeSessionData)
end
local function invalidatePendingTradesForPlayer(player)
for i, v in pairs(pendingTrade_guids) do
if v.playerToTradeWith == player or v.tradeRequester == player then
pendingTrade_guids[i] = nil
end
end
end
local invitationCD = {}
local function playerRequest_requestTrade(tradeRequester, playerToTradeWith)
if not configuration.getConfigurationValue("isTradingEnabled", tradeRequester) or not configuration.getConfigurationValue("isTradingEnabled", playerToTradeWith) then
return false, "Trading is disabled right now."
end
if tradeRequester:FindFirstChild("DataSaveFailed") then
network:fireClient("alertPlayerNotification", tradeRequester, {text = "Cannot trade during DataStore outage."; textColor3 = Color3.fromRGB(255, 57, 60)})
return false, "This feature is temporarily disabled"
end
if tradeRequester and playerToTradeWith and tradeRequester ~= playerToTradeWith then
if not getTradeSessionDataByPlayer(tradeRequester) and not getTradeSessionDataByPlayer(playerToTradeWith) then
if not invitationCD[tradeRequester] or (tick() - invitationCD[tradeRequester] > 3) then
invitationCD[tradeRequester] = tick()
local guid = HttpService:GenerateGUID(false)
pendingTrade_guids[guid] = {
tradeRequester = tradeRequester;
playerToTradeWith = playerToTradeWith;
}
network:fireClient("signal_playerTradeRequest", playerToTradeWith, tradeRequester, guid)
return true
else
return false, "stop sending trades so fast."
end
end
elseif tradeRequester == playerToTradeWith then
return false, "you can't trade with yourself, idiot."
end
return false, "player is already trading"
end
-- playerInventoryChanged_server
local function isPlayerInventoryTransferDataValid(player, inventoryTransferDataCollection)
local playerData = network:invoke("getPlayerData", player)
local count = 0 do
for i, inventoryTransferData in pairs(inventoryTransferDataCollection) do
local itemBaseData = itemLookup[inventoryTransferData.id]
if itemBaseData.soulbound then
return false
end
if not inventoryTransferData.stacks then
inventoryTransferData.stacks = 1
end
if inventoryTransferData.stacks <= 0 then
return false
elseif math.floor(inventoryTransferData.stacks) ~= inventoryTransferData.stacks then
return false
end
count = count + 1
end
end
if playerData then
local matches = 0
local trueInventoryTransferDataCollection = {}
for i, inventorySlotData in pairs(playerData.inventory) do
for ii, inventoryTransferData in pairs(inventoryTransferDataCollection) do
if inventorySlotData.position == inventoryTransferData.position and inventorySlotData.id == inventoryTransferData.id and (inventoryTransferData.stacks or 1) <= (inventorySlotData.stacks or 1) then
if inventorySlotData.soulbound then
return false
end
trueInventoryTransferDataCollection[ii] = inventorySlotData
matches = matches + 1
break
end
end
end
return matches == count, trueInventoryTransferDataCollection
end
end
local function getTradeSessionDataById(tradeSessionId)
for i, tradeSessionData in pairs(tradeSessionDataCollection) do
if tradeSessionData.id == tradeSessionId then
return tradeSessionData
end
end
return nil
end
local function playerRequest_cancelTrade(player)
local tradeSessionData = getTradeSessionDataByPlayer(player)
if tradeSessionData then
tradeSessionData.state = "canceled"
tradeSessionData.playerTradeSessionData_player1.state = "denied"
tradeSessionData.playerTradeSessionData_player2.state = "denied"
propogateTradeDataUpdate(tradeSessionData)
for i, _tradeSessionData in pairs(tradeSessionDataCollection) do
if _tradeSessionData == tradeSessionData then
table.remove(tradeSessionDataCollection, i)
break
end
end
end
end
local processTicketDuplicationValidationQueue = {}
local function playerRequest_updatePlayerTradeSessionData(player, guid, key, value)
local tradeSessionData = getTradeSessionDataByPlayer(player)
if not tradeSessionData then return false, "no tradeSessionData found for player" end
if tradeSessionData.guid ~= guid then return false, "invalid guid for tradeSessionData" end
local p1 = tradeSessionData.playerTradeSessionData_player1.player
local p2 = tradeSessionData.playerTradeSessionData_player2.player
-- stop teleporting while trading
if p1.Parent == nil or p1:FindFirstChild("teleporting") or p1:FindFirstChild("DataLoaded") == nil then
return false, "invalid players"
end
-- stop teleporting while trading
if p2.Parent == nil or p2:FindFirstChild("teleporting") or p2:FindFirstChild("DataLoaded") == nil then
return false, "invalid players"
end
local playerData = network:invoke("getPlayerData", player)
if playerData and tradeSessionData and tradeSessionData.state ~= "completed" and tradeSessionData.state ~= "canceled" then
local playerTradeSessionData_player = (tradeSessionData.playerTradeSessionData_player1.player == player and tradeSessionData.playerTradeSessionData_player1) or (tradeSessionData.playerTradeSessionData_player2.player == player and tradeSessionData.playerTradeSessionData_player2)
if key == "state" and (value == "approved" or value == "denied" or value == "none") then
if value ~= playerTradeSessionData_player.state then
playerTradeSessionData_player.state = value
-- prevent players from spamming approve!
local processTicket = HttpService:GenerateGUID(false)
processTicketDuplicationValidationQueue[guid] = processTicket
if key == "state" and value == "denied" and tradeSessionData.state == "countdown" then
tradeSessionData.state = "active"
propogateTradeDataUpdate(tradeSessionData)
return true
end
if tradeSessionData.state ~= "countdown" and tradeSessionData.playerTradeSessionData_player1.state == "approved" and tradeSessionData.playerTradeSessionData_player2.state == "approved" then
tradeSessionData.state = "countdown"
propogateTradeDataUpdate(tradeSessionData)
local startTime = tick()
while (tick() - startTime) < 6 and (tradeSessionData.playerTradeSessionData_player1.state == "approved" and tradeSessionData.playerTradeSessionData_player2.state == "approved") do
wait(1 / 4)
end
-- stop teleporting while trading
if p1.Parent ~= game.Players or p1:FindFirstChild("teleporting") or p1:FindFirstChild("DataLoaded") == nil or not network:invoke("getPlayerData", p1) then
return false, "invalid players call 2"
end
-- stop teleporting while trading
if p2.Parent ~= game.Players or p2:FindFirstChild("teleporting") or p2:FindFirstChild("DataLoaded") == nil or not network:invoke("getPlayerData", p2) then
return false, "invalid players call 2"
end
if not isPlayerInventoryTransferDataValid(p1, tradeSessionData.playerTradeSessionData_player1.inventoryTransferDataCollection) then
return false, tostring(p1) .. " has invalid trade data"
end
if not isPlayerInventoryTransferDataValid(p2, tradeSessionData.playerTradeSessionData_player2.inventoryTransferDataCollection) then
return false, tostring(p2) .. " has invalid trade data"
end
if processTicketDuplicationValidationQueue[guid] == processTicket and (tradeSessionData.playerTradeSessionData_player1.state == "approved" and tradeSessionData.playerTradeSessionData_player2.state == "approved") then
local success, errMsg = network:invoke("requestTradeBetweenPlayers", tradeSessionData.playerTradeSessionData_player1.player, tradeSessionData.playerTradeSessionData_player1.inventoryTransferDataCollection, tradeSessionData.playerTradeSessionData_player1.gold, tradeSessionData.playerTradeSessionData_player2.player, tradeSessionData.playerTradeSessionData_player2.inventoryTransferDataCollection, tradeSessionData.playerTradeSessionData_player2.gold)
if success then
tradeSessionData.state = "completed"
propogateTradeDataUpdate(tradeSessionData)
else
playerRequest_cancelTrade(player)
end
-- empty the guid
processTicketDuplicationValidationQueue[guid] = nil
for i, v in pairs(tradeSessionDataCollection) do
if v.guid == guid then
table.remove(tradeSessionDataCollection, i)
end
end
return success, errMsg
end
else
tradeSessionData.state = "active"
propogateTradeDataUpdate(tradeSessionData)
end
return true
end
elseif key == "gold" and (type(value) == "number" and value >= 0) then
if playerData.gold >= value then
playerTradeSessionData_player.gold = value
tradeSessionData.playerTradeSessionData_player1.state = "none"
tradeSessionData.playerTradeSessionData_player2.state = "none"
tradeSessionData.state = "active"
propogateTradeDataUpdate(tradeSessionData)
return true
else
return false, "invalid gold"
end
elseif key == "inventoryTransferDataCollection" and (typeof(value) == "table") then
local playerInventoryTransferDataCollectionIsValid, trueInventoryTransferDataCollection = isPlayerInventoryTransferDataValid(player, value)
if playerInventoryTransferDataCollectionIsValid then
tradeSessionData.playerTradeSessionData_player1.state = "none"
tradeSessionData.playerTradeSessionData_player2.state = "none"
tradeSessionData.state = "active"
playerTradeSessionData_player.inventoryTransferDataCollection = trueInventoryTransferDataCollection
propogateTradeDataUpdate(tradeSessionData)
return true
else
return false, "invalid trade transfer data"
end
else
return false, "invalid key"
end
end
return false, "invalid"
end
local function playerRequest_acceptTradeRequest(player, guid)
if player:FindFirstChild("DataSaveFailed") then
network:fireClient("alertPlayerNotification", player, {text = "Cannot trade during DataStore outage."; textColor3 = Color3.fromRGB(255, 57, 60)})
return false, "This feature is temporarily disabled"
end
if pendingTrade_guids[guid] then
-- cancel all current trades involving player except for this trade.
local pendingTradeData = pendingTrade_guids[guid]
invalidatePendingTradesForPlayer(pendingTradeData.tradeRequester)
invalidatePendingTradesForPlayer(pendingTradeData.playerToTradeWith)
if not pendingTradeData.tradeRequester.Parent or not pendingTradeData.playerToTradeWith.Parent then return false end
--[[
playerTradeSessionData {}
instance player
string state
int gold
{inventoryTransferData} inventoryTransferDataCollection
tradeSessionData {}
string guid
string state
playerTradeSessionData playerTradeSessionData_player1
playerTradeSessionData playerTradeSessionData_player2
--]]
local tradeSessionData = {}
tradeSessionData.guid = guid
tradeSessionData.state = "active"
tradeSessionData.playerTradeSessionData_player1 = {}
tradeSessionData.playerTradeSessionData_player1.player = pendingTradeData.tradeRequester
tradeSessionData.playerTradeSessionData_player1.state = "pending"
tradeSessionData.playerTradeSessionData_player1.gold = 0
tradeSessionData.playerTradeSessionData_player1.inventoryTransferDataCollection = {}
tradeSessionData.playerTradeSessionData_player2 = {}
tradeSessionData.playerTradeSessionData_player2.player = pendingTradeData.playerToTradeWith
tradeSessionData.playerTradeSessionData_player2.state = "pending"
tradeSessionData.playerTradeSessionData_player2.gold = 0
tradeSessionData.playerTradeSessionData_player2.inventoryTransferDataCollection = {}
-- register this trade :]
table.insert(tradeSessionDataCollection, tradeSessionData)
propogateTradeDataUpdate(tradeSessionData)
return true
end
return false, "invalid or inactive guid"
end
local function onPlayerInventoryChanged_server(player)
local tradeSessionData = getTradeSessionDataByPlayer(player)
if tradeSessionData then
tradeSessionData.playerTradeSessionData_player1.state = "none"
tradeSessionData.playerTradeSessionData_player2.state = "none"
tradeSessionData.state = "active"
end
end
local function onPlayerRemoving(player)
invitationCD[player] = nil
end
function module.init(Modules)
network = Modules.network
configuration = Modules.configuration
game.Players.PlayerRemoving:connect(onPlayerRemoving)
network:create("playerRequest_cancelTrade", "RemoteFunction", "OnServerInvoke", playerRequest_cancelTrade)
network:create("playerRequest_requestTrade", "RemoteFunction", "OnServerInvoke", playerRequest_requestTrade)
network:create("playerRequest_acceptTradeRequest", "RemoteFunction", "OnServerInvoke", playerRequest_acceptTradeRequest)
network:create("playerRequest_updatePlayerTradeSessionData", "RemoteFunction", "OnServerInvoke", playerRequest_updatePlayerTradeSessionData)
network:create("signal_playerTradeRequest", "RemoteEvent")
network:create("signal_tradeSessionChanged", "RemoteEvent")
network:connect("playerInventoryChanged_server", "Event", onPlayerInventoryChanged_server)
end
return module |
--- === cp.apple.finalcutpro.cmd.CommandDetail ===
---
--- This class provides a UI for displaying the details of a command when it is selected on the `CommandList`.
local require = require
-- local log = require "hs.logger".new "CommandDetail"
local fn = require "cp.fn"
local ax = require "cp.fn.ax"
local Group = require "cp.ui.Group"
local StaticText = require "cp.ui.StaticText"
local ScrollArea = require "cp.ui.ScrollArea"
local TextArea = require "cp.ui.TextArea"
local chain = fn.chain
local matchesExactItems = fn.table.matchesExactItems
local CommandDetail = Group:subclass("cp.apple.finalcutpro.cmd.CommandDetail")
--- cp.apple.finalcutpro.cmd.CommandDetail.matches(element) -> boolean
--- Function
--- Checks if the element matches the criteria for this class.
---
--- Parameters:
--- * element - The element to check.
---
--- Returns:
--- * `true` if the element matches, `false` otherwise.
CommandDetail.static.matches = ax.matchesIf(
-- It's a Group
Group.matches,
-- ...with exactly one child
chain // ax.children >> matchesExactItems(
fn.all(
-- It's a Group
Group.matches,
-- ...containing exactly...
chain // ax.childrenTopDown >> matchesExactItems(
-- ... a StaticText...
StaticText.matches,
-- ... and a ScrollArea...
ScrollArea.matches
)
)
)
)
-- cp.apple.finalcutpro.cmd.CommandDetail._contentGroupUI <cp.prop: axuielement>
-- Field
-- The [axuielement](cp.prop.axuielement) for the content Group.
function CommandDetail.lazy.prop:_contentGroupUI()
return self.UI:mutate(ax.childMatching(Group.matches))
end
-- cp.apple.finalcutpro.cmd.CommandDetail._labelUI <cp.prop: axuielement>
-- Field
-- The [axuielement](cp.prop.axuielement) for the label.
function CommandDetail.lazy.prop:_labelUI()
return self._contentGroupUI:mutate(ax.childMatching(StaticText.matches))
end
--- cp.apple.finalcutpro.cmd.CommandDetail.label <cp.ui.StaticText>
--- Field
--- The StaticText that displays the label.
function CommandDetail.lazy.value:label()
return StaticText(self, self._labelUI)
end
-- cp.apple.finalcutpro.cmd.CommandDetail._detailUI <cp.prop: axuielement>
-- Field
-- The [axuielement](cp.prop.axuielement) for the detail `AXScrollArea`.
function CommandDetail.lazy.prop:_detailUI()
return self._contentGroupUI:mutate(ax.childMatching(ScrollArea.matches))
end
--- cp.apple.finalcutpro.cmd.CommandDetail.detail <cp.ui.ScrollArea>
--- Field
--- The [ScrollArea](cp.ui.ScrollArea.md) that displays the contained [TextArea](cp.ui.TextArea.md).
function CommandDetail.lazy.value:detail()
return ScrollArea:containing(TextArea)(self, self._detailUI)
end
--- cp.apple.finalcutpro.cmd.CommandDetail.contents <cp.ui.TextArea>
--- Field
--- The TextArea that displays the content.
function CommandDetail.lazy.value:contents()
return self.detail.contents
end
return CommandDetail |
id = 'V-38491'
severity = 'high'
weight = 10.0
title = 'There must be no .rhosts or hosts.equiv files on the system.'
description = 'Trust files are convenient, but when used in conjunction with the R-services, they can allow unauthenticated access to a system.'
fixtext = [=[The files "/etc/hosts.equiv" and "~/.rhosts" (in each user's home directory) list remote hosts and users that are trusted by the local system when using the rshd daemon. To remove these files, run the following command to delete them from any location.
# rm /etc/hosts.equiv
$ rm ~/.rhosts]=]
checktext = [=[The existence of the file "/etc/hosts.equiv" or a file named ".rhosts" inside a user home directory indicates the presence of an Rsh trust relationship.
If these files exist, this is a finding.]=]
function test()
end
function fix()
end
|
local the = require"the"
local obj,has = the.get"metas obj has"
local abs = the.get"maths abs"
local push,per = the.get"tables push per"
local Num= obj"Num"
function Num.new(i,s)
s=s or ""
return has(Num,{
at=i or 0,txt=s, n=0,_contents={}, lo=1E32,hi=-1E32, ok=false,
w =s:find"+" and 1 or s:find"-" and -1 or 0}) end
function Num:add(x)
if x=="?" then return x end
self.n = self.n + 1
if x>self.hi then self.hi=x end
if x<self.lo then self.lo=x end
push(self._contents, x)
self.ok = false end -- note: the updated contents are no longer sorted
-- Ensure the contents are shorted; them return those concents.
function Num:all(x)
if not self.ok then self.ok=true; table.sort(self._contents) end
return self._contents end
-- If either of `x,y` is unknown, guess a value that maximizes the distance.
function Num:dist(x,y)
if x=="?" then y = self:norm(x); x = y>.5 and 0 or 1
elseif y=="?" then x = self:norm(x); y = x>.5 and 0 or 1
else x,y = self:norm(x), self:norm(y) end
return abs(x-y) end
-- central tendency
function Num:mid( a) a=self:all(); return a[#a//2] end
-- convert `x` to 0..1 for min..max.
function Num:norm(x, lo,hi)
lo,hi = self.lo,self.hi
return abs(lo - hi)< 1E-16 and 0 or (x - lo)/(hi-lo) end
-- The standard deviation of a list of sorted numbers is the
-- 90th - 10th percentile, divided by 2.56. Why? It is widely
-- know that ± 1 to 2 standard deviations is 66 to 95%
-- of the probability. Well, it is also true that
-- ± is 1.28 is 90% of the mass which, to say that
-- another way, one standard deviation is 2\*1.28 of ± 90%.
function Num:spread( a) a=self:all(); return (per(a,.9) - per(a,.1))/2.56 end
return Num
|
--[[
© 2013 GmodLive private project do not share
without permission of its author (Andrew Mensky vk.com/men232).
--]]
local gc = gc;
local tostring = tostring;
local CurTime = CurTime;
local pairs = pairs;
local type = type;
local math = math;
gc.attributes = gc.attributes or gc.kernel:NewLibrary("Attributs");
if !gc.datastream then include( "sh_datastream.lua" ); end;
if (SERVER) then
function gc.attributes:Progress(player, attribute, amount, gradual)
local attributeTable = gc.attribute:FindByID(attribute);
local attributes = player:GetAttributes();
if (attributeTable) then
attribute = attributeTable.uniqueID;
if (gradual and attributes[attribute]) then
if (amount > 0) then
amount = math.max(amount - ((amount / attributeTable.maximum) * attributes[attribute].amount), amount / attributeTable.maximum);
else
amount = math.min((amount / attributeTable.maximum) * attributes[attribute].amount, amount / attributeTable.maximum);
end;
end;
amount = amount * gc.config:Get("scale_attribute_progress"):Get();
if (attributes[attribute]) then
if (attributes[attribute].amount == attributeTable.maximum) then
if (amount > 0) then
return false, "Vous avez atteint le maximum de attribute!";
end;
end;
else
attributes[attribute] = {amount = attributeTable.default or 0, progress = 0};
end;
local progress = attributes[attribute].progress + amount;
local remaining = math.max(progress - 100, 0);
if (progress >= 100) then
attributes[attribute].progress = 0;
player:UpdateAttribute(attribute, 1);
if (remaining > 0) then
return player:ProgressAttribute(attribute, remaining);
end;
elseif (progress < 0) then
attributes[attribute].progress = 100;
player:UpdateAttribute(attribute, -1);
if (progress < 0) then
return player:ProgressAttribute(attribute, progress);
end;
else
attributes[attribute].progress = progress;
end;
if (attributes[attribute].amount == 0 and attributes[attribute].progress == 0) then
attributes[attribute] = nil;
end;
if (player:HasInitialized()) then
if (!player.gcCachedAttrProgress) then
player.gcCachedAttrProgress = {};
end;
if (attributes[attribute]) then
player.gcAttrProgress[attribute] = math.floor(attributes[attribute].progress);
else
player.gcAttrProgress[attribute] = 0;
end;
local progressDifferent = math.abs((player.gcCachedAttrProgress[attribute] or 0) - player.gcAttrProgress[attribute]);
if ( progressDifferent > 1 ) then
player.gcAttrProgressTime = 0;
player.gcCachedAttrProgress[attribute] = player.gcAttrProgress[attribute];
end;
gc.plugin:Call("PlayerAttributeProgress", player, attributeTable, amount );
end;
else
return false, "That is not a valid attribute!";
end;
end;
-- A function to update a player's attribute.
function gc.attributes:Update(player, attribute, amount)
local attributeTable = gc.attribute:FindByID(attribute);
local attributes = player:GetAttributes();
if (attributeTable) then
attribute = attributeTable.uniqueID;
if (!attributes[attribute]) then
attributes[attribute] = {amount = attributeTable.default or 0, progress = 0};
elseif (attributes[attribute].amount == attributeTable.maximum) then
if (amount and amount > 0) then
return false, "Vous avez atteint le maximum de attribute!";
end;
end;
attributes[attribute].amount = math.Clamp(attributes[attribute].amount + (amount or 0), 0, attributeTable.maximum);
if (amount and amount > 0) then
attributes[attribute].progress = 0;
if (player:HasInitialized()) then
player.gcAttrProgress[attribute] = 0;
player.gcAttrProgressTime = 0;
end;
end;
gc.datastream:Start(player, "AttrUpdate", {
index = attributeTable.index, amount = attributes[attribute].amount, progress = attributes[attribute].progress
});
if (attributes[attribute].amount == 0
and attributes[attribute].progress == 0) then
attributes[attribute] = nil;
end;
gc.plugin:Call("PlayerAttributeUpdated", player, attributeTable, amount);
return true;
else
return false, "Ce n'est pas un attribut valide!";
end;
end;
-- A function to clear a player's attribute boosts.
function gc.attributes:ClearBoosts(player)
gc.datastream:Start(player, "AttrBoostClear", true);
player.gcAttrBoosts = {};
end;
--- A function to get whether a boost is active for a player.
function gc.attributes:IsBoostActive(player, identifier, attribute, amount, duration)
if (player.gcAttrBoosts) then
local attributeTable = gc.attribute:FindByID(attribute);
if (attributeTable) then
attribute = attributeTable.uniqueID;
if (player.gcAttrBoosts[attribute]) then
local attributeBoost = player.gcAttrBoosts[attribute][identifier];
if (attributeBoost) then
if (amount and duration) then
return attributeBoost.amount == amount and attributeBoost.duration == duration;
elseif (amount) then
return attributeBoost.amount == amount;
elseif (duration) then
return attributeBoost.duration == duration;
else
return true;
end;
end;
end;
end;
end;
end;
-- A function to boost a player's attribute.
function gc.attributes:Boost(player, identifier, attribute, amount, duration)
local attributeTable = gc.attribute:FindByID(attribute);
if (attributeTable) then
attribute = attributeTable.uniqueID;
if (amount) then
if (!identifier) then
identifier = tostring({});
end;
if (!player.gcAttrBoosts[attribute]) then
player.gcAttrBoosts[attribute] = {};
end;
if (duration) then
player.gcAttrBoosts[attribute][identifier] = {
duration = duration,
endTime = CurTime() + duration,
default = amount,
amount = amount,
};
else
player.gcAttrBoosts[attribute][identifier] = {
amount = amount
};
end;
local gcIndex = attributeTable.index;
local gcAmount = player.gcAttrBoosts[attribute][identifier].amount;
local gcDuration = player.gcAttrBoosts[attribute][identifier].duration;
local gcEndTime = player.gcAttrBoosts[attribute][identifier].endTime;
local gcIdentifier = identifier;
gc.datastream:Start(player, "AttrBoost", {
index = gcIndex, amount = gcAmount, duration = gcDuration, endTime = gcEndTime, identifier = gcIdentifier
});
return identifier;
elseif (identifier) then
if (self:IsBoostActive(player, identifier, attribute)) then
if (player.gcAttrBoosts[attribute]) then
player.gcAttrBoosts[attribute][identifier] = nil;
end;
gc.datastream:Start(player, "AttrBoostClear", {
index = attributeTable.index, identifier = identifier
});
end;
return true;
elseif (player.gcAttrBoosts[attribute]) then
gc.datastream:Start(player, "AttrBoostClear", {
index = attributeTable.index
});
player.gcAttrBoosts[attribute] = {};
return true;
end;
else
self:ClearBoosts(player);
return true;
end;
end;
-- A function to get a player's attribute as a fraction.
function gc.attributes:Fraction(player, attribute, fraction, negative)
local attributeTable = gc.attribute:FindByID(attribute);
if (attributeTable) then
local maximum = attributeTable.maximum;
local amount = self:Get(player, attribute, nil, negative) or 0;
if (amount < 0 and type(negative) == "number") then
fraction = negative;
end;
if (!attributeTable.cache[amount][fraction]) then
attributeTable.cache[amount][fraction] = (fraction / maximum) * amount;
end;
return attributeTable.cache[amount][fraction];
end;
end;
-- A function to get whether a player has an attribute.
function gc.attributes:Get(player, attribute, boostless, negative)
local attributeTable = gc.attribute:FindByID(attribute);
if (attributeTable) then
attribute = attributeTable.uniqueID;
local maximum = attributeTable.maximum;
local default = player:GetAttributes()[attribute];
local boosts = player.gcAttrBoosts[attribute];
if ( !default and attributeTable.default ) then
default = { amount = attributeTable.default, progress = 0 };
end;
if (boostless) then
if (default) then
return default.amount, default.progress;
end;
else
local progress = 0;
local amount = 0;
if (default) then
amount = amount + default.amount;
progress = progress + default.progress;
end;
if (boosts) then
for k, v in pairs(boosts) do
amount = amount + v.amount;
end;
end;
if (negative) then
amount = math.Clamp(amount, -maximum, maximum);
else
amount = math.Clamp(amount, 0, maximum);
end;
return math.ceil(amount), progress;
end;
end;
end;
function gc.attributes:PlayerSpawn( player, bFirstSpawn, bInitialized )
player.gcAttrBoosts = {};
end;
function gc.attributes:PlayerDeath( player, inflictor, attacker, damageInfo )
for k, v in pairs(gc.attribute:GetAll()) do
player:ProgressAttribute( k, -15, false );
end;
end;
function gc.attributes:PlayerCharacterLoaded( player )
player.gcAttrProgress = {};
player.gcAttrProgressTime = 0;
for k, v in pairs(gc.attribute:GetAll()) do
player:UpdateAttribute(k);
end;
for k, v in pairs(player:GetAttributes()) do
player.gcAttrProgress[k] = math.floor(v.progress);
end;
end;
function gc.attributes:PlayerAttributeUpdated( player, attributeTable, amount )
if ( attributeTable.isShared ) then
local attribute = attributeTable.uniqueID;
local attributes = player:GetAttributes()[attribute] or {};
player:SetSharedVar{ ["atb_"..attribute] = attributes.amount or attributeTable.default or 0 };
end;
if ( player:HasInitialized() and amount and amount != 0 ) then
player:SaveCharacter();
end;
end;
-- Called at an interval while a player is connected.
function gc.attributes:PlayerThink( player, curTime, infoTable, bAlive )
if ( bAlive and player:WaterLevel() == 0 ) then
if ( !player:InVehicle() and player:GetMoveType() == MOVETYPE_WALK ) then
if ( player:IsInWorld() ) then
if ( !player:IsOnGround() ) then
player:ProgressAttribute(ATB_ACROBATICS, 0.25, true);
elseif ( infoTable.isRunning ) then
player:ProgressAttribute(ATB_AGILITY, 0.125, true);
elseif ( infoTable.isJogging ) then
player:ProgressAttribute(ATB_AGILITY, 0.0625, true);
end;
end;
end;
end;
local acrobatics = gc.attributes:Fraction(player, ATB_ACROBATICS, 100, 50);
local agility = gc.attributes:Fraction(player, ATB_AGILITY, 50, 25);
infoTable.jumpPower = infoTable.jumpPower + acrobatics;
infoTable.runSpeed = infoTable.runSpeed + agility;
end;
function greenCode.attributes:PlayerSetSharedVars( player, tSharedData, curTime )
player:HandleAttributeProgress( curTime );
player:HandleAttributeBoosts( curTime );
end;
else
gc.attributes.stored = gc.attributes.stored or {};
gc.attributes.boosts = gc.attributes.boosts or {};
-- A function to get the local player's attribute as a fraction.
function gc.attributes:Fraction(attribute, fraction, negative)
local attributeTable = gc.attribute:FindByID(attribute);
if (attributeTable) then
local maximum = attributeTable.maximum;
local amount = self:Get(attribute, nil, negative) or 0;
if (amount < 0 and type(negative) == "number") then
fraction = negative;
end;
if (!attributeTable.cache[amount][fraction]) then
attributeTable.cache[amount][fraction] = (fraction / maximum) * amount;
end;
return attributeTable.cache[amount][fraction];
end;
end;
-- A function to get whether the local player has an attribute.
function gc.attributes:Get(attribute, boostless, negative)
local attributeTable = gc.attribute:FindByID(attribute);
if (attributeTable) then
attribute = attributeTable.uniqueID;
local maximum = attributeTable.maximum;
local default = self.stored[attribute];
local boosts = self.boosts[attribute];
if ( !default and attributeTable.default ) then
default = { amount = attributeTable.default, progress = 0 };
end;
if (boostless) then
if (default) then
return default.amount, default.progress;
end;
else
local progress = 0;
local amount = 0;
if (default) then
amount = amount + default.amount;
progress = progress + default.progress;
end;
if (boosts) then
for k, v in pairs(boosts) do
amount = amount + v.amount;
end;
end;
if (negative) then
amount = math.Clamp(amount, -maximum, maximum);
else
amount = math.Clamp(amount, 0, maximum);
end;
return math.ceil(amount), progress;
end;
end;
end;
gc.datastream:Hook("AttrBoostClear", function(data)
local index = nil;
local identifier = nil;
if (type(data) == "table") then
index = data.index;
identifier = data.identifier;
end;
local attributeTable = gc.attribute:FindByID(index);
if (attributeTable) then
local attribute = attributeTable.uniqueID;
if (identifier and identifier != "") then
if (gc.attributes.boosts[attribute]) then
gc.attributes.boosts[attribute][identifier] = nil;
end;
else
gc.attributes.boosts[attribute] = nil;
end;
else
gc.attributes.boosts = {};
end;
end);
gc.datastream:Hook("AttrBoost", function(data)
local index = data.index;
local amount = data.amount;
local duration = data.duration;
local endTime = data.endTime;
local identifier = data.identifier;
local attributeTable = gc.attribute:FindByID(index);
if (attributeTable) then
local attribute = attributeTable.uniqueID;
if (!gc.attributes.boosts[attribute]) then
gc.attributes.boosts[attribute] = {};
end;
if (amount and amount == 0) then
gc.attributes.boosts[attribute][identifier] = nil;
elseif (duration and duration > 0 and endTime and endTime > 0) then
gc.attributes.boosts[attribute][identifier] = {
duration = duration,
endTime = endTime,
default = amount,
amount = amount
};
else
gc.attributes.boosts[attribute][identifier] = {
default = amount,
amount = amount
};
end;
end;
end);
gc.datastream:Hook("AttributeProgress", function(data)
local index = data.index;
local amount = data.amount;
local attributeTable = gc.attribute:FindByID(index);
if (attributeTable) then
local attribute = attributeTable.uniqueID;
if (gc.attributes.stored[attribute]) then
gc.attributes.stored[attribute].progress = amount;
else
gc.attributes.stored[attribute] = {amount = attributeTable.default or 0, progress = amount};
end;
end;
end);
gc.datastream:Hook("AttrUpdate", function(data)
local index = data.index;
local amount = data.amount;
local progress = data.progress;
local attributeTable = gc.attribute:FindByID(index);
if (attributeTable) then
local attribute = attributeTable.uniqueID;
gc.attributes.stored[attribute] = {amount = amount or attributeTable.default or 0, progress = progress or 0};
end;
end);
gc.datastream:Hook("AttrClear", function(data)
gc.attributes.stored = {};
gc.attributes.boosts = {};
end);
end; |
------------------------------
-- function
------------------------------
function gen_coordinate_positive(coordinate, targets)
local coordinate_positive
coordinate_positive = {}
coordinate_positive['adult_females'] = {}
coordinate_positive['subadult_males'] = {}
coordinate_positive['adult_males'] = {}
coordinate_positive['pups'] = {}
coordinate_positive['juveniles'] = {}
for _, target in ipairs(targets) do
for _, label in ipairs(labels) do
for _, tb in ipairs(coordinate[tostring(target)][label]) do
local lion_x = tb[1]
local lion_y = tb[2]
table.insert(coordinate_positive[label], {target, lion_x, lion_y})
end
end
end
return coordinate_positive
end
|
local aes = require "resty.aes"
local hmac = require "resty.hmac"
local os = require "os"
local _M = {_VERSION="0.1.1"}
local mt = {__index=_M}
local aesBlocksize = 16
local version = 0x80
local luaPush = 1
local versionOffset = 1 + 0
local tsOffset = 1 + 1
local ivOffset = 1 + 1 + 8
local payOffset = 1 + 1 + 8 + 16
local maxClockSkew = 60 * 1
getmetatable('').__call = string.sub
local function log(s)
ngx.log(ngx.WARN, s)
end
-- function string.fromhex(str)
-- return (str:gsub('..', function (cc)
-- return string.char(tonumber(cc, 16))
-- end))
-- end
function string.tohex(str)
return (str:gsub('.', function (c)
return string.format('%02X', string.byte(c))
end))
end
function string.bytes(str)
return (str:gsub('.', function (c)
return string.byte(c)
end))
end
local function parse(token_str)
local raw_payload = _M:fernet_decode(token_str)
local len = string.len(raw_payload);
local raw_version = string.byte(raw_payload(versionOffset, 1), 1, -1)
local raw_ts = raw_payload(tsOffset, 1 + 8)
local ts = tonumber("0x" .. string.tohex(raw_ts)) --uint64
local iv = raw_payload(ivOffset, 1 + 8 + 16)
local payload = raw_payload(payOffset, len - 32)
local signed = raw_payload(1, len - 32)
local sha256 = raw_payload(1 + len - 32, len)
if raw_version ~= version then
error({reason="invalid version: " .. raw_version})
end
return {
ts=ts,
iv=iv,
payload=payload,
signed=signed,
sha256=sha256
}
end
function _M.fernet_decode(self, b64_str)
b64_str = ngx.unescape_uri(b64_str):gsub("-", "+"):gsub("_", "/")
local reminder = #b64_str % 4
if reminder > 0 then
b64_str = b64_str .. string.rep("=", 4 - reminder)
end
local data = ngx.decode_base64(b64_str)
if not data then
return nil
end
return data
end
function _M.load_fernet(self, fernet_str)
local success, ret = pcall(parse, fernet_str)
if not success then
return {
valid=false,
verified=false,
reason=ret["reason"] or "invalid fernet string"
}
end
local fernet_obj = ret
fernet_obj["verified"] = false
fernet_obj["valid"] = true
return fernet_obj
end
function _M.unpad(payload)
if payload == nil then return nil else return payload end
end
function _M.verify_fernet_obj(self, secret, fernet_obj, ttl, now)
if not fernet_obj.valid then
return fernet_obj
end
local secret_len = string.len(secret) / 2
local sign_secret = secret(1, secret_len)
local crypt_secret = secret(1 + secret_len, -1)
if ttl > 0 then
if tonumber(os.date(now)) > tonumber(os.date(fernet_obj.ts + ttl)) then
fernet_obj["reason"] = "token expired"
elseif tonumber(os.date(fernet_obj.ts)) > tonumber(os.date(now + maxClockSkew)) then
fernet_obj["reason"] = "token expired"
end
end
local signature = hmac:new(sign_secret, hmac.ALGOS.SHA256):final(fernet_obj.signed)
if signature == fernet_obj.sha256 then
-- token valid!
if string.len(fernet_obj.payload) % aesBlocksize ~= 0 then
fernet_obj["reason"] = "wrong blocksize"
else
local aes_128_cbc_with_iv = assert(aes:new(crypt_secret,
nil, aes.cipher(128,"cbc"), {iv=fernet_obj.iv}))
local payload = aes_128_cbc_with_iv:decrypt(fernet_obj.payload)
payload = _M.unpad(payload)
if payload == nil then
fernet_obj["reason"] = "invalid padding"
else
fernet_obj["payload"] = payload
end
end
else
fernet_obj["reason"] = "invalid mac"
end
if not fernet_obj["reason"] then
fernet_obj["verified"] = true
end
return fernet_obj
end
function _M.decode_base64url(secret)
local r = #secret % 4
if r == 2 then
secret = secret .. "=="
elseif r == 3 then
secret = secret .. "="
end
secret = secret:gsub("-", "+"):gsub("_", "/")
secret = ngx.decode_base64(secret)
return secret
end
function _M.verify(self, secret, fernet_str, ttl, now)
local secret = _M.decode_base64url(secret)
fernet_obj = _M.load_fernet(self, fernet_str)
if not fernet_obj.valid then
return {verified=false, reason=fernet_obj["reason"]}
end
return _M.verify_fernet_obj(self, secret, fernet_obj, ttl, now)
end
return _M
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
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$
]]--
m = Map("samba")
s = m:section(TypedSection, "samba", "Samba")
s.anonymous = true
s:option(Value, "name")
s:option(Value, "description")
s:option(Value, "workgroup")
s:option(Flag, "homes")
s = m:section(TypedSection, "sambashare")
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "name", translate("name"))
s:option(Value, "path").titleref = luci.dispatcher.build_url("admin", "system", "fstab")
s:option(Value, "users").rmempty = true
ro = s:option(Flag, "read_only")
ro.rmempty = false
ro.enabled = "yes"
ro.disabled = "no"
go = s:option(Flag, "guest_ok")
go.rmempty = false
go.enabled = "yes"
go.disabled = "no"
cm = s:option(Value, "create_mask")
cm.rmempty = true
cm.size = 4
dm = s:option(Value, "dir_mask")
dm.rmempty = true
dm.size = 4
return m
|
--script.Parent = game.Lighting
wait()
name = "Rock Thrower"
scale = 1
animate = true
follow = false
attacking = false
attacking2 = false
touched1 = nil
touched2 = nil
meh = nil
player = nil
pose = "Standing"
toolAnim = "None"
toolAnimTime = 0
climbExtra = 0
Colors={BrickColor.new("New Yeller"),BrickColor.new("Really red")}
attacking2 = true
coroutine.resume(coroutine.create(function()
while attacking2 == true do
wait()
meh = findNearestTorso(Character.Torso.Position)
end
end))
w = Instance.new("Weld")
function move(time)
if animate == false then return end
local amplitude
local frequency
if pose == "Jumping" then
RightShoulder.MaxVelocity = 0.5
LeftShoulder.MaxVelocity = 0.5
RightShoulder.DesiredAngle = 3.14
LeftShoulder.DesiredAngle = -3.14
RightHip.DesiredAngle = 0
LeftHip.DesiredAngle = 0
return
end
if pose == "FreeFall" then
RightShoulder.MaxVelocity = 0.5
LeftShoulder.MaxVelocity = 0.5
RightShoulder.DesiredAngle = 3.14
LeftShoulder.DesiredAngle = -3.14
RightHip.DesiredAngle = 0
LeftHip.DesiredAngle = 0
return
end
if pose == "Seated" then
RightShoulder.MaxVelocity = 0.15
LeftShoulder.MaxVelocity = 0.15
RightShoulder.DesiredAngle = 3.14 / 2
LeftShoulder.DesiredAngle = -3.14 / 2
RightHip.DesiredAngle = 3.14 / 2
LeftHip.DesiredAngle = -3.14 / 2
return
end
if pose == "Running" then
RightShoulder.MaxVelocity = 0.15
LeftShoulder.MaxVelocity = 0.15
amplitude = 1
frequency = 9
elseif pose == "climbExtra" then
RightShoulder.MaxVelocity = 0.5
LeftShoulder.MaxVelocity = 0.5
amplitude = 1
frequency = 9
climbExtra = 3.14
else
amplitude = 0.1
frequency = 1
end
desiredAngle = amplitude * math.sin(time * frequency)
RightShoulder.DesiredAngle = desiredAngle + climbExtra
LeftShoulder.DesiredAngle = desiredAngle - climbExtra
RightHip.DesiredAngle = -desiredAngle
LeftHip.DesiredAngle = -desiredAngle
for _, Children in ipairs(Character:GetChildren()) do
if Children.className == "Tool" then
local tool = Children
end
end
if tool then
for _, Children in ipairs(Character:GetChildren()) do
if Children.Name == "toolanim" and Children.className == "StringValue" then
local animStringValueObject = Children
end
end
if animStringValueObject then
toolAnim = animStringValueObject.Value
animStringValueObject.Parent = nil
elseif time > toolAnimTime then
toolAnimTime = 0
end
if toolAnim == "None" then
RightShoulder.DesiredAngle = 1.57
elseif toolAnim == "Slash" then
RightShoulder.MaxVelocity = 0.5
RightShoulder.DesiredAngle = 0
elseif toolAnim == "Lunge" then
RightShoulder.MaxVelocity = 0.5
LeftShoulder.MaxVelocity = 0.5
RightHip.MaxVelocity = 0.5
LeftHip.MaxVelocity = 0.5
RightShoulder.DesiredAngle = 1.57
LeftShoulder.DesiredAngle = 1.0
RightHip.DesiredAngle = 1.57
LeftHip.DesiredAngle = 1.0
end
else
toolAnim = "None"
toolAnimTime = 0
end
end
Template = Instance.new("Part")
Template.formFactor = "Symmetric"
Template.Size = Vector3.new(scale, scale, scale)
Template.BrickColor = BrickColor.new("New Yeller")
Template.Locked = true
leftarmcolor = Template.BrickColor
rightarmcolor = Template.BrickColor
leftlegcolor = Template.BrickColor
rightarmcolor = Template.BrickColor
torsocolor = Template.BrickColor
pos = Vector3.new(0, 10, 0)
leftarmcolor = BrickColor.new("Sand green")
rightarmcolor = BrickColor.new("Sand green")
leftlegcolor = BrickColor.new("Sand green")
rightlegcolor = BrickColor.new("Sand green")
torsocolor = BrickColor.new("Dark stone grey")
headcolor = BrickColor.new("Dark stone grey")
LeftArm = Template:Clone()
LeftArm.formFactor = "Symmetric"
LeftArm.Size = Vector3.new(scale, scale * 2, scale)
LeftArm.Name = "Left Arm"
LeftArm.BrickColor = leftarmcolor
RightArm = Template:Clone()
RightArm.Size = Vector3.new(scale, scale * 2, scale)
RightArm.Name = "Right Arm"
RightArm.BrickColor = rightarmcolor
local rock = Instance.new("Part")
rock.Size = Vector3.new(3,3,3)
rock.BrickColor = rightarmcolor
LeftLeg = Template:Clone()
LeftLeg.Size = Vector3.new(scale, scale * 2, scale)
LeftLeg.Name = "Left Leg"
LeftLeg.BrickColor = leftlegcolor
RightLeg = Template:Clone()
RightLeg.Size = Vector3.new(scale, scale * 2, scale)
RightLeg.Name = "Right Leg"
RightLeg.BrickColor = rightlegcolor
Torso = Template:Clone()
Torso.Size = Vector3.new(scale * 2, scale * 2, scale)
Torso.LeftSurface = "Weld"
Torso.RightSurface = "Weld"
Torso.Position = pos + Vector3.new(0, scale * 3.5, 0)
Torso.Name = "Torso"
Torso.BrickColor = torsocolor
Head = Template:Clone()
Head.Size = Vector3.new(scale * 2, scale, scale)
Head.TopSurface = "Smooth"
Head.BottomSurface = "Smooth"
Head.Name = "Head"
Head.BrickColor = headcolor
Mesh = Instance.new("SpecialMesh")
Mesh.MeshType = "Head"
Mesh.Scale = Vector3.new(1.25, 1.25, 1.25)
Mesh.Parent = Head
Face = Instance.new("Decal")
Face.Parent = Head
Face.Name = "face"
if math.random(1,2) == 1 then
Face.Texture = "http://www.roblox.com/asset/?id=25547935"
else
Face.Texture = "http://www.roblox.com/asset/?id=32333940"
end
Character = Instance.new("Model")
Character.Name = name
--script.Parent = Character
Humanoid = Instance.new("Humanoid")
Humanoid.WalkSpeed = 13
LeftArm.Parent = Character
RightArm.Parent = Character
rock.Parent = Character
LeftLeg.Parent = Character
RightLeg.Parent = Character
Torso.Parent = Character
Head.Parent = Character
Humanoid.Parent = Character
local weld = Instance.new("Weld")
weld.Parent = rock
weld.Part0 = rock
weld.Part1 = RightArm
weld.C0 = CFrame.new(0,1,0)
LeftShoulder = Instance.new("Motor")
LeftShoulder.Parent = Torso
LeftShoulder.Part0 = Torso
LeftShoulder.Part1 = LeftArm
LeftShoulder.MaxVelocity = 0.1
LeftShoulder.C0 = CFrame.new(-Torso.Size.x / 2 - LeftArm.Size.x / 2, LeftArm.Size.y / 4, 0) * CFrame.fromEulerAnglesXYZ(0, -3.14 / 2, 0)
LeftShoulder.C1 = CFrame.new(0, LeftArm.Size.y / 4, 0) * CFrame.fromEulerAnglesXYZ(0, -3.14 / 2, 0)
LeftShoulder.Name = "Left Shoulder"
RightShoulder = Instance.new("Motor")
RightShoulder.Parent = Torso
RightShoulder.Part0 = Torso
RightShoulder.Part1 = RightArm
RightShoulder.MaxVelocity = 0.1
RightShoulder.C0 = CFrame.new(Torso.Size.x / 2 + RightArm.Size.x / 2, RightArm.Size.y / 4, 0) * CFrame.fromEulerAnglesXYZ(0, 3.14 / 2, 0)
RightShoulder.C1 = CFrame.new(0, RightArm.Size.y / 4, 0) * CFrame.fromEulerAnglesXYZ(0, 3.14 / 2, 0)
RightShoulder.Name = "Right Shoulder"
LeftHip = Instance.new("Motor")
LeftHip.Parent = Torso
LeftHip.Part0 = Torso
LeftHip.Part1 = LeftLeg
LeftHip.MaxVelocity = 0.1
LeftHip.C0 = CFrame.new(-LeftLeg.Size.x / 2, -(LeftLeg.Size.y / 4) * 3, 0) * CFrame.fromEulerAnglesXYZ(0, -3.14 / 2, 0)
LeftHip.C1 = CFrame.new(0, LeftLeg.Size.y / 4, 0) * CFrame.fromEulerAnglesXYZ(0, -3.14 / 2, 0)
LeftHip.Name = "Left Hip"
RightHip = Instance.new("Motor")
RightHip.Parent = Torso
RightHip.Part0 = Torso
RightHip.Part1 = RightLeg
RightHip.MaxVelocity = 0.1
RightHip.C0 = CFrame.new(RightLeg.Size.x / 2, -(RightLeg.Size.y / 4) * 3, 0) * CFrame.fromEulerAnglesXYZ(0, 3.14 / 2, 0)
RightHip.C1 = CFrame.new(0, RightLeg.Size.y / 4, 0) * CFrame.fromEulerAnglesXYZ(0, 3.14 / 2, 0)
RightHip.Name = "Right Hip"
Neck = Instance.new("Weld")
Neck.Name = "Neck"
Neck.Part0 = Torso
Neck.Part1 = Head
Neck.C0 = CFrame.new(0, 1.5 * scale, 0)
Neck.C1 = CFrame.new()
Neck.Parent = Torso
--[[Children = owner.Character:GetChildren()
for i = 1, #Children do
if Children[i].className == "Shirt" or Children[i].className == "Pants" and scale == 1 then
Children[i]:Clone().Parent = Character
end
if Children[i].className == "Hat" then
if Children[i]:FindFirstChild("Handle") ~= nil then
Hat = Instance.new("Hat")
Children[i].Handle:Clone().Parent = Hat
Hat.Handle.Size = Hat.Handle.Size * scale
Hat.Handle.Mesh.Scale = Hat.Handle.Mesh.scale * scale
if scale == 1 then TempScale = 1 else TempScale = scale * 1.5 end
Hat.AttachmentPos = Children[i].AttachmentPos * TempScale
Hat.AttachmentUp = Children[i].AttachmentUp
Hat.AttachmentForward = Children[i].AttachmentForward
Hat.AttachmentRight = Children[i].AttachmentRight
Hat.Parent = Character
end
end
end]]
Character.Parent = game:GetService("Workspace")
Humanoid.Died:connect(function() pose = "Dead" wait(5.5) if Character == nil then script:Remove() return end Character:Remove() script:Remove() end)
Humanoid.Running:connect(function(speed) if speed > 0 then pose = "Running" else pose = "Standing" end end)
Humanoid.Jumping:connect(function() pose = "Jumping" end)
Humanoid.Climbing:connect(function() pose = "climbExtra" end)
Humanoid.GettingUp:connect(function() pose = "GettingUp" end)
Humanoid.FreeFalling:connect(function() pose = "FreeFall" end)
Humanoid.FallingDown:connect(function() pose = "FallingDown" end)
Humanoid.Seated:connect(function() pose = "Seated" end)
Humanoid.PlatformStanding:connect(function() pose = "PlatformStanding" end)
function kill(hit)
if hit.Parent:FindFirstChild("Humanoid") ~= nil and hit.Name ~= "Base" and hit.Parent.Name ~= "Rock Thrower" then
hit.Parent.Humanoid.Health = hit.Parent.Humanoid.Health - 1
end
end
Torso.Touched:connect(function(hit) kill(hit) end)
coroutine.resume(coroutine.create(function()
local larm = Character:FindFirstChild("Left Arm")
local rarm = Character:FindFirstChild("Right Arm")
function findNearestTorso(pos)
local list = game.Workspace:children()
local torso = nil
local dist = 1000
local temp = nil
local human = nil
local temp2 = nil
for x = 1, #list do
temp2 = list[x]
if (temp2.className == "Model") and (temp2 ~= Character) and (temp2.Name ~= "Rock Thrower") then
temp = temp2:findFirstChild("Torso")
human = temp2:findFirstChild("Humanoid")
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
if (temp.Position - pos).magnitude < dist then
torso = temp
dist = (temp.Position - pos).magnitude
end
end
end
end
return torso
end
while true do
wait(0.1)
local target = meh
if target ~= nil then
Character.Humanoid:MoveTo(target.Position, target)
end
end
end))
coroutine.resume(coroutine.create(function()
while true do
wait(1)
local target = findNearestTorso(Character.Torso.Position)
if target ~= nil then
if attacking2 == true then
local RSH = Torso["Right Shoulder"]
RSH.Parent = nil
local RW = Instance.new("Weld")
RW.Parent = RightArm
RW.Part0 = Torso
RW.Part1 = RightArm
RW.C0 = CFrame.new(1.5, 0.5, 0)
RW.C1 = CFrame.new(0, 0.5, 0)
-- if math.random(1,2) == 1 then
wait(4)
for i = 0,1,0.1 do
wait()
RW.C0 = CFrame.new(1.5, 0.5, 0) * CFrame.fromEulerAnglesXYZ(math.rad(200)*i,0,0)
end
wait(0.3)
for i = 0,1,0.2 do
wait()
RW.C0 = CFrame.new(1.5, 0.5, 0) * CFrame.fromEulerAnglesXYZ(-math.rad(120)*i+math.rad(200),0,0)
end
Character.Humanoid.WalkSpeed = 16
rock:BreakJoints()
rock.Velocity = Torso.CFrame.lookVector * 300
rockhit = 0
rock.Touched:connect(function(hit) kill(b,hit) end)
function kill(brick,hit)
if hit.Parent:FindFirstChild("Humanoid") ~= nil and hit.Name ~= "Base" and hit.Parent.Name ~= "Rock Thrower" then
if rockhit == 0 then
rockhit = 1
local p = Instance.new("Part")
p.Parent = game.workspace
p.CFrame = rock.CFrame
p.Name = "tinyrock"
p.Size = Vector3.new(1,1,1)
p.BrickColor = rightarmcolor
p:BreakJoints()
local p2 = p:Clone()
p2.Parent = workspace
p2.Name = "tinyrock"
p2:BreakJoints()
p3 = p2:Clone()
p3.Parent = workspace
p3.Name = "tinyrock"
p3:BreakJoints()
p4 = p2:Clone()
p4.Parent = workspace
p4.Name = "tinyrock"
p4:BreakJoints()
rock.Parent = nil
hit.Parent.Humanoid.Health = hit.Parent.Humanoid.Health - 30
hit.Parent.Humanoid.PlatformStand = true
wait(0.5)
hit.Parent.Humanoid.PlatformStand = false
wait(4)
p:Remove()
p2:Remove()
p3:Remove()
p4:Remove()
end
end
end
wait(1)
RW.Parent = nil
RSH.Parent = Torso
wait(3)
Humanoid.WalkSpeed = 13
rock.Parent = Character
local weld = Instance.new("Weld")
weld.Parent = rock
weld.Part0 = rock
weld.Part1 = RightArm
weld.C0 = CFrame.new(0,1,0)
--[[ else
local LSH = Torso["Left Shoulder"]
LSH.Parent = nil
local LW = Instance.new("Weld")
LW.Parent = RightArm
LW.Part0 = Torso
LW.Part1 = RightArm
LW.C0 = CFrame.new(-1.5, 0.5, 0) * CFrame.fromEulerAnglesXYZ(math.rad(120),0,0)
LW.C1 = CFrame.new(0, 0.5, 0)
RW.C0 = CFrame.new(1.5, 0.5, 0) * CFrame.fromEulerAnglesXYZ(math.rad(120),0,0)
end]]
end
end
end
end))
while Character.Parent ~= nil do
wait(0.1)
move(game:GetService("Workspace").DistributedGameTime)
if Character.Parent ~= nil then
if Character.Humanoid.Sit == true then
wait(math.random(0,3))
Character.Humanoid.Jump = true
Character.Humanoid.Sit = false
end
end
if Character.Parent ~= nil then
if Character.Humanoid.PlatformStand == true then
wait(math.random(0,3))
Character.Humanoid.PlatformStand = false
end
end
end
-- lego blockland This acts as a chat filter. Don't ask why I do it. I just do >.>
--[[
Copyrighted (C) Fenrier 2011
This script is copyrighted for Fenrier. Any use of this script is breaking
this copyright.
All Rights Reserved.
]] |
---------------------------------------------------------------------------------------------------
-- Issue: https://github.com/smartdevicelink/sdl_core/issues/3469
---------------------------------------------------------------------------------------------------
-- Description: Check SDL sends RC.SetGlobalProperties during resumption if app defines global properties
-- with 'userLocation' parameter
--
-- Steps:
-- 1. App is registered
-- 2. App sends SetGlobalProperties with 'userLocation' parameter
-- 3. App unexpectedly disconnects and reconnects
-- SDL does:
-- - Start resumption process
-- - Send RC.SetGlobalProperties with 'userLocation' parameter
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local common = require('user_modules/sequences/actions')
local utils = require("user_modules/utils")
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
--[[ Local Variables ]]
local params = {
userLocation = { grid = { col = 2, colspan = 1, row = 0, rowspan = 1, level = 0, levelspan = 1 } }
}
local hashId
--[[ Local Functions ]]
local function unexpectedDisconnect()
common.getHMIConnection():ExpectNotification("BasicCommunication.OnAppUnregistered", { unexpectedDisconnect = true })
:Times(common.mobile.getAppsCount())
common.mobile.disconnect()
utils.wait(1000)
end
local function sendSetGlobalProperties()
local cid = common.getMobileSession():SendRPC("SetGlobalProperties", params)
common.getHMIConnection():ExpectRequest("RC.SetGlobalProperties", params)
:Do(function(_, data)
common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
common.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
common.getMobileSession():ExpectNotification("OnHashChange")
:Do(function(_, data)
hashId = data.payload.hashID
end)
end
local function reRegisterApp()
common.app.getParams().hashID = hashId
common.app.registerNoPTU()
common.getHMIConnection():ExpectRequest("RC.SetGlobalProperties", params)
:Do(function(_, data)
common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("Register App", common.app.registerNoPTU)
runner.Step("Set RC Global Properties", sendSetGlobalProperties)
runner.Title("Test")
runner.Step("Unexpected disconnect", unexpectedDisconnect)
runner.Step("Connect mobile", common.mobile.connect)
runner.Step("Re-register App", reRegisterApp)
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
|
object_tangible_collection_reward_col_reward_hoth_ice_sculpture_tauntaun_01 = object_tangible_collection_reward_shared_col_reward_hoth_ice_sculpture_tauntaun_01:new {
}
ObjectTemplates:addTemplate(object_tangible_collection_reward_col_reward_hoth_ice_sculpture_tauntaun_01, "object/tangible/collection/reward/col_reward_hoth_ice_sculpture_tauntaun_01.iff")
|
module_version("/14.0.1.134", "14")
module_version("/13.2.345", "13")
module_alias( "z13", "z/13")
|
--Script Name : jlp_Go to next marker (no seeking).lua
--Author : Jean Loup Pecquais
--Description : Go to next marker (no seeking)
--v1.0.0
local libPath = reaper.GetExtState("Reaper Evolution", "libPath")
if not libPath or libPath == "" then
reaper.MB("Reaper Evolution library is not found. Please refer to user guide", "Library not found", 0)
return
end
loadfile(libPath .. "reaVolutionLib.lua")()
-------------------------------------------------------------------------------------------------------------
setEditCursorToNextMarker() |
--
-- Please see the license.txt file included with this distribution for
-- attribution and copyright information.
--
local vToResolve;
local resolveActorOriginal;
local getActorRecordTypeFromPathOriginal;
-- Initialization
function onInit()
resolveActorOriginal = ActorManager.resolveActor;
ActorManager.resolveActor = resolveActor;
getActorRecordTypeFromPathOriginal = ActorManager.getActorRecordTypeFromPath;
ActorManager.getActorRecordTypeFromPath = getActorRecordTypeFromPath;
end
function onClose()
ActorManager.resolveActor = resolveActorOriginal;
end
function beginResolvingItem(v)
vToResolve = v;
end
function endResolvingItem()
vToResolve = nil;
end
function resolveActor(v)
local rActor = resolveActorOriginal(v);
if not rActor and vToResolve then
rActor = resolveActorOriginal(vToResolve) or {sName = ""};
end
return rActor;
end
-- Internal use only
function getActorRecordTypeFromPath(sActorNodePath)
if sActorNodePath:match("%.inventorylist%.") then
return nil;
else
return getActorRecordTypeFromPathOriginal(sActorNodePath);
end
end |
--------------------------------------------------------------------------------
-- Handler.......... : onToggleVsync
-- Author........... :
-- Description...... :
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function ApplicationRuntimeOptions.onToggleVsync ( bEnable )
--------------------------------------------------------------------------------
-- vsync at full monitor refresh rate
this.fVsync ( bEnable, false )
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
|
-- scaffolding entry point for zstd
return dofile("zstd.lua")
|
stationsNames = {} -- using station ID, ex. stationNames[ID] = "kwejk fm"
stations = {} -- path
stationType = {} -- 0 GTA radio, 1+ internet radio ex. = stationType["radio kwejk fm"] = 1, stationType["radio off"] = 0
usedStations = {} -- stations IDs, script use stations[ID]
notUsedStations = {} -- stations IDs
usedRadiosXML = xmlLoadFile ("used.xml")
currentStationID = 0 -- 0 = off
currentStation = nil
stationsCount = 0
usedStationsCount = 0
canUse = false
volume = 30
local scrollLimit = 800 --one stations change per 1000ms
local scrollTimer = nil
local lastGTAChannel = 0
local withoutBeingInCar = false
allowVehicles = {}
allowVehicles["Automobile"] = true
allowVehicles["Plane"] = true
allowVehicles["Bike"] = true
allowVehicles["Helicopter"] = true
allowVehicles["Boat"] = true
allowVehicles["Train"] = true
allowVehicles["Trailer"] = false
allowVehicles["BMX"] = true
allowVehicles["Monster Truck"] = true
allowVehicles["Quad"] = true
function loadUsedStations ()
if not usedRadiosXML then
usedRadiosXML = xmlCreateFile ("used.xml", "root")
usedRadiosUsedNode = xmlCreateChild (usedRadiosXML,"radios")
usedRadiosVolumeNode = xmlCreateChild (usedRadiosXML, "volume")
xmlNodeSetValue (usedRadiosVolumeNode, "30")
xmlSaveFile (usedRadiosXML)
end
local usedChild = xmlFindChild (usedRadiosXML, "radios", 0)
local children = xmlNodeGetChildren (usedChild)
for key,value in ipairs(children) do
local attributes = xmlNodeGetAttributes (value)
if attributes then
for name,v in pairs(attributes) do
if name == "name" then
rName = v
end
if name == "ID" then
rID = tonumber(v)
end
end
local founded = false
for k,v in ipairs(notUsedStations) do
if v == rID then
founded = k
break
end
end
if tonumber(founded) then
table.insert (usedStations, key, rID)
usedStationsCount = usedStationsCount + 1
table.remove (notUsedStations, founded)
else
outputDebugString ("There is no such a station on server")
end
end
end
local volumeChild = xmlFindChild (usedRadiosXML, "volume", 0)
if volumeChild then
volume = tonumber(xmlNodeGetValue(volumeChild))
end
end
addEvent ("onRadioListLoad", true)
addEventHandler ("onRadioListLoad", getRootElement(), loadUsedStations)
function getStationName (ID)
if ID == 0 then
return "Radio Wyłączone /radios"
else
local nm = stationsNames[ID]
if nm then
return nm
else
return false
end
end
end
function getStationID (name)
local finded = nil
if name then
for k,v in ipairs(stationsNames) do
if v == name then
finded = k
break
end
end
if tonumber(finded) then
return finded
else
return false
end
end
end
function onStart ()
triggerServerEvent ("requestForRadiosList", getLocalPlayer(), getLocalPlayer())
end
addEventHandler ("onClientResourceStart", getResourceRootElement(getThisResource()), onStart)
function onJoin (names, st, typ, withoutCarSetting)
stationsNames = names
stations = st
stationType = typ
for k,v in ipairs(stationsNames) do
stationsCount = stationsCount + 1
table.insert (notUsedStations, k, k)
end
triggerEvent ("onRadioListLoad", getRootElement())
if withoutCarSetting == "true" then
withoutBeingInCar = true
elseif withoutCarSetting == "false" then
withoutBeingInCar = false
end
if withoutBeingInCar == true then
canUse = true
setRadioStation ("off")
bindKey ("mouse_wheel_up", "both", scroll)
bindKey ("mouse_wheel_down", "both", scroll)
else
addEventHandler("onClientPlayerVehicleEnter", getRootElement(), onEnterVeh)
addEventHandler("onClientPlayerVehicleExit", getRootElement(), onExitVeh)
addEventHandler ("onClientPlayerWasted", getLocalPlayer(), onWasted)
end
end
addEvent ("sendRadioList", true)
addEventHandler ("sendRadioList", getRootElement(), onJoin)
function saveRadios ()
local radiosChild = xmlFindChild (usedRadiosXML, "radios", 0)
if radiosChild then
local children = xmlNodeGetChildren (radiosChild)
for k,v in ipairs(children) do
xmlDestroyNode (v)
end
for k,v in ipairs(usedStations) do
local newChild = xmlCreateChild (radiosChild, "used")
xmlNodeSetAttribute (newChild, "name", getStationName(v))
xmlNodeSetAttribute (newChild, "ID", v)
end
end
local volumeChild = xmlFindChild (usedRadiosXML, "volume", 0)
if volumeChild then
xmlNodeSetValue (volumeChild, tostring(volume))
end
xmlSaveFile (usedRadiosXML)
end
addEventHandler ("onClientResourceStop", getResourceRootElement(getThisResource()), saveRadios)
-------veh---------------------
-------------------------------
-------------------------------
function onEnterVeh(veh, seat)
if source == getLocalPlayer () then
if allowVehicles[getVehicleType(veh)] == true then
canUse = true
setRadioStation (currentStationID)
end
end
end
function onExitVeh(veh, seat)
if source == getLocalPlayer() then
canUse = false
setRadioStation ("off")
end
end
function onWasted ()
canUse = false
setRadioStation ("off")
end
function scroll (key, keystate)
if canUse == true then
if isTimer (scrollTimer) == false then
scrollTimer = setTimer (
function ()
scrollTimer = nil
end
,scrollLimit,1
)
if key == "radio_next" or key == "mouse_wheel_up" then -- scroll forwards
setRadioStation ("next")
elseif key == "radio_previous" or key == "mouse_wheel_down" then -- scroll backwards
setRadioStation ("back")
end
else
exSetRadioChannel (lastGTAChannel)
end
end
end
bindKey ("radio_next", "both", scroll)
bindKey ("radio_previous", "both", scroll)
function exSetRadioChannel (c)
local c = tonumber(c)
lastGTAChannel = c
setRadioChannel (c)
end
function playRadioChangeSound (id)
local sound = playSoundFrontEnd (34)
setTimer (playSoundFrontEnd, 500, 1, 35)
end
addEvent ("onRadioStationChange", true)
addEventHandler ("onRadioStationChange", getRootElement(), playRadioChangeSound)
function setRadioStation (st) -- st can be off, number of station (useful on veh enter), "next" and "back"
if tonumber(st) then
if currentStation then
stopSound (currentStation)
end
if st >= usedStationsCount then
currentStationID = usedStationsCount
else
currentStationID = st
end
if st == 0 then
exSetRadioChannel (0)
currentStation = nil
stName = "Radio Wyłączone"
stType = 0
else
stName = stationsNames[usedStations[currentStationID]]
stType = tonumber(stationType[stName])
if stName then
if stType == 0 then
currentStation = nil
local stID = stations[stName]
if stID then
exSetRadioChannel (stID)
end
else
exSetRadioChannel (0)
local stPath = stations[stName]
if stPath then
currentStation = playSound (stPath)
if currentStation then
setSoundVolume (currentStation, volume/100)
end
end
end
else
outputChatBox ("error", 255,0,0)
end
end
triggerEvent ("onRadioStationChange", getRootElement(), currentStationID)
showStationText (stName, stType)
elseif st == "off" then
if stationType[stationsNames[usedStations[currentStationID]]] == 0 then
exSetRadioChannel (0)
else
if currentStation then
stopSound (currentStation)
currentStation = nil
end
end
elseif st == "next" then
if currentStation then
stopSound (currentStation)
end
if currentStationID >= usedStationsCount then
currentStationID = 0
exSetRadioChannel (0)
stName = "Radio Wyłączone"
stType = 0
else
currentStationID = currentStationID + 1
stName = stationsNames[usedStations[currentStationID]]
stType = tonumber(stationType[stName])
if stType == 0 then -- gta radio
currentStation = nil
local stID = stations[stName]
if stID then
exSetRadioChannel (stID)
end
else
exSetRadioChannel (0)
local stPath = stations[stName]
if stPath then
currentStation = playSound (stPath)
if currentStation then
setSoundVolume (currentStation, volume/100)
end
else
outputChatBox ("error", 255,0,0)
end
end
end
triggerEvent ("onRadioStationChange", getRootElement(), currentStationID)
showStationText (stName, stType)
elseif st == "back" then
if currentStation then
stopSound (currentStation)
end
currentStationID = currentStationID - 1
if currentStationID > usedStationsCount then -- possible when someone delete used stations in car
currentStationID = usedStationsCount -- set on last station
elseif currentStationID < 0 then
currentStationID = usedStationsCount
end
if currentStationID == 0 then
exSetRadioChannel (0)
currentStation = nil
stName = "Radio Wyłączone"
stType = 0
else
stName = stationsNames[usedStations[currentStationID]]
stType = tonumber(stationType[stName])
if stType == 0 then -- gta radio
currentStation = nil
local stID = stations[stName]
if stID then
exSetRadioChannel (stID)
end
else
exSetRadioChannel (0)
local stPath = stations[stName]
if stPath then
currentStation = playSound (stPath)
if currentStation then
setSoundVolume (currentStation, volume/100)
end
else
outputChatBox ("error", 255,0,0)
end
end
end
triggerEvent ("onRadioStationChange", getRootElement(), currentStationID)
showStationText (stName, stType)
end
end |
ITEM.name = "Котелок"
ITEM.desc = "Металлический котелолок, можно подвесить на костер или плиту, приготовить что-нибудь"
ITEM.model = "models/props/furnitures/mn/mn_stewpan/mn_stewpan.mdl"
ITEM.width = 1
ITEM.height = 1 |
function GetVehicle(player)
local vehicle = GetPlayerVehicle(player)
CallRemoteEvent(player, "Kuzkay:ReturnVehicle", vehicle)
end
AddRemoteEvent("Kuzkay:GetVehicle", GetVehicle)
function OnEnterVehicle(player, _vehicle, seat)
CallRemoteEvent(player, "Kuzkay:ReturnVehicle", _vehicle)
end
AddEvent("OnPlayerEnterVehicle", OnEnterVehicle)
function OnLeaveVehicle(player, _vehicle, seat)
CallRemoteEvent(player, "Kuzkay:ReturnVehicle", 0)
end
AddEvent("OnPlayerLeaveVehicle", OnLeaveVehicle)
|
local settingsutil = require('__spice-rack-core__/util/settingsutil')
local tableutil = require('__spice-rack-core__/util/tableutil')
------ >> Long Range Turret
if settingsutil.get_startup_setting("longrange-turret") then
local gunturret_longrange = util.table.deepcopy(data.raw['ammo-turret']['gun-turret'])
gunturret_longrange.name = "spice-rack-longrange-turret"
gunturret_longrange.minable = {mining_time = 0.5, result = "spice-rack-longrange-turret"}
gunturret_longrange.max_health = 500
gunturret_longrange.automated_ammo_count = 5
gunturret_longrange.attack_parameters.range = 24
--gunturret_longrange.attacking_speed = 0.1
gunturret_longrange.attack_parameters.cooldown = 15
--gunturret_longrange.attack_parameters.damage_modifier = 1.5
local function changetint(layer, color)
layer.apply_runtime_tint = false
layer.tint = color
layer.hr_version.apply_runtime_tint = false
layer.hr_version.tint = color
end
local green = {r=0.5, g=1, b=0.5, a=1}
changetint(gunturret_longrange.folded_animation.layers[2], green)
changetint(gunturret_longrange.preparing_animation.layers[2], green)
changetint(gunturret_longrange.prepared_animation.layers[2], green)
changetint(gunturret_longrange.attacking_animation.layers[2], green)
changetint(gunturret_longrange.folding_animation.layers[2], green)
data:extend({gunturret_longrange})
end
------ << Long Range Turret
------ >> Shotgun
if settingsutil.get_startup_setting("shotgun-change") then
data:extend({
{
type = "sticker",
name = "spice-rack-short-stun-sticker",
flags = {"not-on-map"},
duration_in_ticks = 0.5*60,
target_movement_modifier = 0
},
})
end
------ << Shotgun
------ >> Landmine
if settingsutil.get_startup_setting("landmine-change") then
data:extend({
{
type = "sticker",
name = "spice-rack-landmine-stun-sticker",
flags = {"not-on-map"},
duration_in_ticks = 1.5*60,
target_movement_modifier = 0
},
})
data:extend({
{
type = "sticker",
name = "spice-rack-landmine-slowdown-sticker",
flags = {"not-on-map"},
duration_in_ticks = 4*60,
target_movement_modifier = 0.3
},
})
end
------ << Landmine |
local function HoursAndMinutes(ticks)
local seconds = ticks/TICKS_PER_SECOND;
local minutes = math.floor((seconds)/60);
local hours = math.floor(minutes/60);
minutes = minutes - 60 * hours;
return string.format("%3d:%02d", hours, minutes);
end
local function StatusCommand_ShowStatus(player, xplayer)
if xplayer ~= nil then
local status = string.format("%s played %s. Location %d,%d",
xplayer.name,
HoursAndMinutes(xplayer.online_time),
math.floor(xplayer.position.x),
math.floor(xplayer.position.y));
game.player.print(status);
end
end
commands.remove_command("status");
commands.add_command("status", "shows your location, time in game", function(command)
local players = {};
for _,p in pairs(game.players) do
if p ~= nil then
players[_] = p;
end
end
table.sort(players,
function(a,b)
if a~=nil and b~=nil then
return a.online_time < b.online_time;
end
return false;
end
);
local player = game.player;
if player ~= nil then
if (command.parameter ~= nil) then
StatusCommand_ShowStatus(player, game.players[command.parameter]);
else
for _,xplayer in pairs(players) do
StatusCommand_ShowStatus(player, xplayer);
end
end
end
end)
|
-- This Source Code Form is subject to the terms of the bCDDL, v. 1.1.
-- If a copy of the bCDDL was not distributed with this
-- file, You can obtain one at http://beamng.com/bCDDL-1.1.txt
local M = {}
local logTag = 'ResearchGE'
local version = 'v1.17'
local socket = require('libs/luasocket/socket.socket')
local rcom = require('utils/researchCommunication')
local scenariosLoader = require('scenario/scenariosLoader')
local scenarioHelper = require('scenario/scenariohelper')
local procPrimitives = require('util/trackBuilder/proceduralPrimitives')
local host = '127.0.0.1'
local port = 64256
local skt = nil
local clients = {}
local gameState = 'menu'
local conSleep = 1
local stepsLeft = 0
local stepACK = false
local loadNotified = false
local loadRequested = false
local startRequested = false
local restartRequested = false
local waitingForMainMenu = false
local sensors = {}
local lidars = {}
local spawnPending = nil
local objectCount = 1
local frameDelayTimer = -1
local frameDelayFunc = nil
local debugLines = {}
local _log = log
local function log(level, message)
_log(level, logTag, message)
end
local function checkMessage()
local message, err = rcom.readMessage(clients)
if err ~= nil then
skt = nil
clients = {}
conSleep = 5
return false
end
if message ~= nil then
local msgType = message['type']
if msgType ~= nil then
msgType = 'handle' .. msgType
local handler = M[msgType]
if handler ~= nil then
return handler(message)
else
extensions.hook('onSocketMessage', skt, message)
return true
end
else
return true
end
else
return false
end
end
local function connect()
log('I', 'Trying to connect to: ' .. host .. ':' .. tostring(port))
skt = socket.connect(host, port)
if skt ~= nil then
log('I', 'Connected!')
table.insert(clients, skt)
local hello = {type = 'Hello', version = version}
rcom.sendMessage(skt, hello)
else
log('I', 'Could not connect...')
end
end
M.onPreRender = function(dt)
if skt == nil then
if conSleep <= 0 then
conSleep = 5
connect()
else
conSleep = conSleep - dt
end
return
end
if frameDelayTimer > 0 then
frameDelayTimer = frameDelayTimer - 1
if frameDelayTimer == 0 then
frameDelayFunc()
frameDelayFunc = nil
frameDelayTimer = 0
end
end
if stepsLeft > 0 then
stepsLeft = stepsLeft - 1
if stepsLeft == 0 and stepACK then
rcom.sendACK(skt, 'Stepped')
end
end
if waitingForMainMenu then
if next(core_gamestate.state) == nil then
rcom.sendACK(skt, 'ScenarioStopped')
waitingForMainMenu = false
end
end
if stepsLeft == 0 then
while checkMessage() do end
end
end
M.onScenarioUIReady = function(state)
if state == 'start' and loadRequested and loadNotified == false then
rcom.sendACK(skt, 'MapLoaded')
loadNotified = true
loadRequested = false
end
end
M.onCountdownEnded = function()
if startRequested then
rcom.sendACK(skt, 'ScenarioStarted')
loadNotified = false
startRequested = false
end
end
M.onScenarioRestarted = function()
if restartRequested then
M.handleStartScenario(nil)
rcom.sendACK(skt, 'ScenarioRestarted')
restartRequested = false
end
end
M.onInit = function()
log("E", "researchGE", "onINIT")
local cmdArgs = Engine.getStartingArgs()
for i, v in ipairs(cmdArgs) do
if v == "-rport" then
port = tonumber(cmdArgs[i + 1])
end
if v == "-rhost" then
host = cmdArgs[i + 1]
end
end
settings.setValue('uiUnits', 'metric')
settings.setValue('uiUnitLength', 'metric')
settings.setValue('uiUnitTemperature', 'c')
settings.setValue('uiUnitWeight', 'kg')
settings.setValue('uiUnitTorque', 'metric')
settings.setValue('uiUnitConsumptionRate', 'metric')
settings.setValue('uiUnitEnergy', 'metric')
settings.setValue('uiUnitDate', 'iso')
settings.setValue('uiUnitPower', 'hp')
settings.setValue('uiUnitVolume', 'l')
settings.setValue('uiUnitPressure', 'bar')
extensions.load('util/partAnnotations')
end
-- Handlers
M.handleLoadScenario = function(msg)
local scenarioPath = msg["path"]
local ret = scenariosLoader.startByPath(scenarioPath)
log('I', 'Loading scenario: '..scenarioPath)
if ret then
log('I', 'Scenario found...')
loadRequested = true
else
log('I', 'Scenario not found...')
rcom.sendBNGValueError(skt, 'Scenario not found: "' .. scenarioPath .. '"')
end
return false
end
M.handleStartScenario = function(msg)
scenario_scenarios.changeState("running")
scenario_scenarios.getScenario().showCountdown = false
scenario_scenarios.getScenario().countDownTime = 0
guihooks.trigger("ChangeState", "menu")
startRequested = true
return true
end
M.handleRestartScenario = function(msg)
scenario_scenarios.restartScenario()
restartRequested = true
return false
end
M.handleStopScenario = function(msg)
returnToMainMenu()
waitingForMainMenu = true
return false
end
M.handleGetScenarioName = function(msg)
local name = scenario_scenarios.getscenarioName()
local resp = {type = 'ScenarioName', name = name}
rcom.sendMessage(skt, resp)
end
M.handleHideHUD = function(msg)
be:executeJS('document.body.style.opacity = "0.0";')
return true
end
M.handleShowHUD = function(msg)
be:executeJS('document.body.style.opacity = "1.0";')
return true
end
M.handleSetPhysicsDeterministic = function(msg)
be:setPhysicsSpeedFactor(-1)
rcom.sendACK(skt, 'SetPhysicsDeterministic')
return true
end
M.handleSetPhysicsNonDeterministic = function(msg)
be:setPhysicsSpeedFactor(0)
rcom.sendACK(skt, 'SetPhysicsNonDeterministic')
return true
end
M.handleFPSLimit = function(msg)
settings.setValue('FPSLimiter', msg['fps'], true)
settings.setState({FPSLimiterEnabled = true}, true)
rcom.sendACK(skt, 'SetFPSLimit')
return true
end
M.handleRemoveFPSLimit = function(msg)
settings.setState({FPSLimiterEnabled = false}, true)
rcom.sendACK(skt, 'RemovedFPSLimit')
return true
end
M.handlePause = function(msg)
be:setPhysicsRunning(false)
rcom.sendACK(skt, 'Paused')
return true
end
M.handleResume = function(msg)
be:setPhysicsRunning(true)
rcom.sendACK(skt, 'Resumed')
return true
end
M.handleStep = function(msg)
local count = msg["count"]
be:physicsStep(count)
stepsLeft = count
stepACK = msg["ack"]
return true
end
M.handleTeleport = function(msg)
local vID = msg['vehicle']
local veh = scenarioHelper.getVehicleByName(vID)
if msg['rot'] ~= nil then
local quat = quat(msg['rot'][1], msg['rot'][2], msg['rot'][3], msg['rot'][4])
veh:setPositionRotation(msg['pos'][1], msg['pos'][2], msg['pos'][3], quat.x, quat.y, quat.z, quat.w)
else
veh:setPosition(Point3F(msg['pos'][1], msg['pos'][2], msg['pos'][3]))
end
rcom.sendACK(skt, 'Teleported')
return true
end
M.handleTeleportScenarioObject = function(msg)
local sobj = scenetree.findObject(msg['id'])
if msg['rot'] ~= nil then
local quat = quat(msg['rot'][1], msg['rot'][2], msg['rot'][3], msg['rot'][4])
sobj:setPosRot(msg['pos'][1], msg['pos'][2], msg['pos'][3], quat.x, quat.y, quat.z, quat.w)
else
sobj:setPosition(Point3F(msg['pos'][1], msg['pos'][2], msg['pos'][3]))
end
rcom.sendACK(skt, 'ScenarioObjectTeleported')
return true
end
M.handleVehicleConnection = function(msg)
local vID, vHost, vPort, veh, command
vID = msg['vid']
vHost = msg['host']
vPort = msg['port']
command = 'extensions.load("researchVE")'
veh = scenarioHelper.getVehicleByName(vID)
veh:queueLuaCommand(command)
local exts = msg['exts']
if exts then
for idx, ext in pairs(exts) do
command = 'extensions.load("' .. ext .. '")'
veh:queueLuaCommand(command)
end
end
command = 'researchVE.startConnecting("' .. vHost .. '", '
command = command .. tostring(vPort) .. ')'
veh:queueLuaCommand(command)
return true
end
M.handleOpenShmem = function(msg)
local name = msg['name']
local size = msg['size']
Engine.openShmem(name, size)
rcom.sendACK(skt, 'OpenedShmem')
return true
end
M.handleCloseShmem = function(msg)
local name = msg['name']
Engine.closeShmem(name)
rcom.sendACK(skt, 'ClosedShmem')
return true
end
M.handleWaitForSpawn = function(msg)
local name = msg['name']
spawnPending = name
return true
end
M.onVehicleSpawned = function(vID)
if spawnPending ~= nil then
local obj = scenetree.findObject(spawnPending)
log('I', 'Vehicle spawned: ' .. tostring(vID))
if obj ~= nil and obj:getID() == vID then
local resp = {type = 'VehicleSpawned', name = spawnPending}
spawnPending = nil
rcom.sendMessage(skt, resp)
end
end
end
M.handleSpawnVehicle = function(msg)
local name = msg['name']
local model = msg['model']
local pos = msg['pos']
local rot = msg['rot']
local cling = msg['cling']
pos = vec3(pos[1], pos[2], pos[3])
rot = quat(rot)
local partConfig = msg['partConfig']
local options = {}
options.config = partConfig
options.pos = pos
options.rot = rot
options.cling = cling
options.vehicleName = name
options.color = msg['color']
options.color2 = msg['color2']
options.color3 = msg['color3']
options.licenseText = msg['licenseText']
spawnPending = name
core_vehicles.spawnNewVehicle(model, options)
end
M.handleDespawnVehicle = function(msg)
local name = msg['vid']
local veh = scenetree.findObject(name)
if veh ~= nil then
veh:delete()
end
rcom.sendACK(skt, 'VehicleDespawned')
end
sensors.Camera = function(req, callback)
local offset, orientation, up
local pos, direction, rot, fov, resolution, nearFar, vehicle, vehicleObj, data
local color, depth, annotation
color = req['color']
depth = req['depth']
annotation = req['annotation']
if req['vehicle'] then
vehicle = scenarioHelper.getVehicleByName(req['vehicle'])
orientation = vec3(vehicle:getDirectionVector())
up = vec3(vehicle:getDirectionVectorUp())
orientation = quatFromDir(orientation, up)
--log("E", "orientation=" .. tostring(orientation))
offset = vec3(vehicle:getPosition())
else
orientation = quatFromEuler(0, 0, 0)
offset = vec3(0, 0, 0)
end
direction = req['direction']
direction = vec3(direction[1], direction[2], direction[3])
fov = math.rad(req['fov'])
resolution = req['resolution']
nearFar = req['near_far']
rot = quatFromDir(direction, vec3(0, 0, 1)) * orientation
pos = req['pos']
pos = vec3(pos[1], pos[2], pos[3])
if req['vehicle'] then
--log("E", "pos=" .. tostring(pos))
pos = offset + orientation * pos
--log("E", "offset + orientation * pos=" .. tostring(offset + orientation * pos))
--log("E", "orientation * pos = " .. tostring(orientation * pos))
--log("E", "offset+orientation=" .. tostring(offset+orientation))
else
pos = offset + pos
end
pos = Point3F(pos.x, pos.y, pos.z)
rot = QuatF(rot.x, rot.y, rot.z, rot.w)
-- meriel added
--log("E", "CAMERA POSITION in sensors.Camera :" .. tostring(pos) .. " ROT:" .. tostring(rot))
--log("E", "CAMERA RPY?: " .. tostring(core_camera.getRollPitchYaw()))
--log("I", "CAMERA POSITION in sensors.Camera :" .. tostring(obj:getCameraDataById(vid)))
--for index, data in ipairs(core_camera.getCameraDataById(vid)) do
-- log("I", tostring(index))
--end
resolution = Point2F(resolution[1], resolution[2])
nearFar = Point2F(nearFar[1], nearFar[2])
local data = Engine.renderCameraShmem(color, depth, annotation, pos, rot, resolution, fov, nearFar)
data['pos'] = tostring(pos)
data['rot'] = tostring(rot)
--for index, d in ipairs(data) do
-- log("I", tostring(index) .. " data:" .. tostring(d))
--end
callback(data)
end
sensors.Lidar = function(req, callback)
local name = req['name']
local lidar = lidars[name]
if lidar ~= nil then
lidar:requestDataShmem(function(realSize)
callback({size = realSize})
end)
else
callback(nil)
end
end
sensors.Timer = function(req, callback)
callback({time = scenario_scenarios.getScenario().timer})
end
local function getSensorData(request, callback)
local response, sensor_type, handler
-- meriel added
--log("E", "in researchGE, getSensorData(" .. tostring(request) .. ")")
--for index, data in pairs(request) do
-- log("I", " index:" .. tostring(index) .. " data:" .. tostring(data))
--end
sensor_type = request['type']
handler = sensors[sensor_type]
if handler ~= nil then
handler(request, callback)
else
callback(nil)
end
end
local function getNextSensorData(requests, response, callback)
local key = next(requests)
if key == nil then
callback(response)
return
end
local request = requests[key]
requests[key] = nil
local cb = function(data)
response[key] = data
getNextSensorData(requests, response, callback)
end
getSensorData(request, cb)
end
M.handleSensorRequest = function(msg)
local requests
local cb = function(response)
response = {type = 'SensorData', data = response}
rcom.sendMessage(skt, response)
end
requests = msg['sensors']
getNextSensorData(requests, {}, cb)
return true
end
M.handleGetDecalRoadVertices = function(msg)
local response = Sim.getDecalRoadVertices()
response = {type = "DecalRoadVertices", vertices = response}
rcom.sendMessage(skt, response)
return true
end
M.handleGetDecalRoadData = function(msg)
local resp = {type = 'DecalRoadData'}
local data = {}
local roads = scenetree.findClassObjects('DecalRoad')
for idx, roadID in ipairs(roads) do
local road = scenetree.findObject(roadID)
local roadData = {
drivability = road:getField('drivability', ''),
lanesLeft = road:getField('lanesLeft', ''),
lanesRight = road:getField('lanesRight', ''),
oneWay = road:getField('oneWay', '') ~= nil,
flipDirection = road:getField('flipDirection', '') ~= nil
}
data[roadID] = roadData
end
resp['data'] = data
rcom.sendMessage(skt, resp)
return true
end
M.handleGetDecalRoadEdges = function(msg)
local roadID = msg['road']
local response = {type = 'DecalRoadEdges'}
local road = scenetree.findObject(roadID)
local edges = {}
for i, e in ipairs(road:getEdgesTable()) do
local edge = {
left = {
e[1].x,
e[1].y,
e[1].z
},
middle = {
e[2].x,
e[2].y,
e[2].z
},
right = {
e[3].x,
e[3].y,
e[3].z
}
}
table.insert(edges, edge)
end
response['edges'] = edges
rcom.sendMessage(skt, response)
return true
end
M.handleEngineFlags = function(msg)
log('I', 'Setting engine flags!')
local flags = msg['flags']
if flags['annotations'] then
Engine.Annotation.enable(true)
end
rcom.sendACK(skt, 'SetEngineFlags')
return true
end
M.handleTimeOfDayChange = function(msg)
core_environment.setTimeOfDay({time = msg['tod']})
rcom.sendACK(skt, 'TimeOfDayChanged')
end
local function getVehicleState(vid)
local vehicle = scenetree.findObject(vid)
local state = {
pos = vehicle:getPosition(),
dir = vehicle:getDirectionVector(),
up = vehicle:getDirectionVectorUp(),
vel = vehicle:getVelocity()
}
state['pos'] = {
state['pos'].x,
state['pos'].y,
state['pos'].z
}
state['dir'] = {
state['dir'].x,
state['dir'].y,
state['dir'].z
}
state['up'] = {
state['up'].x,
state['up'].y,
state['up'].z
}
state['vel'] = {
state['vel'].x,
state['vel'].y,
state['vel'].z
}
return state
end
M.handleUpdateScenario = function(msg)
-- log("E", "handleUpdateScenario", "sending message to get scenario state (i.e. state of all vehicles)")
local response = {type = 'ScenarioUpdate'}
local vehicleStates = {}
for idx, vid in ipairs(msg['vehicles']) do
vehicleStates[vid] = getVehicleState(vid)
end
response['vehicles'] = vehicleStates
rcom.sendMessage(skt, response)
return true
end
M.handleOpenLidar = function(msg)
log('I', 'Opening lidar!')
local name = msg['name']
local shmem = msg['shmem']
local shmemSize = msg['size']
local vid = msg['vid']
local vid = scenetree.findObject(vid):getID()
local vRes = msg['vRes']
local vAngle = math.rad(msg['vAngle'])
local rps = msg['rps']
local hz = msg['hz']
local angle = math.rad(msg['angle'])
local maxDist = msg['maxDist']
local offset = msg['offset']
offset = Point3F(offset[1], offset[2], offset[3])
local direction = msg['direction']
direction = Point3F(direction[1], direction[2], direction[3])
local lidar = research.LIDAR(vid, offset, direction, vRes, vAngle, rps, hz, angle, maxDist)
lidar:open(shmem, shmemSize)
lidar:enabled(true)
if msg['visualized'] then
log('I', 'Visualizing lidar!')
lidar:visualized(true)
else
log('I', 'Not visualizing lidar!')
lidar:visualized(false)
end
lidars[name] = lidar
rcom.sendACK(skt, 'OpenedLidar')
return true
end
M.handleCloseLidar = function(msg)
local name = msg['name']
local lidar = lidars[name]
if lidar ~= nil then
-- lidar:close()
lidars[name] = nil
end
rcom.sendACK(skt, 'ClosedLidar')
return true
end
M.handleSetWeatherPreset = function(msg)
local preset = msg['preset']
local time = msg['time']
core_weather.switchWeather(preset, time)
rcom.sendACK(skt, 'WeatherPresetChanged')
end
M.handleGameStateRequest = function(msg)
local state = core_gamestate.state.state
resp = {type = 'GameState'}
if state == 'scenario' then
resp['state'] = 'scenario'
resp['scenario_state'] = scenario_scenarios.getScenario().state
else
resp['state'] = 'menu'
end
rcom.sendMessage(skt, resp)
return true
end
M.handleDisplayGuiMessage = function(msg)
local message = msg['message']
guihooks.message(message)
rcom.sendACK(skt, 'GuiMessageDisplayed')
end
M.handleSwitchVehicle = function(msg)
local vID = msg['vid']
local vehicle = scenetree.findObject(vID)
be:enterVehicle(0, vehicle)
rcom.sendACK(skt, 'VehicleSwitched')
end
M.handleSetFreeCamera = function(msg)
local pos = msg['pos']
local direction = msg['dir']
local rot = quatFromDir(vec3(direction[1], direction[2], direction[3]))
commands.setFreeCamera()
commands.setCameraPosRot(pos[1], pos[2], pos[3], rot.x, rot.y, rot.z, rot.w)
rcom.sendACK(skt, 'FreeCameraSet')
return true
end
M.handleParticlesEnabled = function(msg)
local enabled = msg['enabled']
Engine.Render.ParticleMgr.setEnabled(enabled)
rcom.sendACK(skt, 'ParticlesSet')
end
M.handleAnnotateParts = function(msg)
local vehicle = scenetree.findObject(msg['vid'])
util_partAnnotations.annotateParts(vehicle:getID())
rcom.sendACK(skt, 'PartsAnnotated')
end
M.handleRevertAnnotations = function(msg)
print('Handling annotation reversion')
local vehicle = scenetree.findObject(msg['vid'])
util_partAnnotations.revertAnnotations(vehicle:getID())
rcom.sendACK(skt, 'AnnotationsReverted')
end
M.handleGetPartAnnotations = function(msg)
local vehicle = scenetree.findObject(msg['vid'])
local colors = util_partAnnotations.getPartAnnotations(vehicle:getID())
local converted = {}
for key, val in pairs(colors) do
converted[key] = {val.r, val.g, val.b}
end
rcom.sendMessage(skt, {type = 'PartAnnotations', colors = converted})
end
M.handleGetPartAnnotation = function(msg)
local part = msg['part']
local color = util_partAnnotations.getPartAnnotation(part)
if color ~= nil then
color = {color.r, color.g, color.b}
end
rcom.sendMessage(skt, {type = 'PartAnnotation', color = color})
end
M.handleFindObjectsClass = function(msg)
local clazz = msg['class']
local objects = scenetree.findClassObjects(clazz)
local resp = {type='ClassObjects'}
local list = {}
for idx, object in ipairs(objects) do
object = scenetree.findObject(object)
local obj = {type=clazz, id=object:getID(), name=object:getName()}
local scl = object:getScale()
local pos = object:getPosition()
local rot = object:getRotation()
if clazz == 'BeamNGVehicle' then
local vehicleData = map.objects[obj.id]
rot = quatFromDir(vehicleData.dirVec, vehicleData.dirVecUp)
end
pos = {pos.x, pos.y, pos.z}
rot ={rot.x, rot.y, rot.z, rot.w}
scl = {scl.x, scl.y, scl.z}
obj['position'] = pos
obj['rotation'] = rot
obj['scale'] = scl
obj['options'] = {}
for fld, nfo in pairs(object:getFieldList()) do
if fld ~= 'position' and fld ~= 'rotation' and fld ~= 'scale' and fld ~= 'id' and fld ~= 'type' and fld ~= 'name' then
local val = object:getField(fld, '')
obj['options'][fld] = val
end
end
table.insert(list, obj)
end
resp['objects'] = list
rcom.sendMessage(skt, resp)
end
M.handleGetDecalRoadVertices = function(msg)
local response = Sim.getDecalRoadVertices()
response = {type = "DecalRoadVertices", vertices = response}
rcom.sendMessage(skt, response)
return true
end
local function placeObject(name, mesh, pos, rot)
if name == nil then
name = 'procObj' .. tostring(objectCount)
objectCount = objectCount + 1
end
pos = vec3(pos)
rot = quat(rot):toTorqueQuat()
local proc = createObject('ProceduralMesh')
proc:registerObject(name)
proc.canSave = false
scenetree.MissionGroup:add(proc.obj)
proc:createMesh({{mesh}})
proc:setPosition(pos:toPoint3F())
proc:setField('rotation', 0, rot.x .. ' ' .. rot.y .. ' ' .. rot.z .. ' ' .. rot.w)
proc.scale = Point3F(1, 1, 1)
be:reloadCollision()
return proc
end
M.handleCreateCylinder = function(msg)
local name = msg['name']
local radius = msg['radius']
local height = msg['height']
local material = msg['material']
local pos = msg['pos']
local rot = msg['rot']
local cylinder = procPrimitives.createCylinder(radius, height, material)
placeObject(name, cylinder, pos, rot)
rcom.sendACK(skt, 'CreatedCylinder')
end
M.handleCreateBump = function(msg)
local name = msg['name']
local length = msg['length']
local width = msg['width']
local height = msg['height']
local upperLength = msg['upperLength']
local upperWidth = msg['upperWidth']
local material = msg['material']
local pos = msg['pos']
local rot = msg['rot']
local bump = procPrimitives.createBump(length, width, height, upperLength, upperWidth, material)
placeObject(name, bump, pos, rot)
rcom.sendACK(skt, 'CreatedBump')
end
M.handleCreateCone = function(msg)
local name = msg['name']
local radius = msg['radius']
local height = msg['height']
local material = msg['material']
local pos = msg['pos']
local rot = msg['rot']
local cone = procPrimitives.createCone(radius, height, material)
placeObject(name, cone, pos, rot)
rcom.sendACK(skt, 'CreatedCone')
end
M.handleCreateCube = function(msg)
local name = msg['name']
local size = vec3(msg['size'])
local material = msg['material']
local pos = msg['pos']
local rot = msg['rot']
local cube = procPrimitives.createCube(size, material)
placeObject(name, cube, pos, rot)
rcom.sendACK(skt, 'CreatedCube')
end
M.handleCreateRing = function(msg)
local name = msg['name']
local radius = msg['radius']
local thickness = msg['thickness']
local material = msg['material']
local pos = msg['pos']
local rot = msg['rot']
local ring = procPrimitives.createRing(radius, thickness, material)
placeObject(name, ring, pos, rot)
rcom.sendACK(skt, 'CreatedRing')
end
M.handleGetBBoxCorners = function(msg)
local veh = scenetree.findObject(msg['vid'])
local resp = {type = 'BBoxCorners'}
local points = {}
local bbox = veh:getSpawnWorldOOBB()
for i = 0, 7 do
local point = bbox:getPoint(i)
point = {tonumber(point.x), tonumber(point.y), tonumber(point.z)}
table.insert(points, point)
end
resp['points'] = points
rcom.sendMessage(skt, resp)
end
M.handleSetGravity = function(msg)
local gravity = msg['gravity']
core_environment.setGravity(gravity)
rcom.sendACK(skt, 'GravitySet')
end
M.handleGetAvailableVehicles = function(msg)
local resp = {type = 'AvailableVehicles', vehicles = {}}
local models = core_vehicles.getModelList().models
local configs = core_vehicles.getConfigList().configs
for model, modelData in pairs(models) do
local data = deepcopy(modelData)
data.configurations = {}
for key, config in pairs(configs) do
if config.model_key == model then
data.configurations[config.key] = config
end
end
resp.vehicles[model] = data
end
rcom.sendMessage(skt, resp)
end
M.handleStartTraffic = function(msg)
local participants = msg.participants
local ids = {}
for idx, participant in ipairs(participants) do
local veh = scenetree.findObject(participant)
if veh == nil then
rcom.sendBNGValueError(skt, 'Vehicle not present for traffic: ' .. tostring(participant))
return false
end
table.insert(ids, veh:getID())
end
gameplay_traffic.activate(ids)
rcom.sendACK(skt, 'TrafficStarted')
end
M.handleStopTraffic = function(msg)
local stop = msg.stop
gameplay_traffic.deactivate(stop)
rcom.sendACK(skt, 'TrafficStopped')
end
M.handleChangeSetting = function(msg)
local key = msg['key']
local value = msg['value']
settings.setValue(key, value, true)
rcom.sendACK(skt, 'SettingsChanged')
end
M.handleApplyGraphicsSetting = function(msg)
core_settings_graphic.applyGraphicsState()
rcom.sendACK(skt, 'GraphicsSettingApplied')
end
M.handleSetRelativeCam = function(msg)
core_camera.setByName(0, 'relative', false, {})
local vid = be:getPlayerVehicle(0):getID()
local pos = msg['pos']
local rot = msg['rot']
frameDelayTimer = 3
frameDelayFunc = function()
pos = vec3(pos[1], pos[2], pos[3])
core_camera.getCameraDataById(vid)['relative'].pos = pos
if rot ~= nil then
rot = quat(rot[1], rot[2], rot[3], rot[4]):toEulerYXZ()
core_camera.getCameraDataById(vid)['relative'].rot = rot
end
-- meriel added
log("I", "CAMERA POSITION in M.handleSetRelativeCam:" .. tostring(core_camera.getCameraDataById(vid)))
for index, data in ipairs(core_camera.getCameraDataById(vid)) do
log("I", tostring(index))
--for key, value in pairs(data) do
-- log('I', '\t' .. tostring(key) .. " " .. tostring(value))
--end
end
rcom.sendACK(skt, 'RelativeCamSet')
end
end
M.handleAddDebugLine = function(msg)
local points = msg['points']
local pointColors = msg['pointColors']
local spheres = msg['spheres']
local sphereColors = msg['sphereColors']
local cling = msg['cling'] or false
local groundOffset = msg['offset'] or 0
if #points ~= #pointColors then
rcom.sendBNGValueError(skt, 'Different amount of debug line points and colors given!')
return
end
if spheres ~= nil and sphereColors ~= nil then
if #spheres ~= #sphereColors then
rcom.sendBNGValueError(skt, 'Different amount of debug spheres and colors given!')
return
end
end
local convertedPoints = {}
local convertedPointColors = {}
for i = 1, #points do
local point = points[i]
local color = pointColors[i]
point = Point3F(point[1], point[2], point[3])
if cling then
local height = be:getSurfaceHeightBelow(point)
point = Point3F(point.x, point.y, height + groundOffset)
end
table.insert(convertedPoints, point)
table.insert(convertedPointColors, ColorF(color[1], color[2], color[3], color[4]))
end
local line = {
points = convertedPoints,
pointColors = convertedPointColors
}
if spheres ~= nil then
local convertedSpheres = {}
local convertedSphereColors = {}
for i = 1, #spheres do
local point = spheres[i]
local color = sphereColors[i]
point = Point3F(point[1], point[2], point[3])
if cling then
point.z = 10000
local height = be:getSurfaceHeightBelow(point)
point = Point3F(point.x, point.y, height + groundOffset)
end
table.insert(convertedSpheres, { point = point, radius = spheres[i][4] })
table.insert(convertedSphereColors, ColorF(color[1], color[2], color[3], color[4]))
end
line.spheres = convertedSpheres
line.sphereColors = convertedSphereColors
end
table.insert(debugLines, line)
local resp = {type = 'DebugLineAdded', lineID = #debugLines}
rcom.sendMessage(skt, resp)
end
M.handleRemoveDebugLine = function(msg)
local lineID = msg['lineID']
debugLines[lineID] = {}
rcom.sendACK(skg, 'DebugLineRemoved')
end
M.onDrawDebug = function(dtReal, lastFocus)
for i = 1, #debugLines do
local line = debugLines[i]
if line.spheres ~= nil then
for j = 1, #line.spheres do
local point = line.spheres[j].point
local radius = line.spheres[j].radius
local color = line.sphereColors[j]
debugDrawer:drawSphere(point, radius, color)
end
end
for j = 1, #line.points - 1 do
local a = line.points[j]
local b = line.points[j + 1]
debugDrawer:drawLine(a, b, line.pointColors[j + 1])
end
end
end
M.handleQueueLuaCommandGE = function(msg)
local func, loading_err = load(msg.chunk)
if func then
local status, err = pcall(func)
if not status then
log('E', 'execution error: "' .. err .. '"')
end
else
log('E', 'compilation error in: "' .. msg.chunk .. '"')
end
rcom.sendACK(skt, 'ExecutedLuaChunkGE')
end
return M
|
local M = {}
local cjson = require "cjson"
function M.split(s, delimiter)
result = {};
for match in (s..delimiter):gmatch("(.-)"..delimiter) do
table.insert(result, match);
end
return result;
end
function M.startswith(s, value)
return string.sub(s, 1, string.len(value)) == value
end
function M.has_at_least_one(s, array)
for _, item in pairs(array) do
if M.startswith(s, item) then
return true
end
end
return false
end
function M.random(template)
math.randomseed(os.clock()+os.time())
local rnd = math.random
local function randid()
return string.gsub(template, '[xy]', function (c)
local v = (c == 'x') and rnd(0, 0xf) or rnd(8, 0xb)
return string.format('%x', v)
end)
end
return randid()
end
function M.is_valid_url(url)
if url == nill or url == "" then
return false
end
local i, _ = string.find(url, "://", 1, true)
return i ~= nill
end
function M.to_json(content)
return cjson.encode(content)
end
function M.from_json(content)
return cjson.decode(content)
end
return M
|
--[[
Lua 5.1 Copyright (C) 1994-2006 Lua.org, PUC-Rio
]]
local Http = require ("contrib/http");
local Sql = require ("contrib/sql");
local Session = require ("contrib/session");
local pgmoon = require("pgmoon");
local db = pgmoon.new(Sql.Conf);
assert(db:connect());
local Pass = Session.LoginRequired ();
if not Pass then
Http.Response ({Result = 0, Error = "Login required"});
return;
end
local Method = Http.Request ("Method");
--CheckCode
if Method == "CheckCode" then
local Code = Http.Request ("Code");
local Q = Sql.Query;
Q:New ([[SELECT "Name" FROM "Accounting"."Account" WHERE "Code"=?;]]);
Q:SetString (Code);
local R = db:query (Q.Stm);
Http.Response (R);
return;
end
--NextNumber
if Method == "NextNumber" then
local Q = Sql.Query;
Q:New ([[SELECT "Number" FROM "Accounting"."Note" ORDER BY "Number" DESC LIMIT 1;]]);
local R = db:query (Q.Stm);
Http.Response (R);
return;
end
--AutoFill
if Method == "AutoFill" then
local Number = Http.Request ("Number");
local Q = Sql.Query;
Q:New ([[SELECT "Number", "Date", "Concept", "Code", "Name", "Partial", "Debit", "Credit" FROM "Accounting"."NoteAll" WHERE "Number"=?;]]);
Q:SetNumber (Number);
local R = db:query (Q.Stm);
Http.Response (R);
return;
end
--Insert
if Method == "Insert" then
local Number = Http.Request ("Number");
local Date = Http.Request ("Date");
local Concept = Http.Request ("Concept");
local R, Err = db:query ("BEGIN;");
local Q = Sql.Query;
Q:New ([[INSERT INTO "Accounting"."Note"("Number", "Date", "Concept") VALUES(?, ?, ?);]]);
Q:SetNumber (Number);
Q:SetString (Date);
Q:SetString (Concept);
local R, Err = db:query (Q.Stm);
if not R then
Http.Response ({Error = Err});
db:query ("ROLLBACK;");
return;
end
local Records = Http.Request ("Records");
for i, o in pairs(Records) do
Q:New ([[INSERT INTO "Accounting"."NoteRecord"("NoteId", "AccountId", "Debit", "Credit")
SELECT "Accounting"."Note"."Id", "Accounting"."Account"."Id", ?, ? FROM "Accounting"."Note" INNER JOIN "Accounting"."Account" ON "Accounting"."Note"."Number"=? AND "Accounting"."Account"."Code"=?;]]);
Q:SetNumber (Records[i].Debit);
Q:SetNumber (Records[i].Credit);
Q:SetNumber (Records[i].Number);
Q:SetString (Records[i].Code);
R, Err = db:query (Q.Stm);
if not R then
Http.Response ({Error = Err});
db:query ("ROLLBACK;");
return;
end
end
R = db:query ("COMMIT;");
Http.Response ({affected_rows=1});
return;
end
--ngx.log(ngx.ERR, Q.Stm);
--Update
if Method == "Update" then
local Number = Http.Request ("Number");
local Date = Http.Request ("Date");
local Concept = Http.Request ("Concept");
local Q = Sql.Query;
Q:New ([[UPDATE "Accounting"."Note" SET "Date"=?, "Concept"=? WHERE "Number"=?;]]);
Q:SetString (Date);
Q:SetString (Concept);
Q:SetNumber (Number);
local R, Err = db:query ("BEGIN;");
R, Err = db:query (Q.Stm);
if not R then
Http.Response ({Error = "Error en update"});
db:query ("ROLLBACK;");
return;
end
Q:New ([[DELETE FROM "Accounting"."NoteRecord" USING "Accounting"."Note" WHERE "NoteId"="Accounting"."Note"."Id" AND "Number"=?]]);
Q:SetNumber (Number);
R, Err = db:query (Q.Stm);
if not R then
Http.Response ({Error = "Error en delete records"});
db:query ("ROLLBACK;");
return;
end
local Records = Http.Request ("Records");
for i, o in pairs(Records) do
Q:New ([[INSERT INTO "Accounting"."NoteRecord"("NoteId", "AccountId", "Debit", "Credit")
SELECT "Accounting"."Note"."Id", "Accounting"."Account"."Id", ?, ? FROM "Accounting"."Note" INNER JOIN "Accounting"."Account" ON "Accounting"."Note"."Number"=? AND "Accounting"."Account"."Code"=?;]]);
Q:SetNumber (Records[i].Debit);
Q:SetNumber (Records[i].Credit);
Q:SetNumber (Records[i].Number);
Q:SetString (Records[i].Code);
R, Err = db:query (Q.Stm);
if not R then
Http.Response ({Error = "Error en records, rollback"});
db:query ("ROLLBACK;");
return;
end
end
R = db:query ("COMMIT;");
Http.Response ({affected_rows=1});
return;
end
--Delete
if Method == "Delete" then
local Number = Http.Request ("Number");
local Q = Sql.Query;
Q:New ([[DELETE FROM "Accounting"."Note" WHERE "Number"=?;]]);
Q:SetNumber (Number);
local R = db:query (Q.Stm);
Http.Response (R);
return;
end
db:keepalive ();
|
require 'torch'
require 'image'
function save_images(x, n, file)
file = file or "./out.png"
local input = x:narrow(1, 1, n)
local view = image.toDisplayTensor({input = input,
padding = 2,
nrow = 9,
symmetric = true})
image.save(file, view)
end
return true |
-- model file
model_file = './obj/modern_tables.obj'
-- directory to save result
result_directory = './result_table/'
-- save result per frame
save_per_frame = 50
-- set true to enable view
view = true
-- set true to save image
save_image = true
-- result width
width = 600
-- result height
height = 400
-- result fov
fov = 50
-- model center offset, center = center + center_offset
center_offset = {-50, 20, 50}
-- camera eye offset, eye = center + eye_offset
eye_offset = {10, 30, 55}
-- camera up direction
up = {0, 1, 0}
-- max iteration depth for ray
max_depth = 5
-- scene ambient
scene_ambient = {0.2, 0.2, 0.2}
-- external light illumination
external_light_num = 0
|
include("shared.lua")
function ENT:Draw()
self:DrawModel()
end
function ENT:Think()
if self.IsSetup then return end
local class = self:GetBenchType()
if class then
local bench = impulse.Inventory.Benches[class]
if bench then
self.HUDName = bench.Name
self.HUDDesc = bench.Desc
self.IsSetup = true
end
end
end |
local condition = Condition(CONDITION_POISON, CONDITIONID_COMBAT)
condition:setParameter(CONDITION_PARAM_DELAYED, true)
condition:setParameter(CONDITION_PARAM_MINVALUE, 20)
condition:setParameter(CONDITION_PARAM_MAXVALUE, 70)
condition:setParameter(CONDITION_PARAM_STARTVALUE, 50)
condition:setParameter(CONDITION_PARAM_TICKINTERVAL, 6000)
condition:setParameter(CONDITION_PARAM_FORCEUPDATE, true)
function onStepIn(creature, item, position, fromPosition)
local player = creature:getPlayer()
if not player then
return true
end
player:getPosition():sendMagicEffect(CONST_ME_GREEN_RINGS)
player:addCondition(condition)
item:transform(417)
return true
end |
Script.Load("lua/PowerConsumerMixin.lua")
local networkVarsEx = {}
AddMixinNetworkVars(PowerConsumerMixin, networkVarsEx)
local ns2_Sentry_OnCreate = Sentry.OnCreate
function Sentry:OnCreate()
ns2_Sentry_OnCreate(self)
-- add the power consumer mixin so sentries work with power nodes
InitMixin(self, PowerConsumerMixin)
end
function Sentry:GetRequiresPower()
return true
end
function Sentry:OnPowerOn()
self.attachedToBattery = true
end
function Sentry:OnPowerOff()
self.attachedToBattery = false
end
Shared.LinkClassToMap("Sentry", Sentry.kMapName, networkVarsEx)
|
local ply = FindMetaTable("Player")
function ply:ClassLoad()
if(self:GetPData("Class") == nil) then
self:SetPData("Class", 1)
else
self:SetPData("Class", self:GetPData("Class"))
end
end
concommand.Add( "fwclass", function(ply, cmd, args)
if ply.ProfileLoadStatus == nil then
local class = tonumber(args[1])
local truncatedid = string.gsub(ply:SteamID(), ":", "_")
local classcost = Classes[class].COST
local classtbl = ply.classes
if !( table.HasValue(classtbl, class) ) then
if (ply.cash >= classcost) then
ply:TakeMoney(classcost)
ply:AddClass(class)
else
ply:ChatPrint("You do not have enough money to purchase this class!")
end
elseif ( table.HasValue(classtbl, class) ) then
if ply:Alive() then
ply:Kill()
end
ply:SetPData("Class", class )
end
end
end)
concommand.Add( "buyspecial", function(ply, cmd, args)
if ply.ProfileLoadStatus == nil then
local class = tonumber(args[1])
local truncatedid = string.gsub(ply:SteamID(), ":", "_")
local speccost = Classes[class].SPECIALABILITY_COST
local spectbl = ply.specials
if !( table.HasValue(spectbl, class) ) then
if (ply.cash >= speccost) then
ply:TakeMoney(speccost)
ply:AddSpecial(class)
else
ply:ChatPrint("You do not have enough money to purchase this special ability!")
end
elseif ( table.HasValue(spectbl, class) ) then
ply:ChatPrint("You already have this special ability!")
end
end
end) |
module_version("java/1.8.0-B","1.8")
|
local reject_func
async.promise(function(_, reject)
reject_func = reject
end)
reject_func("Test")
reject_func("Test") -- Will cause an error
|
--[[
FiveM Scripts
Copyright C 2018 Sighmir
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
at your option any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]
cfg = {}
-- ALL CREDITS FOR THE CSS GOES TO LEE FALL AND LEVY
-- you can load external images/fonts/etc using the NUI absolute path: nui://my_resource/myfont.ttf
cfg.menu = [[
/* ALL CREDITS FOR THE CSS GOES TO |LEVY| AND LEE FALL */
@font-face {
font-family: bankgothic;
src: url(nui://vrp_esx_phone/gui/font/bankgothic.ttf);
}
.menu{
background-image: url(nui://vrp_esx_phone/gui/img/red2.jpg); /*Change the phone wallpaper here. You can use 'grey.jpg' 'red.jpg' 'code.jpg' 'blue.jpg' or add you own in gui/img/--> [Make sure to resize the pic so that the hight is 401px!] */
font-family: bankgothic;
background-size: cover;
color: white;
width: 400px;
font-size: 9px;
text-align: center;
height: 55%;
margin-left: 3%;
margin-top: 2%;
position: absolute;
float: left;
border-style: solid;
border-width: 30px 9px 30px 9px;
border-image: url(nui://vrp_esx_phone/gui/img/menu.png) 30 9 30 9;
border-radius: 32px;
box-shadow: -1px -1px 60px -1px rgba(0,0,0,1);
}
.menu_description{
border-radius: 0px 0px 4px 4px;
box-shadow: inset -1px -1px 60px 0px rgba(0,0,0,1);
box-shadow: -1px -1px 60px 0px rgba(0,0,0,1);
background-color: rgba(0,0,0,0.5);
font-family: bankgothic;
color: white;
float: left;
position: absolute;
font-weight: bold;
padding: 9px;
font-size: 1.2em;
max-width: 500px;
}
.menu h1{
background-color: rgb(44, 189, 247);
font-family: bankgothic;
color: white;
text-transform: uppercase;
text-align: center;
font-size: 1.6em;
font-weight: bold;
padding: 6px;
border: 1px solid #000000;
box-shadow: inset -1px -1px 60px 0px rgba(0,0,0,1);
}
.choices{
overflow-y: scroll;
overflow-x: hidden;
max-height: 90%;
}
.choices::-webkit-scrollbar{
display: none;
}
.choices div{
padding: 8px;
border: 1px solid #000000;
font-size: 15px;
font-weight: bold;
}
/*
Blue------------------>"background-color: rgba(0, 182, 255,0.90);"
Grey------------------>"background-color: rgba(96, 92, 92,0.90);"
RED------------------> "background-color: rgba(175, 24, 24,0.90);"
Code------------------>"background-color: rgba(58, 160, 53,0.90);"
*/
.choices .selected{
background-color: rgba(0, 182, 255,0.90); /*<<<<<<<<<<<---------------Put it on this line!*/
color: black;
box-shadow: inset -1px 2px 19px 0px rgba(0,0,0,1);
}
]]
return cfg
|
dofilepath("data:leveldata/campaign/FX_Path/ai/turanic_hard.lua")
|
local M = {}
function M.eval(l)
return vim.api.nvim_eval(l)
end
return M
|
local appPath = "app.demo.JoeyChen"
local changePokerViewCtr = class("changePokerViewCtr",cc.load("boyaa").mvc.BoyaaCtr);
local changePokerView = require(appPath..".changePokerTest.changePokerView")
local PaixingUtil = import(".PaixingUtil")
function changePokerViewCtr:ctor(pokerfig)
self.cardList = {}
self:initView(pokerfig)
print("changePokerViewCtr");
end
-- 初始化ui
function changePokerViewCtr:initView(pokerfig)
local changePokerView = changePokerView.new();
changePokerView:bindCtr(self);
changePokerView:addPoker(pokerfig);
changePokerView:setAnchorPoint(0.5,0.5)
changePokerView:move(0,0);
self:setView(changePokerView)
end
-- 接收view发来的换牌数据
function changePokerViewCtr:receiveCardListInfo(cardListInfo, isOver)
-- 通知view做相应的UI处理
self.cardList = cardListInfo
local cardTypeInfo = self:checkCardType()
self.view:changeUIByCardType(cardTypeInfo)
-- 将数据发送给后端
-- @cardListInfo 换牌数据
-- @isOver 换牌流程是否结束
-- 结束流程
if isOver then
self.view:cleanAll()
end
end
-- 判断换牌区域分别拥有的牌型
function changePokerViewCtr:checkCardType()
local cardTypeInfo = {list = {[1] = {name = "顺子",card = {},result = true}},all = {}}
for row ,rowCardDataList in ipairs(self.cardList) do
local judgeData = PaixingUtil:checkPaixing(rowCardDataList)
if judgeData.result then
cardTypeInfo.list[row] = judgeData
end
end
PaixingUtil:checkPaixingSort(cardTypeInfo.list)
dump(cardTypeInfo,"chao")
return cardTypeInfo
end
return changePokerViewCtr; |
Test = require('connecttest')
require('cardinalities')
local events = require('events')
local mobile_session = require('mobile_session')
local mobile = require('mobile_connection')
local tcp = require('tcp_connection')
local file_connection = require('file_connection')
---------------------------------------------------------------------------------------------
-----------------------------Required Shared Libraries---------------------------------------
---------------------------------------------------------------------------------------------
require('user_modules/AppTypes')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonTestCases = require('user_modules/shared_testcases/commonTestCases')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
APIName = "UnsubscribeWayPoints" -- use for above required scripts.
---------------------------------------------------------------------------------------------
-------------------------------------------Preconditions-------------------------------------
---------------------------------------------------------------------------------------------
--1. Backup smartDeviceLink.ini file
commonPreconditions:BackupFile("smartDeviceLink.ini")
--2. Update smartDeviceLink.ini file: PendingRequestsAmount = 3
commonFunctions:SetValuesInIniFile_PendingRequestsAmount(3)
--3. Activation App by sending SDL.ActivateApp
commonSteps:ActivationApp()
--ToDo: This TC is blocked on ATF 2.2 by defect APPLINK-19188. Please try ATF on commit f86f26112e660914b3836c8d79002e50c7219f29
--local PTName = testCasesForPolicyTable:createPolicyTableFile(PermissionLinesForBase4, PermissionLinesForGroup1, PermissionLinesForApplication)
--ToDo: Update when new policy table update flow finishes implementation
-- testCasesForPolicyTable:updatePolicy(PTName)
--local PTName = "files/ptu_general.json"
--testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt(PTName)
function Test:backUpPreloadedPt()
-- body
os.execute('cp ' .. config.pathToSDL .. 'sdl_preloaded_pt.json' .. ' ' .. config.pathToSDL .. 'backup_sdl_preloaded_pt.json')
os.execute('rm ' .. config.pathToSDL .. 'policy.sqlite')
end
Test:backUpPreloadedPt()
function Test:updatePreloadedJson()
-- body
pathToFile = config.pathToSDL .. 'sdl_preloaded_pt.json'
local file = io.open(pathToFile, "r")
local json_data = file:read("*all") -- may be abbreviated to "*a";
file:close()
local json = require("modules/json")
local data = json.decode(json_data)
for k,v in pairs(data.policy_table.functional_groupings) do
if (data.policy_table.functional_groupings[k].rpcs == nil) then
--do
data.policy_table.functional_groupings[k] = nil
else
--do
local count = 0
for _ in pairs(data.policy_table.functional_groupings[k].rpcs) do count = count + 1 end
if (count < 30) then
--do
data.policy_table.functional_groupings[k] = nil
end
end
end
data.policy_table.functional_groupings["Base-4"]["rpcs"]["SubscribeWayPoints"] = {}
data.policy_table.functional_groupings["Base-4"]["rpcs"]["SubscribeWayPoints"]["hmi_levels"] = {"BACKGROUND", "FULL","LIMITED"}
data.policy_table.functional_groupings["Base-4"]["rpcs"]["UnsubscribeWayPoints"] = {}
data.policy_table.functional_groupings["Base-4"]["rpcs"]["UnsubscribeWayPoints"]["hmi_levels"] = {"BACKGROUND", "FULL","LIMITED"}
data = json.encode(data)
file = io.open(pathToFile, "w")
file:write(data)
file:close()
end
Test:updatePreloadedJson()
-----------------------------------------------------------------------------------------------
-------------------------------------------TEST BLOCK V----------------------------------------
-------------------------------------Checks All Result Codes-----------------------------------
-----------------------------------------------------------------------------------------------
--Begin Test case ResultCodeChecks
--Description: Check TOO_MANY_PENDING_REQUESTS resultCode
--Requirement id in JAMA: SDLAQ-CRS-633
--Verification criteria: The system has more than 1000 requests at a time that haven't been responded yet. The system sends the responses with TOO_MANY_PENDING_REQUESTS error code for all the further requests until there are less than 1000 requests at a time that haven't been responded by the system yet.
function Test:UnSubscribeWayPoints_VerifyResultCode_TOO_MANY_PENDING_REQUESTS()
print("vao ko")
local numberOfRequest = 20
for i = 1, numberOfRequest do
--mobile side: send the request
self.mobileSession:SendRPC("UnsubscribeWayPoints",{})
end
commonTestCases:verifyResultCode_TOO_MANY_PENDING_REQUESTS(numberOfRequest)
end
--End Test case ResultCodeChecks
--Post condition: Restore smartDeviceLink.ini file for SDL
function Test:RestoreFile_smartDeviceLink_ini()
commonPreconditions:RestoreFile("smartDeviceLink.ini")
end
--Postcondition: Restore_preloaded_pt
-- testCasesForPolicyTable:Restore_preloaded_pt()
return Test
|
local app = require "kong.api.app"
require "kong.tools.ngx_stub"
local stub = {
req = { headers = {} },
add_params = function() end,
params = { foo = "bar", number = 10, ["config.nested"] = 1, ["config.nested_2"] = 2 }
}
describe("App", function()
describe("#parse_params()", function()
it("should normalize nested properties for parsed form-encoded parameters", function()
-- Here Lapis already parsed the form-encoded parameters but we are normalizing
-- the nested ones (with "." keys)
local f = app.parse_params(function(stub)
assert.are.same({
foo = "bar",
number = 10,
config = {
nested = 1,
nested_2 = 2
}
}, stub.params)
end)
f(stub)
end)
it("should parse a JSON body", function()
-- Here we are simply decoding a JSON body (which is a string)
ngx.req.get_body_data = function() return '{"foo":"bar","number":10,"config":{"nested":1,"nested_2":2}}' end
stub.req.headers["Content-Type"] = "application/json; charset=utf-8"
local f = app.parse_params(function(stub)
assert.are.same({
foo = "bar",
number = 10,
config = {
nested = 1,
nested_2 = 2
}
}, stub.params)
end)
f(stub)
end)
it("should normalize sub-nested properties for parsed form-encoded parameters", function()
stub.params = { foo = "bar", number = 10, ["config.nested_1"] = 1, ["config.nested_2"] = 2,
["config.nested.sub-nested"] = "hi"
}
local f = app.parse_params(function(stub)
assert.are.same({
foo = 'bar',
number = 10,
config = {
nested = {
["sub-nested"] = "hi"
},
nested_1 = 1,
nested_2 = 2
}
}, stub.params)
end)
f(stub)
end)
it("should normalize nested properties when they are plain arrays", function()
stub.params = { foo = "bar", number = 10, ["config.nested"] = {["1"]="hello", ["2"]="world"}}
local f = app.parse_params(function(stub)
assert.are.same({
foo = 'bar',
number = 10,
config = {
nested = {"hello", "world"},
}}, stub.params)
end)
f(stub)
end)
it("should normalize very complex values", function()
stub.params = {
api_id = 123,
name = "request-transformer",
["config.add.headers"] = "x-new-header:some_value, x-another-header:some_value",
["config.add.querystring"] = "new-param:some_value, another-param:some_value",
["config.add.form"] = "new-form-param:some_value, another-form-param:some_value",
["config.remove.headers"] = "x-toremove, x-another-one",
["config.remove.querystring"] = "param-toremove, param-another-one",
["config.remove.form"] = "formparam-toremove"
}
local f = app.parse_params(function(stub)
assert.are.same({
api_id = 123,
name = "request-transformer",
config = {
add = {
form = "new-form-param:some_value, another-form-param:some_value",
headers = "x-new-header:some_value, x-another-header:some_value",
querystring = "new-param:some_value, another-param:some_value"
},
remove = {
form = "formparam-toremove",
headers = "x-toremove, x-another-one",
querystring = "param-toremove, param-another-one"
}
}
}, stub.params)
end)
f(stub)
end)
end)
end)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.