content
stringlengths 5
1.05M
|
---|
box.cfg {
listen=3303,
logger="tarantool.log",
log_level=5,
logger_nonblock=true,
wal_mode="none",
pid_file="tarantool.pid"
}
box.schema.space.create("ycsb", {id = 1024})
box.space.ycsb:create_index('primary', {type = 'hash', parts = {1, 'STR'}})
box.schema.user.grant('guest', 'read,write,execute', 'universe')
|
local Tunnel = module("vrp", "lib/Tunnel")
local Proxy = module("vrp", "lib/Proxy")
vRP = Proxy.getInterface("vRP")
vRPclient = Tunnel.getInterface("vRP", "vrp_wallet")
RegisterServerEvent('vrp_wallet:getMoneys')
AddEventHandler('vrp_wallet:getMoneys', function()
local user_id = vRP.getUserId({source})
if user_id then
local money = vRP.getMoney({user_id})
local bank = vRP.getBankMoney({user_id})
TriggerClientEvent("vrp_wallet:setValues", source, money, bank)
end
end)
|
local usage = arg[0] .. ' <prefix> <output> <inputs...>'
assert(arg[1], 'Missing <prefix>\n' .. usage)
assert(arg[2], 'Missing <output>\n' .. usage)
assert(arg[3], 'Missing <inputs...>\n' .. usage)
local prefix = arg[1]
local function strip_prefix(s)
return string.format("%q", s:sub(#prefix + 1))
end
local output = strip_prefix(arg[2])
local input = {}
for i = 3, #arg do table.insert(input, strip_prefix(arg[i])) end
local cmd = string.format("cd %q && zip -9 %s %s", prefix, output, table.concat(input, ' '))
assert(io.popen(cmd)):read('*a')
|
local core = require "core"
local command = require "core.command"
local Doc = require "core.doc"
local keymap = require "core.keymap"
command.add("core.docview", {
["move-to-to-start-of-line-ignoring-whitespace"] = function()
local doc = core.active_view.doc
local current_line, current_pos = doc:get_selection()
local current_line_length = #doc.lines[current_line]
local i = 1
while i <= current_line_length and doc.lines[current_line]:sub(i, i) == " " do
i = i + 1
end
if i == current_pos then i = 1 end
core.log("first_char_pos = %u", i)
doc:set_selection(current_line, i)
end,
})
keymap.add { ["home"] = "move-to-to-start-of-line-ignoring-whitespace" }
|
local cjson = require "cjson"
local _M = {}
function _M.merge_table(base_table, up_table)
if "table" ~= type(base_table) then
return up_table
end
if "table" ~= type(up_table) then
return base_table
end
local new_table = {}
for k, v in pairs(base_table) do
if "table" == type(v) then
new_table[k] = _M.merge_table(v, up_table[k])
elseif "number" == type(v) then
new_table[k] = v + (up_table[k] or 0)
else
new_table[k] = up_table[k] or v
end
end
for k, v in pairs(up_table) do
if new_table[k] == nil then
new_table[k] = v
end
end
return new_table
end
function _M.split_no_pat(s, delim, max_lines)
if type(delim) ~= "string" or string.len(delim) <= 0 then
return {}
end
if nil == max_lines or max_lines < 1 then
max_lines = 0
end
local count = 0
local start = 1
local t = {}
while true do
local pos = s:find(delim, start, true) -- plain find
if not pos then
break
end
table.insert (t, s:sub(start, pos - 1))
start = pos + string.len (delim)
count = count + 1
if max_lines > 0 and count >= max_lines then
break
end
end
if max_lines > 0 and count >= max_lines then
else
table.insert (t, s:sub(start))
end
return t
end
function _M.load_file_to_string(path)
-- body
local fd, err = io.open(path, 'r')
local t = nil
if fd then
t = fd:read()
fd:close()
else
return ngx.log(ngx.ERR, "open config file err: ", err)
end
return t
end
function _M.save_string_to_file(path, str)
-- body
local fd, err = io.open(path, 'w')
if fd then
fd:write(str)
fd:close()
else
ngx.log(ngx.ERR, "open config file err: ", err)
return false, err
end
return true, nil
end
function _M.store_in_shared_cache(cache, key, value, expire)
-- body
local shared_cache = ngx.shared[cache]
shared_cache:set(key, value, expire or 0)
-- ngx.log(ngx.DEBUG, "store value:", value, " to ", cache, ":", key, " and expires", expire or "0")
end
function _M.fetch_from_shared_cache(cache, key)
-- body
local value, _ = ngx.shared[cache]:get(key)
return value
end
function _M.json_decode(str)
local ok, json_value = pcall(cjson.decode, str)
if not ok then
json_value = nil
end
return json_value
end
function _M.json_encode(data, empty_table_as_object)
--lua的数据类型里面,array和dict是同一个东西。对应到json encode的时候,就会有不同的判断
--对于linux,我们用的是cjson库:A Lua table with only positive integer keys of type number will be encoded as a JSON array. All other tables will be encoded as a JSON object.
--cjson对于空的table,就会被处理为object,也就是{}
--dkjson默认对空table会处理为array,也就是[]
--处理方法:对于cjson,使用encode_empty_table_as_object这个方法。文档里面没有,看源码
--对于dkjson,需要设置meta信息。local a= {};a.s = {};a.b='中文';setmetatable(a.s, { __jsontype = 'object' });ngx.say(comm.json_encode(a))
local json_value = nil
if cjson.encode_empty_table_as_object then
cjson.encode_empty_table_as_object(empty_table_as_object or false) -- 空的table默认为array
end
if require("ffi").os ~= "Windows" then
cjson.encode_sparse_array(true)
end
--json_value = json.encode(data)
pcall(function (data) json_value = cjson.encode(data) end, data)
return json_value
end
function _M.err_handle()
ngx.log(ngx.ERR, debug.traceback())
end
return _M
|
local function doScale(um)
local ply = um:ReadEntity()
local scale = um:ReadFloat()
if not IsValid(ply) then return end
ply:SetModelScale(scale, 1)
ply:SetHull(Vector(-16, -16, 0), Vector(16, 16, 72 * scale))
end
usermessage.Hook("frenchrp_playerscale", doScale)
|
data:extend({
{
enabled = false,
energy_required = 20,
ingredients = {
{"laser-turret", 1 * 50 },
{"stone-wall", 20 * 50 },
{"processing-unit", 1 * 50}
},
name = "pulse-laser",
result = "pulse-laser",
type = "recipe"
},
{
enabled = false,
energy_required = 5,
ingredients = {
{"pulse-laser", 1 },
},
name = "p-pulse-laser",
result = "p-pulse-laser",
type = "recipe"
}
}) |
print("Hello,", "World !")
|
local people = getRootElement()
local gate1 = getElementByID("toldicht1")
local marker1 = getElementByID("tolmarker1")
local x1, y1, z1 = getElementPosition(gate1)
function open1()
if (gate1) then
moveObject (gate1, 1500, x1, y1, z1, 0, 90, 0)
setTimer(close1, 3000, 1)
end
end
addEventHandler("onMarkerHit", marker1, function()
clearElementVisibleTo(marker1)
setTimer(open1, 2000, 1)
end
)
function close1()
if (gate1) then
moveObject (gate1, 1500, x1, y1, z1, 0, -90, 0)
setElementVisibleTo(marker1, people, true)
end
end
local gate2 = getElementByID("toldicht2")
local marker2 = getElementByID("tolmarker2")
local x2, y2, z2 = getElementPosition(gate2)
function open2()
if (gate2) then
moveObject (gate2, 1500, x2, y2, z2, 0, 90, 0)
setTimer(close2, 3000, 1)
end
end
addEventHandler("onMarkerHit", marker2, function()
clearElementVisibleTo(marker2)
setTimer(open2, 2000, 1)
end
)
function close2()
if (gate2) then
moveObject (gate2, 1500, x2, y2, z2, 0, -90, 0)
setElementVisibleTo(marker2, people, true)
end
end
local gate3 = getElementByID("toldicht3")
local marker3 = getElementByID("tolmarker3")
local x3, y3, z3 = getElementPosition(gate3)
function open3()
if (gate3) then
moveObject (gate3, 1500, x3, y3, z3, 0, 90, 0)
setTimer(close3, 3000, 1)
end
end
addEventHandler("onMarkerHit", marker3, function()
clearElementVisibleTo(marker3)
setTimer(open3, 2000, 1)
end
)
function close3()
if (gate3) then
moveObject (gate3, 1500, x3, y3, z3, 0, -90, 0)
setElementVisibleTo(marker3, people, true)
end
end
local gate4 = getElementByID("toldicht4")
local marker4 = getElementByID("tolmarker4")
local x4, y4, z4 = getElementPosition(gate4)
function open4()
if (gate4) then
moveObject (gate4, 1500, x4, y4, z4, 0, 90, 0)
setTimer(close4, 3000, 1)
end
end
addEventHandler("onMarkerHit", marker4, function()
clearElementVisibleTo(marker4)
setTimer(open4, 2000, 1)
end
)
function close4()
if (gate4) then
moveObject (gate4, 1500, x4, y4, z4, 0, -90, 0)
setElementVisibleTo(marker4, people, true)
end
end
local weaponizer = createColSphere (-2271.525390625, 1543.455078125, 30.481227874756, 8)
function weaponize(numberOne, matchingDimension)
giveWeapon(numberOne, 29, 300, true)
outputChatBox("You have a weapon, now you can do driveby's", numberOne, 255, 255, 255, false)
end
addEventHandler("onColShapeHit", weaponizer, weaponize)
|
--------------------------------------------------------------------------------
--
-- This file is part of the Doxyrest toolkit.
--
-- Doxyrest is distributed under the MIT license.
-- For details see accompanying license.txt file,
-- the public copy of which is also available at:
-- http://tibbo.com/downloads/archive/doxyrest/license.txt
--
--------------------------------------------------------------------------------
--!
--! \defgroup frame-config
--! \grouporder 2
--! \title Frame Settings
--!
--! This section describes frame settings controlling input and output paths,
--! titles, force-includes, declaration coding style, etc.
--!
--! A default ``doxyrest-config.lua`` file for standard frames can be found at
--! ``$DOXYREST_FRAME_DIR/doxyrest-config.lua``. Copy it to your project
--! directory and then adjust all the necessary parameters.
--!
--! @{
--!
--!
--! Table containing a list of frame directories. All frame files will be
--! searched in directories -- and in the sequence -- specified here.
--!
FRAME_DIR_LIST = {}
--!
--! The output master (index) reStructuredText file. Usually, the index frame
--! also generates auxillary files -- they will be placed next to the master
--! file. The command line option ``-f`` *overrides* this value.
--! If neither ``FRAME_FILE`` nor ``-f`` is specified, ``index.rst.in`` will be
--! used as the default frame file.
--!
FRAME_FILE = nil
--!
--! The input master (index) XML file. Specifying it here allows calling
--! ``doxyrest`` without parameters; otherwise, the master XML *must* be passed
--! via the command line. If both ``INPUT_FILE`` and command line parameter are
--! specified, the command line takes precedence.
--!
INPUT_FILE = nil
--!
--! The output master (index) reStructuredText file. Usually, the index frame
--! also generates auxillary files -- they will be placed next to the master
--! file. The command line option ``-o`` *overrides* this value. If neither
--! ``OUTPUT_FILE`` nor ``-o`` is specified, ``index.rst`` will be used as
--! the default output master file.
--!
OUTPUT_FILE = nil
--!
--! File with project-specific reStructuredText definitions. When non``nil``,
--! this file will be included at the top of every generated ``.rst`` file.
--!
FORCE_INCLUDE_FILE = nil
--!
--! If you want to add extra reStructuredText documentation pages, do so
--! by adding them to this list.
--!
EXTRA_PAGE_LIST = {}
--!
--! The title of the main (index) page. This only is used when ``INTRO_FILE``
--! is not set (otherwise, the title of intro file will be used).
--!
INDEX_TITLE = "My Project Documentation"
--!
--! File with project introduction (reStructuredText). When non-nil, this file
--! will be included into ``index.rst`` file and NOT added to the list of other
--! documentation pages.
--!
INTRO_FILE = nil
--!
--! Specify whether to sort groups lexicographically (by ``title``) or
--! logically (by ``id``).
--!
SORT_GROUPS_BY = "title"
--[[!
By default, the page for the global namespace page will be called
"Global Namespace" and will contain no description except that for the
global compounds and members.
It's possible to override this behaviour by defining an auxillary compound
(page or group) with a special ``id``; this page/group may contain a
user-defined title, a brief description and a detailed description. Use
``GLOBAL_AUX_COMPOUND_ID`` to define this special id.
.. note::
To make sure you use the correct **Doxygen** XML ID of the group/page,
find the definition of the group in one of ``.xml`` files and copy
the value of ``id`` attribute.
For example, if the group was declared as ``\defgroup global`` then
the its ``id`` will probably be either ``group_<your-group-name>`` or
``group__<your-group-name>``.
]]
GLOBAL_AUX_COMPOUND_ID = "group_global"
--[[!
Doxyrest offers a workaround for the lack of footnotes in Doxygen by
getting documentation blocks for specially named pseudo-members and
converting those into footnotes.
``FOOTNOTE_MEMBER_PREFIX`` specifies the name prefix for such
pseudo-members. If it is set to ``nil`` or an empty string, Doxyrest
will not attempt to convert any members to footnotes.
\sa :ref:`footnotes`
]]
FOOTNOTE_MEMBER_PREFIX = nil
--!
--! Specify the main language of your project; this string will be used for
--! the reStructuredText ``.. code-block::`` sections and for conditional formatting
--! of module item declarations.
--!
LANGUAGE = cpp
--!
--! Convert ``\verbatim`` sections in doxy-comments to ``.. code-block::``
--! sections in the output reStructuredText. The string value of
--! ``VERBATIM_TO_CODE_BLOCK`` will be used as the language of
--! ``.. code-block::`` section. By default, it's ``"none"`` which results in
--! no syntax highlighting. To disable conversion at all, use ``nil``.
--!
VERBATIM_TO_CODE_BLOCK = "none"
--!
--! If the original doxy comments contain asterisks, they have to be escaped
--! in reStructuredText (asterisks are used to mark **bold** or *italic* blocks).
--!
ESCAPE_ASTERISKS = false
--!
--! If the original doxy comments contain pipe characters ``|``, they have to be
--! escaped in reStructuredText (pipes are used for substitution references).
--!
ESCAPE_PIPES = false
--!
--! If the original doxy comments contain trailingasterisks, they have to be
--! escaped in reStructuredText (trailing underscores are used for internal
--! links).
--!
ESCAPE_TRAILING_UNDERSCORES = false
--!
--! Exclude items declared in specific locations. Use a regular expression to
--! define a mask of directories/source files to completely exclude from the
--! final documentation. For example, ``.*/impl/.*lua$`` will exclude all
--! ``.lua`` files located in ``impl/`` directory.
--!
EXCLUDE_LOCATION_PATTERN = nil
--!
--! Exclude variables and functions without any documentation (no doxy-comments).
--!
EXCLUDE_UNDOCUMENTED_ITEMS = false
--!
--! \subgroup
--!
--! By default, Doxyrest tries to translate Doxygen ``\section``,
--! ``\subsection``, and ``\subsubsection`` commands (as well as the
--! ``<heading level="n">`` blocks generated by Doxygen from Markdown titles
--! inside comments) into reStructuredText titles.
--!
--! This sometimes leads to problems because Doxygen headings may appear outside
--! of the global scope (e.g. inside lists) while reStructuredText titles are
--! only allowed at the global scope. Another issue is Doxygen headings may
--! yield inconsistent title structure (e.g. a title level 1 followed by level
--! 3).
--!
--! If you run into these issues, use ``SECTION_TO_RUBRIC`` or
--! ``HEADING_TO_RUBRIC`` to always convert Doxygen sections or ``<heading>``
--! blocks or into reStructuredText ``.. rubric::`` directives. This yields
--! uni-level headings, but solves both aforementioned problems.
--!
SECTION_TO_RUBRIC = false
HEADING_TO_RUBRIC = false
--[[!
By default, Doxyrest frames build a Python dictionary to be used later on by
the ``:cref:`` (code-reference) role. This database maps language-specific
qualified names of items to their IDs.
This, together with setting the Sphinx ``default_role`` to ``cref``, allows
to conveniently reference items from Doxy-comments or regular ``.rst`` files
as such:
.. code-block:: none
The `ui::Dialog` class is a base to the `ui::FileDialog` class.
However, if this facility is not used, building (and loading) of the
cref-database can be omitted to save both space and time.
]]
CREF_DB = false
--[[!
Exclude items with higher protection level than ``PROTECTION_FILTER``:
1. ``public``
2. ``protected``
3. ``private``
4. ``package``
By default, only public items are included into documentation.
]]
PROTECTION_FILTER = "public"
--!
--! In many projects empty defines are *only* used as include-guards (and as
--! such, should be excluded from the documentation). If this is not the case
--! and empty defines should be kept in the final documentation, change this
--! setting to ``false``.
--!
EXCLUDE_EMPTY_DEFINES = true
--!
--! If non-``nil``, each define will be checked using this regular expression
--! and if its name matches, this define will be excluded from the documentation.
--!
EXCLUDE_DEFINE_PATTERN = nil
--!
--! Usually providing documentation blocks for default constructors is
--! not necessary (as to avoid redundant meaningless "Constructs a new object"
--! paragraphs). Change this to ``false`` if default constructors *should* be
--! included.
--!
EXCLUDE_DEFAULT_CONSTRUCTORS = true
--!
--! Usually providing documentation blocks for a destructors is
--! not necessary (as to avoid redundant meaningless "Destructs an object"
--! paragraphs). Change this to ``false`` if destructors *should* be
--! included.
--!
EXCLUDE_DESTRUCTORS = true
--[[!
Usually providing documentation blocks for primitive C typedefs such as:
.. code-block:: C
typedef struct S S;
is not necessary. Change this to ``false`` if such typedefs *should* be
included.
]]
EXCLUDE_PRIMITIVE_TYPEDEFS = true
--!
--! For a base class/struct, show all the types directly derived from it.
--!
SHOW_DIRECT_DESCENDANTS = true
--[[!
\subgroup
Insert space between function name and parameter list like this:
.. code-block:: C
void foo ();
By default, ``PRE_PARAM_LIST_SPACE`` is ``false`` which yields:
.. code-block:: C
void foo();
]]
PRE_PARAM_LIST_SPACE = false
PRE_OPERATOR_NAME_SPACE = true
PRE_OPERATOR_PARAM_LIST_SPACE = true
--[[!
Insert a new line before the body of a enum, struct, class, etc.
When ``PRE_BODY_NL`` is ``false``:
.. code-block:: cpp
class MyClass {
...
}
When ``PRE_BODY_NL`` is ``true``:
.. code-block:: cpp
class MyClass
{
...
}
]]
PRE_BODY_NL = true
--[[!
Use multi-line parameter lists in function declarations if parameter count is
greater than this threshold. ``nil`` means don't use parameter count
threshold.
For example, when ``ML_PARAM_LIST_COUNT_THRESHOLD`` is ``2``, the function
declarations will look as such:
.. code-block:: C
void fn0();
void fn1(int a);
void fn2(int a, int b);
void fn3(
int a,
int b
int c
);
]]
ML_PARAM_LIST_COUNT_THRESHOLD = nil
--[[!
Use multi-line parameter lists in function declarations if single-line
declaration length parameter count is greater than this threshold.
``nil`` means don't use length threshold.
Similar to ``ML_PARAM_LIST_COUNT_THRESHOLD``, but the threshold parameter
here is *declaration length* and not *declaration parameter count*.
Example:
.. code-block:: C
void foo(int a, int b, int c);
void bar(
int veryLongParameterName,
int anotherVeryLongParameterName
);
]]
ML_PARAM_LIST_LENGTH_THRESHOLD = 80
--[[!
Use multi-line specifier-modifier lists in function declarations, i.e
allocate a dedicated line for each type specifier/morifier.
For example, when ``ML_SPECIFIER_MODIFIER_LIST`` is ``true``, the function
declarations will look as such:
.. code-block:: C
void
foo();
static
bool
__cdecl
bar(int a);
]]
ML_SPECIFIER_MODIFIER_LIST = false
--[[!
Use the new C++11 syntax for ``typedef``-s:
When ``TYPEDEF_TO_USING`` is ``false``:
.. code-block:: cpp
typedef unsigned int uint_t;
typedef void Foo(int);
typedef void (*FooPtr)(int);
When ``TYPEDEF_TO_USING`` is ``true``:
.. code-block:: cpp
using uint_t = unsigned int;
using Foo typedef void (int);
using FooPtr typedef void (*)(int);
]]
TYPEDEF_TO_USING = false
--[[!
Sometimes, it's required to redirect a Doxygen link to some external location.
In this case, add an entry to ``IMPORT_URL_MAP`` with the target URL, e.g.:
.. code-block:: lua
IMPORT_URL_MAP =
{
[ "cfd9ea7a-35de-4090-a83b-3d214b3ff358/type_jnc_scheduler" ] =
"https://vovkos.github.io/jancy/stdlib/class_jnc_Scheduler.html"
}
The key of the map is an ``importid`` attribute. This is a non-standard Doxygen
attribute; Jancy compiler generates is when a referenced item is contained in an
imported extensions library (``.jncx``)
]]
IMPORT_URL_MAP = {}
--! @}
|
--------------------------
-- WebKit WebView class --
--------------------------
-- Webview class table
webview = {}
-- Table of functions which are called on new webview widgets.
webview.init_funcs = {
-- Set useragent
set_useragent = function (view, w)
view.user_agent = globals.useragent
end,
-- Check if checking ssl certificates
checking_ssl = function (view, w)
local ca_file = soup.ssl_ca_file
if ca_file and os.exists(ca_file) then
w.checking_ssl = true
end
end,
-- Update window and tab titles
title_update = function (view, w)
view:add_signal("property::title", function (v)
w:update_tablist()
if w.view == v then
w:update_win_title()
end
end)
end,
-- Update uri label in statusbar
uri_update = function (view, w)
view:add_signal("property::uri", function (v)
w:update_tablist()
if w.view == v then
w:update_uri()
end
end)
end,
-- Update history indicator
hist_update = function (view, w)
view:add_signal("load-status", function (v, status)
if w.view == v then
w:update_hist()
end
end)
end,
-- Update tab titles
tablist_update = function (view, w)
view:add_signal("load-status", function (v, status)
if status == "provisional" or status == "finished" or status == "failed" then
w:update_tablist()
end
end)
end,
-- Update scroll widget
scroll_update = function (view, w)
view:add_signal("expose", function (v)
if w.view == v then
w:update_scroll()
end
end)
end,
-- Update progress widget
progress_update = function (view, w)
for _, sig in ipairs({"load-status", "property::progress"}) do
view:add_signal(sig, function (v)
if w.view == v then
w:update_progress()
w:update_ssl()
end
end)
end
end,
-- Display hovered link in statusbar
link_hover_display = function (view, w)
view:add_signal("link-hover", function (v, link)
if w.view == v and link then
w:update_uri(link)
end
end)
view:add_signal("link-unhover", function (v)
if w.view == v then
w:update_uri()
end
end)
end,
-- Clicking a form field automatically enters insert mode.
form_insert_mode = function (view, w)
view:add_signal("button-press", function (v, mods, button, context)
-- Clear start search marker
(w.search_state or {}).marker = nil
if button == 1 and context.editable then
view:emit_signal("form-active")
end
end)
-- Emit root-active event in button release to prevent "missing"
-- buttons or links when the input bar hides.
view:add_signal("button-release", function (v, mods, button, context)
if button == 1 and not context.editable then
view:emit_signal("root-active")
end
end)
view:add_signal("form-active", function ()
if not w.mode.passthrough then
w:set_mode("insert")
end
end)
view:add_signal("root-active", function ()
if w.mode.reset_on_focus ~= false then
w:set_mode()
end
end)
end,
-- Catch keys in non-passthrough modes
mode_key_filter = function (view, w)
view:add_signal("key-press", function ()
if not w.mode.passthrough then
return true
end
end)
end,
-- Try to match a button event to a users button binding else let the
-- press hit the webview.
button_bind_match = function (view, w)
view:add_signal("button-release", function (v, mods, button, context)
(w.search_state or {}).marker = nil
if w:hit(mods, button, { context = context }) then
return true
end
end)
end,
-- Reset the mode on navigation
mode_reset_on_nav = function (view, w)
view:add_signal("load-status", function (v, status)
if status == "provisional" and w.view == v then
if w.mode.reset_on_navigation ~= false then
w:set_mode()
end
end
end)
end,
-- Domain properties
domain_properties = function (view, w)
view:add_signal("load-status", function (v, status)
if status ~= "committed" or v.uri == "about:blank" then return end
-- Get domain
local domain = lousy.uri.parse(v.uri).host
-- Strip leading www.
domain = string.match(domain or "", "^www%.(.+)") or domain or "all"
-- Build list of domain props tables to join & load.
-- I.e. for luakit.org load .luakit.org, luakit.org, .org
local props = {domain_props.all or {}, domain_props[domain] or {}}
repeat
table.insert(props, 2, domain_props["."..domain] or {})
domain = string.match(domain, "%.(.+)")
until not domain
-- Join all property tables
for k, v in pairs(lousy.util.table.join(unpack(props))) do
info("Domain prop: %s = %s (%s)", k, tostring(v), domain)
view[k] = v
end
end)
end,
-- Action to take on mime type decision request.
mime_decision = function (view, w)
-- Return true to accept or false to reject from this signal.
view:add_signal("mime-type-decision", function (v, uri, mime)
info("Requested link: %s (%s)", uri, mime)
-- i.e. block binary files like *.exe
--if mime == "application/octet-stream" then
-- return false
--end
end)
end,
-- Action to take on window open request.
--window_decision = function (view, w)
-- view:add_signal("new-window-decision", function (v, uri, reason)
-- if reason == "link-clicked" then
-- window.new({uri})
-- else
-- w:new_tab(uri)
-- end
-- return true
-- end)
--end,
create_webview = function (view, w)
-- Return a newly created webview in a new tab
view:add_signal("create-web-view", function (v)
return w:new_tab()
end)
end,
-- Creates context menu popup from table (and nested tables).
-- Use `true` for menu separators.
--populate_popup = function (view, w)
-- view:add_signal("populate-popup", function (v)
-- return {
-- true,
-- { "_Toggle Source", function () w:toggle_source() end },
-- { "_Zoom", {
-- { "Zoom _In", function () w:zoom_in() end },
-- { "Zoom _Out", function () w:zoom_out() end },
-- true,
-- { "Zoom _Reset", function () w:zoom_set() end }, }, },
-- }
-- end)
--end,
-- Action to take on resource request.
resource_request_decision = function (view, w)
view:add_signal("resource-request-starting", function(v, uri)
info("Requesting: %s", uri)
-- Return false to cancel the request.
end)
end,
}
-- These methods are present when you index a window instance and no window
-- method is found in `window.methods`. The window then checks if there is an
-- active webview and calls the following methods with the given view instance
-- as the first argument. All methods must take `view` & `w` as the first two
-- arguments.
webview.methods = {
-- Reload with or without ignoring cache
reload = function (view, w, bypass_cache)
if bypass_cache then
view:reload_bypass_cache()
else
view:reload()
end
end,
-- Toggle source view
toggle_source = function (view, w, show)
if show == nil then
view.view_source = not view.view_source
else
view.view_source = show
end
view:reload()
end,
-- Zoom functions
zoom_in = function (view, w, step, full_zoom)
view.full_content_zoom = not not full_zoom
step = step or globals.zoom_step or 0.1
view.zoom_level = view.zoom_level + step
end,
zoom_out = function (view, w, step, full_zoom)
view.full_content_zoom = not not full_zoom
step = step or globals.zoom_step or 0.1
view.zoom_level = math.max(0.01, view.zoom_level) - step
end,
zoom_set = function (view, w, level, full_zoom)
view.full_content_zoom = not not full_zoom
view.zoom_level = level or 1.0
end,
-- History traversing functions
back = function (view, w, n)
view:go_back(n or 1)
end,
forward = function (view, w, n)
view:go_forward(n or 1)
end,
}
function webview.methods.scroll(view, w, new)
local s = view.scroll
for _, axis in ipairs{ "x", "y" } do
-- Relative px movement
if rawget(new, axis.."rel") then
s[axis] = s[axis] + new[axis.."rel"]
-- Relative page movement
elseif rawget(new, axis .. "pagerel") then
s[axis] = s[axis] + math.ceil(s[axis.."page_size"] * new[axis.."pagerel"])
-- Absolute px movement
elseif rawget(new, axis) then
local n = new[axis]
if n == -1 then
s[axis] = s[axis.."max"]
else
s[axis] = n
end
-- Absolute page movement
elseif rawget(new, axis.."page") then
s[axis] = math.ceil(s[axis.."page_size"] * new[axis.."page"])
-- Absolute percent movement
elseif rawget(new, axis .. "pct") then
s[axis] = math.ceil(s[axis.."max"] * (new[axis.."pct"]/100))
end
end
end
function webview.new(w)
local view = widget{type = "webview"}
view.show_scrollbars = false
view.enforce_96_dpi = false
-- Call webview init functions
for k, func in pairs(webview.init_funcs) do
func(view, w)
end
return view
end
-- Insert webview method lookup on window structure
table.insert(window.indexes, 1, function (w, k)
if k == "view" then
local view = w.tabs[w.tabs:current()]
if view and type(view) == "widget" and view.type == "webview" then
w.view = view
return view
end
end
-- Lookup webview method
local func = webview.methods[k]
if not func then return end
local view = w.view
if view then
return function (_, ...) return func(view, w, ...) end
end
end)
-- vim: et:sw=4:ts=8:sts=4:tw=80
|
module ('mock')
local function AuroraSpriteLoader( node )
--[[
sprite <package>
.moduletexture <texture>
.modules <uvquad[...]>
.frames <deck_quadlist>
]]
local data = loadAssetDataTable( node:getObjectFile('def') )
local textures = {}
local texRects = {}
local uvRects = {}
--load images
for i, image in pairs( data.images ) do
if i>1 then error("multiple image not supported") end
local imgFile = node:getSiblingPath( image.file )
local tex, texNode = loadAsset( imgFile )
if not tex then
_error( 'cannot load sprite texture', imgFile )
return nil
end
local mtex, uvRect = tex:getMoaiTextureUV()
textures[ i ] = mtex
local tw, th = mtex:getSize()
local ox, oy = 0, 0 --todo
texRects[ i ] = { tw, th, ox, oy }
end
local deck = MOAIGfxQuadListDeck2D.new()
deck:reservePairs( data.partCount ) --one pair per frame component
deck:reserveQuads( data.partCount ) --one quad per frame component
deck:reserveUVQuads( #data.modules ) --one uv per module
deck:reserveLists( #data.frames ) --one list per frame
deck:setTexture( textures[1] )
for i, m in ipairs( data.modules ) do
if m.type == 'image' then
local x, y, w, h = unpack( m.rect )
local texRect = texRects[ m.image+1 ]
local tw, th, ox, oy = unpack( texRect )
local u0, v0, u1, v1 = (x+ox+0.1)/tw, (y+oy+0.1)/th, (x+ox+w)/tw, (y+oy+h)/th
m.uv = {u0, v0, u1, v1}
deck:setUVRect(i, u0, v0, u1, v1)
end
end
local partId = 1
for i, frame in ipairs( data.frames ) do
local basePartId = partId
for j, part in ipairs( frame.parts ) do
local uvId = part.module
local x0, y0, x1, y1 = unpack( part.rect )
deck:setRect(partId, x0, -y1, x1, -y0)
deck:setPair(partId, uvId, partId)
partId = partId + 1
end
deck:setList( i, basePartId, partId - basePartId )
end
preloadIntoAssetNode( node:getChildPath('frames'), deck )
--animations
local EaseFlat = MOAIEaseType.FLAT
local EaseLinear = MOAIEaseType.LINEAR
local animations = {}
for i, animation in ipairs( data.animations ) do
local name = animation.name
--create anim curve
local indexCurve = MOAIAnimCurve.new()
local offsetXCurve = MOAIAnimCurve.new()
local offsetYCurve = MOAIAnimCurve.new()
local count = #animation.frames
indexCurve :reserveKeys( count + 1 )
offsetXCurve:reserveKeys( count + 1 )
offsetYCurve:reserveKeys( count + 1 )
--TODO: support flags? or just forbid it!!!!
local offsetEaseType = EaseLinear
local ftime = 0
for fid, frame in ipairs( animation.frames ) do
local ox, oy = unpack( frame.offset )
offsetXCurve:setKey( fid, ftime, ox, offsetEaseType )
offsetYCurve:setKey( fid, ftime, -oy, offsetEaseType )
indexCurve :setKey( fid, ftime, frame.id, EaseFlat )
local delay = frame.time
delay = math.max( delay, 1 )
ftime = ftime + delay --will use anim:setSpeed to fit real playback FPS
if fid == count then --copy last frame to make loop smooth
offsetXCurve:setKey( fid + 1, ftime, ox, offsetEaseType )
offsetYCurve:setKey( fid + 1, ftime, -oy, offsetEaseType )
indexCurve :setKey( fid + 1, ftime, frame.id, EaseFlat )
end
end
animations[ name ] = {
offsetXCurve = offsetXCurve,
offsetYCurve = offsetYCurve,
indexCurve = indexCurve,
length = ftime,
name = name,
}
end
local sprite = {
frameDeck = deck,
animations = animations,
texture = tex
}
return sprite
end
registerAssetLoader( 'aurora_sprite', AuroraSpriteLoader )
|
-----------------------------------------------------------------------------
-- A LUA script for MySQL proxy to output failed SQL queries as JSON
--
-- Version: 0.3
-- This script is released under the MIT License (MIT).
-- Please see LICENCE.txt for details.
--
-- REQUIREMENTS:
-- JSON module (https://github.com/craigmj/json4lua)
-----------------------------------------------------------------------------
local proto = require("mysql.proto")
function read_query(packet)
local tp = packet:byte()
if tp == proxy.COM_QUERY or tp == proxy.COM_STMT_PREPARE or tp == proxy.COM_STMT_EXECUTE or tp == proxy.COM_STMT_CLOSE then
proxy.queries:append(1, packet, { resultset_is_needed = true } )
return proxy.PROXY_SEND_QUERY
end
end
local prepared_stmts = { }
function read_query_result(inj)
local tp = string.byte(inj.query)
local res = assert(inj.resultset)
local query = ""
-- Preparing statement...
if tp == proxy.COM_STMT_PREPARE then
if inj.resultset.raw:byte() == 0 then
local stmt_prepare = assert(proto.from_stmt_prepare_packet(inj.query))
local stmt_prepare_ok = assert(proto.from_stmt_prepare_ok_packet(inj.resultset.raw))
prepared_stmts[stmt_prepare_ok.stmt_id] = {
query = stmt_prepare.stmt_text,
num_columns = stmt_prepare_ok.num_columns,
num_params = stmt_prepare_ok.num_params,
}
end
elseif tp == proxy.COM_STMT_CLOSE then -- ...closing statement
local stmt_close = assert(proto.from_stmt_close_packet(inj.query))
prepared_stmts[stmt_close.stmt_id] = nil -- cleaning up
end
-- An error occured...
if(res.query_status == proxy.MYSQLD_PACKET_ERR or res.warning_count > 0) then
-- ... while executing a prepared statement
if tp == proxy.COM_STMT_EXECUTE then
local stmt_id = assert(proto.stmt_id_from_stmt_execute_packet(inj.query))
local stmt_execute = assert(proto.from_stmt_execute_packet(inj.query, prepared_stmts[stmt_id].num_params))
query = prepared_stmts[stmt_id].query
if stmt_execute.new_params_bound then
local params = ""
for ndx, v in ipairs(stmt_execute.params) do
params = params .. ("[%d] %s (type = %d) "):format(ndx, tostring(v.value), v.type)
end
query = query .. " - " .. params
end
elseif tp == proxy.COM_QUERY then -- ... or an exec() query
query = string.sub(inj.query, 2)
else
do return end
end
local err_code = res.raw:byte(2) + (res.raw:byte(3) * 256)
if(err_code ~= 0) and (err_code ~= 1) then
local err_sqlstate = res.query_status == proxy.MYSQLD_PACKET_ERR and res.raw:sub(5, 9) or 0
local err_msg = res.query_status == proxy.MYSQLD_PACKET_ERR and res.raw:sub(10) or ''
local objDt = {
user = proxy.connection.server.username,
db = proxy.connection.server.default_db,
query = query,
msg = err_msg,
code = err_code,
state = err_sqlstate
}
print(require('json').encode(objDt))
io.flush()
end
end
end
|
-- start with standard + ap mode
wifi.setmode(wifi.STATIONAP);
-- create access-point
apCfg = {};
apCfg.ssid = "my1btn";
--apCfg.ssid = "myBtn_"..string.sub(string.upper(string.gsub(wifi.sta.getmac(), ":", "")), -6);
apCfg.pwd = "12345678";
wifi.ap.config(apCfg);
-- configure access-point
ipcfg = {};
ipcfg.ip = "192.168.1.1";
ipcfg.netmask = "255.255.255.0";
ipcfg.gateway = "192.168.1.1";
wifi.ap.setip(ipcfg);
-- start listening to the webserver
srv = net.createServer(net.TCP);
print("config started "..wifi.ap.getip());
print(apCfg.ssid.." [ "..apCfg.pwd.." ]");
function strSplit(inputstr, sep)
local t = {};
i = 1;
for str in string.gmatch(inputstr, '([^'..sep..']+)') do
t[i] = str;
i = i + 1;
end
return t;
end
function readFile(fName)
file.open(fName, "r");
htmlText = file.read();
htmlText = string.gsub(htmlText, "{{MAC}}", "MAC: "..string.upper(wifi.sta.getmac()));
local ip = wifi.sta.getip();
if ip ~= nil then
htmlText = string.gsub(htmlText, "{{MYIP}}", "MY IP: "..string.upper(ip));
end
file.close(fName);
return htmlText;
end
function sendResponse(conn, color, content, response)
setLED(color);
if content == 'F' then
response = readFile(response);
end
conn:send("HTTP/1.1 200 OK\r\nContent-type:text/html\r\n\r\n"..response);
conn:close();
print(response);
setLED(0);
end
-- now listen
srv:listen(80, function(conn)
conn:on("receive", function(conn, payload)
if payload ~= nil then
data = string.sub(payload, string.find(payload, "GET /") + 5, string.find(payload, "HTTP/") - 1);
if string.find(payload, "favicon.ico") == nil then
-- perform URL decoding
data = string.gsub(data, "+", " ");
data = string.gsub(data, "%%(%x%x)", function(h)
return string.char(tonumber(h, 16));
end);
data = string.gsub (data, "\r\n", "\n");
-- print every data received
print(#data.." "..data);
str1 = {nil, nil};
if #data > 10 then
str1 = strSplit(data, '/');
end
if str1[1] ~= nil then
_, ssid_start = string.find(str1[1], "ssid=");
ssid_end, pass_start = string.find(str1[1], "pass=");
pass_end, _ = string.find(str1[1], "action=");
ssid = string.sub(str1[1], ssid_start + 1, ssid_end - 2);
pass = string.sub(str1[1], pass_start + 1, pass_end - 2);
-- print(ssid, pass);
wifi.setmode(wifi.STATIONAP);
wifi.sta.config(ssid, pass, 1);
local attempt = 0;
tmr.alarm(1, 250, tmr.ALARM_AUTO, function()
-- 30 attempts = 15 sec timeout
if attempt > 30 then
-- stop timer
tmr.stop(1);
-- send failure status
sendResponse(conn, MAGENTA, 'F', "login.html");
else
if wifi.sta.getip() ~= nil then
-- stop timer
tmr.stop(1);
-- send success status with assigned ip
local ip = wifi.sta.getip();
sendResponse(conn, BLUE, 'T', "Connected to "..ip..", restarting in 5 seconds ! You can close the browser now.");
-- sendResponse(conn, BLUE, 'F', "showmacnip.html");
tmr.alarm(1, 5000, tmr.ALARM_AUTO, function()
node.restart();
end);
else
attempt = attempt + 1;
end
end
end);
else
sendResponse(conn, MAGENTA, 'F', "login.html");
end
end
end
-- clean-up
collectgarbage();
end)
end); |
if SERVER then
util.AddNetworkString( "guthwhitelistsystem:SetJobWhitelist" )
net.Receive( "guthwhitelistsystem:SetJobWhitelist", function( _, ply )
if not ply or not ply:IsValid() then return end
if not ply:WLIsAdmin() then return end
local job = net.ReadUInt( guthwhitelistsystem.JobIDBit )
local bool = net.ReadBool()
local vip = net.ReadBool()
guthwhitelistsystem:WLSetJobWhitelist( job, bool or false, vip or false )
end )
end
if not CLIENT then return end
guthwhitelistsystem.setPanel( guthwhitelistsystem.getLan( "Jobs" ), "icon16/briefcase.png", 2, function( sheet )
local pnlJ = vgui.Create( "DPanel", sheet ) -- panel jobs
local ply = LocalPlayer()
if not DarkRP then
guthwhitelistsystem.panelNotif( pnlJ, "icon16/exclamation.png", guthwhitelistsystem.getLan( "PanelDarkRP" ), -1, Color( 214, 45, 45 ) )
end
local listJ = vgui.Create( "DListView", pnlJ )
listJ:Dock( FILL )
listJ:DockMargin( 10, 10, 10, 10 )
listJ:SetMultiSelect( false )
listJ:AddColumn( guthwhitelistsystem.getLan( "Jobs" ) )
listJ:AddColumn( guthwhitelistsystem.getLan( "Whitelist ?" ) )
listJ:AddColumn( guthwhitelistsystem.getLan( "VIP ?" ) )
function listJ:Actualize()
self:Clear()
for k, v in pairs( RPExtraTeams or {} ) do
if k == GAMEMODE.DefaultTeam then continue end -- can't whitelist the DefaultTeam
local wl = guthwhitelistsystem:WLGetJobWhitelist( k )
listJ:AddLine( ("%s (%d)"):format( team.GetName( k ), k ), guthwhitelistsystem.getLan( wl.active and "Yes !" or "No !" ), guthwhitelistsystem.getLan( wl.vip and "Yes !" or "No !" ) )
end
end
function listJ:OnRowRightClick( _, line )
surface.PlaySound( "UI/buttonclickrelease.wav" )
local m = DermaMenu( pnlJ )
if line:GetValue( 2 ) == guthwhitelistsystem.getLan( "No !" ) then
local add = m:AddOption( guthwhitelistsystem.getLan( "ActivateWhitelist" ), function()
local id = string.match( line:GetValue( 1 ), "(%(%d+%))$" )
if not id then return end
id = tonumber( string.match( id, "(%d+)" ) )
if not id then return end
if not ply:WLIsAdmin() then
guthwhitelistsystem.panelNotif( pnlJ, "icon16/shield_delete.png", guthwhitelistsystem.getLan( "PanelNotAdmin" ), 3, Color( 214, 45, 45 ) )
return
end
net.Start( "guthwhitelistsystem:SetJobWhitelist" )
net.WriteUInt( id, guthwhitelistsystem.JobIDBit )
net.WriteBool( true )
net.WriteBool( false )
net.SendToServer()
guthwhitelistsystem:WLSetJobWhitelist( id, true, false )
guthwhitelistsystem.chat( (guthwhitelistsystem.getLan( "ChatActivateWhitelist" )):format( line:GetValue( 1 ) ) )
guthwhitelistsystem.panelNotif( pnlJ, "icon16/accept.png", (guthwhitelistsystem.getLan( "PanelWhitelistJob" )):format( team.GetName( id ) ), 3, Color( 45, 174, 45 ) )
self:Actualize()
end )
add:SetIcon( "icon16/accept.png" )
else
local remove = m:AddOption( guthwhitelistsystem.getLan( "DesactivateWhitelist" ), function()
local id = string.match( line:GetValue( 1 ), "(%(%d+%))$" )
if not id then return end
id = tonumber( string.match( id, "(%d+)" ) )
if not id then return end
if not ply:WLIsAdmin() then
guthwhitelistsystem.panelNotif( pnlJ, "icon16/shield_delete.png", guthwhitelistsystem.getLan( "PanelNotAdmin" ), 3, Color( 214, 45, 45 ) )
return
end
net.Start( "guthwhitelistsystem:SetJobWhitelist" )
net.WriteUInt( id, guthwhitelistsystem.JobIDBit )
net.WriteBool( false )
net.WriteBool( false )
net.SendToServer()
guthwhitelistsystem:WLSetJobWhitelist( id, false, false )
guthwhitelistsystem.chat( (guthwhitelistsystem.getLan( "ChatDesactivateWhitelist" )):format( line:GetValue( 1 ) ) )
guthwhitelistsystem.panelNotif( pnlJ, "icon16/delete.png", (guthwhitelistsystem.getLan( "PanelUnwhitelistJob" )):format( team.GetName( id ) ), 3, Color( 214, 45, 45 ) )
self:Actualize()
end )
remove:SetIcon( "icon16/delete.png" )
end
if line:GetValue( 2 ) == guthwhitelistsystem.getLan( "Yes !" ) and line:GetValue( 3 ) == guthwhitelistsystem.getLan( "No !" ) then
local add = m:AddOption( "Activate VIP", function()
local id = string.match( line:GetValue( 1 ), "(%(%d+%))$" )
if not id then return end
id = tonumber( string.match( id, "(%d+)" ) )
if not id then return end
if not ply:WLIsAdmin() then
guthwhitelistsystem.panelNotif( pnlJ, "icon16/shield_delete.png", guthwhitelistsystem.getLan( "PanelNotAdmin" ), 3, Color( 214, 45, 45 ) )
return
end
net.Start( "guthwhitelistsystem:SetJobWhitelist" )
net.WriteUInt( id, guthwhitelistsystem.JobIDBit )
net.WriteBool( true )
net.WriteBool( true )
net.SendToServer()
guthwhitelistsystem:WLSetJobWhitelist( id, true, true )
guthwhitelistsystem.chat( (guthwhitelistsystem.getLan( "ChatActivateVIP" ):format( line:GetValue( 1 ) ) ) )
guthwhitelistsystem.panelNotif( pnlJ, "icon16/money_add.png", (guthwhitelistsystem.getLan( "PanelWhitelistJobVIP" )):format( team.GetName( id ) ), 3, Color( 45, 174, 45 ) )
self:Actualize()
end )
add:SetIcon( "icon16/accept.png" )
elseif line:GetValue( 2 ) == guthwhitelistsystem.getLan( "Yes !" ) then
local remove = m:AddOption( guthwhitelistsystem.getLan( "DesactivateVIP" ), function()
local id = string.match( line:GetValue( 1 ), "(%(%d+%))$" )
if not id then return end
id = tonumber( string.match( id, "(%d+)" ) )
if not id then return end
if not ply:WLIsAdmin() then
guthwhitelistsystem.panelNotif( pnlJ, "icon16/shield_delete.png", guthwhitelistsystem.getLan( "PanelNotAdmin" ), 3, Color( 214, 45, 45 ) )
return
end
net.Start( "guthwhitelistsystem:SetJobWhitelist" )
net.WriteUInt( id, guthwhitelistsystem.JobIDBit )
net.WriteBool( true )
net.WriteBool( false )
net.SendToServer()
guthwhitelistsystem:WLSetJobWhitelist( id, true, false )
guthwhitelistsystem.chat( guthwhitelistsystem.getLan( "ChatDesactivateVIP" ):format( line:GetValue( 1 ) ) )
guthwhitelistsystem.panelNotif( pnlJ, "icon16/money_delete.png", guthwhitelistsystem.getLan( "PanelUnwhitelistJobVIP" ):format( team.GetName( id ) ), 3, Color( 214, 45, 45 ) )
self:Actualize()
end )
remove:SetIcon( "icon16/delete.png" )
end
m:Open()
end
listJ:Actualize()
return pnlJ
end )
|
---------------------------------------------------------------------
-- Project: irc
-- Author: MCvarial
-- Contact: [email protected]
-- Version: 1.0.0
-- Date: 31.10.2010
---------------------------------------------------------------------
local x,y = guiGetScreenSize()
local window = guiCreateWindow(0.25,0.3,0.5,0.6,"Internet Relay Chat",true)
local tabpanel = guiCreateTabPanel(0,0.08,1,0.9,true,window)
local tab = guiCreateTab("#MCvarial",tabpanel)
------------------------------------
-- Client
------------------------------------
guiCreateMemo(0.005,0.01,0.75,0.99,"test",true,tab) |
function AddGamesToScrollArea(entry)
if entry == nil then
AddAllGames();
elseif callbacks.containerFrame ~= nil then
AddGameToScrollArea(entry);
end
end
L = {};
function AddGameToScrollArea(gameEntry)
-- Have a static list L that keeps all the new game containers
-- Create a container for new game
-- Create the actual entry at the new spot
local gameEntryWindow = CreateGameEntry("GameEntryFlexWindow"..#L, gameEntry, -40 * (#L + 1));
-- Push back containerFrame by (#L + 1) * gameEntryBoxHeight
local cpoint, crelativeTo, crelativePoint, cxOfs, cyOfs = callbacks.containerFrame:GetPoint(); -- containerFrame = nil after skirmish game, when having 0 games registered
callbacks.containerFrame:SetPoint("TOPLEFT", 0, cyOfs - 40);
callbacks.containerFrame:Show();
-- Save the container to L
tinsert(L, gameEntryWindow);
-- Resize the callbacks.gameScrollArea to the correct height (e.g. former height + gameEntryBoxHeight)
callbacks.gameScrollArea:SetHeight(callbacks.gameScrollArea:GetHeight() + 40);
end
function AddAllGames()
-- Determine what dates we played
local datesWePlayed = DatesPlayed();
-- Have a base container to contain all the dynamic elements
callbacks.containerFrame = Position(nil, callbacks.gameScrollArea, nil, callbacks.gameScrollerWindow:GetWidth(), nil, nil, 0, -70);
-- The first header is special
CreateFirstHeaderEntry();
-- We sort the table from new to old so we get dates from new to old
table.sort(data, function (a,b) return a.timeStamp > b.timeStamp end);
-- Keep an offset so we know where to start the next header/entry
local offset = 0;
-- For each day
for i,currentDay in ipairs(datesWePlayed) do
CreateDayHeader(i, offset, currentDay);
offset = offset + 70;
for j, gameEntry in ipairs(data) do
if date("%d-%m-%Y", gameEntry.timeStamp) == currentDay then
CreateGameEntry("GameEntryWindow"..i, gameEntry, offset);
offset = offset + 40;
end
end
end
-- (For each day added * height) + (For each game added * height) we set the scrollbox height
if offset == 0 then
callbacks.containerFrame:SetHeight(10);
else
callbacks.containerFrame:SetHeight(offset);
end
callbacks.gameScrollArea:SetHeight(offset + 70);
end
function DatesPlayed()
local datesWePlayed = {};
local datesWePlayedStamps = {};
for i, gameEntry in ipairs(data) do
if tContains(datesWePlayed, date("%d-%m-%Y", gameEntry.timeStamp)) == false then
tinsert(datesWePlayed, date("%d-%m-%Y", gameEntry.timeStamp));
tinsert(datesWePlayedStamps, gameEntry.timeStamp);
end
end
table.sort(datesWePlayedStamps, function (a, b) return a > b end);
local returnValue = {};
for k, v in ipairs(datesWePlayedStamps) do
tinsert(returnValue, date("%d-%m-%Y", v));
end
return returnValue;
end
function CreateDayHeader(i, offset, currentDay)
local dayHeaderWindow = Position(nil, callbacks.containerFrame, nil, callbacks.gameScrollerWindow:GetWidth() - 10, 70, nil, 5, -offset);
local wins = 0;
local losses = 0;
for j, gameEntry in ipairs(data) do
if date("%d-%m-%Y", gameEntry.timeStamp) == currentDay then
if gameEntry.playerSide == gameEntry.winner then
wins = wins + 1;
else
losses = losses + 1;
end
end
end
local dayHeaderText = Text(dayHeaderWindow, texts.dayText);
tinsert(sectionHandles, dayHeaderWindow);
dayHeaderText:SetText(currentDay);
if wins > 0 or losses > 0 then
if wins == 1 and losses == 1 then
dayHeaderWindow:SetScript("OnEnter", function(self, motion)
dayHeaderText:SetText(textInserts.headerOneWin.." - "..textInserts.headerOneLoss);
end);
elseif wins == 1 then
dayHeaderWindow:SetScript("OnEnter", function(self, motion)
dayHeaderText:SetText(textInserts.headerOneWin.." - "..losses..textInserts.headerLosses);
end);
elseif losses == 1 then
dayHeaderWindow:SetScript("OnEnter", function(self, motion)
dayHeaderText:SetText(wins..textInserts.headerWins.." - "..textInserts.headerOneLoss);
end);
else
dayHeaderWindow:SetScript("OnEnter", function(self, motion)
dayHeaderText:SetText(wins..textInserts.headerWins.." - "..losses..textInserts.headerLosses);
end);
end
end
dayHeaderWindow:SetScript("OnLeave", function(self, motion)
dayHeaderText:SetText(currentDay);
end);
end
function CreateFirstHeaderEntry()
callbacks.firstDayHeaderWindow = Position(nil, callbacks.gameScrollArea, nil, callbacks.gameScrollerWindow:GetWidth() - 10, 70, nil, 5, 0);
tinsert(sectionHandles, callbacks.firstDayHeaderWindow);
Text(callbacks.firstDayHeaderWindow, texts.sessionHeader);
end |
-- evoker: mount.lua
-- could be mount or unmount.
-- processed on all
local _=function(event)
log("mount_ok:"..pack(event))
-- created in ClientAction.toggleMount
local mountEvent=event.mountEvent
local isMounting=mountEvent.targetEntityName~=nil
local mount=nil
if isMounting then
mount=Entity.find(mountEvent.targetEntityName,mountEvent.targetEntityId,
mountEvent.targetEntityLogin)
assert(mount)
--assert(mount.mountedBy==nil)
end
local actor=Entity.find(mountEvent.actorEntityName,mountEvent.actorEntityId,
mountEvent.actorEntityLogin)
assert(actor)
-- тут все проверки пройдены, садим райдера на маунта
if isMounting then
assert(actor.mountedOn==nil)
else
assert(actor.mountedOn~=nil)
end
-- set connection
if isMounting then
mount.mountedBy=Entity.getReference(actor)
actor.mountedOn=Entity.getReference(mount)
local riderX,riderY=Entity.getRiderPoint(mount,actor)
Entity.smoothMove(actor,0.5,riderX,riderY)
else
mount=Entity.findByRef(actor.mountedOn)
mount.mountedBy=nil
actor.mountedOn=nil
end
end
return _ |
--[[
LibC
Copyright Amlal El Mahrouss All rights reserved
Core functionalities.
]]
LibC = LibC or {}
function LibC:AddCommand(Name, Func, Perms)
LibC.Promise:Init(function(Name, Func, Perms)
return isfunction(Func) && istable(Perms) && isstring(Name)
end, Name, Func, Perms):Do():Then(function(Name)
concommand.Add(Name, function(target, cmd, args, argStr)
if target:IsPlayer() && Perms[target:GetUserGroup()] then Func(target, cmd, args, argStr); end
end);
LibC:Log(Color(0, 122, 0), "Added ", Name, " to commands list!");
return true;
end, Name):Catch();
end |
-- Copyright (c) 2010-2011 by Robert G. Jakabosky <[email protected]>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
local _require = LibStub:GetLibrary('pblua.require')
local require = _require.require
local _M = LibStub:NewLibrary("pblua.unpack", 1)
local assert = assert
local pairs = pairs
local print = print
local error = error
local tostring = tostring
local setmetatable = setmetatable
local sformat = string.format
local type = type
local pcall = pcall
local rawset = rawset
local mod_path = string.match(...,".*%.") or ''
local unknown = require(mod_path .. "unknown")
local new_unknown = unknown.new
local buffer = require(mod_path .. "buffer")
local new_buffer = buffer.new
local pack = require(mod_path .. "pack")
local encode_field_tag = pack.encode_field_tag
local wire_types = pack.wire_types
--local struct = require"struct"
local sunpack = {}
local bit = require"bit"
local band = bit.band
local bor = bit.bor
local bxor = bit.bxor
local lshift = bit.lshift
local rshift = bit.rshift
local arshift = bit.arshift
local char = string.char
-- un-ZigZag encode/decode
local function unzigzag64(num)
if band(num, 1) == 1 then
num = -(num + 1)
end
return num / 2
end
local function unzigzag32(num)
return bxor(arshift(num, 1), -band(num, 1))
end
-- module(...)
----------------------------------------------------------------------------------
--
-- Unpack code.
--
----------------------------------------------------------------------------------
local function unpack_varint64(data, off)
local b = data:byte(off)
local num = band(b, 0x7F)
local boff = 7
while b >= 128 do
off = off + 1
b = data:byte(off)
num = bor(num, lshift(band(b, 0x7F), boff))
boff = boff + 7
end
return num, off + 1
end
local function unpack_varint32(data, off)
local b = data:byte(off)
local num = band(b, 0x7F)
local boff = 7
while b >= 128 do
off = off + 1
b = data:byte(off)
num = bor(num, lshift(band(b, 0x7F), boff))
boff = boff + 7
end
return num, off + 1
end
local basic = {
varint64 = unpack_varint64,
varint32 = unpack_varint32,
svarint64 = function(data, off)
local num
num, off = unpack_varint64(data, off)
return unzigzag64(num), off
end,
svarint32 = function(data, off)
local num
num, off = unpack_varint32(data, off)
return unzigzag32(num), off
end,
fixed64 = function(data, off)
return sunpack('<I8', data, off)
end,
sfixed64 = function(data, off)
return sunpack('<i8', data, off)
end,
double = function(data, off)
return sunpack('<d', data, off)
end,
fixed32 = function(data, off)
return sunpack('<I4', data, off)
end,
sfixed32 = function(data, off)
return sunpack('<i4', data, off)
end,
float = function(data, off)
return sunpack('<f', data, off)
end,
string = function(data, off)
local len
-- decode string length.
len, off = unpack_varint32(data, off)
-- decode string data.
local end_off = off + len
return data:sub(off, end_off - 1), end_off
end,
}
local function decode_field_tag(data, off)
local tag_type
tag_type, off = unpack_varint32(data, off)
local tag = rshift(tag_type, 3)
local wire_type = band(tag_type, 7)
return tag, wire_type, off
end
--
-- WireType unpack functions for unknown fields.
--
local unpack_unknown_field
local function try_unpack_unknown_message(data, off, len)
local tag, wire_type, val
-- create new list of unknown fields.
local msg = new_unknown()
-- unpack fields for unknown message
while (off <= len) do
-- decode field tag & wire_type
tag, wire_type, off = decode_field_tag(data, off)
-- unpack field
val, off = unpack_unknown_field(data, off, len, tag, wire_type, msg)
end
-- validate message
if (off - 1) ~= len then
error(sformat("Malformed Message, truncated ((off:%d) - 1) ~= len:%d): %s",
off, len, tostring(msg)))
end
return msg, off
end
local fixed64 = basic.fixed64
local fixed32 = basic.fixed32
local string = basic.string
local wire_unpack = {
[0] = function(data, off, len, tag, unknowns)
local val
-- unpack varint
val, off = unpack_varint32(data, off)
-- add to list of unknown fields
unknowns:addField(tag, 0, val)
return val, off
end,
[1] = function(data, off, len, tag, unknowns)
local val
-- unpack 64-bit field
val, off = fixed64(data, off)
-- add to list of unknown fields
unknowns:addField(tag, 1, val)
return val, off
end,
[2] = function(data, off, len, tag, unknowns)
local len, end_off, val
-- decode data length.
len, off = unpack_varint32(data, off)
end_off = off + len
-- try to decode as a message
local status
if len > 1 then
status, val = pcall(try_unpack_unknown_message, data, off, end_off - 1)
end
if not status then
-- failed to decode as a message
-- decode as raw data.
val = data:sub(off, end_off - 1)
end
-- add to list of unknown fields
unknowns:addField(tag, 2, val)
return val, end_off
end,
[3] = function(data, off, len, group_tag, unknowns)
local tag, wire_type, val
-- add to list of unknown fields
local group = unknowns:addGroup(group_tag)
-- unpack fields for unknown group.
while (off <= len) do
-- decode field tag & wire_type
tag, wire_type, off = decode_field_tag(data, off)
-- check for 'End group' tag
if wire_type == 4 then
if tag ~= group_tag then
error("Malformed Group, invalid 'End group' tag")
end
return group, off
end
-- unpack field
val, off = unpack_unknown_field(data, off, len, tag, wire_type, group)
end
error("Malformed Group, missing 'End group' tag")
end,
[4] = nil,
[5] = function(data, off, len, tag, unknowns)
local val
-- unpack 32-bit field
val, off = fixed32(data, off)
-- add to list of unknown fields
unknowns:addField(tag, 5, val)
return val, off
end,
}
function unpack_unknown_field(data, off, len, tag, wire_type, unknowns)
local funpack = wire_unpack[wire_type]
if funpack then
return funpack(data, off, len, tag, unknowns)
end
error(sformat("Invalid wire_type=%d, for unknown field=%d, off=%d, len=%d",
wire_type, tag, off, len))
end
--
-- packed repeated fields
--
local packed = setmetatable({},{
__index = function(tab, ftype)
local funpack
if type(ftype) == 'string' then
-- basic type
funpack = basic[ftype]
else
-- complex type (Enums)
funpack = ftype
end
rawset(tab, ftype, function(data, off, len, arr)
local i=#arr
while (off <= len) do
i = i + 1
arr[i], off = funpack(data, off, len, nil)
end
return arr, off
end)
end,
})
local unpack_field
local unpack_fields
local function unpack_length_field(data, off, len, field, val)
-- decode field length.
local field_len
field_len, off = unpack_varint32(data, off, len)
-- unpack field
return field.unpack(data, off, off + field_len - 1, val)
end
local function unpack_field(data, off, len, field, mdata)
local name = field.name
local val
if field.is_repeated then
local arr = mdata[name]
-- create array for repeated fields.
if not arr then
arr = field.new()
mdata[name] = arr
end
if field.is_packed then
-- unpack length-delimited packed array
return unpack_length_field(data, off, len, field, arr)
end
-- unpack repeated field (just one)
if field.has_length then
-- unpack length-delimited field.
arr[#arr + 1], off = unpack_length_field(data, off, len, field, nil)
else
arr[#arr + 1], off = field.unpack(data, off, len)
end
return arr, off
elseif field.has_length then
-- unpack length-delimited field
val, off = unpack_length_field(data, off, len, field, mdata[name])
mdata[name] = val
return val, off
end
-- is basic type.
val, off = field.unpack(data, off, len)
mdata[name] = val
return val, off
end
local function unpack_fields(data, off, len, msg, tags, is_group)
local tag, wire_type, field, val
local mdata = msg['.data']
local unknowns
while (off <= len) do
-- decode field tag & wire_type
tag, wire_type, off = decode_field_tag(data, off)
-- check for "End group"
if wire_type == 4 then
if not is_group then
error("Malformed Message, found extra 'End group' tag: " .. tostring(msg))
end
return msg, off
end
field = tags[tag]
if field then
if field.wire_type ~= wire_type then
error(sformat("Malformed Message, wire_type of field doesn't match (%d ~= %d)!",
field.wire_type, wire_type))
end
val, off = unpack_field(data, off, len, field, mdata)
else
if not unknowns then
-- check if Message already has Unknown fields object.
unknowns = mdata.unknown_fields
if not unknowns then
-- need to create an Unknown fields object.
unknowns = new_unknown()
mdata.unknown_fields = unknowns
end
end
-- unpack Unknown field
val, off = unpack_unknown_field(data, off, len, tag, wire_type, unknowns)
end
end
-- Groups should not end here.
if is_group then
error("Malformed Group, truncated, missing 'End group' tag: " .. tostring(msg))
end
-- validate message
if (off - 1) ~= len then
error(sformat("Malformed Message, truncated ((off:%d) - 1) ~= len:%d): %s",
off, len, tostring(msg)))
end
return msg, off
end
local function group(data, off, len, msg, tags, end_tag)
-- Unpack group fields.
msg, off = unpack_fields(data, off, len, msg, tags, true)
-- validate 'End group' tag
if data:sub(off - #end_tag, off - 1) ~= end_tag then
error("Malformed Group, invalid 'End group' tag: " .. tostring(msg))
end
return msg, off
end
local function message(data, off, len, msg, tags)
-- Unpack message fields.
return unpack_fields(data, off, len, msg, tags, false)
end
--
-- Map field types to common wire types
--
-- map types.
local map_types = {
-- varints
int32 = "varint32",
uint32 = "varint32",
bool = "varint32",
enum = "varint32",
int64 = "varint64",
uint64 = "varint64",
sint32 = "svarint32",
sint64 = "svarint64",
-- bytes
bytes = "string",
}
for k,v in pairs(map_types) do
basic[k] = basic[v]
end
local register_fields
local function get_type_unpack(mt)
local unpack = mt.unpack
-- check if this type has a unpack function.
if not unpack then
-- create a unpack function for this type.
if mt.is_enum then
local unpack_enum = basic.enum
local values = mt.values
unpack = function(data, off, len, enum)
local enum
enum, off = unpack_enum(data, off, len)
return values[enum], off
end
elseif mt.is_message then
local tags = mt.tags
local new = mt.new
unpack = function(data, off, len, msg)
if not msg then
msg = new()
end
return message(data, off, len, msg, tags)
end
register_fields(mt)
elseif mt.is_group then
local tags = mt.tags
local new = mt.new
-- encode group end tag.
local end_tag = encode_field_tag(mt.tag, wire_types.group_end)
unpack = function(data, off, len, msg)
if not msg then
msg = new()
end
return group(data, off, len, msg, tags, end_tag)
end
register_fields(mt)
end
-- cache unpack function.
mt.unpack = unpack
end
return unpack
end
function register_fields(mt)
-- check if the fields where already registered.
if mt.unpack then return end
local tags = mt.tags
local fields = mt.fields
for i=1,#fields do
local field = fields[i]
local tag = field.tag
local ftype = field.ftype
local wire_type = wire_types[ftype]
-- check if the field is a user type
local user_type_mt = field.user_type_mt
if user_type_mt then
field.unpack = get_type_unpack(user_type_mt)
if field.is_group then
wire_type = wire_types.group_start
elseif user_type_mt.is_enum then
wire_type = wire_types.enum
if field.is_unpacked then
field.unpack = packed[field.unpack]
end
else
wire_type = wire_types.message
end
elseif field.is_unpacked then
field.unpack = packed[ftype]
else
field.unpack = basic[ftype]
end
-- create field tag_type.
local tag_type = encode_field_tag(tag, wire_type)
field.tag_type = tag_type
field.wire_type = wire_type
end
end
function _M.register_msg(mt)
local tags = mt.tags
-- setup 'unpack' function for this message type.
get_type_unpack(mt)
-- create decode callback closure for this message type.
return function(msg, data, off)
return message(data, off, #data, msg, tags)
end
end
|
local IR = require("ir/insts")
local PUSH = setmetatable({}, { __tostring=function()
return "[PUSH]"
end })
local function same(a, b)
local t = a[1]
if b[1] ~= t then return false end
if t == IR.CONST then
return a[2] == b[2]
elseif t == IR.GETLOCAL then
return a[2] == b[2]
end
return false
end
local base = {}
base[IR.PUSH] = function(self, ir)
local bc = {}
for i=2,#ir do
if type(ir[i]) == "number" then
self:reg(self:localreg(ir[i]), PUSH)
bc[i-1] = ""
else
local a, ra = self:compile(ir[i])
self:reg(ra, PUSH)
bc[i-1] = a
end
end
return table.concat(bc, "")
end
base[IR.POP] = function(self, ir)
local bc = {}
for i=2,#ir do
if type(ir[i]) == "number" then
self:reg(self:localreg(ir[i]), false)
bc[i-1] = ""
else
-- pushes are important allocations (i.e. locals),
-- they shouldn't be overriden with expressions (e.g. assignments),
-- which compile to IR.POP
local a, ra = self:compile(ir[i])
if self.regs[ra] ~= PUSH then
self:reg(ra, false)
end
bc[i-1] = a
end
end
return table.concat(bc, "")
end
base[IR.LAST] = function(self, ir)
local r
local bc = {}
for i=2,#ir do
local a, ra = self:compile(ir[i])
if ra ~= #ir and self.regs[ra] ~= PUSH then
self:reg(ra, false)
end
bc[i-1] = a
r = ra
end
return table.concat(bc, ""), r
end
return { same=same, base=base, PUSH=PUSH }
|
--[[
Basic generic ground mode AI implementation.
An entity running this AI will randomly turn and wander a bit from time to time.
]]--
require 'common'
local BaseAI = require 'ai.ground_baseai'
local BaseState = require 'ai.base_state'
-------------------------------
-- States Class Definitions
-------------------------------
--[[------------------------------------------------------------------------
Idle state:
The entity will determine an idle action to take after a certain amount of time has passed.
It will play its idle animation meanwhile. And if it has a current task to execute it will
switch to the "Act" state.
]]--------------------------------------------------------------------------
local StateIdle = Class('StateIdle', BaseState)
--The range of possible wait time between idle movements, in number of calls to the state's "Run" method/frames
StateIdle.WaitMin = 40
StateIdle.WaitMax = 180
function StateIdle:initialize(parentai)
StateIdle.super.initialize(self, parentai)
--Set a time in ticks for the next idle action
self.idletimer = GAME.Rand:Next(self.parentAI.IdleDelayMin, self.parentAI.IdleDelayMax)
end
function StateIdle:Begin(prevstate, entity)
assert(self, "StateIdle:Begin(): Error, self is nil!")
StateIdle.super.Begin(self, prevstate, entity)
--Play Idle anim
end
function StateIdle:Run(entity)
DEBUG.EnableDbgCoro() --Enable debugging this coroutine
assert(self, "StateIdle:Run(): Error, self is nil!")
StateIdle.super.Run(self, entity)
local ent = LUA_ENGINE:CastToGroundAIUser(entity)
-- If a task is set, move to act
if ent:CurrentTask() then self.parentAI:SetState("Act") end
--Suspend while interacting with the entity
if ent.IsInteracting then
return
end
--If enough time passed, wander or turn
if self.idletimer <= 0 then
self:DoIdle()
end
--Tick down the idle timer
self.idletimer = self.idletimer - 1
end
-- Does pick an idle action to perform
function StateIdle:DoIdle()
self.idletimer = GAME.Rand:Next(StateIdle.WaitMin, StateIdle.WaitMax) -- Set the idle time for the next update
local choice = GAME.Rand:Next(0, 5) --Randomly decide to turn or wander
if choice == 0 then
self.parentAI:SetState("IdleTurn")
else
self.parentAI:SetState("IdleWander")
end
end
--[[------------------------------------------------------------------------
Act state:
In this special state, the AI will run the currently assigned
task if there is one. Then fall back to idle!
]]--------------------------------------------------------------------------
local StateAct = Class('StateAct', BaseState)
function StateAct:Begin(prevstate, entity)
assert(self, "StateAct:Begin(): Error, self is nil!")
StateAct.super.Begin(self, prevstate, entity)
--Stop Idle anim
end
function StateAct:Run(entity)
DEBUG.EnableDbgCoro() --Enable debugging this coroutine
assert(self, "StateAct:Run(): Error, self is nil!")
StateAct.super.Run(self, entity)
--Run current task if any
local ent = LUA_ENGINE:CastToGroundAIUser(entity)
--When interaction stopped, return to idle
if not ent:CurrentTask() then self.parentAI:SetState("Idle") end
end
--[[------------------------------------------------------------------------
IdleWander state:
When the entity is in this state, it will try to move to a random position.
]]--------------------------------------------------------------------------
local StateIdleWander = Class('StateIdleWander', BaseState)
StateIdleWander.WanderStepMin = 16
StateIdleWander.WanderStepMax = 32
function StateIdleWander:initialize(parentai)
assert(self, "StateIdleWander:initialize(): Error, self is nil!")
StateIdleWander.super.initialize(self, parentai)
--Set a maximum time to reach the position, since we don't really do pathfinding or anything, and something
-- in the way can get the entity stuck in this state forever
self.timeout = StateIdle.WaitMax
self.timeWandering = 0
self.WanderComplete = false
end
function StateIdleWander:Begin(prevstate, entity)
assert(self, "StateIdleWander:Begin(): Error, self is nil!")
StateIdleWander.super.Begin(self, prevstate, entity)
self.timeWandering = 0
self.wanderRadius = GAME.Rand:Next(self.parentAI.WanderStepMin, self.parentAI.WanderStepMax)
self:CalculateWanderPos(entity)
self:SetTask(entity)
end
-- Determine a random position around the entity to move to
function StateIdleWander:CalculateWanderPos(entity)
assert(self, "StateIdleWander:Begin(): Error, self is nil!")
self.WanderPos = entity.Position
self.WanderPos.X = self.WanderPos.X + (GAME.Rand:Next(0, self.wanderRadius * 2) - self.wanderRadius)
self.WanderPos.Y = self.WanderPos.Y + (GAME.Rand:Next(0, self.wanderRadius * 2) - self.wanderRadius)
--Clamp target position within the allowed move zone
if self.WanderPos.X > self.parentAI.WanderZonePos.X + self.parentAI.WanderZoneSize.X then
self.WanderPos.X = self.parentAI.WanderZonePos.X + self.parentAI.WanderZoneSize.X
elseif self.WanderPos.X < self.parentAI.WanderZonePos.X then
self.WanderPos.X = self.parentAI.WanderZonePos.X
end
if self.WanderPos.Y > self.parentAI.WanderZonePos.Y + self.parentAI.WanderZoneSize.Y then
self.WanderPos.Y = self.parentAI.WanderZonePos.Y + self.parentAI.WanderZoneSize.Y
elseif self.WanderPos.Y < self.parentAI.WanderZonePos.Y then
self.WanderPos.Y = self.parentAI.WanderZonePos.Y
end
local travelvector = self.WanderPos - entity.Position
local distance = math.sqrt(travelvector.X * travelvector.X) +
math.sqrt(travelvector.Y * travelvector.Y);
if distance == 0 then
self.wanderStep = RogueElements.Loc()
else
local xpos = travelvector.X / distance
local ypos = travelvector.Y / distance
self.wanderStep = {X = xpos, Y = ypos}
end
end
function StateIdleWander:SetTask(entity)
local wanderpos = self.WanderPos
local state = self
TASK:StartEntityTask(entity,
function()
GROUND:MoveToPosition(entity, wanderpos.X, wanderpos.Y, false, self.parentAI.WanderSpeed)
state.WanderComplete = true
end)
end
function StateIdleWander:Run(entity)
DEBUG.EnableDbgCoro() --Enable debugging this coroutine
assert(self, "StateIdleWander:Run(): Error, self is nil!")
StateIdleWander.super.Run(self, entity)
local ent = LUA_ENGINE:CastToGroundChar(entity)
-- If a task is set, move to act
if ent:CurrentTask() then self.parentAI:SetState("Act") end
--Suspend while interacting with the entity
if ent.IsInteracting then
self.parentAI:SetState("Idle")
end
-- When the position is reached, or we've been trying to wander for too long, go back to idle
local entXDiff = math.abs(ent.X - self.WanderPos.X)
local entYDiff = math.abs(ent.Y - self.WanderPos.Y)
if (entXDiff <= 1.0 or entYDiff <= 1.0) or self.WanderComplete or self.timeWandering >= self.timeout then
self.parentAI:SetState("Idle")
end
-- Step towards a random position decided at the transition to wander
-- local dir = GAME:VectorToDirection(self.wanderStep.X, self.wanderStep.Y)
-- if dir ~= RogueElements.Dir8.None then
-- ent.CurrentCommand = RogueEssence.Dungeon.GameAction(RogueEssence.Dungeon.GameAction.ActionType.Move, dir, 0);
-- end
--Increment timeout counter
self.timeWandering = self.timeWandering + 1
end
--[[------------------------------------------------------------------------
IdleTurn state:
When the entity is in this state, it will perform a slow turn towards a
random direction.
]]--------------------------------------------------------------------------
local StateIdleTurn = Class('IdleTurn', BaseState)
function StateIdleTurn:Begin(prevstate, entity)
assert(self, "StateIdleTurn:Begin(): Error, self is nil!")
StateIdleTurn.super.Begin(self, prevstate, entity)
-- Determine a random direction
self.turnDir = GAME.Rand:Next(0, 7)
end
function StateIdleTurn:Run(entity)
DEBUG.EnableDbgCoro() --Enable debugging this coroutine
assert(self, "StateIdleTurn:Run(): Error, self is nil!")
StateIdleTurn.super.Run(self, entity)
local ent = LUA_ENGINE:CastToGroundAIUser(entity)
-- If a task is set, move to act
if ent:CurrentTask() then self.parentAI:SetState("Act") end
--Suspend while interacting with the entity
if ent.IsInteracting then
self.parentAI:SetState("Idle")
end
local dir = GAME:RandomDirection()
if dir ~= RogueElements.Dir8.None then
GROUND:EntTurn(ent, dir)
end
-- When the direction is reached, go back to idle
--TODO: If we turn over several frams, add a conditional here!
self.parentAI:SetState("Idle")
end
--------------------------
-- ground_default AI Class
--------------------------
-- Basic ground character AI template
local ground_default = Class('ground_default', BaseAI)
--Constructor
function ground_default:initialize(wanderzoneloc, wanderzonesize, wanderspeed, wanderstepmin, wanderstepmax, idledelaymin, idledelaymax)
assert(self, "ground_default:initialize(): Error, self is nil!")
ground_default.super.initialize(self)
self.Memory = {} -- Where the AI will store any state shared variables it needs to keep track of at runtime (not serialized)
self.NextState = "Idle" --Always set the initial state as the next state, so "Begin" is run!
--Set the wander area
if not wanderzoneloc then
self.WanderZonePos = RogueElements.Loc()
else
self.WanderZonePos = wanderzoneloc
end
if not wanderzonesize then
self.WanderZoneSize = RogueElements.Loc()
else
self.WanderZoneSize = wanderzonesize
end
--Set the wander speed
if wanderspeed >= 1 then
self.WanderSpeed = wanderspeed
else
self.WanderSpeed = 1
end
--Set the delay between idle actions
if not idledelaymin then
self.IdleDelayMin = StateIdle.WaitMin
else
self.IdleDelayMin = idledelaymin
end
if not idledelaymax then
self.IdleDelayMax = StateIdle.WaitMax
else
self.IdleDelayMax = idledelaymax
end
--Set the min and max step possible
if not wanderstepmin then
self.WanderStepMin = StateIdleWander.WanderStepMin
else
self.WanderStepMin = wanderstepmin
end
if not wanderstepmax then
self.WanderStepMax = StateIdleWander.WanderStepMax
else
self.WanderStepMax = wanderstepmax
end
-- Place the instances of the states classes into the States table
self.States.Idle = StateIdle:new(self)
self.States.Act = StateAct:new(self)
self.States.IdleWander = StateIdleWander:new(self)
self.States.IdleTurn = StateIdleTurn:new(self)
end
--Return the class
return ground_default |
--[[
vim.api.nvim_buf_set_lines(0, 4, -1, false, vim.tbl_keys(require('telescope.builtin')))
--]]
require('telescope.builtin').git_files()
RELOAD('telescope'); require('telescope.builtin').oldfiles()
require('telescope.builtin').grep_string()
require('telescope.builtin').lsp_document_symbols()
RELOAD('telescope'); require('telescope.builtin').lsp_workspace_symbols()
require('telescope.builtin').lsp_references()
require('telescope.builtin').builtin()
require('telescope.builtin').fd()
require('telescope.builtin').command_history()
require('telescope.builtin').live_grep()
require('telescope.builtin').loclist()
-- TODO: make a function that puts stuff into quickfix.
-- that way we can test this better.
require('telescope.builtin').quickfix()
|
--Var
local item, recipe, entity, name, icon
--Copies
item = table.deepcopy(data.raw["item"]["roboport"])
recipe = table.deepcopy(data.raw["recipe"]["roboport"])
entity = table.deepcopy(data.raw["roboport"]["roboport"])
icon = "__5dim_logistic__/graphics/icon/roboport/roboport_3.png"
icon_size = 32
name = "5d-roboport-3"
--Changes
--Item
item.name = name
item.icon = icon
item.icon_size = icon_size
item.subgroup = "logistic-roboport"
item.order = "c"
item.place_result = name
--Recipe
recipe.name = name
recipe.icon = icon
recipe.icon_size = icon_size
recipe.result = name
recipe.enabled = "false"
recipe.icon_size = 32
recipe.ingredients = {
{"5d-roboport-2", 1},
{"steel-plate", 20},
{"iron-gear-wheel", 20},
{"advanced-circuit", 20},
{"processing-unit", 20}
}
--Entity
entity.name = name
entity.icon = icon
entity.icon_size = icon_size
entity.minable.result = name
entity.fast_replaceable_group = "roboport"
entity.energy_source.input_flow_limit = "15MW"
entity.energy_source.buffer_capacity = "300MJ"
entity.energy_usage = "300kW"
entity.charging_energy = "3000kW"
entity.logistics_radius = entity.logistics_radius * 2
entity.construction_radius = entity.construction_radius * 2
entity.robot_slots_count = 20
entity.material_slots_count = 20
entity.base = {
layers = {
{
filename = "__5dim_logistic__/graphics/icon/roboport/roboport-base-3.png",
width = 143,
height = 135,
shift = {0.5, 0.25},
hr_version = {
filename = "__5dim_logistic__/graphics/icon/roboport/hr-roboport-base-3.png",
width = 228,
height = 277,
shift = util.by_pixel(2, 7.75),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/roboport/roboport-shadow.png",
width = 147,
height = 102,
draw_as_shadow = true,
shift = util.by_pixel(28.5, 19.25),
hr_version = {
filename = "__base__/graphics/entity/roboport/hr-roboport-shadow.png",
width = 294,
height = 201,
draw_as_shadow = true,
shift = util.by_pixel(28.5, 19.25),
scale = 0.5
}
}
}
}
data:extend({item, recipe, entity})
|
--[[
===============================================================================
** BattleSprite v1.2 **
By Lysferd (C) 2015
===============================================================================
--]]
---------------------------------------------------------------------
-- * Declare BattleSprite.
---------------------------------------------------------------------
BattleSprite = { }
BattleSprite.__index = BattleSprite
function BattleSprite.new( filename )
local obj = setmetatable( { }, BattleSprite )
-- Initialise BattleSprite's bitmap data.
obj.bitmap = love.graphics.newImage( filename )
--
-- Get the default coordinates.
obj.x = WINDOW_WIDTH / 2 -- fixme: this should be given by the caller
obj.y = WINDOW_HEIGHT / 2 -- fixme: this should be given by the caller
obj.z = 1 -- Over ground level
obj.ow = obj.bitmap:getWidth()
obj.oh = obj.bitmap:getHeight()
obj.w = obj.ow / 3
obj.h = obj.oh / 8
--
-- Initialise flow control variables.
obj.sprinting = false -- triggers sprinting
obj.jumping = false -- triggers jumping
obj.jump_height = 0 -- jump height
obj.jump_state = nil -- jump animation state
obj.maximum_height = obj.h -- maximum jump height is its own height
obj.total_jump_frames = 6 -- total number of animation frames
obj.jump_sound = love.audio.newSource( 'audio/se/Jump1.ogg', 'static' )
obj.anime_frame = 0 -- start frame count at 0
obj.total_frames = 3 -- maximum animation frames
obj.move_freq = 10 -- 1 step each 10 frames
obj.move_vel = 1 -- 1 pixel per step
obj.step_frame = 1 -- current frame in the step animation
obj.last_step = 0 -- last frame in the step animation
obj.direction = 'down' -- BattleSprite current direction
obj.turn_rule = { bottom_left = 0,
down = 1,
bottom_right = 2,
left = 3,
right = 4,
upper_left = 5,
up = 6,
upper_right = 7 }
obj.quad = love.graphics.newQuad( 32 * obj.step_frame,
32 * obj.turn_rule[obj.direction],
32, 32, obj.ow, obj.oh )
return obj
end
---------------------------------------------------------------------
-- * Frame update.
---------------------------------------------------------------------
function BattleSprite:update()
if self.jumping then
if self.jump_state == 'ascending' then
self.jump_height = self.jump_height + ( self.maximum_height / self.total_jump_frames )
if self.jump_height >= self.maximum_height then
self.jump_height = self.maximum_height
self.jump_state = 'descending'
end
elseif self.jump_state == 'descending' then
self.jump_height = self.jump_height - ( self.maximum_height / self.total_jump_frames )
if self.jump_height <= 0 then
self.jump_height = 0
self.jumping = false
self.z = 1
end
end
end
end
---------------------------------------------------------------------
-- * Frame draw.
---------------------------------------------------------------------
function BattleSprite:draw()
love.graphics.draw( self.bitmap,
self.quad,
self.x,
self.y - self.jump_height,
0,
1,
1,
self.w / 2,
self.h / 2 )
end
---------------------------------------------------------------------
-- * Make BattleSprite face a certain direction.
---------------------------------------------------------------------
function BattleSprite:turn( direction )
local vx, vy, vw, vh = self.quad:getViewport()
self.quad:setViewport( vx, 32 * self.turn_rule[direction], vw, vh )
end
---------------------------------------------------------------------
-- * Move BattleSprite around.
---------------------------------------------------------------------
function BattleSprite:move( direction )
self:turn( direction )
local multiplier = 1
if self.sprinting then multiplier = 2 end
if direction == 'up' then
self.y = self.y - 1 * multiplier
elseif direction == 'down' then
self.y = self.y + 1 * multiplier
elseif direction == 'left' then
self.x = self.x - 1 * multiplier
elseif direction == 'right' then
self.x = self.x + 1 * multiplier
elseif direction == 'bottom_left' then
self.x = self.x - 1 * multiplier
self.y = self.y + 1 * multiplier
elseif direction == 'bottom_right' then
self.x = self.x + 1 * multiplier
self.y = self.y + 1 * multiplier
elseif direction == 'upper_left' then
self.x = self.x - 1 * multiplier
self.y = self.y - 1 * multiplier
elseif direction == 'upper_right' then
self.x = self.x + 1 * multiplier
self.y = self.y - 1 * multiplier
end
end
---------------------------------------------------------------------
function BattleSprite:jump()
self.jump_sound:play()
self.jumping = true
self.jump_state = 'ascending'
self.z = self.z + 1
end
---------------------------------------------------------------------
-- * Animate BattleSprite walking.
---------------------------------------------------------------------
function BattleSprite:animate()
local multiplier = 1
if self.sprinting then multiplier = 2 end
if self.animate then self.anime_frame = self.anime_frame + self.move_vel * multiplier end
if self.anime_frame >= self.move_freq then
if self.step_frame == 1 then
if self.last_step == 0 then
self.step_frame = 2
else
self.step_frame = 0
end
else
self.last_step = self.step_frame
self.step_frame = 1
end
local vx, vy, vw, vh = self.quad:getViewport()
self.quad:setViewport( 32 * self.step_frame, vy, vw, vh )
self.anime_frame = self.anime_frame - self.move_freq
end
end
---------------------------------------------------------------------
-- * Resets to standing position at movement stop.
---------------------------------------------------------------------
function BattleSprite:straighten()
self.last_step = self.step_frame
self.step_frame = 1
local vx, vy, vw, vh = self.quad:getViewport()
self.quad:setViewport( 32 * self.step_frame, vy, vw, vh )
end
|
local yourScreenWidth = 1920 -- Change to your screen width
local yourScreenHeight = 1080 -- Change to your screen height
local function WidthScaled( x )
return x / yourScreenWidth * ScrW()
end
local function HeightScaled( y )
return y / yourScreenHeight * ScrH()
end
hook.Add( "HUDPaint", "Base", function()
surface.SetDrawColor( 215, 215, 215, 255 )
surface.DrawRect( WidthScaled( 0 ), HeightScaled( 725 ), WidthScaled( 310 ), HeightScaled( 180 ) )
end )
|
describe('lol.league', function()
local league,match
setup(function()
match = require('luassert.match')
league = require('lol.league')
end)
it('loaded okay', function()
assert.not_nil(league)
end)
it('errors if given an invalid api obj', function()
assert.has.errors(function() league({}) end)
end)
describe('league', function()
local file, path
local cacheDir, keyfile, testApi
setup(function()
file = require('pl.file')
path = require('pl.path')
cacheDir = '.testCache'
if not path.isdir(cacheDir) then
path.mkdir(cacheDir)
end
keyfile = '.test_keyfile'
file.write(keyfile,'somerandomapikey')
local api = require('lol.api')
testApi = api(keyfile, 'na', cacheDir)
end)
teardown(function()
file.delete(keyfile)
if path.isdir(cacheDir) then
local dir = require('pl.dir')
dir.rmtree(cacheDir)
end
end)
it('can be created', function()
local testLeague = league(testApi)
assert.is.not_nil(testLeague)
end)
it('has the correct API version', function()
local testLeague = league(testApi)
assert.is_equal(testLeague.version, '2.5')
end)
insulate('getBySummonerId', function()
local testLeague
setup(function()
testLeague = league(testApi)
end)
it('calls getBySummonerIds', function()
local s1 = stub(testLeague, 'getBySummonerIds', function() end)
testLeague:getBySummonerId(123456789, {})
assert.stub(s1).called(1)
assert.stub(s1).called_with(testLeague, {123456789}, {})
end)
end)
insulate('getBySummonerIds', function()
local testLeague
setup(function()
testLeague = league(testApi)
end)
it('calls getByIds', function()
local s1 = stub(testLeague, 'getByIds', function() end)
testLeague:getBySummonerIds({123456789}, {})
assert.stub(s1).called(1)
assert.stub(s1).called_with(testLeague, {123456789}, 'summoner', {})
end)
end)
insulate('getByTeamId', function()
local testLeague
setup(function()
testLeague = league(testApi)
end)
it('calls getByTeamIds', function()
local s1 = stub(testLeague, 'getByTeamIds', function() end)
testLeague:getByTeamId(123456789, {})
assert.stub(s1).called(1)
assert.stub(s1).called_with(testLeague, {123456789}, {})
end)
end)
insulate('getByTeamIds', function()
local testLeague
setup(function()
testLeague = league(testApi)
end)
it('calls getByIds', function()
local s1 = stub(testLeague, 'getByIds', function() end)
testLeague:getByTeamIds({123456789}, {})
assert.stub(s1).called(1)
assert.stub(s1).called_with(testLeague, {123456789}, 'team', {})
end)
end)
insulate('getByIds', function()
local idTypeTestFn = function(idtype)
local testLeague
setup(function()
testLeague = league(testApi)
end)
before_each(function()
testLeague.api.cache:clearAll()
end)
it('uses api get on cache miss', function()
local s1 = stub(testLeague.api, 'get',function() end)
testLeague:getByIds({123456789}, idtype)
assert.stub(s1).called(1)
local url = {
path='/api/lol/${region}/v${version}/league/by-${idtype}/${ids}',
params={version=testLeague.version,idtype=idtype,ids=123456789},
}
assert.stub(s1).called_with(testLeague.api, match.same(url), match.is_function())
s1:revert()
end)
local cacheForXSecsFn = function(secs)
local mockTier = 'TIER'
local mockQueue = 'QUEUE'
local mockId = '123456789'
local mockEntry = {{queue=mockQueue,tier=mockTier,playerOrTeamId=mockId}}
local mockLeagues = {{queue=mockQueue,tier=mockTier,participantId=mockId,entries={{playerOrTeamId=mockId}}}}
local mockRes = {{[mockId] = mockLeagues}, 200, {}}
local api = testLeague.api
local cache = api.cache
local cacheSecs = secs or 7*24*60*60
local s1 = spy.new(function() end)
local s2 = stub(cache, 'set')
local s3 = stub(api, 'get', function(_,_,c) c(unpack(mockRes)) end)
testLeague:getByIds({mockId}, idtype, {callback=s1,expire=secs})
assert.spy(s1).called(1)
assert.spy(s1).called_with(mockLeagues, 200, {})
assert.stub(s2).called(2)
--TODO: Fix this test
--[[local tablex = require('pl.tablex')
local leagueCache = tablex.deepcopy(mockLeagues[1])
leagueCache.participantId = nil -- shouldn't cache the participant id so make sure it isn't
local leagueCacheKey = {api='league',queue=mockQueue,tier=mockTier}
assert.stub(s2).called_with(cache,leagueCacheKey,leagueCache,cacheSecs)]]
local cacheKey = {api='league', [idtype..'Id']=mockId}
assert.stub(s2).called_with(cache,cacheKey,match.same(mockEntry),cacheSecs)
s2:revert()
s3:revert()
end
it('caches api entries for 1 week by default', function()
cacheForXSecsFn()
end)
it('caches api entries for the specified amount of time', function()
cacheForXSecsFn(60)
end)
it('will return previously cached entries', function()
local mockTier = 'TIER'
local mockQueue = 'QUEUE'
local mockId = '123456789'
local mockEntry = {{queue=mockQueue,tier=mockTier,playerOrTeamId=mockId}}
local mockLeague = {queue=mockQueue,tier=mockTier,entries={{playerOrTeamId=mockId}}}
local cache = testLeague.api.cache
local s1 = spy.new(function() end)
local s2 = stub(cache, 'get', function(_,k) return (k.queue and mockLeague) or (k[idtype..'Id'] and mockEntry) end)
testLeague:getByIds({tonumber(mockId)}, idtype, {callback=s1})
assert.spy(s1).called(1)
assert.spy(s1).called_with({mockLeague})
s2:revert()
end)
it('will page results', function()
-- order cache entries back to front
local cacheEntries = {{{queue='QUEUE',tier='TIER',playerOrTeamId='456'}},{{queue='QUEUE',tier='TIER',playerOrTeamId='123'}}}
local api = testLeague.api
local cache = api.cache
local mockData1 = {}
local mockRes1 = {{}, 200, {}}
local ids = {123,456}
for i = 3, 10 do
table.insert(ids, i)
mockRes1[1][tostring(i)] = {{queue='QUEUE',tier='TIER',entries={{playerOrTeamId=tostring(i)}}}}
mockData1[tostring(i)] = {{queue='QUEUE',tier='TIER',playerOrTeamId=tostring(i)}}
end
local mockData2 = {}
local mockRes2 = {{}, 200, {}}
for i = 11,20 do
table.insert(ids, i)
mockRes2[1][tostring(i)] = {{queue='QUEUE',tier='TIER',entries={{playerOrTeamId=tostring(i)}}}}
mockData2[tostring(i)] = {{queue='QUEUE',tier='TIER',playerOrTeamId=tostring(i)}}
end
local reslist = {mockRes2,mockRes1}
local s1 = spy.new(function() end)
local s2 = stub(cache, 'get', function()
-- table.remove removes last entry first
return table.remove(cacheEntries)
end)
local s3 = stub(api, 'get', function(_,_,c) c(unpack(table.remove(reslist))) end)
testLeague:getEntryByIds(ids, idtype, {callback=s1})
assert.spy(s1).called(3) -- 1st & 2nd for api, 3rd for cache
assert.spy(s1).called_with(mockData1, mockRes1[2], mockRes1[3])
assert.spy(s1).called_with(mockData2, mockRes2[2], mockRes2[3])
local cacheRes = {}
cacheRes['123'] = {{queue='QUEUE',tier='TIER',playerOrTeamId='123'}}
cacheRes['456'] = {{queue='QUEUE',tier='TIER',playerOrTeamId='456'}}
assert.spy(s1).called_with(cacheRes)
s2:revert()
s3:revert()
end)
end
idTypeTestFn('summoner')
idTypeTestFn('team')
end)
insulate('getEntryBySummonerId', function()
local testLeague
setup(function()
testLeague = league(testApi)
end)
it('calls getEntryBySummonerIds', function()
local s1 = stub(testLeague, 'getEntryBySummonerIds', function() end)
testLeague:getEntryBySummonerId(123456789, {})
assert.stub(s1).called(1)
assert.stub(s1).called_with(testLeague, {123456789}, {})
end)
end)
insulate('getEntryBySummonerIds', function()
local testLeague
setup(function()
testLeague = league(testApi)
end)
it('calls getEntryByIds', function()
local s1 = stub(testLeague, 'getEntryByIds', function() end)
testLeague:getEntryBySummonerIds({123456789}, {})
assert.stub(s1).called(1)
assert.stub(s1).called_with(testLeague, {123456789}, 'summoner', {})
end)
end)
insulate('getEntryByTeamId', function()
local testLeague
setup(function()
testLeague = league(testApi)
end)
it('calls getEntryByTeamIds', function()
local s1 = stub(testLeague, 'getEntryByTeamIds', function() end)
testLeague:getEntryByTeamId(123456789, {})
assert.stub(s1).called(1)
assert.stub(s1).called_with(testLeague, {123456789}, {})
end)
end)
insulate('getEntryByTeamIds', function()
local testLeague
setup(function()
testLeague = league(testApi)
end)
it('calls getEntryByIds', function()
local s1 = stub(testLeague, 'getEntryByIds', function() end)
testLeague:getEntryByTeamIds({123456789}, {})
assert.stub(s1).called(1)
assert.stub(s1).called_with(testLeague, {123456789}, 'team', {})
end)
end)
insulate('getEntryByIds', function()
local idTypeTestFn = function(idtype)
local testLeague
setup(function()
testLeague = league(testApi)
end)
before_each(function()
testLeague.api.cache:clearAll()
end)
it('uses api get on cache miss', function()
local s1 = stub(testLeague.api, 'get',function() end)
testLeague:getEntryByIds({123456789}, idtype)
assert.stub(s1).called(1)
local url = {
path='/api/lol/${region}/v${version}/league/by-${idtype}/${ids}/entry',
params={version=testLeague.version,idtype=idtype,ids=123456789},
}
assert.stub(s1).called_with(testLeague.api, match.same(url), match.is_function())
s1:revert()
end)
local cacheForXSecsFn = function(secs)
local mockTier = 'TIER'
local mockQueue = 'QUEUE'
local mockId = '123456789'
local mockLeagueDto = {{queue=mockQueue,tier=mockTier,participantId=mockId,entries={{playerOrTeamId=mockId}}}}
local mockRes = {{[mockId] = mockLeagueDto}, 200, {}}
local mockEntry = {{queue=mockQueue,tier=mockTier,playerOrTeamId=mockId}}
local mockEntryRes = {}
mockEntryRes[mockId] = mockEntry
local api = testLeague.api
local cache = api.cache
local cacheSecs = secs or 7*24*60*60
local s1 = spy.new(function() end)
local s2 = stub(cache, 'set')
local s3 = stub(api, 'get', function(_,_,c) c(unpack(mockRes)) end)
testLeague:getEntryByIds({tonumber(mockId)}, idtype, {callback=s1,expire=secs})
assert.spy(s1).called(1)
assert.spy(s1).called_with(mockEntryRes, 200, {})
local cacheKey = {api='league', [idtype..'Id']=mockId}
assert.stub(s2).called(1)
assert.stub(s2).called_with(cache,cacheKey,match.same(mockEntry),cacheSecs)
s2:revert()
s3:revert()
end
it('caches api entries for 1 week by default', function()
cacheForXSecsFn()
end)
it('caches api entries for the specified amount of time', function()
cacheForXSecsFn(60)
end)
it('will return previously cached entries', function()
local mockTier = 'TIER'
local mockQueue = 'QUEUE'
local mockId = '123456789'
local mockEntry = {{queue=mockQueue,tier=mockTier,playerOrTeamId=mockId}}
local mockCacheRes = {}
mockCacheRes[mockId] = mockEntry
local cache = testLeague.api.cache
local s1 = spy.new(function() end)
local s2 = stub(cache, 'get', function() return mockEntry end)
testLeague:getEntryByIds({tonumber(mockId)}, idtype, {callback=s1})
assert.spy(s1).called(1)
assert.spy(s1).called_with(mockCacheRes)
s2:revert()
end)
it('will page results', function()
-- order cache entries back to front
local cacheEntries = {{{queue='QUEUE',tier='TIER',playerOrTeamId='456'}},{{queue='QUEUE',tier='TIER',playerOrTeamId='123'}}}
local api = testLeague.api
local cache = api.cache
local mockData1 = {}
local mockRes1 = {{}, 200, {}}
local ids = {123,456}
for i = 3, 10 do
table.insert(ids, i)
mockRes1[1][tostring(i)] = {{queue='QUEUE',tier='TIER',entries={{playerOrTeamId=tostring(i)}}}}
mockData1[tostring(i)] = {{queue='QUEUE',tier='TIER',playerOrTeamId=tostring(i)}}
end
local mockData2 = {}
local mockRes2 = {{}, 200, {}}
for i = 11,20 do
table.insert(ids, i)
mockRes2[1][tostring(i)] = {{queue='QUEUE',tier='TIER',entries={{playerOrTeamId=tostring(i)}}}}
mockData2[tostring(i)] = {{queue='QUEUE',tier='TIER',playerOrTeamId=tostring(i)}}
end
local reslist = {mockRes2,mockRes1}
local s1 = spy.new(function() end)
local s2 = stub(cache, 'get', function()
-- table.remove removes last entry first
return table.remove(cacheEntries)
end)
local s3 = stub(api, 'get', function(_,_,c) c(unpack(table.remove(reslist))) end)
testLeague:getEntryByIds(ids, idtype, {callback=s1})
assert.spy(s1).called(3) -- 1st & 2nd for api, 3rd for cache
assert.spy(s1).called_with(mockData1, mockRes1[2], mockRes1[3])
assert.spy(s1).called_with(mockData2, mockRes2[2], mockRes2[3])
local cacheRes = {}
cacheRes['123'] = {{queue='QUEUE',tier='TIER',playerOrTeamId='123'}}
cacheRes['456'] = {{queue='QUEUE',tier='TIER',playerOrTeamId='456'}}
assert.spy(s1).called_with(cacheRes)
s2:revert()
s3:revert()
end)
end
idTypeTestFn('summoner')
idTypeTestFn('team')
end)
insulate('getMasterLeague', function()
local testLeague
setup(function()
testLeague = league(testApi)
end)
it('calls getLeague', function()
local s1 = stub(testLeague, 'getLeague', function() end)
testLeague:getMasterLeague('QUEUE', {})
assert.stub(s1).called(1)
assert.stub(s1).called_with(testLeague, 'master', 'QUEUE', {})
end)
end)
insulate('getChallengerLeague', function()
local testLeague
setup(function()
testLeague = league(testApi)
end)
it('calls getLeague', function()
local s1 = stub(testLeague, 'getLeague', function() end)
testLeague:getChallengerLeague('QUEUE', {})
assert.stub(s1).called(1)
assert.stub(s1).called_with(testLeague, 'challenger', 'QUEUE', {})
end)
end)
insulate('getLeague', function()
local leagueTestFn = function(leagueType)
local testLeague
setup(function()
testLeague = league(testApi)
end)
before_each(function()
testLeague.api.cache:clearAll()
end)
it('uses api get on cache miss', function()
local mockQueue = 'RANKED_SOLO_5x5'
local s1 = stub(testLeague.api, 'get',function() end)
testLeague:getLeague(leagueType, mockQueue)
assert.stub(s1).called(1)
local url = {
path='/api/lol/${region}/v${version}/league/${league}',
params={version=testLeague.version,league=leagueType},
query={type=mockQueue}
}
assert.stub(s1).called_with(testLeague.api, match.same(url), match.is_function())
s1:revert()
end)
local cacheForXSecsFn = function(secs)
local mockQueue = 'RANKED_SOLO_5x5'
local mockTier = testLeague.Leagues[leagueType]
local mockId = '123456789'
local mockRes = {{queue=mockQueue,tier=mockTier,entries={{playerOrTeamId=mockId}}}, 200, {}}
local api = testLeague.api
local cache = api.cache
local cacheSecs = secs or 7*24*60*60
local s1 = spy.new(function() end)
local s2 = stub(cache, 'set')
local s3 = stub(api, 'get', function(_,_,c) c(unpack(mockRes)) end)
testLeague:getLeague(leagueType, mockQueue, {callback=s1,expire=secs})
assert.spy(s1).called(1)
assert.spy(s1).called_with(mockRes[1], 200, {})
assert.stub(s2).called(2)
--TODO: Fix this test
--[[local leagueCacheKey = {api='league',queue=mockQueue,tier=mockTier}
assert.stub(s2).called_with(cache,leagueCacheKey,match.same(mockRes[1]),cacheSecs)]]
local idtype = testLeague.RankedQueues[mockQueue]
local cacheKey = {api='league', [idtype..'Id']=mockId}
assert.stub(s2).called_with(cache,cacheKey,{{queue=mockQueue,tier=mockTier,playerOrTeamId=mockId}},cacheSecs)
s2:revert()
s3:revert()
end
it('caches api entries for 1 week by default', function()
cacheForXSecsFn()
end)
it('caches api entries for the specified amount of time', function()
cacheForXSecsFn(60)
end)
it('will return previously cached entries', function()
local mockQueue = 'RANKED_SOLO_5x5'
local mockTier = testLeague.Leagues[leagueType]
local mockId = '123456789'
local mockLeague = {queue=mockQueue,tier=mockTier,entries={{playerOrTeamId=mockId}}}
local cache = testLeague.api.cache
local s1 = spy.new(function() end)
local s2 = stub(cache, 'get', function() return mockLeague end)
testLeague:getLeague(leagueType, mockQueue, {callback=s1})
assert.spy(s1).called(1)
assert.spy(s1).called_with(mockLeague)
s2:revert()
end)
end
leagueTestFn('master')
leagueTestFn('challenger')
end)
end)
end)
|
AddCSLuaFile()
ENT.Base = "base_anim"
ENT.Type = "anim"
ENT.PrintName = "Spider Antidote"
ENT.Spawnable = true
ENT.AdminSpawnable = true
ENT.Category = "Drones Rewrite Tools"
if SERVER then
function ENT:SpawnFunction(ply, tr, class)
if not tr.Hit then return end
local pos = tr.HitPos + tr.HitNormal * 16
local ent = ents.Create(class)
ent:SetPos(pos)
ent:SetAngles(Angle(0, (ply:GetPos() - tr.HitPos):Angle().y + 90, 0))
ent:Spawn()
ent:Activate()
return ent
end
function ENT:Initialize()
self:SetModel("models/props_lab/jar01a.mdl")
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:PhysicsInit(SOLID_VPHYSICS)
self:SetUseType(SIMPLE_USE)
local phys = self:GetPhysicsObject()
if IsValid(phys) then phys:Wake() end
end
function ENT:Use(activator, caller)
if not activator:IsPlayer() then return end
local val = -5
if activator.DRR_Poisoned then
val = 5
activator:ChatPrint("[Drones] You feel bad")
net.Start("dronesrewrite_playsound")
net.WriteString("vo/npc/male01/moan04.wav")
net.Send(activator)
if math.random(1, 2) == 1 then
timer.Create("dronesrewrite_stoppoison_antidote" .. activator:EntIndex(), 2, 1, function()
if IsValid(activator) then
hook.Remove("Think", "dronesrewrite_bite_poison" .. activator:EntIndex())
activator.DRR_Poisoned = false
end
end)
end
else
if activator.SHOULDDIE_ANTIDOTE then
activator:Kill()
activator.SHOULDDIE_ANTIDOTE = false
return
end
activator.SHOULDDIE_ANTIDOTE = true
timer.Create("dronesrewrite_antidoteshit" .. activator:EntIndex(), 30, 1, function()
if IsValid(activator) then
activator.SHOULDDIE_ANTIDOTE = false
end
end)
end
activator:SetHealth(math.min(activator:Health() + val, activator:GetMaxHealth()))
self:Remove()
end
function ENT:OnTakeDamage(dmg)
self:TakePhysicsDamage(dmg)
end
else
function ENT:Draw()
self:DrawModel()
end
end |
local vmf = get_mod("VMF")
local _ingame_ui
local _ingame_ui_disabled
-- There's no direct access to local variable 'transitions' in ingame_ui.
local _ingame_ui_transitions = require("scripts/ui/views/ingame_ui_settings").transitions
local _views_data = {}
local ERRORS = {
THROWABLE = {
-- inject_view:
view_already_exists = "view with name '%s' already persists in original game.",
transition_already_exists = "transition with name '%s' already persists in original game.",
view_initializing_failed = "view initialization failed due to error during 'init_view_function' execution.",
-- validate_view_data:
view_name_wrong_type = "'view_name' must be a string, not %s.",
view_transitions_wrong_type = "'view_transitions' must be a table, not %s.",
view_settings_wrong_type = "'view_settings' must be a table, not %s.",
transition_wrong_type = "all transitions inside 'view_transitions' must be functions, but '%s' transition is %s.",
transition_name_taken = "transition name '%s' is already used by '%s' mod for '%s' view.",
init_view_function_wrong_type = "'view_settings.init_view_function' must be a function, not %s.",
active_wrong_type = "'view_settings.active' must be a table, not %s.",
active_missing_element = "'view_settings.active' must contain 2 elements: 'inn' and 'ingame'.",
active_element_wrong_name = "the only allowed names for 'view_settings.active' elements are 'inn' and 'ingame'; " ..
"you can't name your element '%s'.",
active_element_wrong_type = "'view_settings.active.%s' must be boolean, not %s.",
blocked_transitions_wrong_type = "'view_settings.blocked_transitions' (optional) must be a table, not %s.",
blocked_transitions_missing_element = "'view_settings.blocked_transitions' must contain 2 table elements: " ..
"'inn' and 'ingame'.",
blocked_transitions_element_wrong_name = "the only allowed names for 'view_settings.active' elements are " ..
"'inn' and 'ingame'; you can't name your element '%s'.",
blocked_transitions_element_wrong_type = "'view_settings.blocked_transitions.%s' must be a table, not %s.",
blocked_transition_invalid = "you can't put transition '%s' into 'view_settings.blocked_transitions.%s', " ..
"because it's not listed in 'view_transitions'.",
blocked_transition_wrong_value = "invalid value for 'view_settings.blocked_transitions.%s.%s'; must be 'true'."
},
REGULAR = {
view_not_registered = "[Custom Views] Toggling view with keybind: view '%s' wasn't registered for this mod.",
transition_not_registered = "[Custom Views] Toggling view with keybind: transition '%s' wasn't registered for " ..
"'%s' view."
},
PREFIX = {
view_initializing = "[Custom Views] Calling 'init_view_function'",
view_destroying = "[Custom Views] Destroying view '%s'",
register_view_validation = "[Custom Views] (register_view) View data validating '%s'",
register_view_injection = "[Custom Views] (register_view) View injection '%s'",
ingameui_hook_injection = "[Custom Views] View injection '%s'",
handle_transition_fade = "[Custom Views] (handle_transition) executing 'ingame_ui.transition_with_fade' for " ..
"transition '%s'",
handle_transition_no_fade = "[Custom Views] (handle_transition) executing 'ingame_ui.handle_transition' for " ..
"transition '%s'"
}
}
-- #####################################################################################################################
-- ##### Local functions ###############################################################################################
-- #####################################################################################################################
local function is_view_active_for_current_level(view_name)
local active = _views_data[view_name].view_settings.active
if _ingame_ui.is_in_inn and active.inn or not _ingame_ui.is_in_inn and active.ingame then
return true
end
end
-- @THROWS_ERRORS
local function inject_view(view_name)
if not is_view_active_for_current_level(view_name) then
return
end
local view_settings = _views_data[view_name].view_settings
local mod = _views_data[view_name].mod
local init_view_function = view_settings.init_view_function
local transitions = _views_data[view_name].view_transitions
local blocked_transitions = view_settings.blocked_transitions[_ingame_ui.is_in_inn and "inn" or "ingame"]
-- Check for collisions.
if _ingame_ui.views[view_name] then
vmf.throw_error(ERRORS.THROWABLE.view_already_exists, view_name)
end
for transition_name, _ in pairs(transitions) do
if _ingame_ui_transitions[transition_name] then
vmf.throw_error(ERRORS.THROWABLE.transition_already_exists, transition_name)
end
end
-- Initialize and inject view.
local success, view = vmf.safe_call(mod, ERRORS.PREFIX.view_initializing, init_view_function,
_ingame_ui.ingame_ui_context)
if success then
_ingame_ui.views[view_name] = view
else
vmf.throw_error(ERRORS.THROWABLE.view_initializing_failed)
end
-- Inject view transitions.
for transition_name, transition_function in pairs(transitions) do
_ingame_ui_transitions[transition_name] = transition_function
end
-- Inject view blocked transitions.
for blocked_transition_name, _ in pairs(blocked_transitions) do
_ingame_ui.blocked_transitions[blocked_transition_name] = true
end
end
local function remove_injected_views(on_reload)
-- These elements should be removed only on_reload, because, otherwise, they will be deleted automatically.
if on_reload then
-- If some custom view is active, safely close it.
if _views_data[_ingame_ui.current_view] then
-- Hack to ensure cursor stack safety.
ShowCursorStack.stack_depth = ShowCursorStack.stack_depth + 1
_ingame_ui:handle_transition("exit_menu")
ShowCursorStack.stack_depth = 1
ShowCursorStack.pop()
end
for view_name, view_data in pairs(_views_data) do
-- Remove injected views.
local view = _ingame_ui.views[view_name]
if view then
if type(view.destroy) == "function" then
vmf.safe_call_nr(view_data.mod, {ERRORS.PREFIX.view_destroying, view_name}, view.destroy, view)
end
_ingame_ui.views[view_name] = nil
end
end
end
for _, view_data in pairs(_views_data) do
-- Remove injected transitions.
for transition_name, _ in pairs(view_data.view_transitions) do
_ingame_ui_transitions[transition_name] = nil
end
-- Remove blocked transitions
local blocked_transitions = view_data.view_settings.blocked_transitions[_ingame_ui.is_in_inn and "inn" or "ingame"]
for blocked_transition_name, _ in pairs(blocked_transitions) do
_ingame_ui.blocked_transitions[blocked_transition_name] = nil
end
end
end
-- @THROWS_ERRORS
local function validate_view_data(view_data)
-- Basic checks.
if type(view_data.view_name) ~= "string" then
vmf.throw_error(ERRORS.THROWABLE.view_name_wrong_type, type(view_data.view_name))
end
if type(view_data.view_transitions) ~= "table" then
vmf.throw_error(ERRORS.THROWABLE.view_transitions_wrong_type, type(view_data.view_transitions))
end
if type(view_data.view_settings) ~= "table" then
vmf.throw_error(ERRORS.THROWABLE.view_settings_wrong_type, type(view_data.view_settings))
end
-- VIEW TRANSITIONS
local view_transitions = view_data.view_transitions
for transition_name, transition_function in pairs(view_transitions) do
if type(transition_function) ~= "function" then
vmf.throw_error(ERRORS.THROWABLE.transition_wrong_type, transition_name, type(transition_function))
end
for another_view_name, another_view_data in pairs(_views_data) do
for another_transition_name, _ in pairs(another_view_data.view_transitions) do
if transition_name == another_transition_name then
vmf.throw_error(ERRORS.THROWABLE.transition_name_taken, transition_name, another_view_data.mod:get_name(),
another_view_name)
end
end
end
end
-- VIEW SETTINGS
local view_settings = view_data.view_settings
-- Use default values for optional fields if they are not defined.
view_settings.blocked_transitions = view_settings.blocked_transitions or {inn = {}, ingame = {}}
-- Verify everything.
if type(view_settings.init_view_function) ~= "function" then
vmf.throw_error(ERRORS.THROWABLE.init_view_function_wrong_type, type(view_settings.init_view_function))
end
local active = view_settings.active
if type(active) ~= "table" then
vmf.throw_error(ERRORS.THROWABLE.active_wrong_type, type(active))
end
if active.inn == nil or active.ingame == nil then
vmf.throw_error(ERRORS.THROWABLE.active_missing_element)
end
for level_name, value in pairs(active) do
if level_name ~= "inn" and level_name ~= "ingame" then
vmf.throw_error(ERRORS.THROWABLE.active_element_wrong_name, level_name)
end
if type(value) ~= "boolean" then
vmf.throw_error(ERRORS.THROWABLE.active_element_wrong_type, level_name, type(value))
end
end
local blocked_transitions = view_settings.blocked_transitions
if type(blocked_transitions) ~= "table" then
vmf.throw_error(ERRORS.THROWABLE.blocked_transitions_wrong_type, type(blocked_transitions))
end
if not blocked_transitions.inn or not blocked_transitions.ingame then
vmf.throw_error(ERRORS.THROWABLE.blocked_transitions_missing_element)
end
for level_name, level_blocked_transitions in pairs(blocked_transitions) do
if level_name ~= "inn" and level_name ~= "ingame" then
vmf.throw_error(ERRORS.THROWABLE.blocked_transitions_element_wrong_name, level_name)
end
if type(level_blocked_transitions) ~= "table" then
vmf.throw_error(ERRORS.THROWABLE.blocked_transitions_element_wrong_type, level_name,
type(level_blocked_transitions))
end
for transition_name, value in pairs(level_blocked_transitions) do
if not view_transitions[transition_name] then
vmf.throw_error(ERRORS.THROWABLE.blocked_transition_invalid, transition_name, level_name)
end
if value ~= true then
vmf.throw_error(ERRORS.THROWABLE.blocked_transition_wrong_value, level_name, transition_name)
end
end
end
end
-- #####################################################################################################################
-- ##### VMFMod ########################################################################################################
-- #####################################################################################################################
--[[
Wraps ingame_ui transition handling calls in a lot of safety checks. Returns 'true', if call is successful.
* transition_name [string] : name of a transition that should be perfomed
* ignore_active_menu [boolean] : if 'ingame_ui.menu_active' should be ignored
* fade [boolean] : if transition should be performed with fade
* transition_params [anything]: parameter, which will be passed to callable transition function, 'on_exit' method of
the old view and 'on_enter' method of the new view
--]]
function VMFMod:handle_transition(transition_name, ignore_active_menu, fade, transition_params)
if vmf.check_wrong_argument_type(self, "handle_transition", "transition_name", transition_name, "string") then
return
end
local vt2_player_list_active
if not VT1 then
local ingame_player_list_ui = _ingame_ui.ingame_hud:component("IngamePlayerListUI")
vt2_player_list_active = ingame_player_list_ui and ingame_player_list_ui:is_active()
end
if _ingame_ui
and not _ingame_ui_disabled
and not _ingame_ui:pending_transition()
and not _ingame_ui:end_screen_active()
and (not _ingame_ui.menu_active or ignore_active_menu)
and not _ingame_ui.leave_game
and not _ingame_ui.return_to_title_screen
and (
VT1
and not _ingame_ui.menu_suspended
and not _ingame_ui.popup_join_lobby_handler.visible
or not VT1
and not Managers.transition:in_fade_active()
and not _ingame_ui:cutscene_active()
and not _ingame_ui:unavailable_hero_popup_active()
and (not vt2_player_list_active or ignore_active_menu)
)
then
if fade then
vmf.safe_call_nr(self, {ERRORS.PREFIX.handle_transition_fade, transition_name}, _ingame_ui.transition_with_fade,
_ingame_ui, transition_name,
transition_params)
else
vmf.safe_call_nr(self, {ERRORS.PREFIX.handle_transition_no_fade, transition_name}, _ingame_ui.handle_transition,
_ingame_ui, transition_name,
transition_params)
end
return true
end
end
--[[
Opens a file with a view data and validates it. Registers the view and returns 'true' if everything is correct.
* view_data_file_path [string]: path to a file returning view_data table
--]]
function VMFMod:register_view(view_data)
if vmf.check_wrong_argument_type(self, "register_view", "view_data", view_data, "table") then
return
end
view_data = table.clone(view_data)
local view_name = view_data.view_name
if not vmf.safe_call_nrc(self, {ERRORS.PREFIX.register_view_validation, view_name}, validate_view_data,
view_data) then
return
end
_views_data[view_name] = {
mod = self,
view_settings = view_data.view_settings,
view_transitions = view_data.view_transitions
}
if _ingame_ui then
if not vmf.safe_call_nrc(self, {ERRORS.PREFIX.register_view_injection, view_name}, inject_view, view_name) then
_views_data[view_data.view_name] = nil
end
end
return true
end
-- #####################################################################################################################
-- ##### Hooks #########################################################################################################
-- #####################################################################################################################
vmf:hook_safe(IngameUI, "init", function(self)
_ingame_ui = self
for view_name, _ in pairs(_views_data) do
if not vmf.safe_call_nrc(self, {ERRORS.PREFIX.ingameui_hook_injection, view_name}, inject_view, view_name) then
_views_data[view_name] = nil
end
end
end)
vmf:hook_safe(IngameUI, "destroy", function()
remove_injected_views(false)
_ingame_ui = nil
end)
vmf:hook_safe(IngameUI, "update", function(self, dt_, t_, disable_ingame_ui)
_ingame_ui_disabled = disable_ingame_ui
end)
-- #####################################################################################################################
-- ##### VMF internal functions and variables ##########################################################################
-- #####################################################################################################################
function vmf.remove_custom_views()
if _ingame_ui then
remove_injected_views(true)
end
end
-- Opens/closes a view if all conditions are met. Since keybinds module can't do UI-related checks, all the cheks are
-- done in this function. This function is called every time some view-toggling keybind is pressed.
function vmf.keybind_toggle_view(mod, view_name, keybind_transition_data, can_be_opened, is_keybind_pressed)
if _ingame_ui then
local view_data = _views_data[view_name]
if not view_data or (view_data.mod ~= mod) then
mod:error(ERRORS.REGULAR.view_not_registered, view_name)
return
end
if is_view_active_for_current_level(view_name) then
if _ingame_ui.current_view == view_name then
if keybind_transition_data.close_view_transition_name and not Managers.chat:chat_is_focused() then
if view_data.view_transitions[keybind_transition_data.close_view_transition_name] then
mod:handle_transition(keybind_transition_data.close_view_transition_name, true,
keybind_transition_data.transition_fade,
keybind_transition_data.close_view_transition_params)
else
mod:error(ERRORS.REGULAR.transition_not_registered, keybind_transition_data.close_view_transition_name,
view_name)
end
end
-- Can open views only when keybind is pressed.
elseif can_be_opened and is_keybind_pressed then
if keybind_transition_data.open_view_transition_name then
if view_data.view_transitions[keybind_transition_data.open_view_transition_name] then
mod:handle_transition(keybind_transition_data.open_view_transition_name, true,
keybind_transition_data.transition_fade,
keybind_transition_data.open_view_transition_params)
else
mod:error(ERRORS.REGULAR.transition_not_registered, keybind_transition_data.open_view_transition_name,
view_name)
end
end
end
end
end
end
-- #####################################################################################################################
-- ##### Script ########################################################################################################
-- #####################################################################################################################
-- If VMF is reloaded mid-game, get ingame_ui.
_ingame_ui = (VT1 and Managers.matchmaking and Managers.matchmaking.ingame_ui) or (Managers.ui and Managers.ui._ingame_ui)
|
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- F I N A L C U T P R O A P I --
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--- === cp.apple.finalcutpro.main.MediaBrowser ===
---
--- Media Browser Module.
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
local log = require("hs.logger").new("mediaBrowser")
local inspect = require("hs.inspect")
local just = require("cp.just")
local prop = require("cp.prop")
local axutils = require("cp.ui.axutils")
local PrimaryWindow = require("cp.apple.finalcutpro.main.PrimaryWindow")
local SecondaryWindow = require("cp.apple.finalcutpro.main.SecondaryWindow")
local Button = require("cp.ui.Button")
local Table = require("cp.ui.Table")
local ScrollArea = require("cp.ui.ScrollArea")
local CheckBox = require("cp.ui.CheckBox")
local PopUpButton = require("cp.ui.PopUpButton")
local TextField = require("cp.ui.TextField")
local id = require("cp.apple.finalcutpro.ids") "MediaBrowser"
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local MediaBrowser = {}
MediaBrowser.TITLE = "Photos and Audio"
MediaBrowser.MAX_SECTIONS = 4
MediaBrowser.PHOTOS = 1
MediaBrowser.GARAGE_BAND = 2
MediaBrowser.ITUNES = 3
MediaBrowser.SOUND_EFFECTS = 4
-- TODO: Add documentation
function MediaBrowser:new(parent)
local o = {_parent = parent}
return prop.extend(o, MediaBrowser)
end
-- TODO: Add documentation
function MediaBrowser:parent()
return self._parent
end
-- TODO: Add documentation
function MediaBrowser:app()
return self:parent():app()
end
-----------------------------------------------------------------------
--
-- MEDIABROWSER UI:
--
-----------------------------------------------------------------------
-- TODO: Add documentation
function MediaBrowser:UI()
if self:isShowing() then
return axutils.cache(self, "_ui", function()
return self:parent():UI()
end)
end
return nil
end
-- TODO: Add documentation
MediaBrowser.isShowing = prop.new(function(self)
local parent = self:parent()
return parent:isShowing() and parent:showMedia():isChecked()
end):bind(MediaBrowser)
-- TODO: Add documentation
function MediaBrowser:show()
local menuBar = self:app():menuBar()
-- Go there direct
menuBar:selectMenu({"Window", "Go To", MediaBrowser.TITLE})
just.doUntil(function() return self:isShowing() end)
return self
end
-- TODO: Add documentation
function MediaBrowser:hide()
self:parent():hide()
return self
end
-----------------------------------------------------------------------------
--
-- SECTIONS:
--
-----------------------------------------------------------------------------
-- TODO: Add documentation
function MediaBrowser:mainGroupUI()
return axutils.cache(self, "_mainGroup",
function()
local ui = self:UI()
return ui and axutils.childWithRole(ui, "AXSplitGroup")
end)
end
-- TODO: Add documentation
function MediaBrowser:sidebar()
if not self._sidebar then
self._sidebar = Table.new(self, function()
return axutils.childWithID(self:mainGroupUI(), id "Sidebar")
end)
end
return self._sidebar
end
-- TODO: Add documentation
function MediaBrowser:group()
if not self._group then
self._group = PopUpButton:new(self, function()
return axutils.childWithRole(self:UI(), "AXPopUpButton")
end)
end
return self._group
end
-- TODO: Add documentation
function MediaBrowser:search()
if not self._search then
self._search = TextField:new(self, function()
return axutils.childWithRole(self:mainGroupUI(), "AXTextField")
end)
end
return self._search
end
-- TODO: Add documentation
function MediaBrowser:showSidebar()
self:app():menuBar():checkMenu({"Window", "Show in Workspace", "Sidebar"})
end
-- TODO: Add documentation
function MediaBrowser:topCategoriesUI()
return self:sidebar():rowsUI(function(row)
return row:attributeValue("AXDisclosureLevel") == 0
end)
end
-- TODO: Add documentation
function MediaBrowser:showSection(index)
self:showSidebar()
local topCategories = self:topCategoriesUI()
if topCategories and #topCategories == MediaBrowser.MAX_SECTIONS then
self:sidebar():selectRow(topCategories[index])
end
return self
end
-- TODO: Add documentation
function MediaBrowser:showPhotos()
return self:showSection(MediaBrowser.PHOTOS)
end
-- TODO: Add documentation
function MediaBrowser:showGarageBand()
return self:showSection(MediaBrowser.GARAGE_BAND)
end
-- TODO: Add documentation
function MediaBrowser:showITunes()
return self:showSection(MediaBrowser.ITUNES)
end
-- TODO: Add documentation
function MediaBrowser:showSoundEffects()
return self:showSection(MediaBrowser.SOUND_EFFECTS)
end
-- TODO: Add documentation
function MediaBrowser:saveLayout()
local layout = {}
if self:isShowing() then
layout.showing = true
layout.sidebar = self:sidebar():saveLayout()
layout.search = self:search():saveLayout()
end
return layout
end
-- TODO: Add documentation
function MediaBrowser:loadLayout(layout)
if layout and layout.showing then
self:show()
self:sidebar():loadLayout(layout.sidebar)
self:search():loadLayout(layout.sidebar)
end
end
return MediaBrowser |
return {'joggelen','joggen','jogger','jogging','joggingbroek','joggingpak','jogjakarta','joggel','joggers','jog','jogde','joggend','joggingbroeken','joggingpakken','joggingpakje'} |
require("ts3init")
local registeredEvents = {
onTextMessageEvent = tipps_events.onTextMessageEvent
onClientMoveEvent = tipps_events.onClientMoveEvent
}
ts3RegisterModule("tipps", registeredEvents)
|
function PresentModWinConSettings()
Conditionsrequiredforwinit = Mod.Settings.Conditionsrequiredforwin;
if(Conditionsrequiredforwinit == nil)then
Conditionsrequiredforwinit = 1;
end
Capturedterritoriesinit = Mod.Settings.Capturedterritories;
if(Capturedterritoriesinit == nil)then
Capturedterritoriesinit = 0;
end
Lostterritoriesinit = Mod.Settings.Lostterritories;
if(Lostterritoriesinit == nil)then
Lostterritoriesinit = 0;
end
Ownedterritoriesinit = Mod.Settings.Ownedterritories;
if(Ownedterritoriesinit == nil)then
Ownedterritoriesinit = 0;
end
Capturedbonusesinit = Mod.Settings.Capturedbonuses;
if(Capturedbonusesinit == nil)then
Capturedbonusesinit = 0;
end
Lostbonusesinit = Mod.Settings.Lostbonuses;
if(Lostbonusesinit == nil)then
Lostbonusesinit = 0;
end
Ownedbonusesinit = Mod.Settings.Ownedbonuses;
if(Ownedbonusesinit == nil)then
Ownedbonusesinit = 0;
end
Killedarmiesinit = Mod.Settings.Killedarmies;
if(Killedarmiesinit == nil)then
Killedarmiesinit = 0;
end
Lostarmiesinit = Mod.Settings.Lostarmies;
if(Lostarmiesinit == nil)then
Lostarmiesinit = 0;
end
Ownedarmiesinit = Mod.Settings.Ownedarmies;
if(Ownedarmiesinit == nil)then
Ownedarmiesinit = 0;
end
Eleminateaisinit = Mod.Settings.Eleminateais;
if(Eleminateaisinit == nil)then
Eleminateaisinit = 0;
end
Eleminateplayersinit = Mod.Settings.Eleminateplayers;
if(Eleminateplayersinit == nil)then
Eleminateplayersinit = 0;
end
Eleminateaisandplayersinit = Mod.Settings.Eleminateaisandplayers;
if(Eleminateaisandplayersinit == nil)then
Eleminateaisandplayersinit = 0;
end
terrconditioninit = Mod.Settings.terrcondition
if(terrconditioninit == nil)then
terrconditioninit = {};
end
ShowUI();
end
function ShowUI()
local num = 0;
local conditionnumber = 14;
--TODO check if we can suport commanders OR put up an important text msg about limits.
UI.CreateLabel(vertlistWinCon[0]).SetText('To disable a win condition, set it to 0.');
UI.CreateLabel(vertlistWinCon[1]).SetText('Number of conditions required for a win');
inputConditionsrequiredforwin = UI.CreateNumberInputField(vertlistWinCon[1]).SetSliderMinValue(1).SetSliderMaxValue(11).SetValue(Conditionsrequiredforwinit);
UI.CreateLabel(vertlistWinCon[2]).SetText('Captured this many territories');
inputCapturedterritories = UI.CreateNumberInputField(vertlistWinCon[2]).SetSliderMinValue(0).SetSliderMaxValue(1000).SetValue(Capturedterritoriesinit);
UI.CreateLabel(vertlistWinCon[3]).SetText('Lost this many territories ');
inputLostterritories = UI.CreateNumberInputField(vertlistWinCon[3]).SetSliderMinValue(0).SetSliderMaxValue(1000).SetValue(Lostterritoriesinit);
UI.CreateLabel(vertlistWinCon[4]).SetText('Owns this many territories ');
inputOwnedterritories = UI.CreateNumberInputField(vertlistWinCon[4]).SetSliderMinValue(0).SetSliderMaxValue(1000).SetValue(Ownedterritoriesinit);
UI.CreateLabel(vertlistWinCon[5]).SetText('Captured this many bonuses ');
inputCapturedbonuses = UI.CreateNumberInputField(vertlistWinCon[5]).SetSliderMinValue(0).SetSliderMaxValue(100).SetValue(Capturedbonusesinit);
UI.CreateLabel(vertlistWinCon[6]).SetText('Lost this many bonuses ');
inputLostbonuses = UI.CreateNumberInputField(vertlistWinCon[6]).SetSliderMinValue(0).SetSliderMaxValue(100).SetValue(Lostbonusesinit);
UI.CreateLabel(vertlistWinCon[7]).SetText('Owns this many bonuses ');
inputOwnedbonuses = UI.CreateNumberInputField(vertlistWinCon[7]).SetSliderMinValue(0).SetSliderMaxValue(100).SetValue(Ownedbonusesinit);
UI.CreateLabel(vertlistWinCon[8]).SetText('Killed this many armies ');
inputKilledarmies = UI.CreateNumberInputField(vertlistWinCon[8]).SetSliderMinValue(0).SetSliderMaxValue(1000).SetValue(Killedarmiesinit);
UI.CreateLabel(vertlistWinCon[9]).SetText('Lost this many armies ');
inputLostarmies = UI.CreateNumberInputField(vertlistWinCon[9]).SetSliderMinValue(0).SetSliderMaxValue(1000).SetValue(Lostarmiesinit);
UI.CreateLabel(vertlistWinCon[10]).SetText('Owns this many armies ');
inputOwnedarmies = UI.CreateNumberInputField(vertlistWinCon[10]).SetSliderMinValue(0).SetSliderMaxValue(1000).SetValue(Ownedarmiesinit);
UI.CreateLabel(vertlistWinCon[11]).SetText("Eleminated this many ais(players turned into ai don't count)");
inputEleminateais = UI.CreateNumberInputField(vertlistWinCon[11]).SetSliderMinValue(0).SetSliderMaxValue(39).SetValue(Eleminateaisinit);
UI.CreateLabel(vertlistWinCon[12]).SetText('Eliminated this many players ');
inputEleminateplayers = UI.CreateNumberInputField(vertlistWinCon[12]).SetSliderMinValue(0).SetSliderMaxValue(39).SetValue(Eleminateplayersinit);
UI.CreateLabel(vertlistWinCon[13]).SetText('Eliminated this many AIs and players');
inputEleminateaisandplayers = UI.CreateNumberInputField(vertlistWinCon[13]).SetSliderMinValue(0).SetSliderMaxValue(39).SetValue(Eleminateaisandplayersinit);
--Territory conditions
UI.CreateButton(vertlistWinCon[14]).SetText('Save territory conditions').SetOnClick(saveTerritoryConditions);
inputterrcondition = {};
inputWinConTerr = {}
for i=0,5,1 do
inputWinConTerr[i] = {};
inputWinConTerr[i].Terrname = UI.CreateTextInputField(vertlistWinCon[15+i]).SetPlaceholderText(' Enter territory name').SetText("").SetPreferredWidth(200).SetPreferredHeight(30);
if (terrconditioninit[i] ~= nil )then
if (terrconditioninit[i].Terrname ~= nil) then inputWinConTerr[i].Terrname.SetText(terrconditioninit[i].Terrname) end;
end;
UI.CreateLabel(vertlistWinCon[15+i]).SetText("controlled for ");
inputWinConTerr[i].Turnnum = UI.CreateNumberInputField(vertlistWinCon[15+i]).SetSliderMinValue(0).SetSliderMaxValue(10).SetValue(0);
if (terrconditioninit[i] ~= nil )then
if (terrconditioninit[i].Turnnum ~= nil) then inputWinConTerr[i].Turnnum.SetValue(terrconditioninit[i].Turnnum) end;
end;
UI.CreateLabel(vertlistWinCon[15+i]).SetText("turns");
end;
saveTerritoryConditions();
end
function saveTerritoryConditions()
for i=0,5,1 do
inputterrcondition[i] = inputWinConTerr[i];
end
end;
--TODO remove and use util instead?
function tablelength(arr)
local num = 0;
for _,elem in pairs(arr)do
num = num + 1;
end
return num;
end
|
local skynet = require "skynet"
local utils = require "utils"
local M = {}
function M:init()
self.id_tbl = {}
self.account_tbl = {}
self:load_all()
end
function M:load_all()
local num = 0
local accounts = skynet.call("mongo", "lua", "load_all_account")
for _,obj in ipairs(accounts) do
self.account_tbl[obj.account] = obj
self.id_tbl[obj.userid] = obj.account
num = num + 1
end
skynet.send("xlog", "lua", "log", "加载所有用户成功,num="..num)
end
function M:gen_id()
local id
while true do
id = math.random(100000,999999)
if not self.id_tbl[id] then
return id
end
end
end
function M:get_by_account(account)
return self.account_tbl[account]
end
-- 验证账号密码
function M:verify(account, password)
local info = self.account_tbl[account]
if not info then
return "account not exist"
end
if info.password ~= password then
return "wrong password"
end
return "success", info
end
-- 注册账号
function M:register(info)
if self.account_tbl[info.account] then
return "account exists"
end
local userid = self:gen_id()
local acc = {
userid = userid,
account = info.account,
password = info.password,
sex = info.sex,
openid = "0",
headimgurl = info.headimgurl,
nickname = info.nickname,
}
self.account_tbl[info.account] = acc
skynet.send("mongo", "lua", "new_account", acc)
skynet.send("mysql", "lua", "bind", acc.openid, acc.userid, acc.nickname)
return "success", acc
end
-- 注册微信账号
function M:wx_login(info)
skynet.send("xlog", "lua", "log", "微信账号登录"..utils.table_2_str(info))
local acc = self.account_tbl[info.account]
if not acc then
acc = utils.copy_table(info)
acc.userid = self:gen_id()
self.account_tbl[info.account] = acc
skynet.send("mongo", "lua", "new_account", acc)
skynet.send("mysql", "lua", "bind", acc.openid, acc.userid, acc.nickname)
end
return acc
end
function M:guest()
local account
local code
local time = os.time()
while true do
code = time .. math.random(1,100)
account = "guest" .. code
if not self.account_tbl[account] then
break
end
end
local userid = self:gen_id()
local acc = {
userid = userid,
account = account,
password = tostring(time),
sex = math.random(1,2),
openid = "1",
headimgurl = "",
nickname = "游客"..math.random(100,999)
}
self.account_tbl[account] = acc
skynet.send("mongo", "lua", "new_account", acc)
skynet.send("mysql", "lua", "bind", acc.openid, acc.userid, acc.nickname)
return acc
end
function M:save(info)
local acc = self:get_by_account(info.account)
if not acc then
return
end
skynet.send("mongo", "lua", "update_account", acc)
end
return M
|
local status_ok, lualine = pcall(require, "lualine")
if not status_ok then
print('error loading lualine')
return
end
lualine.setup({
options = {
theme = 'vscode',
},
sections = {
lualine_a = {{'filename', path = 2}},
lualine_b = {'branch', 'diff'},
lualine_c = {},
lualine_x = {},
lualine_y = {},
lualine_z = {},
},
})
|
local ssl = require "ngx.ssl"
local io = require "io"
string.split = function(s, p)
local rt= {}
string.gsub(s, '[^'..p..']+', function(w) table.insert(rt, w) end )
return rt
end
local server_name = ssl.server_name()
if not server_name then
return
end
-- 清除之前设置的证书和私钥
local ok, err = ssl.clear_certs()
if not ok then
ngx.log(ngx.ERR, "failed to clear existing (fallback) certificates")
return ngx.exit(ngx.ERROR)
end
-- 获取证书内容,比如 io.open("my.crt"):read("*a")
local cmd = ("sh /etc/nginx/ssl/lua/certificate.sh ".. server_name)
local handle = io.popen(cmd)
local data = handle:read("*a")
local list = string.split(data, ',')
local cert_data = list[1]
if not cert_data then
return
end
-- 解析出 cdata 类型的证书值,你可以用 lua-resty-lrucache 缓存解析结果
local cert, err = ssl.parse_pem_cert(cert_data)
if not cert then
return
end
local ok, err = ssl.set_cert(cert)
if not ok then
return
end
local pkey_data = list[2]
if not pkey_data then
return
end
local pkey, err = ssl.parse_pem_priv_key(pkey_data)
local ok, err = ssl.set_priv_key(pkey)
if not ok then
return
end
|
local input = require('lib4/inpt')
local game = {}
function game:_load()
love3d:enable()
input.enable_keyevents()
end
return game
|
package.path = "internal/lua/?.lua"
local included = pcall(debug.getlocal, 4, 1)
local T = require("test")
local A = require("argparse")
local expect = T.expect
local is_table = T.is_table
local raised = T.error_raised
local new = function()
local parser = A()
local p = parser:parse({})
is_table(p)
end
local one_arg = function()
local parser = A()
parser:argument("foo")
local args = parser:parse({"bar"})
expect("bar")(args.foo)
end
local opt_arg = function()
local parser = A()
parser:argument("foo"):args("?")
local args = parser:parse({"bar"})
expect("bar")(args.foo)
end
local many_args = function()
local parser = A()
parser:argument("foo1")
parser:argument("foo2")
local args = parser:parse({"bar", "baz"})
expect("bar")(args.foo1)
expect("baz")(args.foo2)
end
local wildcard_args = function()
local parser = A()
parser:argument("foo"):args("*")
local args = parser:parse({"bar", "baz", "qu"})
expect("bar")(args.foo[1])
expect("baz")(args.foo[2])
expect("qu")(args.foo[3])
end
local hyphens = function()
local parser = A()
parser:argument("foo")
local args = parser:parse({"-"})
expect("-")(args.foo)
args = parser:parse({"--", "-q"})
expect("-q")(args.foo)
end
local commands_after_args = function()
local parser = A("name")
parser:argument("file")
parser:command("create")
parser:command("remove")
local args = parser:parse{"temp.txt", "remove"}
expect("temp.txt")(args.file)
expect(true)(args.remove)
end
local command_flags = function()
local parser = A("name")
local install = parser:command("install")
install:flag "-q" "--quiet"
local args = parser:parse{"install", "-q"}
expect(true)(args.install)
expect(true)(args.quiet)
end
local nested_commands = function()
local parser = A("name")
local install = parser:command("install")
install:command("bar")
local args = parser:parse{"install", "bar"}
expect(true)(args.install)
expect(true)(args.bar)
end
local action_args = function()
local parser = A()
local foo
parser:argument("foo"):action(function(_, _, passed)
foo = passed
end)
local baz
parser:argument("baz"):args("*"):action(function(_, _, passed)
baz = passed
end)
parser:parse({"a"})
expect("a")(foo)
expect(0)(#baz)
parser:parse({"b", "c"})
expect("b")(foo)
expect("c")(baz[1])
parser:parse({"d", "e", "f"})
expect("d")(foo)
expect("e")(baz[1])
expect("f")(baz[2])
end
if included then
return function()
T["new parser"] = new
T["one argument"] = one_arg
T["optional argument"] = opt_arg
T["several arguments"] = many_args
T["wildcard arguments"] = wildcard_args
T["hyphens"] = hyphens
T["commands after arguments"] = commands_after_args
T["command flags"] = command_flags
T["nested commands"] = nested_commands
T["action on arguments"] = action_args
end
else
T["new parser"] = new
T["one argument"] = one_arg
T["optional argument"] = opt_arg
T["several arguments"] = many_args
T["wildcard arguments"] = wildcard_args
T["hyphens"] = hyphens
T["commands after arguments"] = commands_after_args
T["command flags"] = command_flags
T["nested commands"] = nested_commands
T["action on arguments"] = action_args
end
|
local library = loadstring(game:HttpGet("https://raw.githubusercontent.com/StopReverseEngineeringMyScripts/WhatAreYouDoingHere/main/YummySource",true))()
local main = library:CreateWindow('Main')
local Items = library:CreateWindow('Items')
local Teams = library:CreateWindow('Teams')
noclip = false
game:GetService('RunService').Stepped:connect(function()
if noclip then
game.Players.LocalPlayer.Character.Humanoid:ChangeState(11)
end
end)
plr = game.Players.LocalPlayer
mouse = plr:GetMouse()
mouse.KeyDown:connect(function(key)
if key == "o" then
noclip = not noclip
game.Players.LocalPlayer.Character.Humanoid:ChangeState(11)
end
end)
local WalkingSlider = main:Slider('Walk Speed Adjuster', {min = 16, max = 200, default = 16}, function(value)
game:GetService('Players').LocalPlayer.Character.Humanoid.WalkSpeed = value
end)
local JumpingSlider = main:Slider('Jump Power Adjuster', {min = 50, max = 300, default = 50}, function(value)
game:GetService('Players').LocalPlayer.Character.Humanoid.JumpPower = value
end)
local HipSlider = main:Slider('HipHeight Adjuster', {min = 0.5, max = 100, default = 0.5}, function(value)
game:GetService('Players').LocalPlayer.Character.Humanoid.HipHeight = value
end)
local Feature = main:Button('Infinite Blocks', function()
for i,v in pairs(game:GetService("Players").LocalPlayer.PlayerGui.BuildGui.InventoryFrame.ScrollingFrame.BlocksFrame:GetChildren()) do
if v:FindFirstChild("AmountText") then
v.AmountText.Text = 999
v.AmountText.Changed:Connect(function()
v.AmountText.Text = 999
end)
end
end
end)
local Feature = main:Button('Clear All Blocks', function()
workspace.ClearAllPlayersBoatParts:FireServer()
end)
local Feature = Items:Button('Open Common Chest', function()
local args = {
[1] = "Common Chest",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Open Uncommon Chest', function()
local args = {
[1] = "Uncommon Chest",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Open Rare Chest', function()
local args = {
[1] = "Rare Chest",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Open Epic Chest', function()
local args = {
[1] = "Epic Chest",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Open Legendary Chest', function()
local args = {
[1] = "Legendary Chest",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy Locked Door', function()
local args = {
[1] = "Locked Doors",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy ObsidianBlock', function()
local args = {
[1] = "ObsidianBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy TitaniumBlock', function()
local args = {
[1] = "TitaniumBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy WoodenBlock', function()
local args = {
[1] = "WoodBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy MarbleBlock', function()
local args = {
[1] = "MarbleBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy MarbleBlock', function()
local args = {
[1] = "MarbleBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy BrickBlock', function()
local args = {
[1] = "BrickBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy CoalBlock', function()
local args = {
[1] = "CoalBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy IceBlock', function()
local args = {
[1] = "IceBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy ConcreteBlock', function()
local args = {
[1] = "ConcreteBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy MetalBlock', function()
local args = {
[1] = "MetalBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy RustedBlock', function()
local args = {
[1] = "RustedBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy SandBlock', function()
local args = {
[1] = "SandBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy GrassBlock', function()
local args = {
[1] = "GrassBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy PlasticBlock', function()
local args = {
[1] = "PlasticBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy FabricBlock', function()
local args = {
[1] = "FabricBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy StoneBlock', function()
local args = {
[1] = "StoneBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy GlassBlock', function()
local args = {
[1] = "GlassBlock",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy DomeCamera', function()
local args = {
[1] = "CameraDome",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy Camera', function()
local args = {
[1] = "Camera",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy Balloons', function()
local args = {
[1] = "Balloons",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = Items:Button('Buy Sign', function()
local args = {
[1] = "Sign",
[2] = 1
}
workspace.ItemBoughtFromShop:InvokeServer(unpack(args))
end)
local Feature = main:Button('Destroy Trees', function()
game:GetService("Workspace").Trees:Destroy()
end)
local Feature = main:Toggle('Enable PVP', function(state)
if state then
game:GetService("Players").LocalPlayer.Settings.PVP.Value = true
else
game:GetService("Players").LocalPlayer.Settings.PVP.Value = false
end
end)
local Feature = Teams:Button('Launch Green Team', function()
workspace.CamoZone.RE:FireServer()
end)
local Feature = Teams:Button('Launch Black Team', function()
workspace.BlackZone.RE:FireServer()
end)
local Feature = Teams:Button('Launch Purple Team', function()
workspace.MagentaZone.RE:FireServer()
end)
local Feature = Teams:Button('Launch Red Team', function()
workspace["Really redZone"].RE:FireServer()
end)
local Feature = Teams:Button('Launch Yellow Team', function()
workspace["New YellerZone"].RE:FireServer()
end)
local Feature = Teams:Button('Launch Blue Team', function()
workspace["Really blueZone"].RE:FireServer()
end)
local Feature = Teams:Button('Launch White Team', function()
workspace.WhiteZone.RE:FireServer()
end)
local Feature = Teams:Button('Request Green Team', function()
local args = {
[1] = game:GetService("Teams").green
}
workspace.ChangeTeam:FireServer(unpack(args))
end)
local Feature = Teams:Button('Request Black Team', function()
local args = {
[1] = game:GetService("Teams").black
}
workspace.ChangeTeam:FireServer(unpack(args))
end)
local Feature = Teams:Button('Request Purple Team', function()
local args = {
[1] = game:GetService("Teams").magenta
}
workspace.ChangeTeam:FireServer(unpack(args))
end)
local Feature = Teams:Button('Request Red Team', function()
local args = {
[1] = game:GetService("Teams").red
}
workspace.ChangeTeam:FireServer(unpack(args))
end)
local Feature = Teams:Button('Request Yellow Team', function()
local args = {
[1] = game:GetService("Teams").yellow
}
workspace.ChangeTeam:FireServer(unpack(args))
end)
local Feature = Teams:Button('Request Yellow Team', function()
local args = {
[1] = game:GetService("Teams").yellow
}
workspace.ChangeTeam:FireServer(unpack(args))
end)
local Feature = Teams:Button('Request Blue Team', function()
local args = {
[1] = game:GetService("Teams").blue
}
workspace.ChangeTeam:FireServer(unpack(args))
end)
local Feature = Teams:Button('Request White Team', function()
local args = {
[1] = game:GetService("Teams").white
}
workspace.ChangeTeam:FireServer(unpack(args))
end)
local Feature = main:Button('Morph Fox', function()
local A_1 = "FoxCharacter"
local Event = game:GetService("Workspace").ChangeCharacter
Event:FireServer(A_1)
end)
local Feature = main:Button('Morph Chicken', function()
local A_1 = "ChickenCharacter"
local Event = game:GetService("Workspace").ChangeCharacter
Event:FireServer(A_1)
end)
local Feature = main:Button('Morph Penguin', function()
local A_1 = "PenguinCharacter"
local Event = game:GetService("Workspace").ChangeCharacter
Event:FireServer(A_1)
end)
local Meme = main:Toggle('Noclip', function(state)
if state then
noclip = true
wait(0.1)
game.StarterGui:SetCore("SendNotification", {
Title = "GrubHub";
Text = "Enabled";
Icon = "rbxassetid://1299491401";
Duration = 3;
})
else
noclip = false
wait(0.1)
game.StarterGui:SetCore("SendNotification", {
Title = "Disabled";
Icon = "rbxassetid://1299491401";
Duration = 3;
})
end
end)
local Meme = main:Button('Autofarm', function()
while true do
wait(0.1)
game:GetService('Players').LocalPlayer.Character.Humanoid.HipHeight = 69
wait(0.1)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,1360)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,1606)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,2110)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,2356)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,2860)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,3610)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,3856)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,4360)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,4606)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,5111)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,5356)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,5860)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,6106)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,6610)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,6857)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,7360)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,7606)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,8110)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(x,y,8356)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(-51.5658951, 23.603878, 8576.83789)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(-54.326313, -334.156006, 8919.47363)
wait(2)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(-58.3624916, -360.209442, 9490.91016)
wait(0.1)
game:GetService('Players').LocalPlayer.Character.Humanoid.HipHeight = 1
wait(18)
end
end)
|
local function foo(k)
return k*k, 2*k + 1
end
local a, b
a, b = 13, foo(3)
print(a, b)
|
local skynet = require "skynet"
local ball = require "ball"
local systemcontainer = require "systemcontainer"
local entity = require "room.components"
local basesystem = require "room.systems.base"
local tiny = require "tiny"
local assert = assert
local cls = class("context")
function cls:ctor(id, ... )
-- body
self.ball = ball()
self.pool = Chestnut.EntitasPP.Pool.Create()
self.joinsystem = Chestnut.Ball.JoinSystem.Create()
self.mapsystem = Chestnut.Ball.MapSystem.Create()
self.movesystem = Chestnut.Ball.MoveSystem.Create()
self.indexsystem = Chestnut.Ball.IndexSystem.Create()
self.pool:Test()
-- self.pool:CreateSystemPtr(self.joinsystem)
-- self.pool:CreateSystemPtr(self.mapsystem)
-- self.pool:CreateSystemPtr(self.movesystem)
-- self.pool:CreateSystemPtr(self.indexsystem)
self.systemcontainer = systemcontainer.new(self.pool)
self.systemcontainer:add(self.joinsystem)
self.systemcontainer:add(self.mapsystem)
self.systemcontainer:add(self.movesystem)
self.systemcontainer:add(self.indexsystem)
self.systemcontainer:setpool()
self.tinyworld = tiny.world(basesystem)
self.mode = nil
self.max_number = 10
return self
end
function cls:push_client(name, args, ... )
-- body
for _,v in pairs(self._playeres) do
local agent = v:get_agent()
skynet.send(agent, "lua", name, args)
end
end
function cls:start(mode, ... )
-- body
self.mode = mode
-- load map id
self.systemcontainer:initialize()
-- update
skynet.fork(function ( ... )
-- body
skynet.sleep(100 / 5) -- 5fps
self:fixedupdate()
end)
return true
end
function cls:close( ... )
-- body
for _,user in pairs(users) do
gate.req.unregister(user.session)
end
return true
end
function cls:fixedupdate( ... )
-- body
self.tinyworld:update()
self.systemcontainer:fixedexcute()
end
function cls:match(conf, ... )
-- body
basesystem:match(self.tinyworld, conf)
return true
end
function cls:join(index, ... )
-- body
self.joinsystem:Join(index)
end
function cls:leave(index, ... )
-- body
self.joinsystem:Leave(index)
end
return cls |
local AddonName, AddonTable = ...
-- TBC Junk
AddonTable.junk = {
22153, -- Tome of Arcane Brilliance
22980, -- Tome of Frost Ward
23938, -- Pristine Ravager Carapace
24368, -- Coilfang Armaments
24508, -- Elemental Fragment
24511, -- Primordial Essence
24576, -- Loosely Threaded Belt
25340, -- Loosely Threaded Vest
25341, -- Dilapidated Cloth Belt
25342, -- Dilapidated Cloth Boots
25343, -- Dilapidated Cloth Bracers
25344, -- Dilapidated Cloth Gloves
25345, -- Dilapidated Cloth Hat
25346, -- Dilapidated Cloth Pants
25347, -- Dilapidated Cloth Shoulderpads
25348, -- Dilapidated Cloth Vest
25349, -- Moldy Leather Armor
25350, -- Moldy Leather Belt
25351, -- Moldy Leather Boots
25352, -- Moldy Leather Bracers
25353, -- Moldy Leather Gloves
25354, -- Moldy Leather Helmet
25355, -- Moldy Leather Pants
25356, -- Moldy Leather Shoulderpads
25357, -- Decaying Leather Armor
25358, -- Decaying Leather Belt
25359, -- Decaying Leather Boots
25360, -- Decaying Leather Bracers
25361, -- Decaying Leather Gloves
25362, -- Decaying Leather Helmet
25363, -- Decaying Leather Pants
25364, -- Decaying Leather Shoulderpads
25365, -- Eroded Mail Armor
25366, -- Eroded Mail Belt
25367, -- Eroded Mail Boots
25368, -- Eroded Mail Bracers
25369, -- Eroded Mail Circlet
25370, -- Eroded Mail Gloves
25371, -- Eroded Mail Pants
25373, -- Corroded Mail Armor
25374, -- Corroded Mail Belt
25375, -- Corroded Mail Boots
25376, -- Corroded Mail Bracers
25377, -- Corroded Mail Circlet
25378, -- Corroded Mail Gloves
25379, -- Corroded Mail Pants
25380, -- Corroded Mail Shoulderpads
25381, -- Tarnished Plate Belt
25382, -- Tarnished Plate Boots
25384, -- Tarnished Plate Chestpiece
25385, -- Tarnished Plate Gloves
25386, -- Tarnished Plate Helmet
25387, -- Tarnished Plate Pants
25388, -- Tarnished PLate Shoulderpads
25389, -- Deteriorating Plate Belt
25390, -- Deteriorating Plate Boots
25391, -- Deteriorating Plate Bracers
25392, -- Deteriorating Plate Chestpiece
25393, -- Deteriorating Plate Gloves
25394, -- Deteriorating Plate Helmet
25396, -- Deteriorating Plate Shoulderpads
25397, -- Eroded Axe
25398, -- Stone Reaper
25399, -- Deteriorating Blade
25400, -- Tarnished Claymore
25401, -- Corroded Mace
25402, -- The Stoppable Force
25403, -- Sharpened Stilleto
25404, -- Dense War Staff
25405, -- Rusted Musket
25406, -- Broken Longbow
25409, -- Resilient Tail Hair
25411, -- Worn Hoof
25418, -- Razor Sharp Fang
25426, -- Brilliant Feather
25428, -- Savage Talon
25429, -- Grime-Encrusted Scale
25435, -- Hardened Carapace
25437, -- Barbed Leg
25445, -- Wretched Ichor
25451, -- Swamp Moss
25453, -- Death Cap Fungus
25454, -- Liminescent Globe
25456, -- Glowing Spores
25478, -- Loosely Threaded Bracers
25813, -- Small Mushroom
27676, -- Strange Spores
28058, -- Shredded Wyrm Wing
28059, -- Iridescent Eye
29549, -- Codex: Prayer of Fortitude
30812, -- Iridescent Scale
30814, -- Enormous Molar
31501, -- Tome of Conjure Food
31944, -- Demonic Capacitor
33547, -- Hardened Claw
36801, -- Crooked Fang
56206, -- Insect nociceptor Sample
}
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local common = ReplicatedStorage:WaitForChild("common")
local Actions = require(common:WaitForChild("Actions"))
return {
id = "coins1000000",
name = "1M Coins",
desc = (
"Gives 1,000,000 coins."
),
productId = 838293310,
onSale = true,
order = 14,
flavorText = "Best deal!",
onProductPurchase = (function(player, server)
server:getModule("StoreContainer"):getStore():andThen(function(store)
store:dispatch(Actions.COIN_ADD(player,1000000))
end)
return true -- Successful
end)
} |
return function(prefix)
local result = {}
local files = FILEMAN:GetDirListing(THEMEDIR().."/Modules/",false,false)
for _,file in pairs(files) do
local pl,pr = string.find( file, prefix.."." )
local sl,sr = string.find( file, ".lua" )
if pl ~= nil and pl == 1 and pr + 1 <= sl - 1 then
result[#result+1] = string.sub( file, pr + 1, sl - 1 )
end
end
return result
end;
|
local tools = require('app.helpers.tools')
local FeedbackView = {}
function FeedbackView:initialize()
end
function FeedbackView:layout()
local MainPanel = self.ui:getChildByName('MainPanel')
MainPanel:setContentSize(cc.size(display.width,display.height))
MainPanel:setPosition(display.cx,display.cy)
self.MainPanel = MainPanel
local middle = MainPanel:getChildByName('middle')
middle:setPosition(display.cx,display.cy)
end
return FeedbackView |
--- This processes commands from the user
-- It maintains a list of commands, ordered by priority and then arbitrarily,
-- such that you can send commands to this and they are processed into one
-- or more events which can be added to the event queue
-- @classmod CommandProcessor
-- region imports
local class = require('classes/class')
local prototype = require('prototypes/prototype')
local array = require('functional/array')
local commands = require('classes/commands/all')
local simple_serializer = require('utils/simple_serializer')
-- endregion
-- region sort commands
local command_priorities_ordered = { 'listener', 'explicit', 'implicit', 'generic' }
local sorted_commands = {}
for _, com in pairs(commands) do
local compr = array.index_of(command_priorities_ordered, com.priority())
local insert_index
for i, v in ipairs(sorted_commands) do
local vpr = array.index_of(command_priorities_ordered, v.priority())
if vpr > compr then
insert_index = i
break
end
end
if not insert_index then
sorted_commands[#sorted_commands + 1] = com
else
table.insert(sorted_commands, insert_index, com)
end
end
-- endregion
local CommandProcessor = {}
simple_serializer.inject(CommandProcessor)
--- Process the given message into a list of events
--
-- @tparam string message the message to process
-- @treturn {Event,...} the events that the given message caused
function CommandProcessor:process(game_ctx, local_ctx, message)
for _, com in ipairs(sorted_commands) do
local succ, events = com:parse(game_ctx, local_ctx, message)
if succ then return events end
end
return {}
end
prototype.support(CommandProcessor, 'serializable')
return class.create('CommandProcessor', CommandProcessor)
|
local Utils = require("contextprint.utils")
local Nodes = require("contextprint.nodes")
local parsers = require("nvim-treesitter.parsers")
local M = {}
function get_name_defaults()
return {
["function"] = "(anonymous)",
["if"] = "if",
["for"] = "for",
["for_in"] = "for_in",
["repeat"] = "repeat",
["while"] = "while",
["do"] = "do",
}
end
-- TODO: If vs elseif seems to be odd
function clean_cache()
local name_defaults = get_name_defaults()
return {
separator = "#",
lua = {
separator = "#",
query = [[
(function (function_name) @function.name) @function.declaration
(function_definition) @function.declaration
(for_statement) @for.declaration
(for_in_statement) @for_in.declaration
(repeat_statement) @repeat.declaration
(while_statement) @while.declaration
(if_statement) @if.declaration
]],
log = function(contents) return "print(\"" .. contents .. "\")" end,
type_defaults = vim.tbl_extend("force", {}, name_defaults),
},
typescript = {
-- I am missing const a = () => { ... }; In a sense, I should be able
-- to get the name, but I don't know how to do reverse lookup via query
-- if there is a name provided
query = [[
(function_declaration (identifier) @function.name) @function.declaration
(class_declaration (type_identifier) @class.name) @class.declaration
(method_definition (property_identifier) @method.name) @method.declaration
(arrow_function) @function.declaration
(if_statement) @if.declaration
(for_statement) @for.declaration
(for_in_statement) @for_in.declaration
(do_statement) @do.declaration
(while_statement) @while.declaration
]],
log = function(contents) return "console.error(\"" .. contents .. "\");" end,
type_defaults = vim.tbl_extend("force", {}, name_defaults),
},
}
end
M.reset_cache = function()
_contextprint_config = clean_cache()
end
-- TODO: Runtime type filter
_contextprint_config = _contextprint_config or clean_cache()
local function first_non_null(...)
local n = select('#', ...)
for i = 1, n do
local value = select(i, ...)
if value ~= nil then
return value
end
end
end
function merge(t1, t2)
for key, value in pairs(t2) do --actualcode
if type(value) == type({}) then
if t1[key] == nil then
t1[key] = value
else
merge(t1[key], value)
end
else
t1[key] = value
end
end
end
-- config[lang] = {
-- query = string
-- }
M.setup = function(opts)
merge(_contextprint_config, opts or {})
end
M.create_statement = function()
local ft = vim.api.nvim_buf_get_option(bufnr, 'ft')
-- Check to see if tree-sitter is setup
local lang = _contextprint_config[ft]
if not lang then
print("contextprint doesn't support this filetype", ft)
return nil
end
local row, col = unpack(vim.api.nvim_win_get_cursor(0))
-- TODO: Uses 0 for current buffer. Should we fix this?
local nodes = Nodes.get_nodes(lang.query, ft, _contextprint_config[ft].type_defaults or {})
if nodes == nil then
print("Unable to find any nodes. Is your query correct?")
return nil
end
nodes = Nodes.sort_nodes(Nodes.intersect_nodes(nodes, row, col))
local path = ""
local first = true
local sep = (_contextprint_config[ft].separator or _contextprint_config.separator)
for idx = 1, #nodes do
if first then
path = nodes[idx].name
first = false
else
path = path .. sep .. nodes[idx].name
end
end
return lang.log(path), row, col
end
M.add_statement = function(below)
below = below or false
local ft = vim.api.nvim_buf_get_option(bufnr, 'ft')
-- Check to see if tree-sitter is setup
if not parsers.has_parser() then
print("tree sitter is not enabled for filetype", ft)
return nil
end
local print_statement, row, col = M.create_statement()
if print_statement == nil then
print("Unable to find anything with your query. Are you sure it is correct?")
return
end
print("print_statement", print_statement, row, col)
if below then
vim.api.nvim_buf_set_lines(0, row, row, false, {print_statement})
vim.api.nvim_feedkeys('j', 'n', false)
vim.api.nvim_feedkeys('=', 'n', false)
vim.api.nvim_feedkeys('=', 'n', false)
vim.api.nvim_feedkeys('$', 'n', false)
else
vim.api.nvim_buf_set_lines(0, row - 1, row - 1, false, {print_statement})
vim.api.nvim_feedkeys('k', 'n', false)
vim.api.nvim_feedkeys('=', 'n', false)
vim.api.nvim_feedkeys('=', 'n', false)
vim.api.nvim_feedkeys('$', 'n', false)
end
end
return M
|
--[[--------------------------------------------------------------------
Copyright (C) 2009, 2010, 2011, 2012 Sidoine De Wispelaere.
Copyright (C) 2012, 2013, 2014, 2015 Johnny C. Lam.
See the file LICENSE.txt for copying permission.
--]]--------------------------------------------------------------------
local OVALE, Ovale = ...
--<class name="OvaleFrame" inherits="Frame" />
do
--<private-static-properties>
local AceGUI = LibStub("AceGUI-3.0")
local Masque = LibStub("Masque", true)
local OvaleBestAction = Ovale.OvaleBestAction
local OvaleCompile = Ovale.OvaleCompile
local OvaleCooldown = Ovale.OvaleCooldown
local OvaleDebug = Ovale.OvaleDebug
local OvaleFuture = Ovale.OvaleFuture
local OvaleGUID = Ovale.OvaleGUID
local OvaleSpellFlash = Ovale.OvaleSpellFlash
local OvaleState = Ovale.OvaleState
local OvaleTimeSpan = Ovale.OvaleTimeSpan
local Type = OVALE .. "Frame"
local Version = 7
local ipairs = ipairs
local next = next
local pairs = pairs
local tostring = tostring
local wipe = wipe
local API_CreateFrame = CreateFrame
local API_GetTime = GetTime
local API_RegisterStateDriver = RegisterStateDriver
local NextTime = OvaleTimeSpan.NextTime
local INFINITY = math.huge
-- GLOBALS: UIParent
-- Mininum time in seconds for refreshing the best action.
local MIN_REFRESH_TIME = 0.05
--</private-static-properties>
--<public-methods>
local function frameOnClose(self)
self.obj:Fire("OnClose")
end
local function closeOnClick(self)
self.obj:Hide()
end
local function frameOnMouseDown(self)
if (not Ovale.db.profile.apparence.verrouille) then
self:StartMoving()
AceGUI:ClearFocus()
end
end
local function ToggleOptions(self)
if (self.content:IsShown()) then
self.content:Hide()
else
self.content:Show()
end
end
local function frameOnMouseUp(self)
self:StopMovingOrSizing()
local profile = Ovale.db.profile
local x, y = self:GetCenter()
local parentX, parentY = self:GetParent():GetCenter()
profile.apparence.offsetX = x - parentX
profile.apparence.offsetY = y - parentY
end
local function frameOnEnter(self)
local profile = Ovale.db.profile
if not (profile.apparence.enableIcons and profile.apparence.verrouille) then
self.obj.barre:Show()
end
end
local function frameOnLeave(self)
self.obj.barre:Hide()
end
local function frameOnUpdate(self, elapsed)
self.obj:OnUpdate(elapsed)
end
local function Hide(self)
self.frame:Hide()
end
local function Show(self)
self.frame:Show()
end
local function OnAcquire(self)
self.frame:SetParent(UIParent)
end
local function OnRelease(self)
end
local function OnWidthSet(self, width)
local content = self.content
local contentwidth = width - 34
if contentwidth < 0 then
contentwidth = 0
end
content:SetWidth(contentwidth)
content.width = contentwidth
end
local function OnHeightSet(self, height)
local content = self.content
local contentheight = height - 57
if contentheight < 0 then
contentheight = 0
end
content:SetHeight(contentheight)
content.height = contentheight
end
local function OnLayoutFinished(self, width, height)
if (not width) then
width = self.content:GetWidth()
end
self.content:SetWidth(width)
self.content:SetHeight(height+50)
end
local function GetScore(self, spellId)
for k,action in pairs(self.actions) do
if action.spellId == spellId then
if not action.waitStart then
-- print("sort "..spellId.." parfait")
return 1
else
local now = API_GetTime()
local lag = now - action.waitStart
if lag>5 then
-- print("sort "..spellId.." ignoré (>5s)")
return nil
elseif lag>1.5 then
-- print("sort "..spellId.." trop lent !")
return 0
elseif lag>0 then
-- print("sort "..spellId.." un peu lent "..lag)
return 1-lag/1.5
else
-- print("sort "..spellId.." juste bon")
return 1
end
end
end
end
-- print("sort "..spellId.." incorrect")
return 0
end
local function OnUpdate(self, elapsed)
--[[
Refresh the best action if we've exceeded the minimum update interval since the last refresh,
or if one of the units the script is tracking needs a refresh.
If the target or focus exists, then the unit needs a refresh, even if out of combat.
--]]
local guid = OvaleGUID:UnitGUID("target") or OvaleGUID:UnitGUID("focus")
if guid then
Ovale.refreshNeeded[guid] = true
end
self.timeSinceLastUpdate = self.timeSinceLastUpdate + elapsed
local refresh = OvaleDebug.trace or self.timeSinceLastUpdate > MIN_REFRESH_TIME and next(Ovale.refreshNeeded)
if refresh then
-- Accumulate refresh interval statistics.
Ovale:AddRefreshInterval(self.timeSinceLastUpdate * 1000)
local state = OvaleState.state
state:Initialize()
if OvaleCompile:EvaluateScript() then
Ovale:UpdateFrame()
end
local profile = Ovale.db.profile
local iconNodes = OvaleCompile:GetIconNodes()
for k, node in ipairs(iconNodes) do
-- Set the true target of "target" references in the icon's body.
if node.namedParams and node.namedParams.target then
state.defaultTarget = node.namedParams.target
else
state.defaultTarget = "target"
end
-- Set the number of enemies on the battlefield, if given via "enemies=N".
if node.namedParams and node.namedParams.enemies then
state.enemies = node.namedParams.enemies
else
state.enemies = nil
end
-- Get the best action for this icon node.
state:Log("+++ Icon %d", k)
OvaleBestAction:StartNewAction(state)
local atTime = state.nextCast
if state.lastSpellId ~= state.lastGCDSpellId then
-- The previous spell cast did not trigger the GCD, so compute the next action at the current time.
atTime = state.currentTime
end
local timeSpan, element = OvaleBestAction:GetAction(node, state, atTime)
local start
if element and element.offgcd then
start = NextTime(timeSpan, state.currentTime)
else
start = NextTime(timeSpan, atTime)
end
-- Refresh the action button for the node.
if profile.apparence.enableIcons then
self:UpdateActionIcon(state, node, self.actions[k], element, start)
end
--Start Rabbs Injection
if profile.apparence.enableIcons then
self:UpdateActionIcon(state, node, self.actions[k], element, start)
if self.actions[4].spellId and self.actions[4].icons[1].cooldownEnd then
if self.actions[4].icons[1].cooldownEnd < API_GetTime() then
Ovale.rabbs4 = self.actions[4].spellId
NeP.DSL:Register('Rabbs4', function()
return Ovale.rabbs4
end)
else
Ovale.rabbs4 = nil
NeP.DSL:Register('Rabbs4', function()
return Ovale.rabbs4
end)
end
elseif self.actions[4].spellId and self.actions[4].waitStart then
Ovale.rabbs4 = self.actions[4].spellId
NeP.DSL:Register('Rabbs4', function()
return Ovale.rabbs4
end)
elseif not self.actions[4].spellid then
Ovale.rabbs4 = nil
Ovale.rabbs5 = self.actions[4].icons[1].actionId
NeP.DSL:Register('Rabbs4', function()
return Ovale.rabbs4
end)
NeP.DSL:Register('Rabbs5', function()
return Ovale.rabbs5
end)
end
end
if profile.apparence.enableIcons then
self:UpdateActionIcon(state, node, self.actions[k], element, start)
if self.actions[1].spellId and self.actions[1].icons[1].cooldownEnd then
if self.actions[1].icons[1].cooldownEnd < API_GetTime() then
Ovale.rabbs1 = self.actions[1].spellId
NeP.DSL:Register('Rabbs1', function()
return Ovale.rabbs1
end)
else
Ovale.rabbs1 = nil
NeP.DSL:Register('Rabbs1', function()
return Ovale.rabbs1
end)
end
elseif self.actions[1].spellId and self.actions[1].waitStart then
Ovale.rabbs1 = self.actions[1].spellId
NeP.DSL:Register('Rabbs1', function()
return Ovale.rabbs1
end)
end
end
if profile.apparence.enableIcons then
self:UpdateActionIcon(state, node, self.actions[k], element, start)
if self.actions[3].spellId and self.actions[3].icons[1].cooldownEnd then
if self.actions[3].icons[1].cooldownEnd < API_GetTime() then
Ovale.rabbs3 = self.actions[3].spellId
NeP.DSL:Register('Rabbs3', function()
return Ovale.rabbs3
end)
else
Ovale.rabbs3 = nil
NeP.DSL:Register('Rabbs3', function()
return Ovale.rabbs3
end)
end
elseif self.actions[3].spellId and self.actions[3].waitStart then
Ovale.rabbs3 = self.actions[3].spellId
NeP.DSL:Register('Rabbs3', function()
return Ovale.rabbs3
end)
end
end
if profile.apparence.enableIcons then
self:UpdateActionIcon(state, node, self.actions[k], element, start)
if self.actions[2].spellId and self.actions[2].icons[1].cooldownEnd then
if self.actions[2].icons[1].cooldownEnd < API_GetTime() then
Ovale.rabbs2 = self.actions[2].spellId
NeP.DSL:Register('Rabbs2', function()
return Ovale.rabbs2
end)
else
Ovale.rabbs2 = nil
NeP.DSL:Register('Rabbs2', function()
return Ovale.rabbs2
end)
end
elseif self.actions[2].spellId and self.actions[2].waitStart then
Ovale.rabbs2 = self.actions[2].spellId
NeP.DSL:Register('Rabbs2', function()
return Ovale.rabbs2
end)
end
end
if profile.apparence.spellFlash.enabled then
OvaleSpellFlash:Flash(state, node, element, start)
end
end
wipe(Ovale.refreshNeeded)
OvaleDebug:UpdateTrace()
Ovale:PrintOneTimeMessages()
self.timeSinceLastUpdate = 0
end
end
local function UpdateActionIcon(self, state, node, action, element, start, now)
local profile = Ovale.db.profile
local icons = action.secure and action.secureIcons or action.icons
now = now or API_GetTime()
if element and element.type == "value" then
local value
if element.value and element.origin and element.rate then
value = element.value + (now - element.origin) * element.rate
end
state:Log("GetAction: start=%s, value=%f", start, value)
local actionTexture
if node.namedParams and node.namedParams.texture then
actionTexture = node.namedParams.texture
end
icons[1]:SetValue(value, actionTexture)
if #icons > 1 then
icons[2]:Update(element, nil)
end
else
local actionTexture, actionInRange, actionCooldownStart, actionCooldownDuration,
actionUsable, actionShortcut, actionIsCurrent, actionEnable,
actionType, actionId, actionTarget, actionResourceExtend = OvaleBestAction:GetActionInfo(element, state)
-- Add any extra time needed to pool resources.
if actionResourceExtend and actionResourceExtend > 0 then
if actionCooldownDuration > 0 then
state:Log("Extending cooldown of spell ID '%s' for primary resource by %fs.", actionId, actionResourceExtend)
actionCooldownDuration = actionCooldownDuration + actionResourceExtend
elseif element.namedParams.pool_resource and element.namedParams.pool_resource == 1 then
state:Log("Delaying spell ID '%s' for primary resource by %fs.", actionId, actionResourceExtend)
start = start + actionResourceExtend
end
end
state:Log("GetAction: start=%s, id=%s", start, actionId)
-- If this action is the same as the spell currently casting in the simulator, then start after the previous cast has finished.
if actionType == "spell" and actionId == state.currentSpellId and start and state.nextCast and start < state.nextCast then
start = state.nextCast
end
if start and node.namedParams.nocd and now < start - node.namedParams.nocd then
icons[1]:Update(element, nil)
else
icons[1]:Update(element, start, actionTexture, actionInRange, actionCooldownStart, actionCooldownDuration,
actionUsable, actionShortcut, actionIsCurrent, actionEnable, actionType, actionId, actionTarget, actionResourceExtend)
end
-- TODO: Scoring should allow for other actions besides spells.
if actionType == "spell" then
action.spellId = actionId
else
action.spellId = nil
end
if start and start <= now and actionUsable then
action.waitStart = action.waitStart or now
else
action.waitStart = nil
end
if profile.apparence.moving and icons[1].cooldownStart and icons[1].cooldownEnd then
local top=1-(now - icons[1].cooldownStart)/(icons[1].cooldownEnd-icons[1].cooldownStart)
if top<0 then
top = 0
elseif top>1 then
top = 1
end
icons[1]:SetPoint("TOPLEFT",self.frame,"TOPLEFT",(action.left + top*action.dx)/action.scale,(action.top - top*action.dy)/action.scale)
if icons[2] then
icons[2]:SetPoint("TOPLEFT",self.frame,"TOPLEFT",(action.left + (top+1)*action.dx)/action.scale,(action.top - (top+1)*action.dy)/action.scale)
end
end
if (node.namedParams.size ~= "small" and not node.namedParams.nocd and profile.apparence.predictif) then
if start then
state:Log("****Second icon %s", start)
state:ApplySpell(actionId, OvaleGUID:UnitGUID(actionTarget), start)
local atTime = state.nextCast
if actionId ~= state.lastGCDSpellId then
-- The previous spell cast did not trigger the GCD, so compute the next action at the current time.
atTime = state.currentTime
end
local timeSpan, nextElement = OvaleBestAction:GetAction(node, state, atTime)
local start
if nextElement and nextElement.offgcd then
start = NextTime(timeSpan, state.currentTime)
else
start = NextTime(timeSpan, atTime)
end
icons[2]:Update(nextElement, start, OvaleBestAction:GetActionInfo(nextElement, state))
else
icons[2]:Update(element, nil)
end
end
end
end
local function UpdateFrame(self)
local profile = Ovale.db.profile
self.frame:SetPoint("CENTER", self.hider, "CENTER", profile.apparence.offsetX, profile.apparence.offsetY)
self.frame:EnableMouse(not profile.apparence.clickThru)
end
local function UpdateIcons(self)
for k, action in pairs(self.actions) do
for i, icon in pairs(action.icons) do
icon:Hide()
end
for i, icon in pairs(action.secureIcons) do
icon:Hide()
end
end
local profile = Ovale.db.profile
self.frame:EnableMouse(not profile.apparence.clickThru)
local left = 0
local maxHeight = 0
local maxWidth = 0
local top = 0
local BARRE = 8
local margin = profile.apparence.margin
local iconNodes = OvaleCompile:GetIconNodes()
for k, node in ipairs(iconNodes) do
if not self.actions[k] then
self.actions[k] = {icons={}, secureIcons={}}
end
local action = self.actions[k]
local width, height, newScale
local nbIcons
if (node.namedParams ~= nil and node.namedParams.size == "small") then
newScale = profile.apparence.smallIconScale
width = newScale * 36 + margin
height = newScale * 36 + margin
nbIcons = 1
else
newScale = profile.apparence.iconScale
width =newScale * 36 + margin
height = newScale * 36 + margin
if profile.apparence.predictif and node.namedParams.type ~= "value" then
nbIcons = 2
else
nbIcons = 1
end
end
if (top + height > profile.apparence.iconScale * 36 + margin) then
top = 0
left = maxWidth
end
action.scale = newScale
if (profile.apparence.vertical) then
action.left = top
action.top = -left-BARRE-margin
action.dx = width
action.dy = 0
else
action.left = left
action.top = -top-BARRE-margin
action.dx = 0
action.dy = height
end
action.secure = node.secure
for l=1,nbIcons do
local icon
if not node.secure then
if not action.icons[l] then
action.icons[l] = API_CreateFrame("CheckButton", "Icon"..k.."n"..l, self.frame, OVALE .. "IconTemplate");
end
icon = action.icons[l]
else
if not action.secureIcons[l] then
action.secureIcons[l] = API_CreateFrame("CheckButton", "SecureIcon"..k.."n"..l, self.frame, "Secure" .. OVALE .. "IconTemplate");
end
icon = action.secureIcons[l]
end
local scale = action.scale
if l> 1 then
scale = scale * profile.apparence.secondIconScale
end
icon:SetPoint("TOPLEFT",self.frame,"TOPLEFT",(action.left + (l-1)*action.dx)/scale,(action.top - (l-1)*action.dy)/scale)
icon:SetScale(scale)
icon:SetRemainsFont(profile.apparence.remainsFontColor)
icon:SetFontScale(profile.apparence.fontScale)
icon:SetParams(node.positionalParams, node.namedParams)
icon:SetHelp((node.namedParams ~= nil and node.namedParams.help) or nil)
icon:SetRangeIndicator(profile.apparence.targetText)
icon:EnableMouse(not profile.apparence.clickThru)
icon.cdShown = (l == 1)
if Masque then
self.skinGroup:AddButton(icon)
end
if l==1 then
icon:Show();
end
end
top = top + height
if (top> maxHeight) then
maxHeight = top
end
if (left + width > maxWidth) then
maxWidth = left + width
end
end
if (profile.apparence.vertical) then
self.barre:SetWidth(maxHeight - margin)
self.barre:SetHeight(BARRE)
self.frame:SetWidth(maxHeight + profile.apparence.iconShiftY)
self.frame:SetHeight(maxWidth+BARRE+margin + profile.apparence.iconShiftX)
self.content:SetPoint("TOPLEFT", self.frame, "TOPLEFT", maxHeight + profile.apparence.iconShiftX, profile.apparence.iconShiftY)
else
self.barre:SetWidth(maxWidth - margin)
self.barre:SetHeight(BARRE)
self.frame:SetWidth(maxWidth) -- + profile.apparence.iconShiftX
self.frame:SetHeight(maxHeight+BARRE+margin) -- + profile.apparence.iconShiftY
self.content:SetPoint("TOPLEFT", self.frame, "TOPLEFT", maxWidth + profile.apparence.iconShiftX, profile.apparence.iconShiftY)
end
end
local function Constructor()
-- Create parent frame for Ovale that auto-hides/shows based on whether the Pet Battle UI is active.
local hider = API_CreateFrame("Frame", OVALE .. "PetBattleFrameHider", UIParent, "SecureHandlerStateTemplate")
hider:SetAllPoints(true)
API_RegisterStateDriver(hider, "visibility", "[petbattle] hide; show")
local frame = API_CreateFrame("Frame", nil, hider)
local self = {}
local profile = Ovale.db.profile
self.Hide = Hide
self.Show = Show
self.OnRelease = OnRelease
self.OnAcquire = OnAcquire
self.LayoutFinished = OnLayoutFinished
self.UpdateActionIcon = UpdateActionIcon
self.UpdateFrame = UpdateFrame
self.UpdateIcons = UpdateIcons
self.ToggleOptions = ToggleOptions
self.OnUpdate = OnUpdate
self.GetScore = GetScore
--<public-properties>
self.type = "Frame"
self.localstatus = {}
self.actions = {}
self.frame = frame
self.hider = hider
self.updateFrame = API_CreateFrame("Frame", OVALE .. "UpdateFrame")
self.barre = self.frame:CreateTexture();
self.content = API_CreateFrame("Frame", nil, self.updateFrame)
if Masque then
self.skinGroup = Masque:Group(OVALE)
end
self.timeSinceLastUpdate = INFINITY
--Cheating with frame object which has an obj property
--TODO: Frame Class
self.obj = nil
--</public-properties>
frame.obj = self
frame:SetWidth(100)
frame:SetHeight(100)
self:UpdateFrame()
frame:SetMovable(true)
frame:SetFrameStrata("MEDIUM")
frame:SetScript("OnMouseDown", frameOnMouseDown)
frame:SetScript("OnMouseUp", frameOnMouseUp)
frame:SetScript("OnEnter", frameOnEnter)
frame:SetScript("OnLeave", frameOnLeave)
-- frame:SetScript("OnUpdate", frameOnUpdate)
frame:SetScript("OnHide",frameOnClose)
frame:SetAlpha(profile.apparence.alpha)
self.updateFrame:SetScript("OnUpdate", frameOnUpdate)
self.updateFrame.obj = self
self.barre:SetTexture(0,0.8,0)
self.barre:SetPoint("TOPLEFT",0,0)
self.barre:Hide()
--Container Support
local content = self.content
content.obj = self
content:SetWidth(200)
content:SetHeight(100)
content:Hide()
content:SetAlpha(profile.apparence.optionsAlpha)
AceGUI:RegisterAsContainer(self)
return self
end
--</public-methods>
AceGUI:RegisterWidgetType(Type,Constructor,Version)
end
|
---@class ui.ListBox:ccui.ScrollView
local M = class('ui.ListBox', ccui.ScrollView)
function M:ctor(size, item_h)
self.size = size or cc.size(192, 256)
self.item_size = cc.size(self.size.width, item_h or 16)
self:setContentSize(self.size)
self:setBackGroundColorType(1)--:setBackGroundColor(cc.c3b(255, 200, 200))
---@type ccui.Button[]
self._children = {}
local hinter = require('cc.ui.sprite').White(self.item_size)
hinter:addTo(self):setVisible(false):alignHCenter()
hinter:setColor(cc.BLUE)
self._hinter = hinter
end
function M:addItem(text)
local idx = self:getItemCount() + 1
local btn = require('cc.ui.button').ButtonNull(self.item_size, function()
self:_select(idx)
end)
btn:addTo(self)
table.insert(self._children, btn)
local lb = require('cc.ui.label').create(text, 13)
lb:addTo(btn):alignVCenter():alignLeft(6)
btn.label = lb
self:_updateLayout()
if idx == 1 then
self:_select(1)
end
end
function M:getItemCount()
return #self._children
end
function M:getIndex()
return self._sel
end
function M:getString()
if self._sel and self._children[self._sel] then
return self._children[self._sel].label:getString()
end
end
function M:reset()
self._sel = nil
for _, v in ipairs(self._children) do
v:removeSelf()
end
self._hinter:setVisible(false)
self:_updateLayout()
end
function M:setOnSelect(cb)
self._onselect = cb
end
function M:selectString(str)
for i, v in ipairs(self._children) do
if v.label:getString() == str then
self:_select(i)
return
end
end
end
function M:_select(idx)
if self._sel and self._children[self._sel] then
self._children[self._sel].label:setTextColor(cc.BLACK)
end
local btn = self._children[idx]
assert(btn and btn.label)
btn.label:setTextColor(cc.WHITE)
self._hinter:setVisible(true):alignTop((idx - 1) * self.item_size.height)
self._sel = idx
if self._onselect then
self:_onselect()
end
end
function M:_updateLayout()
self:setInnerContainerSize(cc.size(
self.size.width,
math.max(self.item_size.height * self:getItemCount(), self.size.height)
))
for i, v in ipairs(self._children) do
v:alignLeft(0):alignTop((i - 1) * self.item_size.height)
end
if self._sel then
self._hinter:alignTop((self._sel - 1) * self.item_size.height)
end
end
return M
|
local scheduler = cc.Director:getInstance():getScheduler()
local SID_STEP1 = 100
local SID_STEP2 = 101
local SID_STEP3 = 102
local IDC_PAUSE = 200
local function IntervalLayer()
local ret = cc.Layer:create()
local m_time0 = 0
local m_time1 = 0
local m_time2 = 0
local m_time3 = 0
local m_time4 = 0
local s = cc.Director:getInstance():getWinSize()
-- sun
local sun = cc.ParticleSun:create()
sun:setTexture(cc.TextureCache:getInstance():addImage("Images/fire.png"))
sun:setPosition( cc.p(VisibleRect:rightTop().x-32,VisibleRect:rightTop().y-32) )
sun:setTotalParticles(130)
sun:setLife(0.6)
ret:addChild(sun)
-- timers
m_label0 = cc.LabelBMFont:create("0", "fonts/bitmapFontTest4.fnt")
m_label1 = cc.LabelBMFont:create("0", "fonts/bitmapFontTest4.fnt")
m_label2 = cc.LabelBMFont:create("0", "fonts/bitmapFontTest4.fnt")
m_label3 = cc.LabelBMFont:create("0", "fonts/bitmapFontTest4.fnt")
m_label4 = cc.LabelBMFont:create("0", "fonts/bitmapFontTest4.fnt")
local function update(dt)
m_time0 = m_time0 + dt
local str = string.format("%2.1f", m_time0)
m_label0:setString(str)
end
ret:scheduleUpdateWithPriorityLua(update, 0)
local function step1(dt)
m_time1 = m_time1 + dt
local str = string.format("%2.1f", m_time1)
m_label1:setString( str )
end
local function step2(dt)
m_time2 = m_time2 + dt
local str = string.format("%2.1f", m_time2)
m_label2:setString( str )
end
local function step3(dt)
m_time3 = m_time3 + dt
local str = string.format("%2.1f", m_time3)
m_label3:setString( str )
end
local function step4(dt)
m_time4 = m_time4 + dt
local str = string.format("%2.1f", m_time4)
m_label4:setString( str )
end
local schedulerEntry1 = nil
local schedulerEntry2 = nil
local schedulerEntry3 = nil
local schedulerEntry4 = nil
local function onNodeEvent(event)
if event == "enter" then
schedulerEntry1 = scheduler:scheduleScriptFunc(step1, 0, false)
schedulerEntry2 = scheduler:scheduleScriptFunc(step2, 0, false)
schedulerEntry3 = scheduler:scheduleScriptFunc(step3, 1.0, false)
schedulerEntry4 = scheduler:scheduleScriptFunc(step4, 2.0, false)
elseif event == "exit" then
scheduler:unscheduleScriptEntry(schedulerEntry1)
scheduler:unscheduleScriptEntry(schedulerEntry2)
scheduler:unscheduleScriptEntry(schedulerEntry3)
scheduler:unscheduleScriptEntry(schedulerEntry4)
if cc.Director:getInstance():isPaused() then
cc.Director:getInstance():resume()
end
end
end
ret:registerScriptHandler(onNodeEvent)
m_label0:setPosition(cc.p(s.width*1/6, s.height/2))
m_label1:setPosition(cc.p(s.width*2/6, s.height/2))
m_label2:setPosition(cc.p(s.width*3/6, s.height/2))
m_label3:setPosition(cc.p(s.width*4/6, s.height/2))
m_label4:setPosition(cc.p(s.width*5/6, s.height/2))
ret:addChild(m_label0)
ret:addChild(m_label1)
ret:addChild(m_label2)
ret:addChild(m_label3)
ret:addChild(m_label4)
-- Sprite
local sprite = cc.Sprite:create(s_pPathGrossini)
sprite:setPosition( cc.p(VisibleRect:left().x + 40, VisibleRect:bottom().y + 50) )
local jump = cc.JumpBy:create(3, cc.p(s.width-80,0), 50, 4)
ret:addChild(sprite)
sprite:runAction( cc.RepeatForever:create(cc.Sequence:create(jump, jump:reverse())))
-- pause button
local item1 = cc.MenuItemFont:create("Pause")
local function onPause(tag, pSender)
if cc.Director:getInstance():isPaused() then
cc.Director:getInstance():resume()
else
cc.Director:getInstance():pause()
end
end
item1:registerScriptTapHandler(onPause)
local menu = cc.Menu:create(item1)
menu:setPosition( cc.p(s.width/2, s.height-50) )
ret:addChild( menu )
return ret
end
function IntervalTestMain()
cclog("IntervalTestMain")
local scene = cc.Scene:create()
local layer = IntervalLayer()
scene:addChild(layer, 0)
scene:addChild(CreateBackMenuItem())
return scene
end
|
id = 'V-38634'
severity = 'medium'
weight = 10.0
title = 'The system must rotate audit log files that reach the maximum file size.'
description = 'Automatically rotating logs (by setting this to "rotate") minimizes the chances of the system unexpectedly running out of disk space by being overwhelmed with log data. However, for systems that must never discard log data, or which use external processes to transfer it and reclaim space, "keep_logs" can be employed.'
fixtext = [==[The default action to take when the logs reach their maximum size is to rotate the log files, discarding the oldest one. To configure the action taken by "auditd", add or correct the line in "/etc/audit/auditd.conf":
max_log_file_action = [ACTION]
Possible values for [ACTION] are described in the "auditd.conf" man page. These include:
"ignore"
"syslog"
"suspend"
"rotate"
"keep_logs"
Set the "[ACTION]" to "rotate" to ensure log rotation occurs. This is the default. The setting is case-insensitive.]==]
checktext = [==[Inspect "/etc/audit/auditd.conf" and locate the following line to determine if the system is configured to rotate logs when they reach their maximum size:
# grep max_log_file_action /etc/audit/auditd.conf
max_log_file_action = rotate
If the "keep_logs" option is configured for the "max_log_file_action" line in "/etc/audit/auditd.conf" and an alternate process is in place to ensure audit data does not overwhelm local audit storage, this is not a finding.
If the system has not been properly set up to rotate audit logs, this is a finding.]==]
function test()
end
function fix()
end
|
--[[
Adobe Experience Manager (AEM) API
Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API
The version of the OpenAPI document: 3.5.0-pre.0
Contact: [email protected]
Generated by: https://openapi-generator.tech
]]
-- saml_configuration_property_items_array class
local saml_configuration_property_items_array = {}
local saml_configuration_property_items_array_mt = {
__name = "saml_configuration_property_items_array";
__index = saml_configuration_property_items_array;
}
local function cast_saml_configuration_property_items_array(t)
return setmetatable(t, saml_configuration_property_items_array_mt)
end
local function new_saml_configuration_property_items_array(name, optional, is_set, type, values, description)
return cast_saml_configuration_property_items_array({
["name"] = name;
["optional"] = optional;
["is_set"] = is_set;
["type"] = type;
["values"] = values;
["description"] = description;
})
end
return {
cast = cast_saml_configuration_property_items_array;
new = new_saml_configuration_property_items_array;
}
|
--!The Make-like Build Utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2017, TBOOX Open Source Group.
--
-- @author ruki
-- @file check.lua
--
-- imports
import("core.tool.tool")
import("platforms.checker", {rootdir = os.programdir()})
-- check the sdk version for ndk
function _check_ndk_sdkver(config)
-- get ndk sdk version
local ndk_sdkver = config.get("ndk_sdkver")
if not ndk_sdkver then
-- get the ndk
local ndk = config.get("ndk")
if ndk then
-- match all sdk directories
local version_maxn = 0
for _, sdkdir in ipairs(os.match(ndk .. "/platforms/android-*", true)) do
-- get version
local filename = path.filename(sdkdir)
local version, count = filename:gsub("android%-", "")
if count > 0 then
-- get the max version
version = tonumber(version)
if version > version_maxn then
version_maxn = version
end
end
end
-- save the version
if version_maxn > 0 then ndk_sdkver = version_maxn end
end
-- probe ok? update it
if ndk_sdkver ~= nil and ndk_sdkver > 0 then
-- save it
config.set("ndk_sdkver", ndk_sdkver)
-- trace
cprint("checking for the SDK version of NDK ... ${green}android-%d", ndk_sdkver)
else
-- trace
cprint("checking for the SDK version of NDK ... ${red}no")
end
end
end
-- check the toolchains
function _check_toolchains(config)
-- get architecture
local arch = config.get("arch")
-- get toolchains
local toolchains = config.get("toolchains")
if not toolchains then
-- get ndk
local ndk = config.get("ndk")
if ndk then
-- match all toolchains
if arch and arch:startswith("arm64") then
toolchains = os.match("%s/toolchains/aarch64-linux-android-**/prebuilt/*/bin/aarch64-linux-android-*", false, ndk)
else
toolchains = os.match("%s/toolchains/arm-linux-androideabi-**/prebuilt/*/bin/arm-linux-androideabi-*", false, ndk)
end
-- save the toolchains directory
for _, filepath in ipairs(toolchains) do
config.set("toolchains", path.directory(filepath))
break
end
end
end
-- get toolchains version
local toolchains = config.get("toolchains")
if toolchains then
local pos, _, toolchains_ver = toolchains:find("%-(%d*%.%d*)[/\\]")
if pos and toolchains_ver then
-- save the toolchains version
config.set("toolchains_ver", toolchains_ver)
-- trace
cprint("checking for the version of toolchains ... ${green}%s", toolchains_ver)
else
-- trace
cprint("checking for the version of toolchains ... ${red}no")
end
end
-- get cross
local cross = "arm-linux-androideabi-"
if arch and arch:startswith("arm64") then
cross = "aarch64-linux-android-"
end
-- done
checker.check_toolchain(config, "cc", cross, "gcc", "the c compiler")
checker.check_toolchain(config, "cxx", cross, "g++", "the c++ compiler")
checker.check_toolchain(config, "as", cross, "gcc", "the assember")
checker.check_toolchain(config, "ld", cross, "g++", "the linker")
checker.check_toolchain(config, "ld", cross, "gcc", "the linker")
checker.check_toolchain(config, "ar", cross, "ar", "the static library archiver")
checker.check_toolchain(config, "ex", cross, "ar", "the static library extractor")
checker.check_toolchain(config, "sh", cross, "g++", "the shared library linker")
checker.check_toolchain(config, "sh", cross, "gcc", "the shared library linker")
end
-- check it
function main(kind)
-- init the check list of config
_g.config =
{
{ checker.check_arch, "armv7-a" }
, checker.check_ccache
, _check_ndk_sdkver
, _check_toolchains
}
-- init the check list of global
_g.global =
{
checker.check_ccache
, _check_ndk_sdkver
}
-- check it
checker.check(kind, _g)
end
|
require("prototypes.prototypes")
require("prototypes.legacy")
|
-- Tests for not doing smart indenting when it isn't set.
local helpers = require('test.functional.helpers')(after_each)
local feed = helpers.feed
local clear = helpers.clear
local insert = helpers.insert
local expect = helpers.expect
local feed_command = helpers.feed_command
describe('unset smart indenting', function()
before_each(clear)
it('is working', function()
insert([[
start text
some test text
test text
test text
test text]])
feed_command('set nocin nosi ai')
feed_command('/some')
feed('2cc#test<Esc>')
expect([[
start text
#test
test text
test text]])
end)
end)
|
wifi.sta.clearconfig() |
--- === TurboBoost ===
---
--- A spoon to load/unload the Turbo Boost Disable kernel extension
--- from https://github.com/rugarciap/Turbo-Boost-Switcher.
---
--- Note: this spoon by default uses sudo to load/unload the kernel
--- extension, so for it to work from Hammerspoon, you need to
--- configure sudo to be able to load/unload the extension without a
--- password, or configure the load_kext_cmd and unload_kext_cmd
--- variables to use some other mechanism that prompts you for the
--- credentials.
---
--- For example, the following configuration (stored in
--- /etc/sudoers.d/turboboost) can be used to allow loading and
--- unloading the module without a password:
--- ```
--- Cmnd_Alias TURBO_OPS = /sbin/kextunload /Applications/Turbo Boost Switcher.app/Contents/Resources/DisableTurboBoost.64bits.kext, /usr/bin/kextutil /Applications/Turbo Boost Switcher.app/Contents/Resources/DisableTurboBoost.64bits.kext
---
--- %admin ALL=(ALL) NOPASSWD: TURBO_OPS
--- ```
---
--- If you use this, please support the author of Turbo Boost Disabler
--- by purchasing the Pro version of the app!
---
--- Download: [https://github.com/Hammerspoon/Spoons/raw/master/Spoons/TurboBoost.spoon.zip](https://github.com/Hammerspoon/Spoons/raw/master/Spoons/TurboBoost.spoon.zip)
local obj={}
obj.__index = obj
-- Metadata
obj.name = "TurboBoost"
obj.version = "0.1"
obj.author = "Diego Zamboni <[email protected]>"
obj.homepage = "https://github.com/Hammerspoon/Spoons"
obj.license = "MIT - https://opensource.org/licenses/MIT"
--- TurboBoost.logger
--- Variable
--- Logger object used within the Spoon. Can be accessed to set the default log level for the messages coming from the Spoon.
obj.logger = hs.logger.new('TurboBoost')
obj.menuBarItem = nil
obj.wakeupWatcher = nil
--- TurboBoost.disable_on_start
--- Variable
--- Boolean to indicate whether Turbo Boost should be disabled when
--- the Spoon starts. Default value: `false`.
obj.disable_on_start = false
--- TurboBoost.reenable_on_stop
--- Variable
--- Boolean to indicate whether Turbo Boost should be reenabled when
--- the Spoon stops. Default value: `true`.
obj.reenable_on_stop = true
--- TurboBoost.kext_path
--- Variable
--- Where the DisableTurboBoost.kext file is located.
--- Default value: `"/Applications/Turbo Boost Switcher.app/Contents/Resources/DisableTurboBoost.64bits.kext"`
obj.kext_path = "/Applications/Turbo Boost Switcher.app/Contents/Resources/DisableTurboBoost.64bits.kext"
--- TurboBoost.load_kext_cmd
--- Variable
--- Command to execute to load the DisableTurboBoost kernel
--- extension. This command must execute with root privileges and
--- either query the user for the credentials, or be configured
--- (e.g. with sudo) to run without prompting. The string "%s" in this
--- variable gets replaced with the value of
--- TurboBoost.kext_path. Default value: `"/usr/bin/sudo /usr/bin/kextutil '%s'"`
obj.load_kext_cmd = "/usr/bin/sudo /usr/bin/kextutil '%s'"
--- TurboBoost.unload_kext_cmd
--- Variable
--- Command to execute to unload the DisableTurboBoost kernel
--- extension. This command must execute with root privileges and
--- either query the user for the credentials, or be configured
--- (e.g. with sudo) to run without prompting. The string "%s" in this
--- variable gets replaced with the value of
--- TurboBoost.kext_path. Default value: `"/usr/bin/sudo /sbin/kextunload '%s'"`
obj.unload_kext_cmd = "/usr/bin/sudo /sbin/kextunload '%s'"
--- TurboBoost.check_kext_cmd
--- Variable
--- Command to execute to check whether the DisableTurboBoost kernel
--- extension is loaded. Default value: `"/usr/sbin/kextstat | grep com.rugarciap.DisableTurboBoost"`
obj.check_kext_cmd = "/usr/sbin/kextstat | grep com.rugarciap.DisableTurboBoost"
--- TurboBoost.notify
--- Variable
--- Boolean indicating whether notifications should be generated when
--- Turbo Boost is enabled/disabled. Default value: `true`
obj.notify = true
--- TurboBoost.enabled_icon_path
--- Variable
--- Where to find the icon to use for the "Enabled" icon. Default value
--- uses the icon from the Turbo Boost application:
--- `"/Applications/Turbo Boost Switcher.app/Contents/Resources/icon.tiff"`
obj.enabled_icon_path = "/Applications/Turbo Boost Switcher.app/Contents/Resources/icon.tiff"
--- TurboBoost.disabled_icon_path
--- Variable
--- Where to find the icon to use for the "Disabled" icon. Default value
--- uses the icon from the Turbo Boost application:
--- `"/Applications/Turbo Boost Switcher.app/Contents/Resources/icon_off.tiff"`
obj.disabled_icon_path = "/Applications/Turbo Boost Switcher.app/Contents/Resources/icon_off.tiff"
--- TurboBoost:setState(state)
--- Method
--- Sets whether Turbo Boost should be disabled (kernel extension
--- loaded) or enabled (normal state, kernel extension not loaded).
---
--- Parameters:
--- * state - A boolean, false if Turbo Boost should be disabled
--- (load kernel extension), true if it should be enabled (unload
--- kernel extension if loaded).
--- * notify - Optional boolean indicating whether a notification
--- should be produced. If not given, the value of
--- TurboBoost.notify is used.
---
--- Returns:
--- * Boolean indicating new state
function obj:setState(state, notify)
local curstatus = self:status()
if curstatus ~= state then
local cmd = string.format(obj.load_kext_cmd, obj.kext_path)
if state then
cmd = string.format(obj.unload_kext_cmd, obj.kext_path)
end
self.logger.df("Will execute command '%s'", cmd)
if notify == nil then
notify = obj.notify
end
out,st,ty,rc = hs.execute(cmd)
if not st then
self.logger.ef("Error executing '%s'. Output: %s", cmd, out)
else
self:setDisplay(state)
if notify then
hs.notify.new({
title = "Turbo Boost " .. (state and "enabled" or "disabled"),
subTitle = "",
informativeText = "",
setIdImage = hs.image.imageFromPath(self.iconPathForState(state))
}):send()
end
end
end
return self:status()
end
--- TurboBoost:status()
--- Method
--- Check whether Turbo Boost is enabled
---
--- Returns:
--- * true if TurboBoost is enabled (kernel ext not loaded), false otherwise.
function obj:status()
local cmd = obj.check_kext_cmd
out,st,ty,rc = hs.execute(cmd)
return (not st)
end
--- TurboBoost:toggle()
--- Method
--- Toggle TurboBoost status
---
--- Returns:
--- * New TurboBoost status, after the toggle
function obj:toggle()
self:setState(not self:status())
return self:status()
end
--- TurboBoost:bindHotkeys(mapping)
--- Method
--- Binds hotkeys for TurboBoost
---
--- Parameters:
--- * mapping - A table containing hotkey objifier/key details for the following items:
--- * hello - Say Hello
function obj:bindHotkeys(mapping)
local spec = { toggle = hs.fnutils.partial(self.toggle, self) }
hs.spoons.bindHotkeysToSpec(spec, mapping)
end
--- TurboBoost:start()
--- Method
--- Starts TurboBoost
---
--- Parameters:
--- * None
---
--- Returns:
--- * The TurboBoost object
function obj:start()
if self.menuBarItem or self.wakeupWatcher then self:stop() end
self.menuBarItem = hs.menubar.new()
self.menuBarItem:setClickCallback(self.clicked)
self:setDisplay(self:status())
self.wakeupWatcher = hs.caffeinate.watcher.new(self.wokeUp):start()
if self.disable_on_start then
self:setState(false)
end
return self
end
--- TurboBoost:stop()
--- Method
--- Stops TurboBoost
---
--- Parameters:
--- * None
---
--- Returns:
--- * The TurboBoost object
function obj:stop()
if self.reenable_on_stop then
self:setState(true)
end
if self.menuBarItem then self.menuBarItem:delete() end
self.menuBarItem = nil
if self.wakeupWatcher then self.wakeupWatcher:stop() end
self.wakeupWatcher = nil
return self
end
function obj.iconPathForState(state)
if state then
return obj.enabled_icon_path
else
return obj.disabled_icon_path
end
end
function obj:setDisplay(state)
obj.menuBarItem:setIcon(obj.iconPathForState(state))
end
function obj.clicked()
obj:setDisplay(obj:toggle())
end
-- This function is called when the machine wakes up and, if the
-- module was loaded, it unloads/reloads it to disable Turbo Boost
-- again
function obj.wokeUp(event)
obj.logger.df("In obj.wokeUp, event = %d\n", event)
if event == hs.caffeinate.watcher.systemDidWake then
obj.logger.d(" Received systemDidWake event!\n")
if not obj:status() then
obj.logger.d(" Toggling TurboBoost on and back off\n")
obj:toggle()
hs.timer.usleep(20000)
obj:toggle()
end
end
end
return obj
|
dofile "../Premake/Setup.lua"
NewSolution("TestFramework")
NewProject("TestFramework", "ConsoleApp") |
------------------------------------------ Define subplot class..
local subplot={}
function subplot.new(self)
local obj=self.windowHandle:newObject();
obj.className="subplot"
obj.draw = subplot.draw;
obj.redraw = subplot.draw;
obj.beginScaling=subplot.beginScaling;
obj.endScaling=subplot.endScaling;
return obj;
end
function subplot.draw(self)
self:beginScaling();
self:cls(true);
self:drawObjects();
self:endScaling();
end
function subplot.beginScaling(self)
local cr=self.windowHandle:begin();
-- cr:translate(self:get('startX'),self:get('startY'))
-- cr:scale((self:get('width'))/(self.parent:get('width')),
-- (self:get('height'))/(self.parent:get('height')))
-- clipping ...
cr:save();
cr:rectangle(self:get('startX'),self:get('startY'),
self:get('width'),self:get('height'))
cr:clip()
end
function subplot.endScaling(self)
local cr=self.windowHandle.cairoHandle;
cr:reset_clip()
cr:restore();
cr=self.windowHandle:theEnd();
end
------------------------------------------ Extend gfx..
function gfx.subplot(self,rows,cols,index)
-- one argument => index an already existing subplot..
if cols==nil then index=rows; rows=#self.objects; cols=1; end
if #self.objects~=rows*cols then -- already created, return handle only
self:cls();
local width=self:get('width')/rows;
local height=self:get('height')/cols;
local windowHandle;
for j=1,cols do
for i=1,rows do
windowHandle=subplot.new(self); -- create new subplot
windowHandle:setg('startX',width*(i-1))
windowHandle:setg('startY',height*(j-1))
windowHandle:setg('width',width)
windowHandle:setg('height',height)
windowHandle:setg('currentAxesHandle',false)
self:addObject(windowHandle); -- add subplot to window
end
end
self:draw();
end
if index==nil then index=1; end
local figure=self.objects[index];
figure:setg('currentFigureHandle',figure);
self:setg('currentFigureHandle',figure);
self.windowHandle:setg('currentFigureHandle',figure);
self.windowHandle:setg('currentAxesHandle',figure:get('currentAxesHandle'))
-- figure:setg('currentAxesHandle',figure:get('currentAxesHandle'))
--local axesHandle=figure:getAxes();
--self.windowHandle:setg('currentAxesHandle',axesHandle)
return figure;
end
function gfx.getFigure(self)
local handle= self:get('currentFigureHandle');
if handle==nil then handle=self.windowHandle; end
return handle;
end
|
require 'nn'
require('../../common/NYU_params')
local ABC_sum, parent = torch.class('nn.ABC_sum', 'nn.Module')
local elementwise_div, Parent = torch.class('nn.elementwise_div', 'nn.Module')
local elementwise_mul, Parent = torch.class('nn.elementwise_mul', 'nn.Module')
local elementwise_shift, Parent = torch.class('nn.elementwise_shift', 'nn.Module')
local elementwise_concat, Parent = torch.class('nn.elementwise_concat', 'nn.Module')
function ABC_sum:__init(mode)
parent.__init(self)
self.constant_X_Y_1 = torch.Tensor(3,g_input_height, g_input_width)
local _offset_x = 0
local _offset_y = 0
if mode == 'center' then
_offset_x = 0
_offset_y = 0
elseif mode == 'left' then
_offset_x = -1
_offset_y = 0
elseif mode == 'right' then
_offset_x = 1
_offset_y = 0
elseif mode == 'up' then
_offset_x = 0
_offset_y = -1
elseif mode == 'down' then
_offset_x = 0
_offset_y = 1
end
for y = 1 , g_input_height do
for x = 1 , g_input_width do
self.constant_X_Y_1[{1,y,x}] = (x + _offset_x - g_cx_rgb) / g_fx_rgb
self.constant_X_Y_1[{2,y,x}] = (y + _offset_y - g_cy_rgb) / g_fy_rgb
end
end
self.constant_X_Y_1[{3,{}}]:fill(1)
end
function ABC_sum:updateOutput(input)
-- the input is a 3 channel volume - the groundtruth normal map: 3 dimension, assume normal[{{},1,{}}] is the x, then y , then z
-- the output is the Ax/f + By/f + C
if self.output then
if self.output:type() ~= input:type() then
self.output = self.output:typeAs(input);
end
self.output:resize(input:size(1), 1, input:size(3), input:size(4))
if self.constant_X_Y_1:type() ~= input:type() then
self.constant_X_Y_1 = self.constant_X_Y_1:typeAs(input);
end
end
for batch_idx = 1 , input:size(1) do -- this might not be the fastest way to do it
self.output[{batch_idx,{}}]:copy(torch.sum(torch.cmul(self.constant_X_Y_1, input[{batch_idx, {}}]), 1))
end
return self.output
end
function ABC_sum:updateGradInput(input, gradOutput)
if self.gradInput then
if self.gradInput:type() ~= input:type() then
self.gradInput = self.gradInput:typeAs(input);
end
self.gradInput:resizeAs(input)
self.gradInput:zero()
end
for batch_idx = 1 , input:size(1) do
self.gradInput[{batch_idx, {}}]:copy(self.constant_X_Y_1)
end
self.gradInput[{{}, 1, {}}]:cmul(gradOutput[{batch_idx, {}}])
self.gradInput[{{}, 2, {}}]:cmul(gradOutput[{batch_idx, {}}])
self.gradInput[{{}, 3, {}}]:cmul(gradOutput[{batch_idx, {}}])
return self.gradInput
end
------------------------
function elementwise_div:__init()
Parent.__init(self)
self.gradInput = {}
self.gradInput[1] = torch.Tensor()
self.gradInput[2] = torch.Tensor()
end
function elementwise_div:updateOutput(input)
-- the input is a table, input[1] / input[2]
if self.output then
if self.output:type() ~= input[1]:type() then
self.output = self.output:typeAs(input[1]);
end
self.output:resizeAs(input[1])
end
self.output:cdiv(input[1], input[2])
-- ignore the element with 0 divisor
local zero_mask = input[2]:eq(0)
self.output[zero_mask] = 0
return self.output
end
function elementwise_div:updateGradInput(input, gradOutput)
-- the input is a table, input[1] / input[2]
if self.gradInput then
for i = 1 , 2 do
if self.gradInput[i]:type() ~= input[i]:type() then
self.gradInput[i] = self.gradInput[i]:typeAs(input[i]);
end
self.gradInput[i]:resizeAs(input[i])
end
end
self.gradInput[1]:cdiv(gradOutput, input[2])
self.gradInput[2]:cmul(gradOutput, input[1])
self.gradInput[2]:cdiv(input[2])
self.gradInput[2]:cdiv(input[2])
self.gradInput[2]:mul(-1)
-- ignore the element with 0 divisor
local zero_mask = input[2]:eq(0)
self.gradInput[1][zero_mask] = 0
self.gradInput[2][zero_mask] = 0
return self.gradInput
end
----------------------------
function elementwise_mul:__init()
Parent.__init(self)
self.gradInput = {}
self.gradInput[1] = torch.Tensor()
self.gradInput[2] = torch.Tensor()
end
function elementwise_mul:updateOutput(input)
if self.output then
if self.output:type() ~= input[1]:type() then
self.output = self.output:typeAs(input[1]);
end
self.output:resizeAs(input[1])
end
-- the input is a table
self.output:cmul(input[1], input[2])
return self.output
end
function elementwise_mul:updateGradInput(input, gradOutput)
if self.gradInput then
for i = 1 , 2 do
if self.gradInput[i]:type() ~= input[i]:type() then
self.gradInput[i] = self.gradInput[i]:typeAs(input[i]);
end
self.gradInput[i]:resizeAs(input[i])
self.gradInput[i]:zero()
end
end
self.gradInput[1]:cmul(gradOutput, input[2])
self.gradInput[2]:cmul(gradOutput, input[1])
return self.gradInput
end
-----------------------------------
function elementwise_shift:__init(mode)
Parent.__init(self)
self.mode = mode
end
function elementwise_shift:updateOutput(input)
-- the input is 4 dim, shift the 3th and 4th dim
if self.output then
if self.output:type() ~= input:type() then
self.output = self.output:typeAs(input);
end
self.output:resizeAs(input)
self.width = input:size(4)
self.height = input:size(3)
self.output:zero()
end
-- the input is a table
if self.mode == 'left' then
self.output[{{},{},{},{1,self.width-1}}]:copy(input[{{},{},{},{2, self.width}}])
elseif self.mode == 'right' then
self.output[{{},{},{},{2, self.width}}]:copy(input[{{},{},{},{1,self.width-1}}])
elseif self.mode == 'up' then
self.output[{{},{},{1,self.height - 1},{}}]:copy(input[{{},{},{2, self.height},{}}])
elseif self.mode == 'down' then
self.output[{{},{},{2, self.height},{}}]:copy(input[{{},{},{1,self.height - 1},{}}])
end
return self.output
end
function elementwise_shift:updateGradInput(input, gradOutput)
if self.gradInput then
if self.gradInput:type() ~= input:type() then
self.gradInput = self.gradInput:typeAs(input);
end
self.gradInput:resizeAs(input)
self.gradInput:zero()
end
if self.mode == 'left' then
self.gradInput[{{},{},{},{2, self.width}}]:copy(gradOutput[{{},{},{},{1,self.width-1}}])
elseif self.mode == 'right' then
self.gradInput[{{},{},{},{1,self.width-1}}]:copy(gradOutput[{{},{},{},{2, self.width}}])
elseif self.mode == 'up' then
self.gradInput[{{},{},{2, self.height},{}}]:copy(gradOutput[{{},{},{1,self.height - 1},{}}])
elseif self.mode == 'down' then
self.gradInput[{{},{},{1,self.height - 1},{}}]:copy(gradOutput[{{},{},{2, self.height},{}}])
end
return self.gradInput
end
-----------------------------------
function elementwise_concat:__init()
Parent.__init(self)
self.gradInput = {}
end
function elementwise_concat:updateOutput(input)
-- input is an array. Each element is a 4 dimesional tensor.
-- we concatenate these tensors along the second dimension
-- we also assume that each element in the input has the same number of channels
if self.output then
if self.output:type() ~= input[1]:type() then
self.output = self.output:typeAs(input[1]);
end
self.output:resize(input[1]:size(1), #input * input[1]:size(2), input[1]:size(3), input[1]:size(4))
self.output:zero()
end
-- the input is a table
for i = 1, #input do
self.output[{{}, {input[1]:size(2) * (i-1) + 1, input[1]:size(2) * i }, {}}]:copy(input[i])
end
return self.output
end
function elementwise_concat:updateGradInput(input, gradOutput)
if self.gradInput then
for i = 1 ,#input do
if self.gradInput[i] == nil then
self.gradInput[i] = torch.Tensor()
end
if self.gradInput[i]:type() ~= input[i]:type() then
self.gradInput[i] = self.gradInput[i]:typeAs(input[i]);
end
self.gradInput[i]:resizeAs(input[i])
self.gradInput[i]:zero()
end
end
for i = 1 ,#input do
self.gradInput[i]:copy(gradOutput[{{}, {input[1]:size(2) * (i-1) + 1, input[1]:size(2) * i }, {}}])
end
return self.gradInput
end
-------------------------------------
require 'nngraph'
function get_theoretical_depth()
print("get_theoretical_depth_v2")
local depth_input = nn.Identity()():annotate{name = 'depth_input', graphAttributes = {color = 'blue'}}
local normal_input = nn.Identity()():annotate{name = 'normal_input', graphAttributes = {color = 'green'}}
local ABC_right = nn.ABC_sum('right')(normal_input):annotate{name = 'ABC_right'}
local ABC_left = nn.ABC_sum('left')(normal_input):annotate{name = 'ABC_left'}
local ABC_down = nn.ABC_sum('down')(normal_input):annotate{name = 'ABC_down'}
local ABC_up = nn.ABC_sum('up')(normal_input):annotate{name = 'ABC_up'}
local z_i_left = nn.elementwise_shift('right')(depth_input)
local z_i_right = nn.elementwise_shift('left')(depth_input)
local z_i_up = nn.elementwise_shift('down')(depth_input)
local z_i_down = nn.elementwise_shift('up')(depth_input)
local left_div_right = nn.elementwise_div()({ABC_left, ABC_right}):annotate{name = 'left_div_right'}
local D_right = nn.elementwise_mul()({left_div_right, z_i_left}):annotate{name = 'D_right'}
local z_o_right = nn.elementwise_shift('right')(D_right):annotate{name = 'z_o_right'}
local right_div_left = nn.elementwise_div()({ABC_right, ABC_left}):annotate{name = 'right_div_left'}
local D_left = nn.elementwise_mul()({right_div_left, z_i_right}):annotate{name = 'D_left'}
local z_o_left = nn.elementwise_shift('left')(D_left):annotate{name = 'z_o_left'}
local up_div_down = nn.elementwise_div()({ABC_up, ABC_down}):annotate{name = 'up_div_down'}
local D_down = nn.elementwise_mul()({up_div_down, z_i_up}):annotate{name = 'D_down'}
local z_o_down = nn.elementwise_shift('down')(D_down):annotate{name = 'z_o_down'}
local down_div_up = nn.elementwise_div()({ABC_down, ABC_up}):annotate{name = 'down_div_up'}
local D_up = nn.elementwise_mul()({down_div_up, z_i_down}):annotate{name = 'D_up'}
local z_o_up = nn.elementwise_shift('up')(D_up):annotate{name = 'z_o_up'}
local z_concat = nn.elementwise_concat()({z_o_up, z_o_down, z_o_left, z_o_right}):annotate{name = 'concat'}
local model = nn.gModule({normal_input, depth_input}, {z_concat})
return model
end
function get_shifted_mask()
print("get_shifted_mask_v2")
local mask_input = nn.Identity()():annotate{name = 'mask_input', graphAttributes = {color = 'green'}}
local mask_o_left = nn.elementwise_shift('left')(mask_input)
local mask_o_right = nn.elementwise_shift('right')(mask_input)
local mask_o_up = nn.elementwise_shift('up')(mask_input)
local mask_o_down = nn.elementwise_shift('down')(mask_input)
local mask_concat = nn.elementwise_concat()({mask_o_up, mask_o_down, mask_o_left, mask_o_right}):annotate{name = 'concat'}
local model = nn.gModule({mask_input}, {mask_concat})
return model
end |
elite_geonosian_warrior = Creature:new {
customName = "Elite Geonosian Warrior",
socialGroup = "geonosian",
faction = "",
level = 300,
chanceHit = 0.85,
damageMin = 800,
damageMax = 1600,
baseXp = 13500,
baseHAM = 60000,
baseHAMmax = 120000,
armor = 2,
resists = {130,125,130,125,125,130,130,130,140},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK + KILLER,
optionsBitmask = AIENABLED,
diet = HERBIVORE,
templates = {
"object/mobile/dressed_geonosian_warrior_01.iff",
"object/mobile/dressed_geonosian_warrior_02.iff",
"object/mobile/dressed_geonosian_warrior_03.iff"},
lootGroups = {
{
groups = {
{group = "weapon_component_advanced", chance = 10000000},
},
lootChance = 3000000
},
{
groups = {
{group = "trash_common", chance = 7000000},
{group = "trash_rare", chance = 3000000},
},
lootChance = 10000000
},
{
groups = {
{group = "geonosian_common", chance = 10000000},
},
lootChance = 5000000
},
{
groups = {
{group = "tierone", chance = 1500000},
{group = "tiertwo", chance = 3500000},
{group = "tierthree", chance = 2500000},
{group = "tierdiamond", chance = 2500000},
},
lootChance = 4000000
}
},
weapons = {"geonosian_weapons"},
conversationTemplate = "",
attacks = merge(brawlermaster,marksmanmaster,pistoleermaster,riflemanmaster)
}
CreatureTemplates:addCreatureTemplate(elite_geonosian_warrior, "elite_geonosian_warrior")
|
local M = {}
local conf_defaults = {
max_lines = 1000;
max_num_results = 20;
sort = true;
priority = 5000;
show_prediction_strength = true;
run_on_every_keystroke = true;
snippet_placeholder = '..';
ignored_file_types = { -- default is not to ignore
-- uncomment to ignore in lua:
-- lua = true
};
}
function M:setup(params)
for k, v in pairs(params) do
conf_defaults[k] = v
end
end
function M:get(what)
return conf_defaults[what]
end
return M
|
-- © https://github.com/ncopa/lua-shell
local shell = {}
function shell.escape(args)
local ret = {}
for _,a in pairs(args) do
s = tostring(a)
if s:match("[^A-Za-z0-9_/:=-]") then
s = "'"..s:gsub("'", "'\\''").."'"
end
table.insert(ret,s)
end
return table.concat(ret, " ")
end
function shell.run(args)
local h = io.popen(shell.escape(args))
local outstr = h:read("*a")
return h:close(), outstr
end
function shell.execute(args)
return os.execute(shell.escape(args))
end
return shell
|
-- 3 steps: remove nullables, remove all cycles, and finally remove immediate left recursion
local left_recursion_elimination = {}
local ll1 = require 'luainlua.ll1.ll1'
local utils = require 'luainlua.common.utils'
local graph = require 'luainlua.common.graph'
local worklist = require 'luainlua.common.worklist'
local function hash(production)
return table.concat({unpack(production)}, '`')
end
local function normalize(production)
local new = {}
for object in utils.loop(production) do
if object ~= '' then
table.insert(new, object)
end
end
return new
end
local function null_out(production, i, nullable_indices)
local new = {unpack(production)}
local changed = {}
local index = 1
while true do
local okay = i % 2 == 0
if okay then
new[nullable_indices[index]] = ''
table.insert(changed, nullable_indices[index])
end
i = math.floor(i / 2)
if i == 0 then break end
index = index + 1
end
return normalize(new)
end
local function insert_into(new_nonterminal, production, production_hashes)
local h = hash(production)
if not production_hashes[h] and #production ~= 0 then
table.insert(new_nonterminal, production)
production_hashes[h] = true
end
end
local function eliminate_nullables(configuration)
local nullables = {}
for variable, nonterminal in pairs(configuration) do
local first_set = configuration:first(variable)
if first_set[''] then
nullables['$' .. variable] = true
end
end
local new_actions = {}
for variable, nonterminal in pairs(configuration) do
-- let's construct a hashset of the original productions
local seen_productions = {}
for production in utils.loop(nonterminal) do
seen_productions[hash(production)] = true
end
-- let's compute the null-eliminated expansion
local new_nonterminal = {}
local production_hashes = {}
for production in utils.loop(nonterminal) do
local action = production.action
local nullable_indices = {}
for i, object in ipairs(production) do
if nullables[object] then
table.insert(nullable_indices, i)
end
end
if #nullable_indices ~= 0 then
-- compute the combinatorial transfer to naturals
for i=0,2^#nullable_indices - 1 do
local new_production, changed = null_out(production, i, nullable_indices)
insert_into(new_nonterminal, new_production, production_hashes)
end
else
insert_into(new_nonterminal, normalize(production), production_hashes)
end
end
new_actions[variable] = new_nonterminal
assert(#new_nonterminal ~= 0)
end
return ll1.configure(new_actions)
end
local function full_dependency_graph(configuration)
-- find all forms of X -> Y
local g = graph()
g.configuration = configuration
for variable, nonterminal in pairs(configuration) do
for production in utils.loop(nonterminal) do
for object in utils.loop(production) do
if object:sub(1,1) == '$' then
g:edge(object:sub(2), variable)
g:edge(variable, object:sub(2))
end
end
end
end
g:set_root('root')
return g
end
-- computes the set of productions that A =*> goes to
local transitive_algorithm = worklist {
-- what is the domain? Sets of productions
initialize = function(self, _, _)
return {}
end,
transfer = function(self, node, _, graph, pred)
local transitive_set = self:initialize(node)
local nonterminal = graph.configuration[node]
local single_set = {}
for production in utils.loop(nonterminal) do
transitive_set[hash(production)] = production
if #production == 1 and production[1]:sub(1, 1) == '$' then
transitive_set = self:merge(
transitive_set,
self.partial_solution[production[1]:sub(2)])
end
end
return transitive_set
end,
changed = function(self, old, new)
-- assuming monotone in the new direction
for key in pairs(new) do
if not old[key] then
return true
end
end
return false
end,
merge = function(self, left, right)
local merged = utils.copy(left)
for key in pairs(right) do
merged[key] = right[key]
end
return merged
end,
tostring = function(self, _, node, input)
local list = {}
for key in pairs(input) do table.insert(list, key) end
return node .. ' -> ' .. table.concat(list, ' | ')
end
}
local function eliminate_cycles(configuration)
local use_graph = full_dependency_graph(configuration)
local transitive_set = transitive_algorithm:forward(use_graph)
local cycle_set = {}
for variable, transitionable in pairs(transitive_set) do
if transitionable['$' .. variable] then
cycle_set[variable] = true
end
end
local noncyclic_set = {}
for key, map in pairs(transitive_set) do
noncyclic_set[key] = utils.kfilter(function(k, v) return not cycle_set[k:sub(2)] end, map)
end
local new_actions = {}
for variable, nonterminal in pairs(configuration) do
if variable ~= 'root' then
-- look for productions that are exactly $Cyclic
local productions_map = {}
for production in utils.loop(nonterminal) do
if #production == 1 and production[1]:sub(1, 1) == '$' then
local other = production[1]:sub(2)
if cycle_set[other] then
for h, other_production in pairs(noncyclic_set[other]) do
productions_map[h] = other_production
end
else
productions_map[hash(production)] = production
end
else
productions_map[hash(production)] = production
end
end
new_actions[variable] = {}
for _, production in pairs(productions_map) do
table.insert(new_actions[variable], production)
end
else
new_actions[variable] = nonterminal
end
end
return ll1.configure(new_actions)
end
local function immediate_elimination(nonterminal)
local variable = nonterminal.variable
local new_variable = variable .. "'new"
local recursive = {{''}, variable = new_variable}
local other = {variable = variable}
for production in utils.loop(nonterminal) do
local local_production = utils.copy(production)
print('\t', variable, utils.to_string(production))
if local_production[1] == variable then
assert(variable == table.remove(local_production, 1))
table.insert(local_production, new_variable)
table.insert(recursive, local_production)
else
table.insert(local_production, new_variable)
table.insert(other, local_production)
end
end
if #recursive == 1 then
return nil
else
return other, recursive
end
end
local function indirect_elimination(configuration)
local actions = utils.copy(configuration)
local variables = {}
for node in configuration:get_dependency_graph():dfs() do table.insert(variables, node) end
for i = 1,#variables do
local old_left = actions[variables[i]]
local new_left = utils.copy(old_left)
local to_remove = {}
for j = 1, #variables do
if i ~= j then
local old_right = actions[variables[j]]
-- find some production of the form A_i := A_j \gamma
for k, production in ipairs(old_left) do
if production[1] == '$' .. variables[j] then
-- expand A_j out
print(variables[i], variables[j], utils.to_string(production))
for production_j in utils.loop(old_right) do
local new_i_k = utils.copy(production_j)
for l = 2, #production do
table.insert(new_i_k, production[l])
end
table.insert(new_left, new_i_k)
to_remove[k] = true
end
end
end
end
end
local needs_removing = {}
for k in pairs(to_remove) do table.insert(needs_removing, k) end
table.sort(needs_removing, function(a,b) return b > a end)
for j in utils.loop(needs_removing) do
print(j)
table.remove(new_left, j)
end
-- rewrite A[i]
local normal, recursive = immediate_elimination(new_left)
if normal then
actions[variables[i]] = normal
actions[recursive.variable:sub(2)] = recursive
else
actions[variables[i]] = new_left
end
end
return ll1.configure(actions)
end
local function direct_factor_elimination(nonterminal)
-- eliminate A -> a \gamma_1 | a \gamma_2 | ... a \gamma_n into
-- A -> a $A'factored | \gamma_{n+1}
-- A'factor#1 -> \gamma_1 | \gamma_2 | ... | \gamma_n
-- we need to keep doing this until we hit a fixed point
local action = {variable = nonterminal.variable}
local new_variables = {}
local variable = nonterminal.variable
-- step 1: compute frequency table of common prefixes
local prefix_freq = {}
for i, production in ipairs(nonterminal) do
if not prefix_freq[production[1]] then prefix_freq[production[1]] = {} end
table.insert(prefix_freq[production[1]], i)
end
-- step 2: compute replacement table
local replacement_id = 1
for prefix, frequencies in pairs(prefix_freq) do
if #frequencies == 1 then
table.insert(action, nonterminal[frequencies[1]])
else
-- create a new variable
local new_variable = variable .. '\'factor#' .. replacement_id
local new_nonterminal = {variable = new_variable}
replacement_id = replacement_id + 1
for id in utils.loop(frequencies) do
local new_production = utils.sublist(nonterminal[id], 2)
if #new_production == 0 then new_production[1] = '' end
table.insert(new_nonterminal, new_production)
end
table.insert(new_variables, new_nonterminal)
table.insert(action, {prefix, new_variable})
end
end
return action, new_variables
end
local function left_factor_elimination(configuration)
local has_changes = false
local actions = utils.copy(configuration)
for variable, nonterminal in pairs(configuration) do
local action, new_variables = direct_factor_elimination(nonterminal)
if #new_variables ~= 0 then
has_changes = true
actions[action.variable:sub(2)] = action
for new in utils.loop(new_variables) do
actions[new.variable:sub(2)] = new
end
end
end
if has_changes then
return left_factor_elimination(actions)
end
return ll1.configure(actions)
end
--[[--
-- testing
local configuration = ll1.configure {
root = {
{'$expr', action = id},
},
base = {
{'consts', action = id},
{'(', '$expr', ')', action = id},
},
expr = {
{'$base'},
{'$base', '+', '$expr'},
{'$base', '$expr'},
{'fun', 'identifier', '->', '$expr', action = id},
},
}
local new_configuration = eliminate_nullables(configuration)
print(new_configuration:pretty())
new_configuration = eliminate_cycles(new_configuration)
print(new_configuration:pretty())
new_configuration = indirect_elimination(new_configuration)
print(new_configuration:pretty())
new_configuration = left_factor_elimination(new_configuration)
print(new_configuration:pretty())
ll1(new_configuration)
print(new_configuration:firsts():dot())
print(new_configuration:follows():dot())
--]]--
left_recursion_elimination.eliminate_nullables = eliminate_nullables
left_recursion_elimination.eliminate_cycles = eliminate_cycles
left_recursion_elimination.immediate_elimination = immediate_elimination
left_recursion_elimination.indirect_elimination = indirect_elimination
left_recursion_elimination.left_factor_elimination = left_factor_elimination
return left_recursion_elimination |
local pipes = require('pipes')
local log = pipes.log
log('boot start')
pipes.console({port=11112})
--local json = require('pipes.json')
--local str = '{"name":"dada", "age":25, "score":98.5, "arr":[123, "hehe123", 456, {"sub":"ddd"}, [55,66,77,88]], "arr2":[], "obj2":{} }'
--local jObj = json.decode(str)
--for k,v in pairs(jObj) do
-- print('item, '..tostring(k)..'='..tostring(v))
--end
--str = json.encode(jObj)
--print(str)
--
pipes.newservice('HttpTest')
pipes.exit()
--[[
local sock = require('pipes.socket')
log('start open')
local id, err = sock.open({
host='www.baidu.com',
port=443,
timeout=15000,
})
if id then
log('boot conn succ, id='..id)
sock.start(id)
sock.send(id, '123\n')
while(true)
do
local rsp, sz = sock.read(id)
if not rsp then
break
end
log(rsp)
end
log('boot disconn')
else
log('boot conn failed, err='..err)
end
--]]
--[[
for i=1, 10 do
pipes.sleep(1000)
log('sleep done ', i)
end
--]]
--[[
--pipes.sleep(10000)
log('start net session: '..id)
sock.start(id)
local str, sz = sock.read(id, 20)
log('read start msg 1: '..tostring(str)..', sz='..sz)
str, sz = sock.read(id, 30)
log('read start msg 2: '..tostring(str)..', sz='..sz)
pipes.timeout(10000, function()
pipes.exit()
end)
while(true)
do
local str, sz = sock.read(id, 1024)
if not str then
break
end
log('dddd recv: sz='..sz..', msg: '..tostring(str))
end
--pipes.sleep(45000)
--log('asdasdasd')
--sock.start(id)
--]]
|
minetest.register_node("tardis:interior_door", {
description = "Tardis Interior Door",
tiles = {"inside_door.png"},
drawtype = "mesh",
mesh = "tardis.obj",
selection_box = {
type = "fixed",
fixed = {
{ -0.5, -0.5, -0.5, 0.5, 1.5, 0.5 },
},
},
collision_box = {
type = "fixed",
fixed = {
{ 0.48, -0.5,-0.5, 0.5, 1.5, 0.5},
{-0.5 , -0.5, 0.48, 0.48, 1.5, 0.5},
{-0.5, -0.5,-0.5 ,-0.48, 1.5, 0.5},
{ -0.7,-0.6,-0.7,0.7,-0.48, 0.7},
}
},
sunlight_propagates = true,
groups = {not_in_creative_inventory = 1},
use_texture_alpha = "clip",
diggable = false,
on_timer = function(pos)
local objs = minetest.get_objects_inside_radius(pos, 0.9)
--[[if #objs ~= 0 then
_tardis.tools.log("Found "..tostring(#objs).." # of objects, at "..minetest.pos_to_string(pos))
end]]
if objs[1] == nil then return true else
if objs[1]:is_player() then -- Check if it's a player or if it's an entity (mob)
local pmeta = objs[1]:get_meta()
local meta = minetest.get_meta(pos)
local id = meta:get_string("id")
local user = _tardis.get_user(id)
if user.version == nil then
_tardis.tools.log("Registering door before after failed to get user '"..id.."'.")
return true
end
local go_pos = user.out_pos
-- Change this based on the tardis's exit direction (rather than hard coded for only one dir)
local look = 0
if user.dest_dir == 0 then -- N
go_pos.z = go_pos.z+1
look = 0
elseif user.dest_dir == 2 then -- S
go_pos.z = go_pos.z-1
look = 180
elseif user.dest_dir == 1 then -- W
go_pos.x = go_pos.x-1
look = 90
elseif user.dest_dir == 3 then -- E
go_pos.x = go_pos.x+1
look = 270
end
objs[1]:set_pos(go_pos)
objs[1]:set_look_horizontal( _tardis.tools.deg2rad(look) )
objs[1]:set_look_vertical( _tardis.tools.deg2rad(0) )
_tardis.tools.log("Player '"..objs[1]:get_player_name().."' exits tardis located at "..minetest.pos_to_string(go_pos))
-- Deal damage to the player because they left while still in the vortex
--[[if pmeta:get_string("vortex") == "yes" then
go_pos.z = go_pos.z-2
objs[1]:set_pos(go_pos)
objs[1]:set_hp(0)
end]]
-- Setup the exterior to change skins and restart the door timer
minetest.after(1, function()
local meta = minetest.get_meta(pos)
local id = meta:get_string("id")
local user = _tardis.get_user(id)
if user.version == nil then
_tardis.tools.log("Registering door at after failed to get user '"..id.."'.")
return
end
local go_pos = user.out_pos
local look = user.exterior_theme
minetest.set_node(go_pos, {name=look, param1=user.dest_dir, param2=user.dest_dir}) -- Set exterior skin
local ometa = minetest.get_meta(go_pos)
ometa:set_string("id", id)
local timer = minetest.get_node_timer(go_pos)
timer:start(0.2) -- Restart door timer
end)
else -- entity not player
local meta = minetest.get_meta(pos)
local id = meta:get_string("id")
local user = _tardis.get_user(id)
if user.version == nil then
_tardis.tools.log("Registering door at entity not player failed to get user '"..id.."'.")
return true
end
local go_pos = user.out_pos
-- Change this based on the tardis's exit direction (rather than hard coded for only one dir)
--go_pos.z = go_pos.z-1
if user.dest_dir == 0 then -- N
go_pos.z = go_pos.z+1
elseif user.dest_dir == 2 then -- S
go_pos.z = go_pos.z-1
elseif user.dest_dir == 1 then -- W
go_pos.x = go_pos.x-1
elseif user.dest_dir == 3 then -- E
go_pos.x = go_pos.x+1
end
objs[1]:set_pos(go_pos)
_tardis.tools.log("Entity exits tardis located at "..minetest.pos_to_string(go_pos))
end
end
return true
end,
})
--fix door timer
minetest.register_lbm({
name = "tardis:fix_door_timers",
nodenames = {"tardis:interior_door"},
action = function(pos, node)
local timer = minetest.get_node_timer(pos)
if timer:is_started() ~= true then -- Start it only if it's needed
_tardis.tools.log("Restarted door timer at "..minetest.pos_to_string(pos))
timer:start(0.2)
end
end
})
|
--- ftable module
-- @classmod ftable
local M = {}
function M.new(t)
return setmetatable(t or {}, {
__index = M,
__tostring = function(t) return M.tostring(t) end
})
end
local function is_from_module(t, new_t)
local mt = getmetatable(t)
if(mt and mt.__index == M and new_t) then
return M.new(new_t)
end
return new_t or t
end
--- Apply a function by each element in table
-- @tparam table t Base table.
-- @func fn Function to apply to each element.
function M.for_each(t, fn)
for k, v in pairs(t) do
fn(v, k , t)
end
end
--- Apply a function by each element in table of reverse way
-- @tparam table t Base table.
-- @func fn Function to apply to each element.
function M.for_each_reverse(t, fn)
local length = #t
for i = length, 1, -1 do
fn(v, k , t)
end
end
--- Create a new table whose values are result of apply a function to each element.
-- @tparam table t Base table.
-- @func fn Function to apply to each element.
-- @treturn table
function M.map(t, fn)
local new_t = {}
for k, v in pairs(t) do
new_t[k] = fn(v, k, t)
end
return is_from_module(t, new_t)
end
--- Create a new table whose values pass a function.
-- @tparam table t Base table.
-- @func fn Function to apply to each element.
-- @treturn table
function M.filter(t, fn)
local new_t = {}
for k, v in pairs(t) do
if(fn(v, k, t)) then table.insert(new_t, v) end
end
return is_from_module(t, new_t)
end
--- Find a new table whose values pass a function.
-- @tparam table t Base table.
-- @func fn Function to apply to each element.
-- @treturn {table|string|number|boolean|nil} number
function M.find(t, fn)
local found, index = nil, -1
for k, v in pairs(t) do
if(fn(v, k, t)) then found = v;index = k break end
end
return found, index
end
--- Find index of first element that pass the function.
-- @tparam table t Base table.
-- @func fn Function to apply to each element.
-- @treturn {number|nil}
function M.find_index(t, fn)
local _, index = M.find(t, fn)
return index
end
--- Find index of first element whose value is same to given.
-- @tparam table t Base table.
-- @param value Value to find index.
-- @treturn {number|nil}
function M.index_of(t, value)
local _, index = M.find(t, function(v) return v == value end)
return index
end
--- Reduce a table to a value passing a function to each element.
-- @tparam table t Base table.
-- @func fn Function to apply to each element. Params (accumulator, element_value, element_key, table).
-- @param accumulator Init value of accumulator.
-- @return accumulator
function M.reduce(t, fn, accumulator)
M.for_each(t, function(v, k, a)
accumulator = fn(accumulator, v, k, a)
end)
return accumulator
end
--- Reduce a reversed table to a value passing a function to each element.
-- @tparam table t Base table.
-- @func fn Function to apply to each element. Params (accumulator, element_value, element_key, table).
-- @param accumulator Init value of accumulator.
-- @return accumulator
function M.reduce_reverse(t, fn, accumulator)
M.for_each_reverse(t, function(v, k, a)
accumulator = fn(accumulator, v, k, a)
end)
return accumulator
end
--- Inserts a value at end of table.
-- @tparam table t Base table.
-- @param value Value to insert
-- @return length of table
function M.push(t, value)
table.insert(t, value)
return #t
end
--- Removes last item of table.
-- @tparam table t Base table.
-- @return item removed
function M.pop(t)
return table.remove(t, #t)
end
--- Inserts a value at start of table.
-- @tparam table t Base table.
-- @param value Value to insert
-- @return length of table
function M.unshift(t, value)
table.insert(t, 1, value)
return #t
end
--- Removes first item of table.
-- @tparam table t Base table.
-- @return item removed
function M.shift(t)
return table.remove(t, 1)
end
--- Reverse a table. Create a new table.
-- @tparam table t Base table.
-- @return reversed table
function M.reverse(t)
local new_t = {}
local length = M.length(t)
for i=length, 1, -1 do
M.push(new_t, t[i])
end
return is_from_module(t, new_t)
end
local function flat(t, depth, new_t, level)
depth = depth or 1
new_t = new_t or {}
level = level or 0
M.for_each(t, function(v, k)
if (type(v) == "table" and depth > level) then
flat(v, depth, new_t, level + 1)
else
M.push(new_t, v)
end
end)
return is_from_module(t, new_t)
end
--- Flat a table. Create a new table.
-- @tparam table t Base table.
-- @number[opt=1] depth Depth to flat the table.
-- @treturn table
function M.flat(t, depth)
return flat(t, depth)
end
--- Flat and map combined. Apply a function to a flat table. Create a new table. Flat depth is 1.
-- @tparam table t Base table.
-- @func fn Function to apply to each element of flatted table.
-- @treturn table
function M.flat_map(t, fn)
local flat = M.flat(t, 1)
return M.map(flat, fn)
end
--- Slice a table start-ends. Create a new table.
-- @tparam table t Base table.
-- @number[opt=1] start Start position.
-- @number[opt=#t] endv End position.
-- @treturn table
function M.slice(t, start, endv)
start = start or 1
endv = endv or #t
local new_t = {}
for i = start, endv do
M.push(new_t, t[i])
end
return is_from_module(t, new_t)
end
--- Sort a table.
-- @tparam table t Base table.
-- @func fn Compare function. fn(a, b)
-- @treturn table
function M.sort(t, fn)
table.sort(t, fn)
return t
end
-- TODO
-- function M.splice(t, start, delete, ...)
-- local length = #t
-- if (start > length) then start = length + 1
-- elseif (start < 0) then start = length + start end
-- local items = {...}
-- if(#items < 1) then return t end
-- local endv = start + delete
-- local items_count = 1
-- local t_before_start = M.slice(t, 1, start)
-- for i = start, endv do
-- end
-- end
--- Check if some element of a table pass a function.
-- @tparam table t Base table.
-- @func fn Function to pass.
-- @treturn table
function M.some(t, fn)
return M.find(t, fn) and true or false
end
--- Check if every element of a table pass a function.
-- @tparam table t Base table.
-- @func fn Function to pass.
-- @treturn boolean
function M.every(t, fn)
local result = true
for k, v in pairs(t) do
if(not fn(v, k, t)) then result = false; break end
end
return result
end
--- Concat a table with other.
-- @tparam table t Base table.
-- @tparam table ot Other table.
-- @treturn table
function M.concat(t, ot)
local new_t = {}
M.for_each(t, function(v)
M.push(new_t, v)
end)
M.for_each(ot, function(v)
M.push(new_t, v)
end)
return is_from_module(t, new_t)
end
--- Fill a table with a element.
-- @tparam table t Base table.
-- @param value Fill element.
-- @tparam number[opt=1] start Start position.
-- @tparam number[opt=#t] endv End position.
-- @treturn table
function M.fill(t, value, start, endv)
start = start or 1
endv = endv or #t
for i = start, endv do
t[i] = value
end
return is_from_module(t, t)
end
--- Fill a table with a element.
-- @tparam table t Base table.
-- @param value Value to include.
-- @treturn boolean
function M.includes(t, value)
return M.some(t, function(v) return v == value end)
end
--- Join table elements to a string.
-- @tparam table t Base table.
-- @string[opt=""] separator Separator.
-- @treturn string
function M.join(t, separator)
separator = separator or ""
local result = ""
M.for_each(t, function(v,k) result = result .. ((k > 1 and separator) or "") .. v end)
return result
end
--- Returns a new table with keys table.
-- @tparam table t Base table.
-- @treturn table
function M.keys(t)
return M.map(t, function(_, k) return k end)
end
--- Returns a new table with values table.
-- @tparam table t Base table.
-- @treturn table
function M.values(t)
return M.map(t, function(v) return v end)
end
--- Returns table length.
-- @tparam table t Base table.
-- @treturn number
function M.length(t)
return #t
end
function pvalue(value)
if(type(value) == "string") then return "\"" .. value .. "\""
else return tostring(value) end
end
local function _tostring(t, depth, level)
level = level or 1
local sep = " "
local result = "{\n"
M.for_each(t, function(v, k)
if(type(v) == "table") then
result = result .. (sep:rep(level)) .. "[" .. k .. "] = " .. (depth > level and _tostring(v, level + 1) or tostring(v)) .. ",\n"
else
result = result .. (sep:rep(level)) .. "[" .. k .. "] = " .. pvalue(v) .. ",\n"
end
end)
return result .. (sep:rep(level-1)) .. "}"
end
--- Returns table tostring.
-- @tparam table t Base table.
-- @number[opt=1] depth Depth.
-- @treturn string
function M.tostring(t, depth)
depth = depth or 1
return _tostring(t, depth)
end
--- Print a table.
-- @tparam table t Base table.
-- @number[opt=1] depth Depth.
function M.print(t, depth)
print(M.tostring(t, depth))
end
return setmetatable({},{
__index = M,
__call = function(cls, t)
return M.new(t)
end
}) |
--[[
This file is part of toml. It is subject to the licence terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/pallene-modules/toml/master/COPYRIGHT. No part of toml, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
Copyright © 2015 The developers of toml. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/pallene-modules/toml/master/COPYRIGHT.
]]--
|
local class = require 'ext.class'
local ViscousFlux = class()
function ViscousFlux:init(args)
self.solver = assert(args.solver)
end
-- insert extra flux calculations into fvsolver's calcFlux() kernel
function ViscousFlux:addCalcFluxCode()
--[[
from "CFD - An Open Approach" section 14.2
dU^I/dt + dF^Ij/dx^j = 0
dU^I/dt = -dF^Ij/dx^j
i = flux direction
j = state variable vector component
Fv^ρ^i = 0
Fv^m^ij = -τ^ij
Fv^E^i = -τ^ij v_j - q^i
τ^ij = mu ((v^i;j + v^j;i) - 2/3 g^ij v^k_;k)
τ^ij_;j = mu ((v^i;j_j + v^j;i_j) - 2/3 g^ij v^k_;kj)
dU^I/dt + dFv^Ii/dx^i = 0
dU^I/dt = -dFv^Ii/dx^i
dρ/dt = 0
dm^j/dt = ∇_i τ^ij
dE/dt = ∇_i (τ^ij v_j + q^i)
dm^j/dt = ∇_i (mu ((∇^j v^i + ∇^i v^j) - 2/3 g^ij ∇_k v^k))
dm^j/dt =
∇_i mu ((∇^j v^i + ∇^i v^j) - 2/3 g^ij ∇_k v^k)
+ mu (
(
∇^j (∇_i v^i)
+ (∇_i ∇^i) v^j
)
- 2/3 g^ij ∇_i (∇_k v^k)
)
dE/dt = ∇_i ((mu ((∇^j v^i + ∇^i v^j) - 2/3 g^ij ∇_k v^k)) v_j + q^i)
... do I really want to modify the flux vector?
or should I just put this in the source term?
flux vector here
source term somewhere else
per-component in cartesian metric
for rhs calcs:
Fv^m^ij = -τ^ij
-Fv^m^ij_,j = τ^ij_,j
-Fv^m^ij_,j = mu ((v_i,jj + v_j,ij) - 2/3 v_j,ji)
-Fv^m^ij_,j = mu (v_i,jj + 1/3 v_j,ij)
-Fv^m^ij_,j = mu (v_i,xx + v_i,yy + v_i,zz + 1/3 v_x,ix + 1/3 v_y,iy + 1/3 v_z,iz)
-Fv^m^xj_,j = mu (4/3 v_x,xx + v_x,yy + v_x,zz + 1/3 v_y,xy + 1/3 v_z,xz)
-Fv^m^yj_,j = mu (4/3 v_y,yy + v_y,xx + v_y,zz + 1/3 v_x,xy + 1/3 v_z,yz)
-Fv^m^zj_,j = mu (4/3 v_z,zz + v_z,xx + v_z,yy + 1/3 v_x,xz + 1/3 v_y,yz)
I could abstract my calculation of variables in my partial deriv code, and finite-difference 'v'
or I could factor our momentum and density ...
-Fv^m^xj_,j = mu (4/3 (m_x/rho),xx + (m_x/rho),yy + (m_x/rho),zz + 1/3 (m_y/rho),xy + 1/3 (m_z/rho),xz)
-Fv^m^yj_,j = mu (4/3 (m_y/rho),yy + (m_y/rho),xx + (m_y/rho),zz + 1/3 (m_x/rho),xy + 1/3 (m_z/rho),yz)
-Fv^m^zj_,j = mu (4/3 (m_z/rho),zz + (m_z/rho),xx + (m_z/rho),yy + 1/3 (m_x/rho),xz + 1/3 (m_y/rho),yz)
(m_i/rho),jk = (m_i,j/rho - m_i rho_,j/rho^2),k
(m_i/rho),jk = (
m_i,jk / rho
- m_i,j rho_,k / rho^2
- m_i,k rho_,j / rho^2
- m_i rho_,jk / rho^2
+ 2 m_i rho_,j rho_,k / rho^3
)
-Fv^m^ij_,j = mu (v_i,jj + 1/3 v_j,ij)
-Fv^m^ij_,j = mu ((m_i/rho),jj + 1/3 (m_j/rho),ij)
-Fv^m^ij_,j = mu (
(
m_i,jj / rho
- m_i,j rho_,j / rho^2
- m_i,j rho_,j / rho^2
- m_i rho_,jj / rho^2
+ 2 m_i rho_,j rho_,j / rho^3
)
+ 1/3 (
m_j,ij / rho
- m_j,i rho_,j / rho^2
- m_j,j rho_,i / rho^2
- m_j rho_,ij / rho^2
+ 2 m_j rho_,i rho_,j / rho^3
)
)
-Fv^m^ij_,j = mu (
+ m_i,jj / rho + 1/3 m_j,ij / rho
- (
+ 2 m_i,j rho_,j
+ m_i rho_,jj
+ 1/3 m_j,i rho_,j
+ 1/3 m_j,j rho_,i
+ 1/3 m_j rho_,ij
) / rho^2
+ (
+ 2 m_i rho_,j rho_,j
+ 2/3 m_j rho_,i rho_,j
) / rho^3
)
... too many terms
-Fv^E^i = τ^ij v_j + q^i
-Fv^E^i_,i = (τ^ij v_j + q^i)_,i
-Fv^E^i_,i = τ^ij_,i v_j + τ^ij v_j_,i + q^i_,i
--]]
return [[
#error TODO
//how about the partials not across the flux axis? time to construct a basis.
//this works fine for grids, but what to do for unstructured?
// even for grids, along the flux dir we will be using dx, but along the perp dirs we will use 2 dx
// and even if I do 2dx along the non-flux axis then we have to recalc centers of faces in neighbors of our current face
real3x3 dv;
dv.x = real3_sub(
real3_real_mul(ppUR->m, 1. / (ppUR->rho * dx)),
real3_real_mul(ppUL->m, 1. / (ppUL->rho * dx))
)
sym3 tau_uu =
]]
end
return ViscousFlux
|
--[[
################################################################################
#
# Copyright (c) 2014-2019 Ultraschall (http://ultraschall.fm)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
################################################################################
]]
-------------------------------------
--- ULTRASCHALL - API - FUNCTIONS ---
-------------------------------------
--- Navigation Module ---
-------------------------------------
if type(ultraschall)~="table" then
-- update buildnumber and add ultraschall as a table, when programming within this file
local retval, string = reaper.BR_Win32_GetPrivateProfileString("Ultraschall-Api-Build", "Functions-Build", "", reaper.GetResourcePath().."/UserPlugins/ultraschall_api/IniFiles/ultraschall_api.ini")
local retval, string = reaper.BR_Win32_GetPrivateProfileString("Ultraschall-Api-Build", "Navigation-Module-Build", "", reaper.GetResourcePath().."/UserPlugins/ultraschall_api/IniFiles/ultraschall_api.ini")
local retval, string2 = reaper.BR_Win32_GetPrivateProfileString("Ultraschall-Api-Build", "API-Build", "", reaper.GetResourcePath().."/UserPlugins/ultraschall_api/IniFiles/ultraschall_api.ini")
if string=="" then string=10000
else
string=tonumber(string)
string=string+1
end
if string2=="" then string2=10000
else
string2=tonumber(string2)
string2=string2+1
end
reaper.BR_Win32_WritePrivateProfileString("Ultraschall-Api-Build", "Functions-Build", string, reaper.GetResourcePath().."/UserPlugins/ultraschall_api/IniFiles/ultraschall_api.ini")
reaper.BR_Win32_WritePrivateProfileString("Ultraschall-Api-Build", "API-Build", string2, reaper.GetResourcePath().."/UserPlugins/ultraschall_api/IniFiles/ultraschall_api.ini")
ultraschall={}
ultraschall.API_TempPath=reaper.GetResourcePath().."/UserPlugins/ultraschall_api/temp/"
end
function ultraschall.ToggleScrollingDuringPlayback(scrolling_switch, move_editcursor, goto_playcursor)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>ToggleScrollingDuringPlayback</slug>
<requires>
Ultraschall=4.00
Reaper=5.40
Lua=5.3
</requires>
<functioncall>ultraschall.ToggleScrollingDuringPlayback(integer scrolling_switch, boolean move_editcursor, boolean goto_playcursor)</functioncall>
<description>
Toggles scrolling during playback and recording. Let's you choose to put the edit-marker at the playposition, where you toggled scrolling.
You can also move the view to the playcursor-position.
It changes, if necessary, the state of the actions 41817, 40036 and 40262 to scroll or not to scroll; keep that in mind, if you use these actions otherwise as well!
returns -1 in case of error
</description>
<retvals>
integer retval - -1, in case of an error
</retvals>
<parameters>
integer scrolling_switch - 1, on; 0, off
boolean move_editcursor - when scrolling stops, shall the editcursor be moved to current position of the playcursor(true) or not(false)
boolean goto_playcursor - true, move view to playcursor; false, don't move
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, scrolling, toggle, edit cursor, play cursor</tags>
</US_DocBloc>
--]]
if math.type(scrolling_switch)~="integer" then ultraschall.AddErrorMessage("ToggleScrollingDuringPlayback", "scrolling_switch", "must be an integer", -1) return -1 end
if scrolling_switch<0 or scrolling_switch>1 then ultraschall.AddErrorMessage("ToggleScrollingDuringPlayback", "scrolling_switch", "0, turn scrolling off; 1, turn scrolling on", -2) return -1 end
if type(move_editcursor)~="boolean" then ultraschall.AddErrorMessage("ToggleScrollingDuringPlayback", "move_editcursor", "must be a boolean", -3) return -1 end
if type(goto_playcursor)~="boolean" then ultraschall.AddErrorMessage("ToggleScrollingDuringPlayback", "goto_playcursor", "must be a boolean", -4) return -1 end
-- get current toggle-states
local scroll_continuous=reaper.GetToggleCommandState(41817)
local scroll_auto_play=reaper.GetToggleCommandState(40036)
local scroll_auto_rec=reaper.GetToggleCommandState(40262)
-- move editcursor, if move_editcursor is set to true
if move_editcursor==true then
reaper.SetEditCurPos(reaper.GetPlayPosition(), true, false)
else
reaper.SetEditCurPos(reaper.GetCursorPosition(), false, false)
end
-- set auto-scrolling-states
if scrolling_switch~=scroll_continuous then
reaper.Main_OnCommand(41817,0) -- continuous scroll
end
if scrolling_switch~=scroll_auto_play then
reaper.Main_OnCommand(40036,0) -- autoscroll during play
end
if scrolling_switch~=scroll_auto_rec then
reaper.Main_OnCommand(40262,0) -- autoscroll during rec
end
-- go to playcursor
if goto_playcursor~=false then
reaper.Main_OnCommand(40150,0) -- go to playcursor
end
end
function ultraschall.SetPlayCursor_WhenPlaying(position)--, move_view)--, length_of_view)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>SetPlayCursor_WhenPlaying</slug>
<requires>
Ultraschall=4.00
Reaper=5.40
Lua=5.3
</requires>
<functioncall>ultraschall.SetPlayCursor_WhenPlaying(number position)</functioncall>
<description>
Changes position of the play-cursor, when playing. Changes view to new playposition.
Has no effect during recording, when paused or stop and returns -1 in these cases!
</description>
<parameters>
number position - in seconds
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, play cursor, set</tags>
</US_DocBloc>
--]]
-- check parameters
if reaper.GetPlayState()~=1 then ultraschall.AddErrorMessage("SetPlayCursor_WhenPlaying", "", "Works only, when it's playing.", -1) return -1 end
if type(position)~="number" then ultraschall.AddErrorMessage("SetPlayCursor_WhenPlaying", "position", "position must be a number", -2) return -1 end
-- prepare variables
if move_view==true then move_view=false
elseif move_view==false then move_viev=true end
-- set playcursor
reaper.SetEditCurPos(position, true, true)
if reaper.GetPlayState()==2 then -- during pause
reaper.Main_OnCommand(1007,0)
reaper.SetEditCurPos(reaper.GetCursorPosition(), false, false)
reaper.Main_OnCommand(1008,0)
else
reaper.SetEditCurPos(reaper.GetCursorPosition(), false, false) -- during play
end
end
function ultraschall.SetPlayAndEditCursor_WhenPlaying(position)--, move_view)--, length_of_view)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>SetPlayAndEditCursor_WhenPlaying</slug>
<requires>
Ultraschall=4.00
Reaper=5.40
Lua=5.3
</requires>
<functioncall>ultraschall.SetPlayAndEditCursor_WhenPlaying(number position)</functioncall>
<description>
Changes position of the play and edit-cursor, when playing. Changes view to new playposition.
Has no effect during recording, when paused or stop and returns -1 in these cases!
</description>
<parameters>
number position - in seconds
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, set, play cursor, edit cursor</tags>
</US_DocBloc>
--]]
-- check parameters
if reaper.GetPlayState()==0 then ultraschall.AddErrorMessage("SetPlayAndEditCursor_WhenPlaying", "", "Works only, when it's not stopped.", -1) return -1 end
if type(position)~="number" then ultraschall.AddErrorMessage("SetPlayAndEditCursor_WhenPlaying", "position", "position must be a number", -2) return -1 end
-- prepare variables
if move_view==true then move_view=false
elseif move_view==false then move_viev=true end
-- set play and edit-cursor
reaper.SetEditCurPos(position, true, true)
end
function ultraschall.JumpForwardBy(seconds, seekplay)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>JumpForwardBy</slug>
<requires>
Ultraschall=4.00
Reaper=5.40
Lua=5.3
</requires>
<functioncall>ultraschall.JumpForwardBy(number seconds, boolean seekplay)</functioncall>
<description>
Jumps editcursor forward by <i>seconds</i> seconds.
Returns -1 if parameter is negative. During Recording: only the playcursor will be moved, the current recording-position is still at it's "old" position! If you want to move the current recording position as well, use <a href="#JumpForwardBy_Recording">ultraschall.JumpForwardBy_Recording</a> instead.
</description>
<parameters>
number seconds - jump forward by seconds
boolean seekplay - true, move playcursor as well; false, don't move playcursor
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, set, forward, jump</tags>
</US_DocBloc>
--]]
-- check parameters
if type(seconds)~="number" then ultraschall.AddErrorMessage("JumpForwardBy","seconds", "must be a number", -1) return -1 end
if type(seekplay)~="boolean" then ultraschall.AddErrorMessage("JumpForwardBy","seekplay", "must be boolean", -2) return -1 end
if seconds<0 then ultraschall.AddErrorMessage("JumpForwardBy","seconds", "must be bigger or equal 0", -3) return -1 end
-- jump forward edit-cursor
if reaper.GetPlayState()==0 then -- during stop
reaper.SetEditCurPos(reaper.GetCursorPosition()+seconds, true, true)
else -- every other play/rec-state
reaper.SetEditCurPos(reaper.GetCursorPosition()+seconds, true, seekplay)
end
end
function ultraschall.JumpBackwardBy(seconds, seekplay)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>JumpBackwardBy</slug>
<requires>
Ultraschall=4.00
Reaper=5.40
Lua=5.3
</requires>
<functioncall>ultraschall.JumpBackwardBy(number seconds, boolean seekplay)</functioncall>
<description>
Jumps editcursor backward by <i>seconds</i> seconds.
Returns -1 if parameter is negative. During Recording: only the playcursor will be moved, the current recording-position is still at it's "old" position! If you want to move the current recording position as well, use <a href="#JumpBackwardBy_Recording">ultraschall.JumpBackwardBy_Recording</a> instead.
</description>
<parameters>
number seconds - jump backwards by seconds
boolean seekplay - true, move playcursor as well; false, leave playcursor at it's old position
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, set, backward, jump</tags>
</US_DocBloc>
--]]
-- check parameters
if type(seconds)~="number" then ultraschall.AddErrorMessage("JumpBackwardBy","seconds", "must be a number", -1) return -1 end
if type(seekplay)~="boolean" then ultraschall.AddErrorMessage("JumpBackwardBy","seekplay", "must be boolean", -2) return -1 end
if seconds<0 then ultraschall.AddErrorMessage("JumpBackwardBy","seconds", "must be bigger or equal 0", -3) return -1 end
-- jump backwards edit-cursor
if reaper.GetPlayState()==0 then -- when stopped
reaper.SetEditCurPos(reaper.GetCursorPosition()-seconds, true, true)
else -- every other play/rec-state
reaper.SetEditCurPos(reaper.GetCursorPosition()-seconds, true, seekplay)
end
end
function ultraschall.JumpForwardBy_Recording(seconds)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>JumpForwardBy_Recording</slug>
<requires>
Ultraschall=4.00
Reaper=5.40
Lua=5.3
</requires>
<functioncall>ultraschall.JumpForwardBy_Recording(number seconds)</functioncall>
<description>
Stops recording, jumps forward by <i>seconds</i> seconds and restarts recording. Will keep paused-recording, if recording was paused. Has no effect during play,play/pause and stop.
returns -1 in case of an error
</description>
<parameters>
number seconds - restart recording forwards by seconds
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, set, forward, recording</tags>
</US_DocBloc>
--]]
-- check parameters
if type(seconds)~="number" then ultraschall.AddErrorMessage("JumpForwardBy_Recording","seconds", "must be a number", -1) return -1 end
if seconds<0 then ultraschall.AddErrorMessage("JumpForwardBy_Recording","seconds", "must be bigger or equal 0", -2) return -1 end
-- stop recording, jump forward and restart recording
if reaper.GetPlayState()==5 then -- during recording
reaper.Main_OnCommand(1016,0)
reaper.SetEditCurPos(reaper.GetPlayPosition()+seconds, true, true)
reaper.Main_OnCommand(1013,0)
elseif reaper.GetPlayState()==6 then -- during paused-recording
reaper.Main_OnCommand(1016,0)
reaper.SetEditCurPos(reaper.GetPlayPosition()+seconds, true, true)
reaper.Main_OnCommand(1013,0)
reaper.Main_OnCommand(1008,0)
else -- when recording hasn't started
ultraschall.AddErrorMessage("JumpForwardBy_Recording", "", "Only while recording or pause recording possible.", -3)
return -1
end
end
function ultraschall.JumpBackwardBy_Recording(seconds)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>JumpBackwardBy_Recording</slug>
<requires>
Ultraschall=4.00
Reaper=5.40
Lua=5.3
</requires>
<functioncall>ultraschall.JumpBackwardBy_Recording(number seconds)</functioncall>
<description>
Stops recording, jumps backward by <i>seconds</i> seconds and restarts recording. Will keep paused-recording, if recording was paused. Has no effect during play,play/pause and stop.
returns -1 in case of an error
</description>
<parameters>
number seconds - restart recording backwards by seconds
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, jump, forward, recording</tags>
</US_DocBloc>
--]]
-- check parameters
if type(seconds)~="number" then ultraschall.AddErrorMessage("JumpBackwardBy_Recording","seconds", "must be a number", -1) return -1 end
if seconds<0 then ultraschall.AddErrorMessage("JumpBackwardBy_Recording","seconds", "must be bigger or equal 0", -2) return -1 end
-- stop recording, jump backward and restart recording
if reaper.GetPlayState()==5 then -- during recording
reaper.Main_OnCommand(1016,0)
reaper.SetEditCurPos(reaper.GetPlayPosition()-seconds, true, true)
reaper.Main_OnCommand(1013,0)
elseif reaper.GetPlayState()==6 then -- during pause-recording
reaper.Main_OnCommand(1016,0)
reaper.SetEditCurPos(reaper.GetPlayPosition()-seconds, true, true)
reaper.Main_OnCommand(1013,0)
reaper.Main_OnCommand(1008,0)
else -- every other play-state
ultraschall.AddErrorMessage("JumpBackwardBy_Recording", "", "Only while recording or paused recording possible.", -3)
return -1
end
end
function ultraschall.GetNextClosestItemEdge(tracksstring, cursor_type, time_position)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>GetNextClosestItemEdge</slug>
<requires>
Ultraschall=4.00
Reaper=5.40
SWS=2.8.8
Lua=5.3
</requires>
<functioncall>number position, integer item_number, string edgetype, MediaItem found_item = ultraschall.GetNextClosestItemEdge(string trackstring, integer cursor_type, optional number time_position)</functioncall>
<description>
returns the position of the next closest item in seconds. It will return the position of the beginning or the end of that item, depending on what is closer.
returns -1 in case of an error
</description>
<retvals>
number position - the position of the next closest item-edge in tracks in trackstring
integer item_number - the itemnumber in the project
string edgetype - "beg" for beginning of the item, "end" for the end of the item
MediaItem found_item - the next closest found MediaItem
</retvals>
<parameters>
string trackstring - a string with the numbers of tracks to check for closest items, separated by a comma (e.g. "0,1,6")
integer cursor_type - next closest item related to the current position of 0 - Edit Cursor, 1 - Play Cursor, 2 - Mouse Cursor, 3 - Timeposition
optional number time_position - only, when cursor_type=3, a time position in seconds, from where to check for the next closest item. When omitted, it will take the current play(during play and rec) or edit-cursor-position.
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, next item, position, edge</tags>
</US_DocBloc>
--]]
local cursortime=0
-- check parameters
local tracks=tracksstring
if ultraschall.IsValidTrackString(tracks)==false then ultraschall.AddErrorMessage("GetNextClosestItemEdge", "tracks", "must be a valid trackstring", -5) return -1 end
-- check cursor_type-parameter and do the proper cursor-type-position
if cursor_type==nil then ultraschall.AddErrorMessage("GetNextClosestItemEdge","cursor_type", "must be an integer", -1) return -1 end
if cursor_type==0 then cursortime=reaper.GetCursorPosition() end
if cursor_type==1 then cursortime=reaper.GetPlayPosition() end
if cursor_type==2 then
reaper.BR_GetMouseCursorContext()
cursortime=reaper.BR_GetMouseCursorContext_Position()
if cursortime==-1 then ultraschall.AddErrorMessage("GetNextClosestItemEdge", "", "Mouse is not in arrange-view.", -2) return -1 end
end
if cursor_type==3 then
if type(time_position)~="number" then ultraschall.AddErrorMessage("GetNextClosestItemEdge","time_position", "must be a number.", -3) return -1 end
cursortime=time_position
end
if cursor_type>3 or cursor_type<0 then ultraschall.AddErrorMessage("GetNextClosestItemEdge","cursor_type", "no such cursor_type existing", -4) return -1 end
if time_position~=nil and type(time_position)~="number" then ultraschall.AddErrorMessage("GetNextClosestItemEdge", "time_position", "must be either nil or a number", -6) return -1 end
-- prepare variables
if time_position==nil and reaper.GetPlayState()==0 then
time_position=reaper.GetCursorPosition()
elseif time_position==nil and reaper.GetPlayState~=0 then
time_position=reaper.GetPlayPosition()
end
local closest_item=reaper.GetProjectLength(0)
local found_item=nil
local another_item=-1
local another_item_nr=-1
local position=""
local item_number=-1
local _count
-- get tracksnumbers from trackstring
local _count, TrackArray = ultraschall.CSV2IndividualLinesAsArray(tracks)
local TrackArray2={}
for k=0, reaper.CountTracks()+1 do
if TrackArray[k]~=nil then TrackArray2[tonumber(TrackArray[k])]=TrackArray[k]end
end
-- find the closest item and it's closest edge
for i=0, reaper.CountMediaItems(0)-1 do
for j=0, reaper.CountTracks(0) do
if TrackArray2[j]~=nil and tracks~=-1 then
if ultraschall.IsItemInTrack(j,i)==true then
-- when item is in track, check beginning and endings of the item
local MediaItem=reaper.GetMediaItem(0, i)
local ItemStart=reaper.GetMediaItemInfo_Value(MediaItem, "D_POSITION")
local ItemEnd=reaper.GetMediaItemInfo_Value(MediaItem, "D_POSITION")+reaper.GetMediaItemInfo_Value(MediaItem, "D_LENGTH")
if ItemStart>cursortime and ItemStart<closest_item then -- check if it's beginning of the item
closest_item=ItemStart
found_item=MediaItem
position="beg"
item_number=i
end
if ItemEnd>cursortime and ItemEnd<=closest_item then -- check if it's end of the item
closest_item=ItemEnd
position="end"
found_item=MediaItem
if MediaItem~=nil then another_item=found_item another_item_nr=i end
item_number=i
end
end
end
end
end
-- return found item
if found_item~=nil then return closest_item, item_number, position, found_item
else ultraschall.AddErrorMessage("GetNextClosestItemEdge", "", "no item found", -6) return -1
end
end
function ultraschall.GetPreviousClosestItemEdge(tracksstring, cursor_type, time_position)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>GetPreviousClosestItemEdge</slug>
<requires>
Ultraschall=4.00
Reaper=5.40
SWS=2.8.8
Lua=5.3
</requires>
<functioncall>number position, number position, integer item_number, string edgetype, MediaItem found_item = ultraschall.GetPreviousClosestItemEdge(string tracks, integer cursor_type, optional number time_position)</functioncall>
<description>
returns the position of the previous closest item-edge in seconds. It will return the position of the beginning or the end of that item, depending on what is closer.
returns -1 in case of an error
</description>
<retvals>
number position - the position of the previous closest item edge in tracks in trackstring
integer item_number - the itemnumber in the project
string edgetype - "beg" for beginning of the item, "end" for the end of the item
MediaItem found_item - the next closest found MediaItem
</retvals>
<parameters>
string tracks - a string with the numbers of tracks to check for closest items, separated by a comma (e.g. "0,1,6")
integer cursor_type - previous closest item related to the current position of 0 - Edit Cursor, 1 - Play Cursor, 2 - Mouse Cursor, 3 - Timeposition
optional time_position - only, when cursor_type=3, a time position in seconds, from where to check for the previous closest item. When omitted, it will take the current play(during play and rec) or edit-cursor-position.
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, previous item, position, edge</tags>
</US_DocBloc>
--]]
local cursortime=0
local _count
-- check parameters
local tracks=tracksstring
if ultraschall.IsValidTrackString(tracks)==false then ultraschall.AddErrorMessage("GetPreviousClosestItemEdge","tracks", "must be a string", -5) return -1 end
if time_position~=nil and type(time_position)~="number" then ultraschall.AddErrorMessage("GetPreviousClosestItemEdge","time_position", "must be either nil or a number", -6) return -1 end
-- check cursor_type-parameter and do the proper cursor-type-position
if math.type(cursor_type)~="integer" then ultraschall.AddErrorMessage("GetPreviousClosestItemEdge","cursor_type", "must be an integer", -1) return -1 end
if cursor_type==0 then cursortime=reaper.GetCursorPosition() end
if cursor_type==1 then cursortime=reaper.GetPlayPosition() end
if cursor_type==2 then
reaper.BR_GetMouseCursorContext()
cursortime=reaper.BR_GetMouseCursorContext_Position()
if cursortime==-1 then ultraschall.AddErrorMessage("GetPreviousClosestItemEdge", "", "mouse not in arrange-view", -2) return -1 end
end
if cursor_type==3 then
if time_position==nil then ultraschall.AddErrorMessage("GetPreviousClosestItemEdge","time_position", "no nil allowed", -3) return -1 end
cursortime=time_position
end
if cursor_type>3 or cursor_type<0 then ultraschall.AddErrorMessage("GetPreviousClosestItemEdge","cursor_type", "no such cursortype existing", -4) return -1 end
-- prepare variables
local _count, TrackArray = ultraschall.CSV2IndividualLinesAsArray(tracks)
if time_position==nil and reaper.GetPlayState()==0 then
time_position=reaper.GetCursorPosition()
elseif time_position==nil and reaper.GetPlayState~=0 then
time_position=reaper.GetPlayPosition()
end
local TrackArray2={}
for k=0, reaper.CountTracks()+1 do
if TrackArray[k]~=nil then TrackArray2[tonumber(TrackArray[k])]=TrackArray[k] end
end
local closest_item=-1
local found_item=nil
local position=""
local item_number=-1
-- find previous closest item and it's edge
for i=0, reaper.CountMediaItems(0)-1 do
for j=0, reaper.CountTracks(0) do
if TrackArray2[j]~=nil and tonumber(tracks)~=-1 then
if ultraschall.IsItemInTrack(j,i)==true then
-- if item is in track, find the closest edge
local MediaItem=reaper.GetMediaItem(0, i)
local Aretval, Astr = reaper.GetItemStateChunk(MediaItem,"<ITEMPOSITION",false)
local ItemStart=reaper.GetMediaItemInfo_Value(MediaItem, "D_POSITION")
local ItemEnd=reaper.GetMediaItemInfo_Value(MediaItem, "D_POSITION")+reaper.GetMediaItemInfo_Value(MediaItem, "D_LENGTH")
if ItemEnd<cursortime and ItemEnd>closest_item then -- if it's item-end
closest_item=ItemEnd
position="end"
found_item=MediaItem
item_number=i
elseif ItemStart<cursortime and ItemStart>closest_item then -- if it's item-beginning
closest_item=ItemStart
found_item=MediaItem
position="beg"
item_number=i
end
end
end
end
end
-- return found item
if found_item~=nil then return closest_item, item_number, position, found_item
else ultraschall.AddErrorMessage("GetPreviousClosestItemEdge", "", "no item found", -6) return -1
end
end
function ultraschall.GetClosestNextMarker(cursor_type, time_position)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>GetClosestNextMarker</slug>
<requires>
Ultraschall=4.00
Reaper=5.40
SWS=2.8.8
Lua=5.3
</requires>
<functioncall>number markerindex, number position, string markertitle = ultraschall.GetClosestNextMarker(integer cursor_type, optional number time_position)</functioncall>
<description>
returns the markerindex(counted from all markers), the position and the name of the next closest marker in seconds.
returns -1 in case of an error
</description>
<retvals>
number markerindex - the next closest markerindex (of all(!) markers)
number position - the position of the next closest marker
string markertitle - the name of the next closest marker
</retvals>
<parameters>
integer cursor_type - previous closest marker related to the current position of 0 - Edit Cursor, 1 - Play Cursor, 2 - Mouse Cursor, 3 - Timeposition
optional number time_position - only, when cursor_type=3, a time position in seconds, from where to check for the next closest marker. When omitted, it will take the current play(during play and rec) or edit-cursor-position.
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, next marker, position, marker </tags>
</US_DocBloc>
--]]
local cursortime=0
if math.type(cursor_type)~="integer" then ultraschall.AddErrorMessage("GetClosestNextMarker", "cursor_type", "must be an integer", -1) return -1 end
if time_position~=nil and type(time_position)~="number" then ultraschall.AddErrorMessage("GetClosestNextMarker", "time_position", "must be either nil or a number", -5) return -1 end
if time_position==nil and cursor_type>2 then ultraschall.AddErrorMessage("GetClosestNextMarker", "time_position", "must be a number when cursortype=3", -6) return -1 end
-- check parameters
if time_position==nil and reaper.GetPlayState()==0 and cursor_type~=3 then
time_position=reaper.GetCursorPosition()
elseif time_position==nil and reaper.GetPlayState~=0 and cursor_type~=3 then
time_position=reaper.GetPlayPosition()
elseif time_position==nil and cursor_type~=3 then
time_position=time_position
end
-- check cursor_type parameter and do the proper cursor-type-position
if cursor_type==0 then cursortime=reaper.GetCursorPosition() end
if cursor_type==1 then cursortime=reaper.GetPlayPosition() end
if cursor_type==2 then
reaper.BR_GetMouseCursorContext()
cursortime=reaper.BR_GetMouseCursorContext_Position()
if cursortime==-1 then ultraschall.AddErrorMessage("GetClosestNextMarker", "", "mouse not in arrange-view", -2) return -1 end
end
if cursor_type==3 then
cursortime=time_position
end
if cursor_type>3 or cursor_type<0 then ultraschall.AddErrorMessage("GetClosestNextMarker","cursor_type", "no such cursor_type existing", -4) return -1 end
-- prepare variables
local retval, num_markers, num_regions = reaper.CountProjectMarkers(0)
local retposition=reaper.GetProjectLength(0)+1--*200000000 --Working Hack, but isn't elegant....
local retindexnumber=-1
local retmarkername=""
-- find next closest marker
for i=0,retval do
local retval2, isrgn, pos, rgnend, name, markrgnindexnumber = reaper.EnumProjectMarkers(i)
if isrgn==false then
if pos>cursortime and pos<retposition then
retposition=pos
retindexnumber=markrgnindexnumber
retmarkername=name
end
end
end
-- return found marker
if retindexnumber==-1 then retposition=-1 end
return retindexnumber, retposition, retmarkername
end
function ultraschall.GetClosestPreviousMarker(cursor_type, time_position)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>GetClosestPreviousMarker</slug>
<requires>
Ultraschall=4.00
Reaper=5.40
SWS=2.8.8
Lua=5.3
</requires>
<functioncall>number markerindex, number position, string markertitle = ultraschall.GetClosestPreviousMarker(integer cursor_type, optional number time_position)</functioncall>
<description>
returns the markerindex(counted from all markers), the position and the name of the previous closest marker in seconds.
</description>
<retvals>
number markerindex - the previous closest markerindex (of all(!) markers)
number position - the position of the previous closest marker
string markertitle - the name of the previous closest marker
</retvals>
<parameters>
integer cursor_type - previous closest marker related to the current position of 0 - Edit Cursor, 1 - Play Cursor, 2 - Mouse Cursor, 3 - Timeposition
optional number time_position - only, when cursor_type=3, a time position in seconds, from where to check for the previous closest marker. When omitted, it will take the current play(during play and rec) or edit-cursor-position.
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, previous marker, position, marker</tags>
</US_DocBloc>
--]]
local cursortime=0
if math.type(cursor_type)~="integer" then ultraschall.AddErrorMessage("GetClosestPreviousMarker", "cursor_type", "must be an integer", -1) return -1 end
if time_position~=nil and type(time_position)~="number" then ultraschall.AddErrorMessage("GetClosestPreviousMarker", "time_position", "must be either nil or a number", -5) return -1 end
if time_position==nil and cursor_type>2 then ultraschall.AddErrorMessage("GetClosestPreviousMarker", "time_position", "must be a number when cursortype=3", -6) return -1 end
-- check parameters
if time_position==nil and reaper.GetPlayState()==0 and cursor_type~=3 then
time_position=reaper.GetCursorPosition()
elseif time_position==nil and reaper.GetPlayState~=0 and cursor_type~=3 then
time_position=reaper.GetPlayPosition()
elseif time_position==nil and cursor_type~=3 then
time_position=time_position
end
-- check parameter cursor_type and do the cursor-type-position
if cursor_type==0 then cursortime=reaper.GetCursorPosition() end
if cursor_type==1 then cursortime=reaper.GetPlayPosition() end
if cursor_type==2 then
reaper.BR_GetMouseCursorContext()
cursortime=reaper.BR_GetMouseCursorContext_Position()
if cursortime==-1 then ultraschall.AddErrorMessage("GetClosestPreviousMarker", "", "mouse not in arrange-view", -2) return -1 end
end
if cursor_type==3 then
cursortime=time_position
end
if cursor_type>3 or cursor_type<0 then ultraschall.AddErrorMessage("GetClosestPreviousMarker","cursor_type", "no such cursor-type existing", -4) return -1 end
-- prepare variables
local retval, num_markers, num_regions = reaper.CountProjectMarkers(0)
local found=false
local retposition=-1
local retindexnumber=-1
local retmarkername=""
-- find previous closest marker
for i=0,retval-1 do
local retval2, isrgn, pos, rgnend, name, markrgnindexnumber = reaper.EnumProjectMarkers(i)
if isrgn==false then
if pos<cursortime and pos>retposition then
retposition=pos
retindexnumber=markrgnindexnumber
retmarkername=name
found=true
end
end
end
-- return found marker
if found==false then retposition=-1 retindexnumber=-1 end
return retindexnumber,retposition, retmarkername
end
function ultraschall.GetClosestNextRegionEdge(cursor_type, time_position)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>GetClosestNextRegionEdge</slug>
<requires>
Ultraschall=4.00
Reaper=5.40
SWS=2.8.8
Lua=5.3
</requires>
<functioncall>number markerindex, number position, string markertitle, string edge_type = ultraschall.GetClosestNextRegionEdge(integer cursor_type, optional number time_position)</functioncall>
<description>
returns the regionindex(counted from all markers and regions), the position and the name of the next closest regionstart/end(depending on which is closer to time_position) in seconds.
returns -1 in case of an error
</description>
<retvals>
number markerindex - the next closest markerindex (of all(!) markers)
number position - the position of the next closest region
string markertitle - the name of the next closest region
string edge_type - the type of the edge of the region, either "beg" or "end"
</retvals>
<parameters>
integer cursor_type - previous closest regionstart/end related to the current position of
- 0, Edit Cursor,
- 1, Play Cursor,
- 2, Mouse Cursor,
- 3, Timeposition
only number time_position - only, when cursor_type=3, a time position in seconds, from where to check for the next closest regionstart/end. When omitted, it will take the current play(during play and rec) or edit-cursor-position.
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, next region, region, position</tags>
</US_DocBloc>
--]]
local cursortime=0
-- check parameters
if tonumber(time_position)==nil and reaper.GetPlayState()==0 and tonumber(cursor_type)~=3 then
time_position=reaper.GetCursorPosition()
elseif tonumber(time_position)==nil and reaper.GetPlayState~=0 and tonumber(cursor_type)~=3 then
time_position=reaper.GetPlayPosition()
elseif tonumber(time_position)==nil and tonumber(cursor_type)~=3 then
time_position=tonumber(time_position)
end
-- check parameter cursor_type and do the cursor-type-position
if math.type(cursor_type)~="integer" then ultraschall.AddErrorMessage("GetClosestNextRegionEdge", "cursor_type", "must be an integer", -1) return -1 end
if tonumber(cursor_type)==0 then cursortime=reaper.GetCursorPosition() end
if tonumber(cursor_type)==1 then cursortime=reaper.GetPlayPosition() end
if tonumber(cursor_type)==2 then
reaper.BR_GetMouseCursorContext()
cursortime=reaper.BR_GetMouseCursorContext_Position()
if cursortime==-1 then ultraschall.AddErrorMessage("GetClosestNextRegionEdge", "", "mouse not in arrange view", -2) return -1 end
end
if tonumber(cursor_type)==3 then
if tonumber(time_position)==nil then ultraschall.AddErrorMessage("GetClosestNextRegionEdge","time_position", "no nil allowed when cursor_type=3", -3) return -1 end
cursortime=tonumber(time_position)
end
if tonumber(cursor_type)>3 or tonumber(cursor_type)<0 then ultraschall.AddErrorMessage("GetClosestNextRegionEdge","cursor_type", "no such cursor_type existing", -4) return -1 end
-- prepare variables
local retval, num_markers, num_regions = reaper.CountProjectMarkers(0)
local retposition=reaper.GetProjectLength()+1--*200000000 --Working Hack, but isn't elegant....
local retindexnumber=-1
local retmarkername=""
local retbegin=""
-- find next region and it's closest edge
for i=0,retval do
local retval2, isrgn, pos, rgnend, name, markrgnindexnumber = reaper.EnumProjectMarkers(i)
if isrgn==true then
if pos>cursortime and pos<retposition then -- beginning of the region
retposition=pos
retindexnumber=markrgnindexnumber
retmarkername=name
retbegin="beg"
end
if rgnend>cursortime and rgnend<retposition then -- ending of the region
retposition=rgnend
retindexnumber=markrgnindexnumber
retmarkername=name
retbegin="end"
end
end
end
-- return found region
if retindexnumber==-1 then retposition=-1 end
return retindexnumber,retposition, retmarkername, retbegin
end
function ultraschall.GetClosestPreviousRegionEdge(cursor_type, time_position)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>GetClosestPreviousRegionEdge</slug>
<requires>
Ultraschall=4.00
Reaper=5.40
SWS=2.8.8
Lua=5.3
</requires>
<functioncall>number markerindex, number position, string markertitle, string edge_type = ultraschall.GetClosestPreviousRegionEdge(integer cursor_type, optional number time_position)</functioncall>
<description>
returns the regionindex(counted from all markers and regions), the position and the name of the previous closest regionstart/end(depending on which is closer to time_position) in seconds.
returns -1 in case of an error
</description>
<retvals>
number markerindex - the previous closest markerindex (of all(!) markers)
number position - the position of the previous closest marker
string markertitle - the name of the previous closest marker
string edge_type - the type of the edge of the region, either "beg" or "end"
</retvals>
<parameters>
integer cursor_type - previous closest regionstart/end related to the current position of 0 - Edit Cursor, 1 - Play Cursor, 2 - Mouse Cursor, 3 - Timeposition
optional number time_position - only, when cursor_type=3, a time position in seconds, from where to check for the previous closest regionstart/end. When omitted, it will take the current play(during play and rec) or edit-cursor-position.
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, previous region, region, position</tags>
</US_DocBloc>
--]]
local cursortime=0
-- check parameters
if tonumber(time_position)==nil and reaper.GetPlayState()==0 and tonumber(cursor_type)~=3 then
time_position=reaper.GetCursorPosition()
elseif tonumber(time_position)==nil and reaper.GetPlayState~=0 and tonumber(cursor_type)~=3 then
time_position=reaper.GetPlayPosition()
elseif tonumber(time_position)==nil and tonumber(cursor_type)~=3 then
time_position=tonumber(time_position)
end
-- check parameter cursor_type and do the cursor-type-position
if math.type(cursor_type)~="integer" then ultraschall.AddErrorMessage("GetClosestPreviousRegionEdge","cursor_type", "must be an integer", -1) return -1 end
if tonumber(cursor_type)==0 then cursortime=reaper.GetCursorPosition() end
if tonumber(cursor_type)==1 then cursortime=reaper.GetPlayPosition() end
if tonumber(cursor_type)==2 then
reaper.BR_GetMouseCursorContext()
cursortime=reaper.BR_GetMouseCursorContext_Position()
if cursortime==-1 then ultraschall.AddErrorMessage("GetClosestPreviousRegionEdge", "", "mouse not in arrange-view", -2) return -1 end
end
if tonumber(cursor_type)==3 then
if tonumber(time_position)==nil then ultraschall.AddErrorMessage("GetClosestPreviousRegionEdge","time_position", "no nil allowed when cursortype=3", -3) return -1 end
cursortime=tonumber(time_position)
end
if tonumber(cursor_type)>3 or tonumber(cursor_type)<0 then ultraschall.AddErrorMessage("GetClosestPreviousRegionEdge","cursor_type", "no such cursortype existing", -4) return -1 end
-- prepare variables
local retval, num_markers, num_regions = reaper.CountProjectMarkers(0)
local retposition=-1
local retindexnumber=-1
local retmarkername=""
local retbeg=""
-- find closest previous region and it's closest edge
for i=0,retval do
local retval2, isrgn, pos, rgnend, name, markrgnindexnumber = reaper.EnumProjectMarkers(i)
if isrgn==true then -- beginning of the item
if pos<cursortime and pos>retposition then
retposition=pos
retindexnumber=markrgnindexnumber
retmarkername=name
retbeg="beg"
end
if rgnend<cursortime and rgnend>retposition then -- ending of the item
retposition=rgnend
retbeg="end"
end
end
end
return retindexnumber, retposition, retmarkername, retbeg
end
function ultraschall.GetClosestGoToPoints(trackstring, time_position, check_itemedge, check_marker, check_region)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>GetClosestGoToPoints</slug>
<requires>
Ultraschall=4.00
Reaper=5.40
SWS=2.8.8
Lua=5.3
</requires>
<functioncall>number elementposition_prev, string elementtype_prev, integer number_prev, number elementposition_next, string elementtype_next, integer number_next = ultraschall.GetClosestGoToPoints(string trackstring, number time_position, optional boolean check_itemedge, optional boolean check_marker, optional boolean check_region)</functioncall>
<description>
returns, what are the closest markers/regions/item starts/itemends to position and within the chosen tracks.
returns -1 in case of error
</description>
<retvals>
number elementposition_prev - previous closest markers/regions/item starts/itemends
string elementtype_prev - type of the previous closest markers/regions/item starts/itemends
-the type can be either Itembeg, Itemend, Marker: name, Region_beg: name; Region_end: name, ProjectStart, ProjectEnd; "name" is the name of the marker or region
integer number_prev - number of previous closest markers/regions/item starts/itemends
number elementposition_next - previous closest markers/regions/item starts/itemends
string elementtype_next - type of the previous closest markers/regions/item starts/itemends
-the type can be either Itembeg, Itemend, Marker: name, Region_beg: name; Region_end: name, ProjectStart, ProjectEnd; "name" is the name of the marker or region
integer number_next - number of previous closest markers/regions/item starts/itemends
</retvals>
<parameters>
string trackstring - tracknumbers, separated by a comma.
number time_position - a time position in seconds, from where to check for the next/previous closest items/markers/regions.
- -1, for editcursorposition; -2, for playcursor-position, -3, the mouse-cursor-position in seconds(where in the project the mousecursor hovers over)
optional boolean check_itemedge - true, look for itemedges as possible goto-points; false, do not
optional boolean check_marker - true, look for markers as possible goto-points; false, do not
optional boolean check_region - true, look for regions as possible goto-point; false, do not
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, previous, next, marker, region, item, edge</tags>
</US_DocBloc>
--]]
-- check parameters
if ultraschall.IsValidTrackString(trackstring)==false then ultraschall.AddErrorMessage("GetClosestGoToPoints", "trackstring", "must be a valid trackstring", -1) return -1 end
if type(time_position)~="number" then ultraschall.AddErrorMessage("GetClosestGoToPoints", "time_position", "must be a number", -2) return -1 end
if check_itemedge~=nil and type(check_itemedge)~="boolean" then ultraschall.AddErrorMessage("GetClosestGoToPoints", "check_itemedge", "must be a boolean", -3) return -1 end
if check_marker~=nil and type(check_marker)~="boolean" then ultraschall.AddErrorMessage("GetClosestGoToPoints", "check_marker", "must be a boolean", -4) return -1 end
if check_region~=nil and type(check_region)~="boolean" then ultraschall.AddErrorMessage("GetClosestGoToPoints", "check_region", "must be a boolean", -5) return -1 end
if check_itemedge==nil then check_itemedge=true end
if check_marker==nil then check_marker=true end
if check_region==nil then check_region=true end
if tonumber(time_position)==-1 then
time_position=reaper.GetCursorPosition()
elseif tonumber(time_position)==-2 then
time_position=reaper.GetPlayPosition()
elseif tonumber(time_position)==-3 then
reaper.BR_GetMouseCursorContext()
time_position=reaper.BR_GetMouseCursorContext_Position()
else
time_position=tonumber(time_position)
end
-- prepare variables
local elementposition_prev, elementtype_prev, number_prev, elementposition_next, elementtype_next, number_next=nil
local elementposition_prev=-1
local elementposition_next=reaper.GetProjectLength()+1
-- get closest items, markers and regions
local nextitempos, nextitemid, nextedgetype =ultraschall.GetNextClosestItemEdge(trackstring,3,time_position)
local previtempos, previtemid, prevedgetype =ultraschall.GetPreviousClosestItemEdge(trackstring,3,time_position)
local nextmarkerid,nextmarkerpos,nextmarkername=ultraschall.GetClosestNextMarker(3, time_position)
local prevmarkerid,prevmarkerpos,prevmarkername=ultraschall.GetClosestPreviousMarker(3,time_position)
local nextrgnID, nextregionpos,nextregionname,nextedgetype=ultraschall.GetClosestNextRegionEdge(3,time_position)
local prevrgnID, prevregionpos,prevregionname,prevedgetype=ultraschall.GetClosestPreviousRegionEdge(3,time_position)
-- now we find, which is the closest element
-- Item-Edges
if check_itemedge==true then
if previtempos~=-1 and elementposition_prev<=previtempos then number_prev=previtemid elementposition_prev=previtempos elementtype_prev="Item"..prevedgetype end
if nextitempos~=-1 and elementposition_next>=nextitempos then number_next=nextitemid elementposition_next=nextitempos elementtype_next="Item"..nextedgetype end
end
-- Markers
if check_marker==true then
if prevmarkerid~=-1 and elementposition_prev<=prevmarkerpos then number_prev=prevmarkerid elementposition_prev=prevmarkerpos elementtype_prev="Marker: "..prevmarkername end
if nextmarkerid~=-1 and elementposition_next>=nextmarkerpos then number_next=nextmarkerid elementposition_next=nextmarkerpos elementtype_next="Marker: "..nextmarkername end
end
-- Region-Edges
if check_region==true then
if elementposition_prev<=prevregionpos and prevrgnID~=-1 then number_prev=prevrgnID elementposition_prev=prevregionpos elementtype_prev="Region_"..prevedgetype..": "..prevregionname end
if elementposition_next>=nextregionpos and nextrgnID~=-1 then number_next=nextrgnID elementposition_next=nextregionpos elementtype_next="Region_"..nextedgetype..": "..nextregionname end
end
-- if none was found, use projectend/projectstart
if elementposition_prev<0 then elementposition_prev=0 elementtype_prev="ProjectStart" end
if elementposition_next>reaper.GetProjectLength() then elementposition_next=reaper.GetProjectLength() elementtype_next="ProjectEnd" end
return elementposition_prev, elementtype_prev, number_prev, elementposition_next, elementtype_next, number_next
end
function ultraschall.CenterViewToCursor(cursortype, position)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>CenterViewToCursor</slug>
<requires>
Ultraschall=4.00
Reaper=5.52
SWS=2.9.7
Lua=5.3
</requires>
<functioncall>ultraschall.CenterViewToCursor(integer cursortype, optional number position)</functioncall>
<description>
centers the arrange-view around a given cursor
returns nil in case of an error
</description>
<parameters>
integer cursortype - the cursortype to center
- 1 - change arrangeview with edit-cursor centered
- 2 - change arrangeview with play-cursor centered
- 3 - change arrangeview with mouse-cursor-position centered
- 4 - change arrangeview with optional parameter position centered
optional number position - the position to center the arrangeview to; only used, when cursortype=4
</parameters>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, center, cursor, mouse, edit, play</tags>
</US_DocBloc>
]]
if math.type(cursortype)~="integer" then ultraschall.AddErrorMessage("CenterViewToCursor","cursortype", "only integer allowed", -1) return end
if position~=nil and type(position)~="number" then ultraschall.AddErrorMessage("CenterViewToCursor","position", "only numbers allowed", -3) return end
local cursor_time
if cursortype<1 or cursortype>4 then ultraschall.AddErrorMessage("CenterViewToCursor","cursortype", "no such cursortype; only 1-3 existing.", -2) return end
if cursortype==1 then cursor_time=reaper.GetCursorPosition() end
if cursortype==2 then cursor_time=reaper.GetPlayPosition() end
if cursortype==3 then
retval, segment, details = reaper.BR_GetMouseCursorContext()
cursor_time=reaper.BR_GetMouseCursorContext_Position()
end
if cursortype==4 then if position~=nil then cursor_time=position else ultraschall.AddErrorMessage("CenterViewToCursor","position", "only numbers allowed", -3) return end end
start_time, end_time = reaper.GetSet_ArrangeView2(0, false, 0, 0)
length=((end_time-start_time)/2)+(1/reaper.GetHZoomLevel())
reaper.BR_SetArrangeView(0, (cursor_time-length), (cursor_time+length))
end
function ultraschall.GetLastCursorPosition()
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>GetLastCursorPosition</slug>
<requires>
Ultraschall=4.00
Reaper=5.95
Lua=5.3
</requires>
<functioncall>number last_editcursor_position, number new_editcursor_position, number statechangetime = ultraschall.GetLastCursorPosition()</functioncall>
<description markup_type="markdown" markup_version="1.0.1" indent="default">
Returns the last and current editcursor-position. Needs Ultraschall-API-background-scripts started first, see [RunBackgroundHelperFeatures()](#RunBackgroundHelperFeatures).
Has an issue, when editcursor-position was changed using a modifier, like alt+click or shift+click! Because of that, you should use this only in defer-scripts.
returns -1, if Ultraschall-API-backgroundscripts weren't started yet.
</description>
<retvals>
number last_editcursor_position - the last cursorposition before the current one; -1, in case of an error
number new_editcursor_position - the new cursorposition; -1, in case of an error
number statechangetime - the time, when the state has changed the last time
</retvals>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, last position, editcursor</tags>
</US_DocBloc>
]]
if reaper.GetExtState("Ultraschall", "defer_scripts_ultraschall_track_old_cursorposition.lua")~="true" then return -1 end
return tonumber(reaper.GetExtState("ultraschall", "editcursor_position_old")), tonumber(reaper.GetExtState("ultraschall", "editcursor_position_new")), tonumber(reaper.GetExtState("ultraschall", "editcursor_position_changetime"))
end
function ultraschall.GetLastPlayState()
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>GetLastPlayState</slug>
<requires>
Ultraschall=4.00
Reaper=5.95
Lua=5.3
</requires>
<functioncall>string last_play_state, string new_play_state, number statechangetime = ultraschall.GetLastPlayState()</functioncall>
<description markup_type="markdown" markup_version="1.0.1" indent="default">
Returns the last and current playstate. Needs Ultraschall-API-background-scripts started first, see [RunBackgroundHelperFeatures()](#RunBackgroundHelperFeatures).
possible states are STOP, PLAY, PLAYPAUSE, REC, RECPAUSE
returns -1, if Ultraschall-API-backgroundscripts weren't started yet.
</description>
<retvals>
string last_play_state - the last playstate before the current one; -1, in case of an error
string new_play_state - the new playstate; -1, in case of an error
number statechangetime - the time, when the state has changed the last time
</retvals>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, last playstate, editcursor</tags>
</US_DocBloc>
]]
if reaper.GetExtState("Ultraschall", "defer_scripts_ultraschall_track_old_playstate.lua")~="true" then return -1 end
return reaper.GetExtState("ultraschall", "playstate_old"), reaper.GetExtState("ultraschall", "playstate_new"), tonumber(reaper.GetExtState("ultraschall", "playstate_changetime"))
end
--ultraschall.RunBackgroundHelperFeatures()
--A=ultraschall.GetLastPlayState()
function ultraschall.GetLastLoopState()
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>GetLastLoopState</slug>
<requires>
Ultraschall=4.00
Reaper=5.95
Lua=5.3
</requires>
<functioncall>string last_loop_state, string new_loop_state, number statechangetime = ultraschall.GetLastLoopState()</functioncall>
<description markup_type="markdown" markup_version="1.0.1" indent="default">
Returns the last and current loopstate. Needs Ultraschall-API-background-scripts started first, see [RunBackgroundHelperFeatures()](#RunBackgroundHelperFeatures).
Possible states are LOOPED, UNLOOPED
returns -1, if Ultraschall-API-backgroundscripts weren't started yet.
</description>
<retvals>
string last_loop_state - the last loopstate before the current one; -1, in case of an error
string new_loop_state - the current loopstate; -1, in case of an error
number statechangetime - the time, when the state has changed the last time
</retvals>
<chapter_context>
Navigation
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, last loopstate, editcursor</tags>
</US_DocBloc>
]]
if reaper.GetExtState("Ultraschall", "defer_scripts_ultraschall_track_old_loopstate.lua")~="true" then return -1 end
return reaper.GetExtState("ultraschall", "loopstate_old"), reaper.GetExtState("ultraschall", "loopstate_new"), tonumber(reaper.GetExtState("ultraschall", "loopstate_changetime"))
end
function ultraschall.GetLoopState()
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>GetLoopState</slug>
<requires>
Ultraschall=4.00
Reaper=5.965
Lua=5.3
</requires>
<functioncall>integer retval = ultraschall.GetLoopState()</functioncall>
<description>
Returns the current loop-state
</description>
<retvals>
integer retval - 0, loop is on; 1, loop is off
</retvals>
<chapter_context>
Navigation
Transport
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>transportmanagement, get, loop</tags>
</US_DocBloc>
--]]
return reaper.GetToggleCommandState(1068)
end
--A=ultraschall.GetLoopState()
function ultraschall.SetLoopState(state)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>SetLoopState</slug>
<requires>
Ultraschall=4.00
Reaper=5.965
Lua=5.3
</requires>
<functioncall>boolean retval = ultraschall.SetLoopState(integer state)</functioncall>
<description>
Sets the current loop-state
returns false in case of an error
</description>
<retvals>
boolean retval - true, if setting was successful; false, if setting was unsuccessful
</retvals>
<parameters>
integer state - 0, loop is on; 1, loop is off
</parameters>
<chapter_context>
Navigation
Transport
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>transportmanagement, set, loop</tags>
</US_DocBloc>
--]]
if math.type(state)~="integer" then ultraschall.AddErrorMessage("SetLoopState", "state", "must be an integer", -1) return false end
if state~=0 and state~=1 then ultraschall.AddErrorMessage("SetLoopState", "state", "must be 1(on) or 0(off)", -2) return false end
if ultraschall.GetLoopState()~=state then
reaper.Main_OnCommand(1068, 0)
end
return true
end
--A=ultraschall.SetLoopState(0)
function ultraschall.Scrubbing_MoveCursor_GetToggleState()
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>Scrubbing_MoveCursor_GetToggleState</slug>
<requires>
Ultraschall=4.00
Reaper=5.965
SWS=2.10.0.1
Lua=5.3
</requires>
<functioncall>boolean state = ultraschall.Scrubbing_MoveCursor_GetToggleState()</functioncall>
<description>
Returns, if scrub is toggled on/off, for when moving editcursor via action or control surface, as set in Preferences -> Playback.
</description>
<retvals>
boolean retval - true, scrub is on; false, scrub is off
</retvals>
<chapter_context>
Navigation
Scrubbing
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, get, scrub, when moving editcursor, action, surface</tags>
</US_DocBloc>
--]]
if reaper.SNM_GetIntConfigVar("scrubmode", -9)&1==0 then return false else return true end
end
function ultraschall.Scrubbing_MoveCursor_Toggle(toggle)
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>Scrubbing_MoveCursor_Toggle</slug>
<requires>
Ultraschall=4.00
Reaper=5.965
SWS=2.10.0.1
Lua=5.3
</requires>
<functioncall>boolean state, optional integer new_scrubmode = ultraschall.Scrubbing_MoveCursor_Toggle(boolean toggle)</functioncall>
<description>
Toggles scrub on/off, for when moving editcursor via action or control surface, as set in Preferences -> Playback.
returns false in case of an error
</description>
<retvals>
boolean retval - true, toggling was successful; false, toggling was unsuccessful
optional integer new_scrubmode - this is the new value of the configvariable scrubmode, which is altered by this function
</retvals>
<parameters>
boolean toggle - true, toggles scrubbing on; false, toggles scrubbing off
</parameters>
<chapter_context>
Navigation
Scrubbing
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_Navigation_Module.lua</source_document>
<tags>navigation, scrub, toggle, when moving editcursor, action, surface</tags>
</US_DocBloc>
--]]
if type(toggle)~="boolean" then ultraschall.AddErrorMessage("Scrubbing_MoveCursor_Toggle", "toggle", "must be a boolean", -1) return false end
return ultraschall.GetSetIntConfigVar("scrubmode", true, toggle)
end
|
myCanvas = hs.canvas.new{ x = 100, y = 100, h = 200, w = 200 }:show()
myCanvas[#myCanvas + 1] = {
id = "primary", -- we check for this in the callback below (_i)
type = "circle",
radius = 100,
center = { x = 100, y = 100 },
action = "fill",
fillColor = { blue = .7, alpha = .7 },
trackMouseDown = true,
trackMouseUp = true,
}
local _cMouseAction -- make local here so it's an upvalue in mouseCallback
-- This example only tracks movement when you click within the specified canvas object (i.e.
-- the blue circle). If you'd rather it move when they click within *any* portion of the
-- canvas, add `myCanvas:canvasMouseEvents(true, true)` and change `_i == "primary"` below to
-- `_i == "_canvas_"`.
myCanvas:clickActivating(false):mouseCallback(function(_c, _m, _i, _x, _y)
print(_m, _i)
if _i == "primary" then
if _m == "mouseDown" then
-- if you want to check other state to see if it should move, do it here
-- e.g. *which* mouse button with `hs.eventtap.checkMouseButtons`,
-- a modifier being held with `hs.eventtap.checkKeyboardModifiers`,
-- etc.
-- exit now if such conditions aren't met, otherwise:
-- uses a coroutine so HS can update the canvas position and do other
-- housekeeping while the mouse button is being held down
_cMouseAction = coroutine.wrap(function()
while _cMouseAction do
-- do the actual moving
local pos = hs.mouse.absolutePosition()
local frame = _c:frame()
frame.x = pos.x - _x
frame.y = pos.y - _y
_c:frame(frame)
-- "exits" so HS can do other things, but a timer resumes
-- the coroutine almost immediately if nothing else is
-- pending
coroutine.applicationYield()
end
end)
_cMouseAction()
elseif _m == "mouseUp" then
-- next time the coroutine resumes, it will clear itself
_cMouseAction = nil
end
end
end)
|
resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5'
files {
'vehicles.meta',
'carvariations.meta',
'carcols.meta',
'handling.meta',
'vehiclelayouts.meta',
'carraddonContentUnlocks.meta',
}
data_file 'HANDLING_FILE' 'handling.meta'
data_file 'VEHICLE_METADATA_FILE' 'vehicles.meta'
data_file 'CARCOLS_FILE' 'carcols.meta'
data_file 'VEHICLE_VARIATION_FILE' 'carvariations.meta'
data_file 'VEHICLE_LAYOUTS_FILE' 'vehiclelayouts.meta'
data_file 'CONTENT_UNLOCKING_META_FILE' 'carraddonContentUnlocks.meta'
client_script 'vehicle_names.lua' |
local local0 = 0.6
local local1 = 0 - local0
local local2 = 0 - local0
local local3 = 3.6 - local0
local local4 = 0 - local0
local local5 = 3.4 - local0
local local6 = 0 - local0
local local7 = 3.2 - local0
local local8 = 0 - local0
local local9 = 2.9 - local0
local local10 = 5 - local0
local local11 = 0 - local0
local local12 = 3.3 - local0
local local13 = 0 - local0
local local14 = 3.9 - local0
local local15 = 0 - local0
local local16 = 4.4 - local0
local local17 = 5.5
local local18 = 0
function OnIf_233000(arg0, arg1, arg2)
if arg2 == 0 then
TheServantOfKing_Sword233000_ActAfter_RealTime(arg0, arg1)
end
return
end
local0 = local18
function TheServantOfKing_Sword233000Battle_Activate(arg0, arg1)
local local0 = {}
local local1 = {}
local local2 = {}
Common_Clear_Param(local0, local1, local2)
if arg0:GetRandam_Int(1, 100) <= 33 then
local local3 = 0
SETUPVAL 7 0 0
else
local local3 = 5
SETUPVAL 7 0 0
end
if arg0:GetTeamOrder(ORDER_TYPE_Role) == ROLE_TYPE_Kankyaku then
local0[22] = 100
elseif arg0:GetTeamOrder(ORDER_TYPE_Role) == ROLE_TYPE_Torimaki then
local0[23] = 100
elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_B, 120) then
local0[20] = 100
elseif 5 <= arg0:GetDist(TARGET_ENE_0) then
local0[1] = 15
local0[2] = 40
local0[3] = 30
local0[4] = 0
local0[5] = 15
elseif arg0:IsTargetGuard(TARGET_ENE_0) == true then
local0[1] = 30
local0[2] = 0
local0[3] = 35
local0[4] = 0
local0[5] = 35
else
local0[1] = 40
local0[2] = 0
local0[3] = 30
local0[4] = 0
local0[5] = 30
end
local1[1] = REGIST_FUNC(arg0, arg1, TheServantOfKing_Sword233000_Act01)
local1[2] = REGIST_FUNC(arg0, arg1, TheServantOfKing_Sword233000_Act02)
local1[3] = REGIST_FUNC(arg0, arg1, TheServantOfKing_Sword233000_Act03)
local1[4] = REGIST_FUNC(arg0, arg1, TheServantOfKing_Sword233000_Act04)
local1[5] = REGIST_FUNC(arg0, arg1, TheServantOfKing_Sword233000_Act05)
local1[20] = REGIST_FUNC(arg0, arg1, TheServantOfKing_Sword233000_Act20)
local1[22] = REGIST_FUNC(arg0, arg1, TheServantOfKing_Sword233000_Act22)
local1[23] = REGIST_FUNC(arg0, arg1, TheServantOfKing_Sword233000_Act23)
local1[30] = REGIST_FUNC(arg0, arg1, TheServantOfKing_Sword233000_Act30)
Common_Battle_Activate(arg0, arg1, local0, local1, REGIST_FUNC(arg0, arg1, TheServantOfKing_Sword233000_ActAfter_AdjustSpace, atkAfterOddsTbl), local2)
return
end
local0 = 3.4 - local0
local0 = local18
function TheServantOfKing_Sword233000_Act01(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = UPVAL0 + 1
Approach_Act(arg0, arg1, UPVAL0, UPVAL0 * UPVAL1, 0, 2)
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, local1, 0, -1)
if arg0:GetRandam_Int(1, 100) <= 50 then
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, local1, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3003, TARGET_ENE_0, local1, 0)
else
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3002, TARGET_ENE_0, local1, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3004, TARGET_ENE_0, local1, 0)
end
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
local0 = 6.3 - local0
local0 = local18
function TheServantOfKing_Sword233000_Act02(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = UPVAL0 + 1
Approach_Act(arg0, arg1, UPVAL0, UPVAL0 * UPVAL1, 0, 2)
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3005, TARGET_ENE_0, local1, 0, -1)
if arg0:GetRandam_Int(1, 100) <= 50 then
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, local1, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3003, TARGET_ENE_0, local1, 0)
else
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3002, TARGET_ENE_0, local1, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3004, TARGET_ENE_0, local1, 0)
end
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
local0 = local12
local0 = local18
function TheServantOfKing_Sword233000_Act03(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
Approach_Act(arg0, arg1, UPVAL0, UPVAL0 * UPVAL1, 0, 2)
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3006, TARGET_ENE_0, UPVAL0 + 1, 0, -1)
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
local0 = local14
local0 = local18
function TheServantOfKing_Sword233000_Act04(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
Approach_Act(arg0, arg1, UPVAL0, UPVAL0 * UPVAL1, 0, 2)
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3007, TARGET_ENE_0, UPVAL0 + 1, 0, -1)
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
local0 = local16
local0 = local18
function TheServantOfKing_Sword233000_Act05(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
Approach_Act(arg0, arg1, UPVAL0, UPVAL0 * UPVAL1, 0, 2)
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3008, TARGET_ENE_0, UPVAL0 + 1, 0, -1)
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
function TheServantOfKing_Sword233000_Act20(arg0, arg1, arg2)
local local0 = arg0:GetRandam_Int(1, 100)
if arg0:GetDist(TARGET_ENE_0) <= 2.5 then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3009, TARGET_ENE_0, DIST_None, 0, -1)
else
arg1:AddSubGoal(GOAL_COMMON_Turn, 2, TARGET_ENE_0, 0, 0, 0)
end
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
function TheServantOfKing_Sword233000_Act22(arg0, arg1, arg2)
Kanshu_Act(arg0, arg1, 0)
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
function TheServantOfKing_Sword233000_Act23(arg0, arg1, arg2)
Torimaki_Act(arg0, arg1, 0)
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
local0 = local17
function TheServantOfKing_Sword233000_Act30(arg0, arg1)
if arg0:GetRandam_Int(1, 100) <= 50 then
if arg0:IsOnNearMesh(TARGET_SELF, AI_DIR_TYPE_L, UPVAL0, 5) == true then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, UPVAL0)
else
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, UPVAL0)
end
elseif arg0:IsOnNearMesh(TARGET_SELF, AI_DIR_TYPE_R, UPVAL0, 5) == true then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, UPVAL0)
else
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, UPVAL0)
end
return true
end
local0 = local17
local0 = local14
function TheServantOfKing_Sword233000_Act31(arg0, arg1)
local local0 = arg0:GetRandam_Int(1, 100)
if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_F, 120) then
if arg0:IsOnNearMesh(TARGET_SELF, AI_DIR_TYPE_B, UPVAL0, 5) == true then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3007, TARGET_ENE_0, UPVAL1 + 1, 0, -1)
else
return TheServantOfKing_Sword233000_Act30(arg0, arg1)
end
else
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3009, TARGET_ENE_0, DIST_None, 0, -1)
end
return true
end
function TheServantOfKing_Sword233000_ActAfter_AdjustSpace(arg0, arg1, arg2)
arg1:AddSubGoal(GOAL_COMMON_If, 10, 0)
return
end
local0 = local14
local0 = local17
function TheServantOfKing_Sword233000_ActAfter_RealTime(arg0, arg1)
if arg0:GetRandam_Int(1, 100) <= 65 and arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_F, 120) and arg0:GetDist(TARGET_ENE_0) <= UPVAL0 and arg0:IsOnNearMesh(TARGET_SELF, AI_DIR_TYPE_B, UPVAL1, 5) == true then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3007, TARGET_ENE_0, UPVAL0 + 1, 0, -1)
arg1:AddSubGoal(GOAL_COMMON_Wait, arg0:GetRandam_Float(0, 2), TARGET_NONE, 0, 0, 0)
end
return
end
function TheServantOfKing_Sword233000Battle_Update(arg0, arg1)
return GOAL_RESULT_Continue
end
function TheServantOfKing_Sword233000Battle_Terminate(arg0, arg1)
return
end
local0 = local14
local0 = local16
local0 = local12
function TheServantOfKing_Sword233000Battle_Interupt(arg0, arg1)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
local local2 = arg0:GetRandam_Int(1, 100)
if FindAttack_Act(arg0, arg1, UPVAL0, 60) then
return TheServantOfKing_Sword233000_Act31(arg0, arg1)
elseif GuardBreak_Act(arg0, arg1, UPVAL1, 90) then
arg1:ClearSubGoal()
if arg0:GetRandam_Int(1, 100) <= 70 then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3006, TARGET_ENE_0, UPVAL2 + 1, 0, -1)
else
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3008, TARGET_ENE_0, UPVAL1 + 1, 0, -1)
end
return true
else
local local3 = Shoot_2dist(arg0, arg1, 5, 20, 60, 80)
if local3 == 1 or local3 == 2 then
arg1:ClearSubGoal()
return TheServantOfKing_Sword233000_Act30(arg0, arg1)
else
return false
end
end
end
return
|
require("cURL")
-- setup easy
c = cURL.easy_init()
c2 = cURL.easy_init()
-- setup url
c:setopt_url("http://www.example.com/")
c2:setopt_url("http://www.hoetzel.info/")
-- c.perform()
m = cURL.multi_init()
m2 = cURL.multi_init()
m:add_handle(c)
m2:add_handle(c2)
-- perform,
-- it = m:perform()
for data, type, easy in m:perform() do
if (type == "data" and c == easy) then print(data) end
end
-- for data,type,easy in m2:perform() do
-- if (type == "header") then print(data) end
-- end |
pg = pg or {}
pg.enemy_data_statistics_378 = {
[213003] = {
cannon = 5,
reload = 150,
speed_growth = 0,
cannon_growth = 432,
pilot_ai_template_id = 10001,
air = 0,
base = 152,
dodge = 22,
durability_growth = 37800,
antiaircraft = 22,
speed = 36,
reload_growth = 0,
dodge_growth = 270,
luck = 10,
battle_unit_type = 50,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 1764,
torpedo = 46,
durability = 95,
armor_growth = 0,
torpedo_growth = 3648,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 213003,
antisub = 0,
world_enhancement = {
9.3,
5.4,
1.2,
0.6,
0.9,
0.9,
0
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100004,
1100139,
1100499
}
},
[213004] = {
cannon = 6,
reload = 150,
speed_growth = 0,
cannon_growth = 480,
pilot_ai_template_id = 10001,
air = 0,
base = 153,
dodge = 22,
durability_growth = 44100,
antiaircraft = 22,
speed = 36,
reload_growth = 0,
dodge_growth = 270,
luck = 10,
battle_unit_type = 50,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 1764,
torpedo = 46,
durability = 110,
armor_growth = 0,
torpedo_growth = 3648,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 213004,
antisub = 0,
world_enhancement = {
9.3,
5.4,
1.2,
0.6,
0.9,
0.9,
0
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100004,
1100139,
1100499
}
},
[213005] = {
cannon = 6,
reload = 150,
speed_growth = 0,
cannon_growth = 492,
base = 297,
air = 0,
durability_growth = 42840,
dodge = 22,
antiaircraft = 23,
speed = 36,
luck = 10,
reload_growth = 0,
dodge_growth = 270,
battle_unit_type = 50,
antisub = 0,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 1800,
torpedo = 49,
durability = 107,
armor_growth = 0,
torpedo_growth = 3912,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 213005,
world_enhancement = {
9.3,
5.4,
1.2,
0.6,
0.9,
0.9,
0
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100004,
1100139,
1100514
}
},
[213006] = {
cannon = 6,
reload = 150,
speed_growth = 0,
cannon_growth = 480,
base = 298,
air = 0,
durability_growth = 39900,
dodge = 22,
antiaircraft = 22,
speed = 36,
luck = 10,
reload_growth = 0,
dodge_growth = 270,
battle_unit_type = 50,
antisub = 0,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 1764,
torpedo = 50,
durability = 100,
armor_growth = 0,
torpedo_growth = 4032,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 213006,
world_enhancement = {
9.3,
5.4,
1.2,
0.6,
0.9,
0.9,
0
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100004,
1100139,
1100514
}
},
[213007] = {
cannon = 6,
reload = 150,
speed_growth = 0,
cannon_growth = 504,
base = 293,
air = 0,
durability_growth = 39900,
dodge = 22,
antiaircraft = 22,
speed = 36,
luck = 10,
reload_growth = 0,
dodge_growth = 270,
battle_unit_type = 50,
antisub = 0,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 1764,
torpedo = 48,
durability = 100,
armor_growth = 0,
torpedo_growth = 3840,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 213007,
world_enhancement = {
9.3,
5.4,
1.2,
0.6,
0.9,
0.9,
0
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100004,
1100139,
1100514
}
},
[213008] = {
cannon = 6,
reload = 150,
speed_growth = 0,
cannon_growth = 480,
base = 294,
air = 0,
durability_growth = 39900,
dodge = 22,
antiaircraft = 23,
speed = 36,
luck = 10,
reload_growth = 0,
dodge_growth = 270,
battle_unit_type = 50,
antisub = 0,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 1848,
torpedo = 48,
durability = 100,
armor_growth = 0,
torpedo_growth = 3840,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 213008,
world_enhancement = {
9.3,
5.4,
1.2,
0.6,
0.9,
0.9,
0
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100004,
1100139,
1100514
}
},
[213009] = {
cannon = 11,
reload = 150,
speed_growth = 0,
cannon_growth = 864,
pilot_ai_template_id = 10001,
air = 0,
base = 182,
dodge = 16,
durability_growth = 47260,
antiaircraft = 50,
speed = 24,
reload_growth = 0,
dodge_growth = 200,
luck = 10,
battle_unit_type = 55,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 4032,
torpedo = 34,
durability = 118,
armor_growth = 0,
torpedo_growth = 2736,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 213009,
antisub = 0,
world_enhancement = {
9.3,
4.6,
1.1,
0,
0.9,
0.9,
0
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100249,
1100279,
1100439,
1100469
}
},
[213010] = {
cannon = 12,
reload = 150,
speed_growth = 0,
cannon_growth = 996,
base = 302,
air = 0,
durability_growth = 50400,
dodge = 16,
speed = 24,
luck = 10,
battle_unit_type = 55,
reload_growth = 0,
dodge_growth = 200,
antisub = 0,
antiaircraft_growth = 3912,
hit = 13,
antisub_growth = 0,
air_growth = 0,
luck_growth = 0,
torpedo = 36,
durability = 126,
armor_growth = 0,
torpedo_growth = 2880,
antiaircraft = 49,
hit_growth = 189,
armor = 0,
id = 213010,
world_enhancement = {
9.3,
4.6,
1.1,
0,
0.9,
0.9,
0
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100249,
1100394,
1100364,
2021601,
2021620
},
random_equipment_list = {
{
2021611
}
},
random_nub = {
1
}
},
[213011] = {
cannon = 11,
reload = 150,
speed_growth = 0,
cannon_growth = 912,
base = 303,
air = 0,
durability_growth = 52500,
dodge = 16,
speed = 24,
luck = 10,
battle_unit_type = 55,
reload_growth = 0,
dodge_growth = 200,
antisub = 0,
antiaircraft_growth = 4440,
hit = 13,
antisub_growth = 0,
air_growth = 0,
luck_growth = 0,
torpedo = 34,
durability = 131,
armor_growth = 0,
torpedo_growth = 2736,
antiaircraft = 56,
hit_growth = 189,
armor = 0,
id = 213011,
world_enhancement = {
9.3,
4.6,
1.1,
0,
0.9,
0.9,
0
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100249,
1100119,
1100499,
2021600,
2021614
},
random_equipment_list = {
{
2021613
}
},
random_nub = {
1
}
},
[213012] = {
cannon = 23,
reload = 150,
speed_growth = 0,
cannon_growth = 1848,
base = 304,
air = 0,
durability_growth = 66160,
dodge = 20,
antiaircraft = 32,
speed = 18,
luck = 10,
reload_growth = 0,
dodge_growth = 100,
battle_unit_type = 55,
antisub = 0,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 2520,
torpedo = 24,
durability = 165,
armor_growth = 0,
torpedo_growth = 1920,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 213012,
world_enhancement = {
9.3,
2.6,
1.7,
0.3,
0.9,
0.9,
0.8
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100674,
2021712,
1100309,
2021700,
2021711
}
},
[213013] = {
cannon = 34,
battle_unit_type = 65,
speed = 14,
speed_growth = 0,
pilot_ai_template_id = 10001,
air = 0,
antisub = 0,
dodge = 24,
luck = 10,
reload = 150,
cannon_growth = 2736,
reload_growth = 0,
dodge_growth = 30,
torpedo = 0,
durability_growth = 103960,
hit = 7,
antisub_growth = 0,
air_growth = 0,
luck_growth = 0,
base = 225,
durability = 260,
armor_growth = 0,
torpedo_growth = 0,
antiaircraft = 28,
hit_growth = 105,
armor = 0,
antiaircraft_growth = 2268,
id = 213013,
world_enhancement = {
9.3,
0.7,
1.7,
0.7,
0.9,
2,
2.2
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100529,
1100559,
1100724,
2021800
},
random_equipment_list = {
{
2021811
}
},
random_nub = {
1
}
},
[213014] = {
cannon = 37,
reload = 150,
speed_growth = 0,
cannon_growth = 2940,
base = 307,
air = 0,
durability_growth = 115500,
dodge = 24,
speed = 14,
luck = 10,
battle_unit_type = 65,
reload_growth = 0,
dodge_growth = 30,
antisub = 0,
antiaircraft_growth = 2568,
hit = 7,
antisub_growth = 0,
air_growth = 0,
luck_growth = 0,
torpedo = 0,
durability = 289,
armor_growth = 0,
torpedo_growth = 0,
antiaircraft = 32,
hit_growth = 105,
armor = 0,
id = 213014,
world_enhancement = {
9.3,
0.7,
1.7,
0.7,
0.9,
2,
2.2
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100104,
1100599,
1100734,
2021800
},
random_equipment_list = {
{
2021812,
2021813,
2021814,
2021815
}
},
random_nub = {
1
}
},
[213015] = {
cannon = 36,
reload = 150,
speed_growth = 0,
cannon_growth = 2880,
base = 308,
air = 0,
durability_growth = 117820,
dodge = 24,
antiaircraft = 32,
speed = 14,
luck = 10,
reload_growth = 0,
dodge_growth = 30,
battle_unit_type = 65,
antisub = 0,
hit = 7,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 2568,
torpedo = 0,
durability = 295,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
hit_growth = 105,
armor = 0,
id = 213015,
world_enhancement = {
9.3,
0.7,
1.7,
0.7,
0.9,
2,
2.2
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100104,
1100599,
1100734,
2021800
}
},
[213016] = {
cannon = 0,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 10001,
air = 46,
base = 237,
dodge = 6,
durability_growth = 94500,
antiaircraft = 41,
speed = 18,
reload_growth = 0,
dodge_growth = 70,
luck = 10,
battle_unit_type = 60,
hit = 7,
antisub_growth = 0,
air_growth = 3696,
antiaircraft_growth = 3276,
torpedo = 0,
durability = 236,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
hit_growth = 105,
armor = 0,
id = 213016,
antisub = 0,
world_enhancement = {
9.3,
1.9,
1.7,
0.7,
0.1,
2,
0.1
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100019,
2021920,
2200769,
2200774,
2200779,
2021900,
2021911,
2021912
}
},
[213017] = {
cannon = 0,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 10001,
air = 48,
base = 238,
dodge = 6,
durability_growth = 99220,
antiaircraft = 41,
speed = 18,
reload_growth = 0,
dodge_growth = 70,
luck = 10,
battle_unit_type = 60,
hit = 7,
antisub_growth = 0,
air_growth = 3878,
antiaircraft_growth = 3276,
torpedo = 0,
durability = 248,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
hit_growth = 105,
armor = 0,
id = 213017,
antisub = 0,
world_enhancement = {
9.3,
1.9,
1.7,
0.7,
0.1,
2,
0.1
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100019,
1100169,
2200769,
2200774,
2200779,
2021900,
2021914,
2021916
}
},
[213018] = {
cannon = 0,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
base = 295,
air = 53,
durability_growth = 89780,
dodge = 6,
antiaircraft = 41,
speed = 18,
luck = 10,
reload_growth = 0,
dodge_growth = 70,
battle_unit_type = 60,
antisub = 0,
hit = 7,
antisub_growth = 0,
air_growth = 4256,
antiaircraft_growth = 3276,
torpedo = 0,
durability = 224,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
hit_growth = 105,
armor = 0,
id = 213018,
world_enhancement = {
9.3,
1.9,
1.7,
0.7,
0.1,
2,
0.1
},
bound_bone = {
cannon = {
{
-0.5,
0.5,
0
}
},
antiaircraft = {
{
0.5,
0.8,
0
},
{
-0.5,
0.8,
0
}
},
plane = {
{
-0.5,
0.5,
0
}
}
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100019,
1100169,
2200769,
2200774,
2200779,
2021900
}
}
}
return
|
project(path.getname(os.getcwd()))
kind "ConsoleApp"
language "c++"
objdir "../obj"
files { "**.cpp", "**.cc", "**.h"} -- recursively add files
includedirs {"../../../glm", "../../../sdl/include", "../../../glew/include", "../src"}
libdirs {"../../../sdl/lib/x86", "../../../glew/lib/x86"}
links { "akari" }
|
dofile(mg.script_name:gsub('[^\\/]*$','')..'util.lua')
if mg.get_var(mg.request_info.query_string,'t')=='d' then
if SHOW_DEBUG_LOG then
t='\\EpgTimerSrvDebugLog.txt'
end
else
if SHOW_NOTIFY_LOG then
t='\\EpgTimerSrvNotify.log'
end
end
if t then
f=edcb.io.open(edcb.GetPrivateProfile('SET','ModulePath','','Common.ini')..t,'rb')
end
if not f then
mg.write(Response(404,nil,nil,0)..'\r\n')
else
ct=CreateContentBuilder(GZIP_THRESHOLD_BYTE)
c=GetVarInt(mg.request_info.query_string,'c',0,1e7) or 1e7
fsize=f:seek('end')
if fsize>=2 then
ofs=math.floor(math.max(fsize/2-1-c,0))
f:seek('set',2+ofs*2)
if ofs~=0 then
repeat
buf=f:read(2)
until not buf or #buf<2 or buf=='\n\0'
end
ct:Append(edcb.Convert('utf-8','utf-16le',f:read('*a') or '') or '')
end
f:close()
ct:Finish()
mg.write(ct:Pop(Response(200,'text/plain','utf-8',ct.len)..(ct.gzip and 'Content-Encoding: gzip\r\n' or '')..'\r\n'))
end
|
local a= 10;
local b= 30;
return a*b; |
local state = {} |
require('lualine').setup {
options = {
icons_enabled = true,
theme = 'material',
component_separators = {},
section_separators = {},
disabled_filetypes = {'NvimTree'},
},
sections = {
lualine_a = {'mode'},
lualine_b = {{'branch'}, {'diff',colored=false}},
lualine_c = {'filename',{'diagnostics', sources={'nvim_diagnostic'}}},
lualine_x = {"os.date('%b %d,%Y')"}, --brings in date
lualine_y = {'ln:','%02l/%L'},
lualine_z = {'progress'}
},
inactive_sections = {
lualine_a = {},
lualine_b = {},
lualine_c = {'%F'},
lualine_x = {'location'},
lualine_y = {},
lualine_z = {}
},
}
|
--- @class GNPC : GEntity
--- This is a list of all methods only available for NPCs. It is also possible to call [Entity](http://wiki.garrysmod.com/index.php?title=Category:Entity) functions on NPCs.
local GNPC = {}
--- Makes the NPC like, hate, feel neutral towards, or fear the entity in question. If you want to setup relationship towards a certain entity `class`, use NPC:AddRelationship.
--- ℹ **NOTE**: NPCs do not see NextBots by default. This can be fixed by adding the FL_OBJECT flag to the NextBot.
--- @param target GEntity @The entity for the relationship to be applied to.
--- @param disposition number @A Enums/D representing the relationship type.
--- @param priority number @How strong the relationship is.
function GNPC:AddEntityRelationship(target, disposition, priority)
end
--- Changes how an NPC feels towards another NPC. If you want to setup relationship towards a certain `entity`, use NPC:AddEntityRelationship.
--- @param relationstring string @A string representing how the relationship should be set up
function GNPC:AddRelationship(relationstring)
end
--- Force an NPC to play his Alert sound.
function GNPC:AlertSound()
end
--- Adds a capability to the NPC.
--- @param capabilities number @Capabilities to add, see Enums/CAP
function GNPC:CapabilitiesAdd(capabilities)
end
--- Removes all of Capabilities the NPC has.
function GNPC:CapabilitiesClear()
end
--- Returns the NPC's capabilities along the ones defined on its weapon.
--- @return number @The capabilities as a bitflag
function GNPC:CapabilitiesGet()
end
--- Remove a certain capability.
--- @param capabilities number @Capabilities to remove, see Enums/CAP
function GNPC:CapabilitiesRemove(capabilities)
end
--- Returns the NPC class. Do not confuse with Entity:GetClass!
--- @return number @See Enums/CLASS
function GNPC:Classify()
end
--- Clears out the specified Enums/COND on this NPC.
--- @param condition number @The Enums/COND to clear out.
function GNPC:ClearCondition(condition)
end
--- Clears the Enemy from the NPC's memory, effectively forgetting it until met again with either the NPC vision or with NPC:UpdateEnemyMemory.
function GNPC:ClearEnemyMemory()
end
--- Clears the NPC's current expression which can be set with NPC:SetExpression.
function GNPC:ClearExpression()
end
--- Clears the current NPC goal or target.
function GNPC:ClearGoal()
end
--- Stops the current schedule that the NPC is doing.
function GNPC:ClearSchedule()
end
--- Translates condition ID to a string.
--- @param cond number @The NPCs condition ID, see Enums/COND
--- @return string @A human understandable string equivalent of that condition.
function GNPC:ConditionName(cond)
end
--- Returns the way the NPC "feels" about the entity.
--- @param ent GEntity @The entity to get the disposition from.
--- @return number @The NPCs disposition, see Enums/D.
function GNPC:Disposition(ent)
end
--- Forces the NPC to drop the specified weapon.
--- @param weapon GWeapon @Weapon to be dropped
--- @param target GVector @If set, launches the weapon at given position
--- @param velocity GVector @If set and previous argument is unset, launches the weapon with given velocity
function GNPC:DropWeapon(weapon, target, velocity)
end
--- Makes an NPC exit a scripted sequence, if one is playing.
function GNPC:ExitScriptedSequence()
end
--- Force an NPC to play his Fear sound.
function GNPC:FearSound()
end
--- Force an NPC to play its FoundEnemy sound.
function GNPC:FoundEnemySound()
end
--- Returns the weapon the NPC is currently carrying, or NULL.
--- @return GEntity @The NPCs current weapon
function GNPC:GetActiveWeapon()
end
--- Returns the NPC's current activity.
--- @return number @Current activity, see Enums/ACT.
function GNPC:GetActivity()
end
--- Returns the aim vector of the NPC. NPC alternative of Player:GetAimVector.
--- @return GVector @The aim direction of the NPC.
function GNPC:GetAimVector()
end
--- Returns the activity to be played when the NPC arrives at its goal
--- @return number
function GNPC:GetArrivalActivity()
end
--- Returns the sequence to be played when the NPC arrives at its goal.
--- @return number @Sequence ID to be played, or -1 if there's no sequence.
function GNPC:GetArrivalSequence()
end
--- Returns the entity blocking the NPC along its path.
--- @return GEntity @Blocking entity
function GNPC:GetBlockingEntity()
end
--- Gets the NPC's current waypoint position (where NPC is currently moving towards), if any is available.
--- @return GVector @The position of the current NPC waypoint.
function GNPC:GetCurWaypointPos()
end
--- Returns the NPC's current schedule.
--- @return number @The NPCs schedule, see Enums/SCHED or -1 if we failed for some reason
function GNPC:GetCurrentSchedule()
end
--- Returns how proficient (skilled) an NPC is with its current weapon.
--- @return number @NPC's proficiency for current weapon
function GNPC:GetCurrentWeaponProficiency()
end
--- Returns the entity that this NPC is trying to fight.
--- 🦟 **BUG**: [This returns nil if the NPC has no enemy. You should use Global.IsValid (which accounts for nil and NULL) on the return to verify validity of the enemy.](https://github.com/Facepunch/garrysmod-issues/issues/3132)
--- @return GNPC @Enemy NPC.
function GNPC:GetEnemy()
end
--- Returns the expression file the NPC is currently playing.
--- @return string @The file path of the expression.
function GNPC:GetExpression()
end
--- Returns NPCs hull type set by NPC:SetHullType.
--- @return number @Hull type, see Enums/HULL
function GNPC:GetHullType()
end
--- Returns the NPC's current movement activity.
--- @return number @Current NPC movement activity, see Enums/ACT.
function GNPC:GetMovementActivity()
end
--- Returns the index of the sequence the NPC uses to move.
--- @return number @The movement sequence index
function GNPC:GetMovementSequence()
end
--- Returns the NPC's state.
--- @return number @The NPC's current state, see Enums/NPC_STATE.
function GNPC:GetNPCState()
end
--- Gets the NPC's next waypoint position, where NPC will be moving after reaching current waypoint, if any is available.
--- @return GVector @The position of the next NPC waypoint.
function GNPC:GetNextWaypointPos()
end
--- Returns the distance the NPC is from Target Goal.
--- @return number @The number of hammer units the NPC is away from the Goal.
function GNPC:GetPathDistanceToGoal()
end
--- Returns the amount of time it will take for the NPC to get to its Target Goal.
--- @return number @The amount of time to get to the target goal.
function GNPC:GetPathTimeToGoal()
end
--- Returns the shooting position of the NPC.
--- ℹ **NOTE**: This only works properly when called on an NPC that can hold weapons, otherwise it will return the same value as Entity:GetPos.
--- @return GVector @The NPC's shooting position.
function GNPC:GetShootPos()
end
--- Returns the NPC's current target set by NPC:SetTarget.
--- 🦟 **BUG**: [This returns nil if the NPC has no target. You should use Global.IsValid (which accounts for nil and NULL) on the return to verify validity of the target.](https://github.com/Facepunch/garrysmod-issues/issues/3132)
--- @return GEntity @Target entity
function GNPC:GetTarget()
end
--- Used to give a weapon to an already spawned NPC.
--- @param weapon string @Class name of the weapon to equip to the NPC.
--- @return GWeapon @The weapon entity given to the NPC.
function GNPC:Give(weapon)
end
--- Returns whether or not the NPC has the given condition.
--- @param condition number @The condition index, see Enums/COND.
--- @return boolean @True if the NPC has the given condition, false otherwise.
function GNPC:HasCondition(condition)
end
--- Force an NPC to play his Idle sound.
function GNPC:IdleSound()
end
--- Returns whether or not the NPC is performing the given schedule.
--- @param schedule number @The schedule number, see Enums/SCHED.
--- @return boolean @True if the NPC is performing the given schedule, false otherwise.
function GNPC:IsCurrentSchedule(schedule)
end
--- Returns whether the NPC is moving or not.
--- @return boolean @Whether the NPC is moving or not.
function GNPC:IsMoving()
end
--- Checks if the NPC is running an **ai_goal**. ( e.g. An npc_citizen NPC following the Player. )
--- @return boolean @Returns true if running an ai_goal, otherwise returns false.
function GNPC:IsRunningBehavior()
end
--- Returns true if the entity was remembered as unreachable. The memory is updated automatically from following engine tasks if they failed:
--- * TASK_GET_CHASE_PATH_TO_ENEMY
--- * TASK_GET_PATH_TO_ENEMY_LKP
--- * TASK_GET_PATH_TO_INTERACTION_PARTNER
--- * TASK_ANTLIONGUARD_GET_CHASE_PATH_ENEMY_TOLERANCE
--- * SCHED_FAIL_ESTABLISH_LINE_OF_FIRE - Combine NPCs, also when failing to change their enemy
--- @param testEntity GEntity @The entity to test.
--- @return boolean @If the entity is reachable or not.
function GNPC:IsUnreachable(testEntity)
end
--- Force an NPC to play his LostEnemy sound.
function GNPC:LostEnemySound()
end
--- Tries to achieve our ideal animation state, playing any transition sequences that we need to play to get there.
function GNPC:MaintainActivity()
end
--- Causes the NPC to temporarily forget the current enemy and switch on to a better one.
function GNPC:MarkEnemyAsEluded()
end
--- Makes the NPC walk toward the given position. The NPC will return to the player after amount of time set by **player_squad_autosummon_time** ConVar.
--- Only works on Citizens (npc_citizen) and is a part of the Half-Life 2 squad system.
--- The NPC **must** be in the player's squad for this to work.
--- @param position GVector @The target position for the NPC to walk to.
function GNPC:MoveOrder(position)
end
--- Sets the goal position for the NPC.
--- @param position GVector @The position to set as the goal
function GNPC:NavSetGoal(position)
end
--- Set the goal target for an NPC.
--- @param target GEntity @The targeted entity to set the goal to.
--- @param offset GVector @The offset to apply to the targeted entity's position.
function GNPC:NavSetGoalTarget(target, offset)
end
--- Creates a random path of specified minimum length between a closest start node and random node in the specified direction.
--- @param minPathLength number @Minimum length of path in units
--- @param dir GVector @Unit vector pointing in the direction of the target random node
function GNPC:NavSetRandomGoal(minPathLength, dir)
end
--- Sets a goal in x, y offsets for the npc to wander to
--- @param xoffset number @X offset
--- @param yoffset number @Y offset
function GNPC:NavSetWanderGoal(xoffset, yoffset)
end
--- Forces the NPC to play a sentence from scripts/sentences.txt
--- @param sentence string @The sentence string to speak.
--- @param delay number @Delay in seconds until the sentence starts playing.
--- @param volume number @The volume of the sentence, from 0 to 1.
--- @return number @Returns the sentence index, -1 if the sentence couldn't be played.
function GNPC:PlaySentence(sentence, delay, volume)
end
--- 🛑 **DEPRECATED**:
--- This function crashes the game no matter how it is used and will be removed in a future update.
--- Use NPC:ClearEnemyMemory instead.
function GNPC:RemoveMemory()
end
--- Starts an engine task.
--- Used internally by the ai_task.
--- @param taskID number @The task ID, see [ai_task.h](https://github.com/ValveSoftware/source-sdk-2013/blob/55ed12f8d1eb6887d348be03aee5573d44177ffb/mp/src/game/serv
--- @param taskData number @The task data.
function GNPC:RunEngineTask(taskID, taskData)
end
--- Stops any sounds (speech) the NPC is currently palying.
--- Equivalent to `Entity:EmitSound( "AI_BaseNPC.SentenceStop" )`
function GNPC:SentenceStop()
end
--- @param act number
function GNPC:SetArrivalActivity(act)
end
function GNPC:SetArrivalDirection()
end
--- Sets the distance to goal at which the NPC should stop moving and continue to other business such as doing the rest of their tasks in a schedule.
--- @param dist number @The distance to goal that is close enough for the NPC
function GNPC:SetArrivalDistance(dist)
end
function GNPC:SetArrivalSequence()
end
function GNPC:SetArrivalSpeed()
end
--- Sets an NPC condition.
--- @param condition number @The condition index, see Enums/COND.
function GNPC:SetCondition(condition)
end
--- Sets the weapon proficiency of an NPC (how skilled an NPC is with its current weapon).
--- @param proficiency number @The proficiency for the NPC's current weapon
function GNPC:SetCurrentWeaponProficiency(proficiency)
end
--- Sets the target for an NPC.
--- @param enemy GEntity @The enemy that the NPC should target
--- @param newenemy boolean @Calls NPC:SetCondition(COND_NEW_ENEMY) if the new enemy is valid and not equal to the last enemy.
function GNPC:SetEnemy(enemy, newenemy)
end
--- Sets the NPC's .vcd expression. Similar to Entity:PlayScene except the scene is looped until it's interrupted by default NPC behavior or NPC:ClearExpression.
--- @param expression string @The expression filepath.
--- @return number
function GNPC:SetExpression(expression)
end
--- Updates the NPC's hull and physics hull in order to match its model scale. Entity:SetModelScale seems to take care of this regardless.
function GNPC:SetHullSizeNormal()
end
--- Sets the hull type for the NPC.
--- @param hullType number @Hull type
function GNPC:SetHullType(hullType)
end
--- Sets the last registered or memorized position for an npc. When using scheduling, the NPC will focus on navigating to the last position via nodes.
--- ℹ **NOTE**: The navigation requires ground nodes to function properly, otherwise the NPC could only navigate in a small area. (https://developer.valvesoftware.com/wiki/Info_node)
--- @param Position GVector @Where the NPC's last position will be set.
function GNPC:SetLastPosition(Position)
end
--- Sets how how long to try rebuilding path before failing task.
--- @param time number @How long to try rebuilding path before failing task
function GNPC:SetMaxRouteRebuildTime(time)
end
--- Sets the activity the NPC uses when it moves.
--- @param activity number @The movement activity, see Enums/ACT.
function GNPC:SetMovementActivity(activity)
end
--- Sets the sequence the NPC navigation path uses for speed calculation. Doesn't seem to have any visible effect on NPC movement.
--- @param sequenceId number @The movement sequence index
function GNPC:SetMovementSequence(sequenceId)
end
--- Sets the state the NPC is in to help it decide on a ideal schedule.
--- @param state number @New NPC state, see Enums/NPC_STATE
function GNPC:SetNPCState(state)
end
--- Sets the NPC's current schedule.
--- @param schedule number @The NPC schedule, see Enums/SCHED.
function GNPC:SetSchedule(schedule)
end
--- Sets the NPC's target. This is used in some engine schedules.
--- @param entity GEntity @The target of the NPC.
function GNPC:SetTarget(entity)
end
--- Forces the NPC to start an engine task, this has different results for every NPC.
--- @param task number @The id of the task to start, see [ai_task.h](https://github.com/ValveSoftware/source-sdk-2013/blob/55ed12f8d1eb6887d348be03aee5573d44177ffb/
--- @param taskData number @The task data as a float, not all tasks make use of it.
function GNPC:StartEngineTask(task, taskData)
end
--- Resets the NPC's movement animation and velocity. Does not actually stop the NPC from moving.
function GNPC:StopMoving()
end
--- Cancels NPC:MoveOrder basically.
--- Only works on Citizens (npc_citizen) and is a part of the Half-Life 2 squad system.
--- The NPC **must** be in the player's squad for this to work.
--- @param target GEntity @Must be a player, does nothing otherwise.
function GNPC:TargetOrder(target)
end
--- Marks the current NPC task as completed.
--- This is meant to be used alongside NPC:TaskFail to complete or fail custom Lua defined tasks. (Schedule:AddTask)
function GNPC:TaskComplete()
end
--- Marks the current NPC task as failed.
--- This is meant to be used alongside NPC:TaskComplete to complete or fail custom Lua defined tasks. (Schedule:AddTask)
--- @param task string @A string most likely defined as a Source Task, for more information on Tasks go to https://developer.valvesoftware.com/wiki/Task
function GNPC:TaskFail(task)
end
--- Force the NPC to update information on the supplied enemy, as if it had line of sight to it.
--- @param enemy GEntity @The enemy to update.
--- @param pos GVector @The last known position of the enemy.
function GNPC:UpdateEnemyMemory(enemy, pos)
end
--- Only usable on "ai" base entities.
--- @return boolean @If we succeeded setting the behavior.
function GNPC:UseActBusyBehavior()
end
--- @return boolean
function GNPC:UseAssaultBehavior()
end
--- Only usable on "ai" base entities.
--- @return boolean @If we succeeded setting the behavior.
function GNPC:UseFollowBehavior()
end
--- @return boolean
function GNPC:UseFuncTankBehavior()
end
--- @return boolean
function GNPC:UseLeadBehavior()
end
--- Undoes the other Use*Behavior functions.
--- Only usable on "ai" base entities.
function GNPC:UseNoBehavior()
end
|
local types = require "resty.nettle.types.common"
local context = require "resty.nettle.types.umac"
local lib = require "resty.nettle.library"
local ffi = require "ffi"
local ffi_new = ffi.new
local ffi_str = ffi.string
local setmetatable = setmetatable
local umacs = {
umac32 = {
length = 4,
context = context.umac32,
buffer = types.uint8_t_4,
setkey = lib.nettle_umac32_set_key,
setnonce = lib.nettle_umac32_set_nonce,
update = lib.nettle_umac32_update,
digest = lib.nettle_umac32_digest
},
umac64 = {
length = 8,
context = context.umac64,
buffer = types.uint8_t_8,
setkey = lib.nettle_umac64_set_key,
setnonce = lib.nettle_umac64_set_nonce,
update = lib.nettle_umac64_update,
digest = lib.nettle_umac64_digest
},
umac96 = {
length = 12,
context = context.umac96,
buffer = types.uint8_t_12,
setkey = lib.nettle_umac96_set_key,
setnonce = lib.nettle_umac96_set_nonce,
update = lib.nettle_umac96_update,
digest = lib.nettle_umac96_digest
},
umac128 = {
length = 16,
context = context.umac128,
buffer = types.uint8_t_16,
setkey = lib.nettle_umac128_set_key,
setnonce = lib.nettle_umac128_set_nonce,
update = lib.nettle_umac128_update,
digest = lib.nettle_umac128_digest
},
}
umacs[32] = umacs.umac32
umacs[64] = umacs.umac64
umacs[96] = umacs.umac96
umacs[128] = umacs.umac128
local umac = {}
umac.__index = umac
function umac:update(data, len)
return self.umac.update(self.context, len or #data, data)
end
function umac:digest()
local umc = self.umac
umc.digest(self.context, umc.length, umc.buffer)
return ffi_str(umc.buffer, umc.length)
end
local function factory(mac)
return setmetatable({
new = function(key, nonce)
local ctx = ffi_new(mac.context)
mac.setkey(ctx, key)
if nonce then
mac.setnonce(ctx, #nonce, nonce)
end
return setmetatable({ context = ctx, umac = mac }, umac)
end
}, {
__call = function(_, key, nonce, data, len)
local ctx = ffi_new(mac.context)
mac.setkey(ctx, key)
if nonce then
mac.setnonce(ctx, #nonce, nonce)
end
mac.update(ctx, len or #data, data)
mac.digest(ctx, mac.length, mac.buffer)
return ffi_str(mac.buffer, mac.length)
end
})
end
return setmetatable({
umac32 = factory(umacs[32]),
umac64 = factory(umacs[64]),
umac96 = factory(umacs[96]),
umac128 = factory(umacs[128])
}, {
__call = function(_, bits, key, nonce, data, len)
local mac = umacs[bits]
if not mac then
return nil, "the supported UMAC algorithm output sizes are 32, 64, 96, and 128 bits"
end
local ctx = ffi_new(mac.context)
mac.setkey(ctx, key)
if nonce then
mac.setnonce(ctx, #nonce, nonce)
end
mac.update(ctx, len or #data, data)
mac.digest(ctx, mac.length, mac.buffer)
return ffi_str(mac.buffer, mac.length)
end
})
|
print("Loading lua file")
print("CTEST_FULL_OUTPUT")
testapp = {counter = 0,
max = 10}
function testapp:initScene()
print("In initScene")
end
function testapp:preFrame(dt)
print("In preFrame")
self.counter = self.counter + 1
print("Counter at " .. tostring(self.counter))
if self.counter >= self.max then
print("Counter at maximum")
vrjKernel.stop()
end
end
print("App delegate defined, now creating OsgAppProxy")
testapp.appProxy = vrjApp.OsgAppProxy()
print ("Now setting OsgAppProxy's delegate")
testapp.appProxy:setAppDelegate(testapp)
print("Loading config files into kernel")
vrjKernel.loadConfigFile("standalone.jconf")
print("Setting kernel application")
testapp.appProxy:setActiveApplication()
print("Starting kernel")
vrjKernel.enter()
|
local LogonView = class("LogonView",function()
local logonView = display.newLayer()
return logonView
end)
local ExternalFun = appdf.req(appdf.EXTERNAL_SRC .. "ExternalFun")
local MultiPlatform = appdf.req(appdf.EXTERNAL_SRC .. "MultiPlatform")
LogonView.BT_LOGON = 1
LogonView.BT_REGISTER = 2
LogonView.CBT_RECORD = 3
LogonView.CBT_AUTO = 4
LogonView.BT_VISITOR = 5
LogonView.BT_WEIBO = 6
LogonView.BT_QQ = 7
LogonView.BT_THIRDPARTY = 8
LogonView.BT_WECHAT = 9
LogonView.BT_FGPW = 10 -- 忘记密码
function LogonView:ctor(serverConfig)
local this = self
self:setContentSize(yl.WIDTH,yl.HEIGHT)
--ExternalFun.registerTouchEvent(self)
local btcallback = function(ref, type)
if type == ccui.TouchEventType.ended then
this:onButtonClickedEvent(ref:getTag(),ref)
end
end
local cbtlistener = function (sender,eventType)
this:onSelectedEvent(sender,eventType)
end
local editHanlder = function ( name, sender )
self:onEditEvent(name, sender)
end
--帐号提示
display.newSprite("Logon/account_text.png")
:move(366,381)
:addTo(self)
--账号输入
self.edit_Account = ccui.EditBox:create(cc.size(490,67), ccui.Scale9Sprite:create("Logon/text_field_frame.png"))
:move(yl.WIDTH/2,381)
:setAnchorPoint(cc.p(0.5,0.5))
:setFontName("fonts/round_body.ttf")
:setPlaceholderFontName("fonts/round_body.ttf")
:setFontSize(24)
:setPlaceholderFontSize(24)
:setMaxLength(31)
:setInputMode(cc.EDITBOX_INPUT_MODE_SINGLELINE)
:addTo(self)
self.edit_Account:registerScriptEditBoxHandler(editHanlder)
--密码提示
display.newSprite("Logon/password_text.png")
:move(366,280)
:addTo(self)
--密码输入
self.edit_Password = ccui.EditBox:create(cc.size(490,67), ccui.Scale9Sprite:create("Logon/text_field_frame.png"))
:move(yl.WIDTH/2,280)
:setAnchorPoint(cc.p(0.5,0.5))
:setFontName("fonts/round_body.ttf")
:setPlaceholderFontName("fonts/round_body.ttf")
:setFontSize(24)
:setPlaceholderFontSize(24)
:setMaxLength(26)
:setInputFlag(cc.EDITBOX_INPUT_FLAG_PASSWORD)
:setInputMode(cc.EDITBOX_INPUT_MODE_SINGLELINE)
:addTo(self)
-- 忘记密码
ccui.Button:create("Logon/btn_login_fgpw.png")
:setTag(LogonView.BT_FGPW)
:move(1000,280)
:addTo(self)
:addTouchEventListener(btcallback)
--记住密码
self.cbt_Record = ccui.CheckBox:create("Logon/rem_password_button.png","","Logon/choose_button.png","","")
:move(515,165)
:setSelected(GlobalUserItem.bSavePassword)
:setTag(LogonView.CBT_RECORD)
:addTo(self)
-- --自动登录
-- self.cbt_Auto = ccui.CheckBox:create("cbt_auto_0.png","","cbt_auto_1.png","","")
-- :move(700-93,245)
-- :setSelected(GlobalUserItem.bAutoLogon)
-- :setTag(LogonView.CBT_AUTO)
-- :addTo(self)
--账号登录
ccui.Button:create("Logon/logon_button_0.png", "Logon/logon_button_1.png", "Logon/logon_button_2.png")
:setTag(LogonView.BT_LOGON)
:move(cc.p(0,0))
:setName("btn_1")
:addTo(self)
:addTouchEventListener(btcallback)
--注册按钮
ccui.Button:create("Logon/regist_button.png","")
:setTag(LogonView.BT_REGISTER)
:move(766,165)
:addTo(self)
:addTouchEventListener(btcallback)
--游客登录
ccui.Button:create("Logon/visitor_button_0.png", "Logon/visitor_button_1.png", "Logon/visitor_button_2.png")
:setTag(LogonView.BT_VISITOR)
:move(cc.p(0,0))
:setEnabled(false)
:setVisible(false)
:setName("btn_2")
:addTo(self)
:addTouchEventListener(btcallback)
--微信登陆
ccui.Button:create("Logon/thrid_part_wx_0.png", "Logon/thrid_part_wx_1.png", "Logon/thrid_part_wx_2.png")
:setTag(LogonView.BT_WECHAT)
:move(cc.p(0,0))
:setVisible(false)
:setEnabled(false)
:setName("btn_3")
:addTo(self)
:addTouchEventListener(btcallback)
self.m_serverConfig = serverConfig or {}
self:refreshBtnList()
end
function LogonView:refreshBtnList( )
for i = 1, 3 do
local btn = self:getChildByName("btn_" .. i)
if btn ~= nil then
btn:setVisible(false)
btn:setEnabled(false)
end
end
local btncount = 1
local btnpos =
{
{cc.p(667, 70), cc.p(0, 0), cc.p(0, 0)},
{cc.p(463, 70), cc.p(868, 70), cc.p(0, 0)},
{cc.p(222, 70), cc.p(667, 70), cc.p(1112, 70)}
}
-- 1:帐号 2:游客 3:微信
local btnlist = {"btn_1"}
if false == GlobalUserItem.getBindingAccount() then
table.insert(btnlist, "btn_2")
end
local enableWeChat = self.m_serverConfig["wxLogon"] or 1
if 0 == enableWeChat then
table.insert(btnlist, "btn_3")
end
local poslist = btnpos[#btnlist]
for k,v in pairs(btnlist) do
local tmp = self:getChildByName(v)
if nil ~= tmp then
tmp:setEnabled(true)
tmp:setVisible(true)
local pos = poslist[k]
if nil ~= pos then
tmp:setPosition(pos)
end
end
end
end
function LogonView:onEditEvent(name, editbox)
--print(name)
if "changed" == name then
if editbox:getText() ~= GlobalUserItem.szAccount then
self.edit_Password:setText("")
end
end
end
function LogonView:onReLoadUser()
if GlobalUserItem.szAccount ~= nil and GlobalUserItem.szAccount ~= "" then
self.edit_Account:setText(GlobalUserItem.szAccount)
else
self.edit_Account:setPlaceHolder("请输入您的游戏帐号")
end
if GlobalUserItem.szPassword ~= nil and GlobalUserItem.szPassword ~= "" then
self.edit_Password:setText(GlobalUserItem.szPassword)
else
self.edit_Password:setPlaceHolder("请输入您的游戏密码")
end
end
function LogonView:onButtonClickedEvent(tag,ref)
if tag == LogonView.BT_REGISTER then
GlobalUserItem.bVisitor = false
self:getParent():getParent():onShowRegister()
elseif tag == LogonView.BT_VISITOR then
GlobalUserItem.bVisitor = true
self:getParent():getParent():onVisitor()
elseif tag == LogonView.BT_LOGON then
GlobalUserItem.bVisitor = false
local szAccount = string.gsub(self.edit_Account:getText(), " ", "")
local szPassword = string.gsub(self.edit_Password:getText(), " ", "")
local bAuto = self:getChildByTag(LogonView.CBT_RECORD):isSelected()
local bSave = self:getChildByTag(LogonView.CBT_RECORD):isSelected()
self:getParent():getParent():onLogon(szAccount,szPassword,bSave,bAuto)
elseif tag == LogonView.BT_THIRDPARTY then
self.m_spThirdParty:setVisible(true)
elseif tag == LogonView.BT_WECHAT then
--平台判定
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) or (cc.PLATFORM_OS_ANDROID == targetPlatform) then
self:getParent():getParent():thirdPartyLogin(yl.ThirdParty.WECHAT)
else
showToast(self, "不支持的登录平台 ==> " .. targetPlatform, 2)
end
elseif tag == LogonView.BT_FGPW then
MultiPlatform:getInstance():openBrowser(yl.HTTP_URL .. "/Mobile/RetrievePassword.aspx")
end
end
function LogonView:onTouchBegan(touch, event)
return self:isVisible()
end
function LogonView:onTouchEnded(touch, event)
local pos = touch:getLocation();
local m_spBg = self.m_spThirdParty
pos = m_spBg:convertToNodeSpace(pos)
local rec = cc.rect(0, 0, m_spBg:getContentSize().width, m_spBg:getContentSize().height)
if false == cc.rectContainsPoint(rec, pos) then
self.m_spThirdParty:setVisible(false)
end
end
return LogonView |
--GPU: Window and canvas creation.
--luacheck: push ignore 211
local Config, GPU, yGPU, GPUVars, DevKit = ...
--luacheck: pop
local events = require("Engine.events")
local RenderVars = GPUVars.Render
local WindowVars = GPUVars.Window
--==Localized Lua Library==--
local mathFloor = math.floor
--==Local Variables==--
local CPUKit = Config.CPUKit
local _Mobile = love.system.getOS() == "Android" or love.system.getOS() == "iOS" or Config._Mobile
local _ZYX_W, _ZYX_H = Config._ZYX_W or 192, Config._ZYX_H or 128 --ZYX-13 screen dimensions.
WindowVars.ZYX_X, WindowVars.ZYX_Y = 0,0 --ZYX-13 screen padding in the HOST screen.
local _PixelPerfect = Config._PixelPerfect --If the ZYX-13 screen must be scaled pixel perfect.
WindowVars.ZYXScale = mathFloor(Config._ZYXScale or 3) --The ZYX13 screen scale to the host screen scale.
WindowVars.Width, WindowVars.Height = _ZYX_W*WindowVars.ZYXScale, _ZYX_H*WindowVars.ZYXScale --The host window size.
if _Mobile then WindowVars.Width, WindowVars.Height = 0,0 end
--==Window creation==--
if not love.window.isOpen() then
love.window.setMode(WindowVars.Width,WindowVars.Height,{
vsync = 1,
resizable = true,
minwidth = _ZYX_W,
minheight = _ZYX_H
})
if Config.title then
love.window.setTitle(Config.title)
else
love.window.setTitle("ZYX-13 ".._ZVERSION)
end
love.window.setIcon(love.image.newImageData("icon.png"))
end
--Incase if the host operating system decided to give us different window dimensions.
WindowVars.Width, WindowVars.Height = love.graphics.getDimensions()
--==Window termination==--
events.register("love:quit", function()
if love.window.isOpen() then
love.graphics.setCanvas()
love.window.close()
end
return false
end)
--==Window Events==--
--Hook the resize function
events.register("love:resize",function(w,h) --Do some calculations
WindowVars.Width, WindowVars.Height = w, h
local TSX, TSY = w/_ZYX_W, h/_ZYX_H --TestScaleX, TestScaleY
WindowVars.ZYXScale = (TSX < TSY) and TSX or TSY
if _PixelPerfect then WindowVars.ZYXScale = mathFloor(WindowVars.ZYXScale) end
WindowVars.ZYX_X, WindowVars.ZYX_Y = (WindowVars.Width-_ZYX_W*WindowVars.ZYXScale)/2, (WindowVars.Height-_ZYX_H*WindowVars.ZYXScale)/2
if _Mobile then WindowVars.ZYX_Y, RenderVars.AlwaysDrawTimer = 0, 1 end
RenderVars.ShouldDraw = true
end)
--Hook to some functions to redraw (when the window is moved, got focus, etc ...)
events.register("love:focus",function(f) if f then RenderVars.ShouldDraw = true end end) --Window got focus.
events.register("love:visible",function(v) if v then RenderVars.ShouldDraw = true end end) --Window got visible.
--File drop hook
events.register("love:filedropped", function(file)
file:open("r")
local data = file:read()
file:close()
if CPUKit then CPUKit.triggerEvent("filedropped",file:getFilename(),data) end
end)
--Alt-Return (Fullscreen toggle) hook
local raltDown, lastWidth, lastHeight = false, 0, 0
events.register("love:keypressed", function(key, scancode,isrepeat)
if key == "ralt" then
raltDown = true --Had to use a workaround, for some reason isDown("ralt") is not working at Rami's laptop
elseif key == "return" and raltDown and not isrepeat then
local screenshot = GPU.screenshot():image()
local canvas = love.graphics.getCanvas() --Backup the canvas.
love.graphics.setCanvas() --Deactivate the canvas.
if love.window.getFullscreen() then --Go windowed
love.window.setMode(lastWidth,lastHeight,{
fullscreen = false,
vsync = 1,
resizable = true,
minwidth = _ZYX_W,
minheight = _ZYX_H
})
else --Go fullscreen
lastWidth, lastHeight = love.window.getMode()
love.window.setMode(0,0,{fullscreen=true})
end
events.trigger("love:resize", love.graphics.getDimensions()) --Make sure the canvas is scaled correctly
love.graphics.setCanvas{canvas,stencil=true} --Reactivate the canvas.
screenshot:draw() --Restore the backed up screenshot
end
end)
events.register("love:keyreleased", function(key, scancode)
if key == "ralt" then raltDown = false end
end)
--==Graphics Initializations==--
love.graphics.clear(0,0,0,1) --Clear the host screen.
events.trigger("love:resize", WindowVars.Width, WindowVars.Height) --Calculate ZYX13 scale to the host window for the first time.
--==GPU Window API==--
function GPU.screenSize() return _ZYX_W, _ZYX_H end
function GPU.screenWidth() return _ZYX_W end
function GPU.screenHeight() return _ZYX_H end
--==Helper functions for WindowVars==--
function WindowVars.HostToZyx(x,y) --Convert a position from HOST screen to ZYX13 screen.
return mathFloor((x - WindowVars.ZYX_X)/WindowVars.ZYXScale), mathFloor((y - WindowVars.ZYX_Y)/WindowVars.ZYXScale)
end
function WindowVars.ZyxToHost(x,y) --Convert a position from ZYX13 screen to HOST
return mathFloor(x*WindowVars.ZYXScale + WindowVars.ZYX_X), mathFloor(y*WindowVars.ZYXScale + WindowVars.ZYX_Y)
end
--==GPUVars Exports==--
WindowVars.ZYX_W, WindowVars.ZYX_H = _ZYX_W, _ZYX_H
--==DevKit Exports==--
DevKit._ZYX_W = _ZYX_W
DevKit._ZYX_H = _ZYX_H
function DevKit.DevKitDraw(bool)
RenderVars.DevKitDraw = bool
end |
r3 = Creature:new {
objectName = "@mob/creature_names:r3",
randomNameType = NAME_R3,
socialGroup = "townsperson",
faction = "townsperson",
level = 4,
chanceHit = 0.24,
damageMin = 40,
damageMax = 45,
baseXp = 62,
baseHAM = 113,
baseHAMmax = 138,
armor = 0,
resists = {15,15,15,15,15,15,15,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = NONE,
creatureBitmask = HERD,
optionsBitmask = AIENABLED,
diet = HERBIVORE,
templates = {
"object/mobile/r3.iff"
},
hues = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63 },
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {}
}
CreatureTemplates:addCreatureTemplate(r3, "r3")
|
local core = assert(l2df, 'L2DF is not available')
local data = assert(data, 'Shared data is not available')
-- UTILS
local utf8 = require 'utf8'
local cfg = core.import 'config'
-- COMPONENTS
local Camera = core.import 'class.component.camera'
local Collision = core.import 'class.component.collision'
local Controller = core.import 'class.component.controller'
local CharAttributes = require 'data.scripts.component.attributes'
-- MANAGERS
local Input = core.import 'manager.input'
local Factory = l2df.import 'manager.factory'
local SceneManager = core.import 'manager.scene'
-- VARIABLES
local function dummyFunc() end
local function enableNode(self) self.node.active = true end
local function disableNode(self) self.node.active = false end
local function defaultAction(self, action, ...) (self.node[action] or dummyFunc)(self.node, ...) end
local Room, RoomData = data.layout('layout/lobby.dat')
local function wrapButton(btn)
if btn.name ~= 'button' then return end
btn.nodes:first():addComponent(Collision)
btn:onChange(function (btn)
if btn.data.state == 1 then
btn.nodes:first().C.frames.set('idle')
elseif btn.data.state == 2 or btn.data.state == 3 then
btn.nodes:first().C.frames.set('hover')
elseif btn.data.state == 4 then
btn.nodes:first().C.frames.set('click')
end
end)
end
-- SELECTION CONSTRUCTION
local AFCOUNT = #RoomData.template.nodes[1].frames
local SELECTION = Room.R.SELECTION()
for y = 0, 1 do
for x = 0, 3 do
local key = ('T%s_%s'):format(x + 1, y + 1)
local group = Factory:create('group', RoomData.template, key)
group.data.x = 153 * x
group.data.y = 211 * y
SELECTION:attach(group)
end
end
local TEAMS = { 'Independent', 'Team 1', 'Team 2', 'Team 3', 'Team 4' }
local function getGroup(player)
local y = 1
if player > Input.localplayers then
y = 2
player = player - Input.localplayers
end
return SELECTION.R[('T%s_%s'):format(player, y)]
end
-- BUTTON BINDINGS
local Menu = Room.R.MENU()
Menu.R.BTN_FIGHT:onClick(function ()
local chars = { }
for i = 1, #Room.data.ready_players do
local player = Room.data.ready_players[i]
local chardata = data.chardata:getById(getGroup(player).data.index)
chars[i] = Factory:create('object', chardata)
chars[i]:addComponent(Controller, player)
chars[i]:addComponent(CharAttributes, chardata)
chars[i]:addComponent(Camera, { kx = 128, ky = 128 })
end
SceneManager:push('battle', chars)
end)
Menu.R.BTN_RESET_ALL:onClick(function () Room:enter() end)
Menu.R.BTN_RESET_RANDOM:onClick(function () Room:randomize() end)
Menu.R.BTN_EXIT:onClick(function () SceneManager:pop() end)
for _, btn in Menu.nodes:enum(true) do
wrapButton(btn)
end
function Room:randomize()
local randoms = self.data.random
if data.chardata.count == 0 or #randoms == 0 then return end
for i = 1, #randoms do
local charid = math.random(1, data.chardata.count)
randoms[i].data.index = charid
randoms[i].R.AVATAR.C.frames.set(AFCOUNT + charid)
randoms[i].R.FIGHTER.data.text = randoms[i].R.AVATAR.data.frame.fighter
end
end
function Room:enable()
self.active = true
end
function Room:disable()
self.active = false
end
function Room:enter()
Menu.active = false
self.data.counting = false
self.data.random = { }
self.data.active_players = 0
self.data.ready_players = { }
for _, group in SELECTION.nodes:enum() do
local avatar = group.R.AVATAR()
if #avatar.C.frames.data().list - AFCOUNT < data.chardata.count then
for i, char in data.chardata:enum() do
avatar.C.frames.add({
pic = AFCOUNT + i - 1,
fighter = char.name,
next = AFCOUNT + i,
wait = 1000
}, AFCOUNT + i)
avatar.C.render.addSprite({ char.head })
end
end
group.R.AVATAR.C.frames.set(1)
group.R.PLAYER.C.frames.set(1)
group.R.FIGHTER.C.frames.set(1)
group.R.TEAM.C.frames.set(1)
group.R.PLAYER.data.hidden = false
group.R.PLAYER.data.text = 'Join?'
group.R.FIGHTER.data.hidden = true
group.R.FIGHTER.data.text = 'Random'
group.R.TEAM.data.hidden = true
group.R.TEAM.data.text = TEAMS[1]
group.R.TEAM.data.team = 0
group.data.index = 0
group.data.ST = 0
end
end
function Room:update()
if SceneManager:current() ~= self then return end
if Menu.active then
if Input:consume('up') then
Menu:prev()
end
if Input:consume('down') then
Menu:next()
end
if Input:consume('attack') then
Menu:choice()
end
return
end
local _, left = Input:consume('left')
local _, right = Input:consume('right')
local _, atk = Input:consume('attack')
local _, jmp = Input:consume('jump')
if atk then
local group = getGroup(atk)
if group.data.ST < 3 then
if group.data.ST == 2 then
group.TEAM.C.frames.set('idle')
self.data.ready_players[#self.data.ready_players + 1] = atk
elseif group.data.ST == 1 then
group.FIGHTER.C.frames.set('idle')
group.TEAM.data.hidden = false
else
group.AVATAR.C.frames.set('random')
group.PLAYER.C.frames.set('idle')
group.PLAYER.data.text = data.players[atk]
group.FIGHTER.data.hidden = false
self.data.active_players = self.data.active_players + 1
if self.data.counting then
self.data.counting = false
for _, group in SELECTION.nodes:enum() do
local frameid = group.R.AVATAR.data.frame.id
if 2 < frameid and frameid < 8 then
group.R.AVATAR.C.frames.set('join')
end
end
end
end
group.data.ST = group.data.ST + 1
end
end
if jmp then
local group = getGroup(jmp)
if group.data.ST > 0 and not self.data.counting then
if group.data.ST == 1 then
group.AVATAR.C.frames.set('join')
group.PLAYER.C.frames.set('flicker')
group.PLAYER.data.text = 'Join?'
group.FIGHTER.data.hidden = true
self.data.active_players = self.data.active_players - 1
elseif group.data.ST == 2 then
group.FIGHTER.C.frames.set('flicker')
group.TEAM.data.hidden = true
else
group.TEAM.C.frames.set('flicker')
for i = 1, #self.data.ready_players do
if self.data.ready_players[i] == jmp then
table.remove(self.data.ready_players, i)
break
end
end
end
group.data.ST = group.data.ST - 1
elseif self.data.active_players == 0 then
SceneManager:pop()
end
end
if left or right then
local sign = right and 1 or -1
local group = left and getGroup(left) or getGroup(right)
if group.data.ST == 1 then
group.data.index = (group.data.index + sign) % (data.chardata.count + 1)
group.AVATAR.C.frames.set(AFCOUNT + group.data.index)
group.FIGHTER.data.text = group.AVATAR.data.frame.fighter
elseif group.data.ST == 2 then
group.TEAM.data.team = (group.TEAM.data.team + sign) % #TEAMS
group.TEAM.data.text = TEAMS[group.TEAM.data.team + 1]
end
end
if self.data.active_players > 0 and self.data.active_players == #self.data.ready_players then
for _, group in SELECTION.nodes:enum() do
if group.R.AVATAR.data.frame.id < 3 then
group.R.AVATAR.C.frames.set('count')
self.data.counting = true
end
if group.R.AVATAR.data.frame.id == AFCOUNT - 1 then
group.R.PLAYER.C.frames.set('idle')
group.R.PLAYER.data.text = '—'
Menu.active = true
self.data.counting = false
end
end
end
if Menu.active then
self.data.random = { }
for _, group in SELECTION.nodes:enum() do
if group.R.AVATAR().data.frame.keyword == 'random' then
self.data.random[#self.data.random + 1] = group
end
end
self:randomize()
end
end
return Room |
local intermediatemulti = angelsmods.marathon.intermediatemulti
data:extend(
{
-- Nitinol Plate
{
type = "recipe",
name = "molten-nitinol-remelting",
category = "induction-smelting",
subgroup = "angels-alloys-casting",
-- Original Angel's Smelting does not add an expensive version to casting.
-- Not sure why, is it applied to some other process earlier in production chain?
normal =
{
enabled = "false",
energy_required = 6,
ingredients ={{type="item", name="nitinol-alloy", amount=4}},
results={{type="fluid",name="liquid-molten-nitinol", amount=35}},
},
expensive =
{
enabled = "false",
energy_required = 6,
ingredients ={{type="item", name="nitinol-alloy", amount=5 * intermediatemulti}},
results={{type="fluid",name="liquid-molten-nitinol", amount=40}},
},
icons = {
{
icon = "__angelssmelting__/graphics/icons/molten-nitinol.png",
},
{
icon = "__angelsextended-remelting__/graphics/icons/remelting.png",
tint = {r = 0.8, g = 0.8, b = 0.8, a = 0.5},
scale = 0.32,
shift = {-12, -12},
}
},
icon_size = 32,
order = "g]",
},
-- Molten Nitinol
{
type = "recipe",
name = "molten-nitinol-alloy-mixing-1",
category = "molten-alloy-mixing",
subgroup = "aragas-nitinol-alloy-mixing",
enabled = "false",
energy_required = 4,
ingredients ={
{type="fluid", name="liquid-molten-titanium", amount=240},
{type="fluid", name="liquid-molten-nickel", amount=120},
},
results={{type="fluid", name="liquid-molten-nitinol", amount=360}},
icons = {
{
icon = "__angelssmelting__/graphics/icons/molten-nitinol.png",
},
{
icon = "__angelsextended-remelting__/graphics/icons/remelting.png",
tint = {r = 0.8, g = 0.8, b = 0.8, a = 0.5},
scale = 0.32,
shift = {-12, -12},
}
},
icon_size = 32,
order = "aa",
},
}
) |
local cls = require('uuclass')
local ExecutionSession = require('nvimRepl.execution_session')
local filetype2cmdMapping = {
javascript = 'node';
typescript = 'node';
}
---@param cmd string
---@return string | nil
local function which(cmd) --<
if filetype2cmdMapping[cmd] then cmd = filetype2cmdMapping[cmd] end
local proc = io.popen("which " .. cmd)
local ans = vim.split(proc:read("*a") or "", "\n")[1]
if #ans == 0 then ans = nil end
return ans
end -->
---@class ExternalExecutionSession: ExecutionSession
---@field private config table
---@field private filetype string
---@field private stdin any
---@field private handle any
---@field private pid any
---@field private closed boolean
local ExternalExecutionSession = cls.Extend(ExecutionSession)
---@param ftype string filetype
---@param config table configuration
---@return ExternalExecutionSession
function ExternalExecutionSession.new(ftype, config) --<
local obj = {}
ExternalExecutionSession.construct(obj)
ExecutionSession.init(obj, ftype, config)
obj.filetype = ftype
obj.config = config
obj.config.cmdpath = obj.config.cmdpath or which(obj.config.cmd or ftype)
if not obj.config.lazy then obj:_start() end
return obj
end -->
function ExternalExecutionSession:_start() --<
local uv = vim.loop
local stdin = uv.new_pipe(true)
local stdout = uv.new_pipe(true)
local stderr = uv.new_pipe(true)
self.stdin = stdin
local handle,pid = uv.spawn(self.config.cmdpath, {
stdio = {stdin, stdout, stderr};
args = self.config.args or { "-i" };
env = self.config.env;
}, vim.schedule_wrap(function(code, _)
self.buffer:hint(string.format("(%s) process %d exit with %d", self.filetype, self.pid, code), code ~= 0)
end))
self.handle = handle
self.pid = pid
uv.read_start(stdout, vim.schedule_wrap(function(err, data)
if err then
self.buffer:stderr(err)
self:_close()
return
end
if data then
if self.config.stdoutSanitizer then
local sout, serr = self.config.stdoutSanitizer(data)
if sout then self.buffer:stdout(sout) end
if serr then self.buffer:stderr(serr) end
else
self.buffer:stdout(data)
end
else
self:_close()
end
end))
uv.read_start(stderr, vim.schedule_wrap(function(err, data)
if err then
self.buffer:stderr(err)
self:_close()
return
end
if data then
if self.config.stderrSanitizer then
local sout, serr = self.config.stderrSanitizer(data)
if sout then self.buffer:stdout(sout) end
if serr then self.buffer:stderr(serr) end
else
self.buffer:stderr(data)
end
else
self:_close()
end
end))
end -->
function ExternalExecutionSession:_close() --<
if self.closed then return end
self.closed = true
if not self.handle then return end
local handle = self.handle
vim.loop.shutdown(self.stdin, vim.schedule_wrap(function() vim.loop.close(handle) end))
self.stdin = nil
self.handle = nil
end -->
function ExternalExecutionSession:isValid() --<
return not self.closed
end -->
function ExternalExecutionSession:close() --<
self:_close()
end -->
---@param codes string | string[]
function ExternalExecutionSession:send(codes) --<
self.buffer:code(codes)
if not self.handle then self:_start() end
if type(codes) == type({}) then
codes = table.concat(codes, '\n')
end
if not string.match(codes, "^%s*\n") then
codes = '\n' .. codes
end
if not string.match(codes, ".*\n%s*$") then
codes = codes .. '\n'
end
vim.loop.write(self.stdin, codes)
end -->
return ExternalExecutionSession
|
local hi = vim.highlight.create
vim.cmd "syntax enable"
vim.o.background = "dark"
vim.cmd "colorscheme delek"
hi("TabLineFill", {ctermfg="None", ctermbg="None", cterm="None"}, false)
hi("TabLine", {ctermfg="Grey", ctermbg="None", cterm="None"}, false)
hi("TabLineSel", {ctermfg="White", ctermbg="None", cterm="None"}, false)
hi("StatusLine", {ctermfg="None", ctermbg="None", cterm="None"}, false)
hi("StatusLineNC", {ctermfg="Yellow", ctermbg="None", cterm="None"}, false)
hi("LineNr", {ctermfg="Yellow", ctermbg="None", cterm="None"}, false)
hi("SignColumn", {ctermfg="White", ctermbg="None", cterm="None"}, false)
hi("VertSplit", {ctermfg="Yellow", ctermbg="None", cterm="None"}, false)
hi("Pmenu", {ctermfg="None", ctermbg="Black", cterm="None"}, false)
hi("Error", {ctermfg="Red"}, false)
hi("NonText", {ctermfg="Black", ctermbg="None", cterm="None"}, false)
hi("Todo", {ctermfg="Black", ctermbg="Red", cterm="None"}, false)
|
-- All the deity anger functions. Contains a common function with key
-- "__default__" (so, this can't be used as a deity ID) which will be
-- called if the lookup for the given deity ID fails.
deity_anger_fns = {}
-- Blue-bolt the worthless!
local function deity_anger_blast(creature_id, deity_id)
set_creature_current_hp(creature_id, 1)
set_creature_current_ap(creature_id, 1)
add_message("DEITY_ACTION_DISPLEASED_BLUE_LIGHTNING")
end
-- Curse the equipment of the irritating!
local function deity_anger_curse(creature_id, deity_id)
curse_equipment(creature_id)
add_message("DEITY_ACTION_DISPLEASED_CURSE_EQUIPMENT")
end
-- Destroy the items of the impious!
local function deity_anger_destroy_items(creature_id, deity_id)
destroy_creature_equipment(creature_id)
destroy_creature_inventory(creature_id)
add_message("DEITY_ACTION_DISPLEASED_DESTROY_ITEMS")
end
-- Summon a bunch of nasties!
local function deity_anger_summon_creatures(creature_id, deity_id)
local monsters = get_deity_summons(deity_id)
local override_hostility = true
summon_monsters_around_creature(monsters, creature_id, 3, override_hostility, deity_id)
add_message("DEITY_ACTION_DISPLEASED_SUMMON")
end
-- Handle deity anger, generally as a result of praying when the
-- deity dislikes you.
function deity_anger_default(creature_id, deity_id, is_world_map)
-- Equal chance of blue-bolting, equipment destruction, or nasties.
local deity_actions = {deity_anger_blast, deity_anger_curse, deity_anger_destroy_items}
if (is_world_map == false) then
table.insert(deity_actions, deity_anger_summon_creatures)
end
local val = RNG_range(1, table.getn(deity_actions))
local action_fn = deity_actions[val]
action_fn(creature_id, deity_id)
end
-- Attempts to look up the anger function, given the deity ID, and then
-- call it. If there was no anger function found for the given deity ID,
-- then try the default.
function anger(creature_id, deity_id, is_world_map)
local deity_fn = deity_anger_fns[deity_id]
if deity_fn == nil then
deity_fn = deity_anger_default
end
-- Call the anger function.
deity_fn(creature_id, deity_id, is_world_map)
end
|
-- add lucky blocks
if minetest.get_modpath("lucky_block") then
lucky_block:add_blocks({
{"dro", {"farming:corn"}, 5},
{"dro", {"farming:coffee_cup_hot"}, 1},
{"dro", {"farming:bread"}, 5},
{"nod", "farming:jackolantern", 0},
{"tro", "farming:jackolantern_on"},
{"nod", "default:river_water_source", 1},
{"tel"},
{"dro", {"farming:trellis", "farming:grapes"}, 5},
{"dro", {"farming:bottle_ethanol"}, 1},
{"nod", "farming:melon", 0},
{"dro", {"farming:donut", "farming:donut_chocolate", "farming:donut_apple"}, 5},
{"dro", {"farming:hemp_leaf", "farming:hemp_fibre", "farming:seed_hemp"}, 5},
{"nod", "fire:permanent_flame", 1},
{"dro", {"farming:chili_pepper", "farming:chili_bowl"}, 5},
{"dro", {"farming:bowl"}, 3},
{"dro", {"farming:saucepan"}, 1},
{"dro", {"farming:pot"}, 1},
{"dro", {"farming:baking_tray"}, 1},
{"dro", {"farming:skillet"}, 1},
{"exp", 4},
{"dro", {"farming:mortar_pestle"}, 1},
{"dro", {"farming:cutting_board"}, 1},
{"dro", {"farming:juicer"}, 1},
{"dro", {"farming:mixing_bowl"}, 1},
{"dro", {"farming:hoe_bronze"}, 1},
{"dro", {"farming:hoe_mese"}, 1},
{"dro", {"farming:hoe_diamond"}, 1},
{"dro", {"farming:hoe_bomb"}, 10},
{"dro", {"farming:turkish_delight"}, 5},
{"lig"},
})
end
|
LobbyBadgeIcon = {
NONE = 0,
ACTIVE_HEADSET = 47,
INACTIVE_HEADSET = 48,
MUTED_HEADSET = 49,
GTAV = 54,
WORLD = 63,
KICK = 64,
RANK_FREEMODE = 65,
SPECTATOR = 66,
IS_CONSOLE_PLAYER = 119,
IS_PC_PLAYER = 120
}
|
-- Copyright 2013 mokasin
-- This file is part of the Awesome Pulseaudio Widget (APW).
--
-- APW is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- APW is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with APW. If not, see <http://www.gnu.org/licenses/>.
-- Simple pulseaudio command bindings for Lua.
local pulseaudio = {}
local cmd = "pacmd"
local default_sink = ""
function pulseaudio:Create()
local o = {}
setmetatable(o, self)
self.__index = self
o.Volume = 0 -- volume of default sink
o.Mute = false -- state of the mute flag of the default sink
-- retrieve current state from pulseaudio
pulseaudio.UpdateState(o)
return o
end
function pulseaudio:UpdateState()
local f = io.popen(cmd .. " dump")
-- if the cmd cannot be found
if f == nil then
return false
end
local out = f:read("*a")
f:close()
-- find default sink
default_sink = string.match(out, "set%-default%-sink ([^\n]+)")
if default_sink == nil then
default_sink = ""
return false
end
-- retrieve volume of default sink
for sink, value in string.gmatch(out, "set%-sink%-volume ([^%s]+) (0x%x+)") do
if sink == default_sink then
self.Volume = tonumber(value) / 0x10000
end
end
-- retrieve mute state of default sink
local m
for sink, value in string.gmatch(out, "set%-sink%-mute ([^%s]+) (%a+)") do
if sink == default_sink then
m = value
end
end
self.Mute = m == "yes"
end
-- Run process and wait for it to end
local function run(command)
local p = io.popen(command)
p:read("*a")
p:close()
end
-- Sets the volume of the default sink to vol from 0 to 1.
function pulseaudio:SetVolume(vol)
if vol > 1 then
vol = 1
end
if vol < 0 then
vol = 0
end
vol = vol * 0x10000
-- set…
run(cmd .. " set-sink-volume " .. default_sink .. " " .. string.format("0x%x", math.floor(vol)))
-- …and update values
self:UpdateState()
end
-- Toggles the mute flag of the default default_sink.
function pulseaudio:ToggleMute()
if self.Mute then
run(cmd .. " set-sink-mute " .. default_sink .. " 0")
else
run(cmd .. " set-sink-mute " .. default_sink .. " 1")
end
-- …and updates values.
self:UpdateState()
end
return pulseaudio
|
local sprite = app.activeSprite
local dlg = Dialog()
--- @param f FILE*
--- @param tag any
local function export_animation_tag(f, tag)
local fps = 10
local animation_type = "PLAYBACK_LOOP_FORWARD"
if tag.aniDir == AniDir.FORWARD then
animation_type = "PLAYBACK_LOOP_FORWARD"
elseif tag.aniDir == AniDir.REVERSE then
animation_type = "PLAYBACK_LOOP_BACKWARD"
elseif tag.aniDir == AniDir.PING_PONG then
animation_type = "PLAYBACK_LOOP_PINGPONG"
end
f:write("animations {\n")
f:write(" id: \""..tag.name.."\"\n")
f:write(" start_tile: "..tostring(tag.fromFrame.frameNumber).."\n")
f:write(" end_tile: "..tostring(tag.toFrame.frameNumber).."\n")
f:write(" playback: "..animation_type.."\n")
f:write(" fps: "..tostring(fps).."\n")
f:write(" flip_horizontal: 0\n")
f:write(" flip_vertical: 0\n")
f:write("}\n")
end
--- @param f FILE*
local function export_header(f, sprite, image)
f:write("image: \""..image.."\"\n")
f:write("tile_width: "..tostring(sprite.width).."\n")
f:write("tile_height: "..tostring(sprite.height).."\n")
f:write("tile_margin: 0\n")
f:write("tile_spacing: 0\n")
f:write("collision: \"\"\n")
f:write("material_tag: \"tile\"\n")
f:write("collision_groups: \"default\"\n")
end
--- @param f FILE*
local function export_footer(f)
f:write("extrude_borders: 2\n")
f:write("inner_padding: 0\n")
end
local function load_image_file(tilesource)
local f=io.open(tilesource, "r")
local image = ""
if f ~= nil then
local ls = f:read("l")
image = string.match(ls, " ?image ?: ?\"(.*)\"")
app.alert(image)
f:close(f)
end
return image
end
local function export(data, sprite)
local image = load_image_file(data.export_file)
local f = io.open(data.export_file, "w")
export_header(f, sprite, image)
for id, tag in ipairs(sprite.tags) do
export_animation_tag(f, tag)
end
export_footer(f)
f:close()
end
dlg:file{ id="export_file",
label="export file(tilesource)",
title="export file(tilesource)",
save=true,
filetypes={ "tilesource" },
onchange=nil }
dlg:button{ text="Export",
onclick=function()
local data = dlg.data
export(data, sprite)
dlg:close()
end }
dlg:button{ text="Close",
onclick=function()
dlg:close()
end }
dlg:show{ wait=true }
|
local uv = require"lluv"
local WS = require"websocket.client_lluv"
local cli = WS() do
cli:on_open(function(ws)
print("Connected")
end)
cli:on_error(function(ws, err)
print("Error:", err)
end)
cli:on_message(function(ws, msg, code)
if math.mod(tonumber(msg), 60) == 0 then
print("Message:", msg)
end
end)
cli:connect("ws://127.0.0.1:12345", "dumb-increment-protocol")
end
local cli = WS() do
local timer = uv.timer():start(0, 5000, function()
cli:send("ECHO")
end):stop()
cli:on_open(function(ws)
print("Connected")
timer:again()
end)
cli:on_error(function(ws, err)
print("Error:", err)
end)
cli:on_message(function(ws, msg, code)
print("Message:", msg)
end)
cli:connect("ws://127.0.0.1:12345", "lws-mirror-protocol")
end
uv.run()
|
local VK = require('./vk')
local Queue = require('./queue')
local APIWrapper = require('./api_wrapper')
local function API(options)
if type(options) == 'string' or not options.token then
options = {token = options}
end
local vk = VK(options.token, options.version)
if options.queued then
vk = Queue(vk)
end
return APIWrapper(vk)
end
-- TO DO: access to logger settings
return {
VK = VK,
Queue = Queue,
APIWrapper = APIWrapper,
API = API,
Router = require('./router'),
LongPoll = require('./longpoll'),
Bot = require('./bot'),
Keyboard = require('./keyboard')
}
|
return function(config, makeImmutable)
config.tiers = {}
config.tiers[0] = {
throughput = 0,
efficiency = 0,
}
config.tiers[1] = {
throughput = 15000,
efficiency = 0.10,
cost_multiplier = 100,
cost = {
{"science-pack-1", 1},
{"science-pack-2", 1},
},
prerequisites = {"battery-equipment"},
effects = {
{
type = "unlock-recipe",
recipe = "induction-coil",
},
},
}
config.tiers[2] = {
throughput = 30000,
efficiency = 0.20,
cost_multiplier = 200,
cost = {
{"science-pack-1", 1},
{"science-pack-2", 1},
{"science-pack-3", 1},
},
prerequisites = {"battery-mk2-equipment"},
effects = {},
}
config.tiers[3] = {
throughput = 60000,
efficiency = 0.30,
cost_multiplier = 300,
cost = {
{"science-pack-1", 1},
{"science-pack-2", 1},
{"science-pack-3", 1},
{"production-science-pack", 1},
},
prerequisites = {},
effects = {},
}
config.tiers[4] = {
throughput = 120000,
efficiency = 0.40,
cost_multiplier = 1000,
cost = {
{"science-pack-1", 1},
{"science-pack-2", 1},
{"science-pack-3", 1},
{"production-science-pack", 1},
{"high-tech-science-pack", 1},
},
prerequisites = {},
effects = {},
}
config.tiers[5] = {
throughput = 240000,
efficiency = 0.50,
cost_multiplier = 2000,
cost = {
{"science-pack-1", 1},
{"science-pack-2", 1},
{"science-pack-3", 1},
{"production-science-pack", 1},
{"high-tech-science-pack", 1},
{"space-science-pack", 1},
},
prerequisites = {},
effects = {},
}
-- Add tiers to table by string whilst also making them immutable
config.technologies = {}
for num, tier in pairs(config.tiers) do
local new = makeImmutable(tier)
config.tiers[num] = new
config.technologies['induction' .. tostring(num)] = new
end
end |
require("hs.spoons").use('Caffeine',
{
hotkeys = {
toggle = { {'ctrl', 'alt'}, 'c' }
},
start = true,
}
)
return spoon.Caffeine
-- -- variation on https://gist.github.com/heptal/50998f66de5aba955c00
--
-- local ampOnIcon = [[ASCII:
-- .....1a..........AC..........E
-- ..............................
-- ......4.......................
-- 1..........aA..........CE.....
-- e.2......4.3...........h......
-- ..............................
-- ..............................
-- .......................h......
-- e.2......6.3..........t..q....
-- 5..........c..........s.......
-- ......6..................q....
-- ......................s..t....
-- .....5c.......................
-- ]]
--
-- local ampOffIcon = [[ASCII:
-- .....1a.....x....AC.y.......zE
-- ..............................
-- ......4.......................
-- 1..........aA..........CE.....
-- e.2......4.3...........h......
-- ..............................
-- ..............................
-- .......................h......
-- e.2......6.3..........t..q....
-- 5..........c..........s.......
-- ......6..................q....
-- ......................s..t....
-- ...x.5c....y.......z..........
-- ]]
--
-- -- caffeine replacement
-- -- local menubar = require"hs.menubar"
-- local menubar = require"hs._asm.guitk.menubar"
-- local caffeinate = require"hs.caffeinate"
--
-- local module = {}
--
-- local function setIcon(state)
-- module.menu:setIcon(state and ampOnIcon or ampOffIcon)
-- end
--
-- module.menu = menubar.new()
-- module.menu:setClickCallback(function() setIcon(caffeinate.toggle("displayIdle")) end)
-- setIcon(caffeinate.get("displayIdle"))
--
-- return module
|
--- ihelp.lua (c) Dirk Laurie 2013, Lua-style MIT license
-- Lua interactive help.
--
-- To get started:
--
-- $ lua -e "help = require'ihelp'"
-- help()
do
local getinfo, open, insert, concat, sort =
debug.getinfo, io.open, table.insert, table.concat, table.sort
local pairs, select, type = pairs, select, type
local utf8len, offset = utf8 and utf8.len, utf8 and utf8.offset
if not offset then offset = function(...) return ... end end
-- sample shorthelp and longhelp
local shorthelp = [[
The following functions are provided:
help
Try `help"topic"`, e.g. help"all", or `help(function)`, e.g. `help(help)`.
]]
local longhelp = {
method = [[
`debug.getinfo(fct).source` contains the Lua source code of `fct`,
or the name of the file from which it was loaded, or the information
that it is precompiled C code. If the actual source is available,
a docstring (see `help"docstring"`) is extracted.
]],
bugs = [[
If the source code is read from a file that you are editing, the
version from which the docstring is extracted may be more recent
than the version you have loaded.
]],
docstring = [[
--- The docstring of a function
-- A comment block from the Lua code of a function, formatted in LDoc
-- style, like this block. The comments may come immediately before the
-- first line of the function or anywhere inside it. All comments must
-- start at position 1 of their lines and the first comment must start
-- with at least three hyphens. For a very short function, the whole
-- code is used as the docstring.
--
-- Not available for functions defined from the terminal while running
-- the standalone Lua interpreter.
]],
customize = [[
After `help(arg,msg)`, where `arg` is nil or any string except `all`,
the message you get when typing `help(arg)` will be `msg`.
]]
}
local helpless = "No help available, try help(%s)."
--
------------------ no changes needed after this line ------------------
local docstring_pattern = "(\n%-%-%-.-\n)[^%-]"
local starts_with_two_hyphens = "^%-%-"
local starts_with_three_hyphens = "^%-%-%-"
local only_hyphens_at_least_three = "^%-%-(%-)+$"
local nohelp = "No help available"
local code={}
local shortenough = 12 -- number of lines in longest self-documenting routine
local docstring = function(fct)
--- docstring(fct)
-- Extracts an LDoc-styled comment block from the Lua code of a function,
-- for example this block. The comments may come immediately before the
-- first line of the function or anywhere inside it. All comments must
-- start at position 1 of their lines and the first comment must start
-- with at least three hyphens.
local getinfo = debug.getinfo
local helptext
if getinfo and getinfo(fct) then
local info=getinfo(fct)
local source=info.source
helptext = source:match(docstring_pattern)
if not helptext then
if source:match"%=%[C%]" then return "Precompiled C function"
elseif source:match"%=stdin" then return "Defined above"
elseif source:match'%@(.+)' then -- source filename provided
local filename=source:match'%@(.+)'
local sourcefile = io.open(filename)
if not code[filename] then -- memoize source code
local c={}
for k in sourcefile:lines() do c[#c+1]=k end
code[filename]=c
end
local fcode=code[filename]
helptext={}
local start, stop = info.linedefined, info.lastlinedefined
local k=start-1 -- first try the preceding comment block
while fcode[k]:match(starts_with_two_hyphens) do
if fcode[k]:match(only_hyphens_at_least_three) then break end
insert(helptext,1,fcode[k])
if fcode[k]:match(starts_with_three_hyphens) then break end
k=k-1
if k==0 then break end
end
if #helptext>0 then helptext=concat(helptext,'\n')
else -- try function body
for k=start,stop do
helptext[#helptext+1] = fcode[k]
end
fcode = helptext
if #helptext>0 then
helptext=concat(helptext,'\n')
helptext = helptext and helptext:match(docstring_pattern)
else helptext=nil
end
-- last resort: full code if it is short enough
if not helptext and (#fcode<=shortenough) then
helptext=concat(fcode,'\n')
end
end
end
end
end
return helptext
end
-- assumes validity of UTF8 encoding
local utflen = utf8len or
function (s) return #s:gsub("[\192-\239][\128-\191]*",'.') end
local fold
fold = function(s)
--- Primitive word-wrap function.
if utflen(s)<=72 then return s end
local n=72
local l
while n>60 do n=n-1
l=offset(s,n)
if s:find("^%s",l) then break end
end
return s:sub(1,l-1)..'\n '..fold(s:sub(l+1))
end
local topics = function (tbl,prefix)
local t={}
for k in pairs(tbl) do if type(k)=='string' then
t[#t+1]=(prefix or '')..k
end end
sort(t)
return concat(t,' ')
end
local help = function(fct,...)
--- help(), help(arg), help(arg1,arg2)
-- help(): Prints short help.
-- help(function): Prints the docstring of `arg`, if any.
-- help(table): Prints `help` field, if any; else contents.
-- help(string): Prints help on the topic, if any.
-- help"all": Prints available topics.
-- help(topic,false): Removes topic from "all"
-- help(arg1,"newhelp"): Redefines what you will get from `help(arg1)`
-- help(arg1,0), help(arg1,nil) (or any second argument except `false`
-- or a string): don't print help, return it as a string instead
if select('#',...)>1 then
print('Too many arguments: try `help(help)`'); return
end
local helptext
local redefine = select('#',...)==1 and type(select(1,...))=='string'
local kill = select(1,...)==false
local printme = select('#',...)==0
if kill then longhelp[fct]=nil
elseif fct==nil then
if redefine then shorthelp=... else helptext=shorthelp end
elseif fct=='all' then
if redefine then print"help cannot be redefined for 'all'"; return
else helptext='Help available via `help"topic"` on these topics:\n '..
fold(topics(longhelp))
end
elseif redefine then longhelp[fct]=...
elseif longhelp[fct] then helptext=longhelp[fct]
elseif type(fct)=="table" then
if type(fct.help)=='string' then helptext=fct.help
else helptext=fold("Contents: "..topics(fct))
end
elseif type(fct)=='function' then helptext=docstring(fct) or nohelp
else print(helpless:format(fct)); return
end
if printme then print(helptext) else return helptext end
end
return help
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.