content
stringlengths 5
1.05M
|
|---|
local vs = [[
VK_UNIFORM_BINDING(0) uniform PerView
{
mat4 u_view_matrix;
mat4 u_projection_matrix;
vec4 u_camera_pos;
vec4 u_time;
};
VK_UNIFORM_BINDING(1) uniform PerRenderer
{
mat4 u_model_matrix;
};
VK_UNIFORM_BINDING(3) uniform PerMaterialVertex
{
vec4 _NoiseScale;
vec4 _NoiseSpeed;
};
layout(location = 0) in vec4 i_vertex;
layout(location = 2) in vec2 i_uv;
layout(location = 4) in vec3 i_normal;
VK_LAYOUT_LOCATION(0) out vec3 v_pos;
VK_LAYOUT_LOCATION(1) out vec2 v_uv;
VK_LAYOUT_LOCATION(2) out vec3 v_normal;
VK_LAYOUT_LOCATION(3) out vec2 v_uv1;
VK_LAYOUT_LOCATION(4) out vec2 v_uv2;
VK_LAYOUT_LOCATION(5) out vec3 v_cam_pos;
void main()
{
mat4 model_matrix = u_model_matrix;
vec4 world_pos = i_vertex * model_matrix;
gl_Position = world_pos * u_view_matrix * u_projection_matrix;
v_pos = world_pos.xyz;
v_uv = i_uv;
v_normal = (vec4(i_normal, 0.0) * model_matrix).xyz;
v_uv1 = world_pos.xy * _NoiseScale.xy + _NoiseSpeed.xy * u_time.y;
v_uv2 = world_pos.xy * _NoiseScale.zw + _NoiseSpeed.zw * u_time.y;
v_cam_pos = u_camera_pos.xyz;
vk_convert();
}
]]
local fs = [[
precision highp float;
VK_SAMPLER_BINDING(0) uniform sampler2D _MainTex;
VK_SAMPLER_BINDING(1) uniform sampler2D _NoiseTex1;
VK_SAMPLER_BINDING(2) uniform sampler2D _NoiseTex2;
VK_UNIFORM_BINDING(4) uniform PerMaterialFragment
{
vec4 _Color;
};
VK_LAYOUT_LOCATION(0) in vec3 v_pos;
VK_LAYOUT_LOCATION(1) in vec2 v_uv;
VK_LAYOUT_LOCATION(2) in vec3 v_normal;
VK_LAYOUT_LOCATION(3) in vec2 v_uv1;
VK_LAYOUT_LOCATION(4) in vec2 v_uv2;
VK_LAYOUT_LOCATION(5) in vec3 v_cam_pos;
layout(location = 0) out vec4 o_color;
void main()
{
vec3 normal = v_normal;
vec3 camDir = normalize(v_pos - v_cam_pos);
float falloff = max(abs(dot(camDir, normal)) - 0.4, 0.0);
falloff = falloff * falloff * 5.0;
vec4 c = _Color;
float n1 = texture(_NoiseTex1, v_uv1).r;
float n2 = texture(_NoiseTex2, v_uv2).r;
c.a *= texture(_MainTex, v_uv).a * n1 * n2 * falloff;
o_color = c;
}
]]
--[[
Cull
Back | Front | Off
ZTest
Less | Greater | LEqual | GEqual | Equal | NotEqual | Always
ZWrite
On | Off
SrcBlendMode
DstBlendMode
One | Zero | SrcColor | SrcAlpha | DstColor | DstAlpha
| OneMinusSrcColor | OneMinusSrcAlpha | OneMinusDstColor | OneMinusDstAlpha
CWrite
On | Off
Queue
Background | Geometry | AlphaTest | Transparent | Overlay
]]
local rs = {
Cull = Off,
ZTest = LEqual,
ZWrite = Off,
SrcBlendMode = SrcAlpha,
DstBlendMode = OneMinusSrcAlpha,
CWrite = On,
Queue = Transparent,
}
local pass = {
vs = vs,
fs = fs,
rs = rs,
uniforms = {
{
name = "PerView",
binding = 0,
members = {
{
name = "u_view_matrix",
size = 64,
},
{
name = "u_projection_matrix",
size = 64,
},
{
name = "u_camera_pos",
size = 16,
},
{
name = "u_time",
size = 16,
},
},
},
{
name = "PerRenderer",
binding = 1,
members = {
{
name = "u_model_matrix",
size = 64,
},
},
},
{
name = "PerMaterialVertex",
binding = 3,
members = {
{
name = "_NoiseScale",
size = 16,
},
{
name = "_NoiseSpeed",
size = 16,
},
},
},
{
name = "PerMaterialFragment",
binding = 4,
members = {
{
name = "_Color",
size = 16,
},
},
},
},
samplers = {
{
name = "PerMaterialFragment",
binding = 4,
samplers = {
{
name = "_MainTex",
binding = 0,
},
{
name = "_NoiseTex1",
binding = 1,
},
{
name = "_NoiseTex2",
binding = 2,
},
},
},
},
}
-- return pass array
return {
pass
}
|
local renamer = require 'renamer'
local utils = require 'renamer.utils'
local popup = require 'plenary.popup'
local mock = require 'luassert.mock'
local stub = require 'luassert.stub'
local spy = require 'luassert.spy'
local eq = assert.are.same
describe('renamer', function()
describe('rename', function()
describe('popup width', function()
it('should equal to cword length if title is too long', function()
renamer.setup { title = string.rep('a', 16) }
local cursor_col, word_start, win_width = 15, 13, 20
local cword = 'test'
local expected_width = #cword
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { 1, cursor_col }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(win_width)
api_mock.nvim_win_get_height.returns(100)
local expand = stub(vim.fn, 'expand').returns(cword)
stub(utils, 'get_word_boundaries_in_line').returns(word_start, word_start + expected_width)
local document_highlight = stub(renamer, '_document_highlight')
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
stub(popup, 'create').returns(1, {})
local _, opts = renamer.rename()
eq(expected_width, opts.opts.width)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
expand.revert(expand)
set_cursor.revert(set_cursor)
end)
it('should equal to cword length if otherwise too short', function()
renamer.setup { title = 'a' }
local cursor_col, word_start, win_width = 15, 13, 20
local cword = 'testing'
local expected_width = #cword
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { 1, cursor_col }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(win_width)
api_mock.nvim_win_get_height.returns(10)
local expand = stub(vim.fn, 'expand').returns(cword)
stub(utils, 'get_word_boundaries_in_line').returns(word_start, word_start + expected_width)
local document_highlight = stub(renamer, '_document_highlight').returns()
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
stub(popup, 'create').returns(1, {})
local _, opts = renamer.rename()
eq(expected_width, opts.opts.width)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
expand.revert(expand)
set_cursor.revert(set_cursor)
end)
end)
describe('with border', function()
before_each(function()
renamer.setup()
end)
it('should call `_set_prompt_border_win_style`', function()
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { 1, 2 }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(100)
api_mock.nvim_win_get_height.returns(10)
local set_prompt_border_win_style = spy.on(renamer, '_set_prompt_border_win_style')
stub(utils, 'get_word_boundaries_in_line').returns(1, 2)
local document_highlight = stub(renamer, '_document_highlight').returns()
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
stub(popup, 'create').returns(1, { border = { win_id = 1 } })
renamer.rename()
assert.spy(set_prompt_border_win_style).was_called_with(1)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
set_cursor.revert(set_cursor)
end)
it('should use cursor line for line position if there is enough space below', function()
local cursor_line = 1
local expected_line_no = 2
local expected_line = 'cursor+' .. expected_line_no
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { cursor_line, 2 }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(cursor_line + expected_line_no + 1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(100)
api_mock.nvim_win_get_height.returns(10)
stub(utils, 'get_word_boundaries_in_line').returns(1, 2)
local document_highlight = stub(renamer, '_document_highlight').returns()
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
stub(popup, 'create').returns(1, {})
local _, opts = renamer.rename()
eq(expected_line, opts.opts.line)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
set_cursor.revert(set_cursor)
end)
it('should use flip line position if at the end of the screen', function()
local expected_line_no = 2
local expected_line = 'cursor-' .. expected_line_no
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { 1, 2 }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(100)
api_mock.nvim_win_get_height.returns(10)
stub(utils, 'get_word_boundaries_in_line').returns(1, 2)
local document_highlight = stub(renamer, '_document_highlight').returns()
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
stub(popup, 'create').returns(1, {})
local _, opts = renamer.rename()
eq(expected_line, opts.opts.line)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
set_cursor.revert(set_cursor)
end)
it('should set the column position at the begining of the cword (cursor column inside word)', function()
local expected_col_no = 2
local expected_col = 'cursor-' .. expected_col_no
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { 1, expected_col_no + 1 }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(100)
api_mock.nvim_win_get_height.returns(10)
stub(utils, 'get_word_boundaries_in_line').returns(expected_col_no, 2)
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
local document_highlight = stub(renamer, '_document_highlight').returns()
stub(popup, 'create').returns(1, {})
local _, opts = renamer.rename()
eq(expected_col, opts.opts.col)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
set_cursor.revert(set_cursor)
end)
it('should set the column position at the begining of the cword (cursor column at word start)', function()
local cursor_col = 10
local expected_col_no = 1
local expected_col = 'cursor-' .. expected_col_no
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { 1, cursor_col }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(100)
api_mock.nvim_win_get_height.returns(10)
stub(utils, 'get_word_boundaries_in_line').returns(cursor_col, 2)
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
local document_highlight = stub(renamer, '_document_highlight').returns()
stub(popup, 'create').returns(1, {})
local _, opts = renamer.rename()
eq(expected_col, opts.opts.col)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
set_cursor.revert(set_cursor)
end)
it('should set the column position at the begining of the cword (cursor column at word end)', function()
local cursor_col = 10
local word_start = 5
local expected_col_no = cursor_col - word_start + 1
local expected_col = 'cursor-' .. expected_col_no
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { 1, cursor_col }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(100)
api_mock.nvim_win_get_height.returns(10)
stub(utils, 'get_word_boundaries_in_line').returns(word_start, 2)
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
local document_highlight = stub(renamer, '_document_highlight').returns()
stub(popup, 'create').returns(1, {})
local _, opts = renamer.rename()
eq(expected_col, opts.opts.col)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
set_cursor.revert(set_cursor)
end)
it('should set the column position to have enough space to draw popup (cword at window end)', function()
local cursor_col = 19
local word_start = 17
local win_width = 20
-- no `word_start` as the formula would have `... - word_start ... + word_start`
local expected_col_no = cursor_col + 1 + #renamer.title + 4 - win_width + 4
local expected_col = 'cursor-' .. expected_col_no
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { 1, cursor_col }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(win_width)
api_mock.nvim_win_get_height.returns(10)
stub(utils, 'get_word_boundaries_in_line').returns(word_start, word_start + 5)
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
local document_highlight = stub(renamer, '_document_highlight').returns()
stub(popup, 'create').returns(1, {})
local _, opts = renamer.rename()
eq(expected_col, opts.opts.col)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
set_cursor.revert(set_cursor)
end)
end)
describe('without border', function()
before_each(function()
renamer.setup { border = false }
end)
it('should use cursor line for line position if there is enough space below', function()
local cursor_line = 1
local expected_line_no = 1
local expected_line = 'cursor+' .. expected_line_no
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { cursor_line, 2 }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(cursor_line + expected_line_no + 1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(100)
api_mock.nvim_win_get_height.returns(10)
stub(utils, 'get_word_boundaries_in_line').returns(1, 2)
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
local document_highlight = stub(renamer, '_document_highlight').returns()
stub(popup, 'create').returns(1, {})
local _, opts = renamer.rename()
eq(expected_line, opts.opts.line)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
set_cursor.revert(set_cursor)
end)
it('should use flip line position if at the end of the screen', function()
local expected_line_no = 1
local expected_line = 'cursor-' .. expected_line_no
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { 1, 2 }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(100)
api_mock.nvim_win_get_height.returns(10)
stub(utils, 'get_word_boundaries_in_line').returns(1, 2)
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
local document_highlight = stub(renamer, '_document_highlight').returns()
stub(popup, 'create').returns(1, {})
local _, opts = renamer.rename()
eq(expected_line, opts.opts.line)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
set_cursor.revert(set_cursor)
end)
it('should set the column position at the begining of the cword (cursor column inside word)', function()
local expected_col_no = 1
local expected_col = 'cursor-' .. expected_col_no
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { 1, expected_col_no + 1 }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(100)
api_mock.nvim_win_get_height.returns(10)
stub(utils, 'get_word_boundaries_in_line').returns(expected_col_no + 1, 2)
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
local document_highlight = stub(renamer, '_document_highlight').returns()
stub(popup, 'create').returns(1, {})
local _, opts = renamer.rename()
eq(expected_col, opts.opts.col)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
set_cursor.revert(set_cursor)
end)
it('should set the column position at the begining of the cword (cursor column at word start)', function()
local cursor_col = 10
local expected_col_no = 0
local expected_col = 'cursor-' .. expected_col_no
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { 1, cursor_col }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(100)
api_mock.nvim_win_get_height.returns(10)
stub(utils, 'get_word_boundaries_in_line').returns(cursor_col + 1, 2)
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
local document_highlight = stub(renamer, '_document_highlight').returns()
stub(popup, 'create').returns(1, {})
local _, opts = renamer.rename()
eq(expected_col, opts.opts.col)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
set_cursor.revert(set_cursor)
end)
it('should set the column position at the begining of the cword (cursor column at word end)', function()
local cursor_col = 10
local word_start = 5
local expected_col_no = cursor_col - word_start + 1
local expected_col = 'cursor-' .. expected_col_no
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { 1, cursor_col }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(100)
api_mock.nvim_win_get_height.returns(10)
stub(utils, 'get_word_boundaries_in_line').returns(word_start, 2)
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
local document_highlight = stub(renamer, '_document_highlight').returns()
stub(popup, 'create').returns(1, {})
local _, opts = renamer.rename()
eq(expected_col, opts.opts.col)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
set_cursor.revert(set_cursor)
end)
it('should set the column position to have enough space to draw popup (cword at window end)', function()
local cursor_col = 19
local word_start = 17
local win_width = 20
-- no `word_start` as the formula would have `... - word_start ... + word_start`
local expected_col_no = cursor_col + 1 + #renamer.title + 4 - win_width
local expected_col = 'cursor-' .. expected_col_no
local api_mock = mock(vim.api, true)
api_mock.nvim_win_get_cursor.returns { 1, cursor_col }
api_mock.nvim_command.returns()
api_mock.nvim_buf_line_count.returns(1)
api_mock.nvim_get_mode.returns {}
api_mock.nvim_win_get_width.returns(win_width)
api_mock.nvim_win_get_height.returns(10)
stub(utils, 'get_word_boundaries_in_line').returns(word_start, word_start + 5)
local set_cursor = stub(renamer, '_set_cursor_to_popup_end')
local document_highlight = stub(renamer, '_document_highlight').returns()
stub(popup, 'create').returns(1, {})
local _, opts = renamer.rename()
eq(expected_col, opts.opts.col)
mock.revert(api_mock)
document_highlight.revert(document_highlight)
set_cursor.revert(set_cursor)
end)
end)
end)
end)
|
return
{
[1122] = {x4=1122,x1=false,x2=2,x3=128,x5=112233445566,x6=1.3,x7=1122,x8_0=13,x8=12,x9=123,x10='yf',x12={x1=1,},x13=5,x14={ _name='DemoD2',x1=1,x2=3,},s1='lua text ',v2={x=1,y=2},v3={x=0.1,y=0.2,z=0.3},v4={x=1,y=2,z=3.5,w=4},t1=-28800,k1={1,2,},k2={2,3,},k3={3,4,},k4={1,2,},k5={1,3,},k6={1,2,},k7={1,8,},k8={[2]=10,[3]=12,},k9={{y1=1,y2=true,},{y1=10,y2=false,},},k15={{ _name='DemoD2',x1=1,x2=3,},},},
}
|
local path, trigger = (...)
local triggerData = {select(3,...)}
local term = require("terminal")
local PATH = term.getPATH()
local PKGProgramsPath = path.."Programs/;"
if trigger == "enable" then
PATH = PATH..PKGProgramsPath
term.setPATH(PATH)
elseif trigger == "disable" then
PATH = PATH:gsub(PKGProgramsPath,"")
term.setPATH(PATH)
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define platform
platform("cross")
-- set hosts
set_hosts("macosx", "linux", "windows")
-- set archs
set_archs("i386", "x86_64", "arm", "arm64", "mips", "mips64", "riscv", "riscv64", "s390x", "ppc", "ppc64", "sh4")
-- set formats
set_formats("static", "lib$(name).a")
set_formats("object", "$(name).o")
set_formats("shared", "lib$(name).so")
set_formats("symbol", "$(name).sym")
-- on check
on_check(function (platform)
import("core.project.config")
import("detect.sdks.find_cross_toolchain")
-- detect arch
local arch = config.get("arch")
if not arch then
local cross = config.get("cross")
if not cross then
local cross_toolchain = find_cross_toolchain(config.get("sdk"), {bindir = config.get("bin")})
if cross_toolchain then
cross = cross_toolchain.cross
end
end
arch = "none"
if cross then
if cross:find("aarch64", 1, true) then
arch = "arm64"
elseif cross:find("arm", 1, true) then
arch = "arm"
elseif cross:find("mips64", 1, true) then
arch = "mips64"
elseif cross:find("mips", 1, true) then
arch = "mips"
elseif cross:find("riscv64", 1, true) then
arch = "riscv64"
elseif cross:find("riscv", 1, true) then
arch = "riscv"
elseif cross:find("s390x", 1, true) then
arch = "s390x"
elseif cross:find("powerpc64", 1, true) then
arch = "ppc64"
elseif cross:find("powerpc", 1, true) then
arch = "ppc"
elseif cross:find("sh4", 1, true) then
arch = "sh4"
elseif cross:find("x86_64", 1, true) then
arch = "x86_64"
elseif cross:find("i386", 1, true) or cross:find("i686", 1, true) then
arch = "i386"
end
end
config.set("arch", arch)
cprint("checking for architecture ... ${color.success}%s", arch)
end
end)
-- set toolchains
set_toolchains("envs", "cross")
|
--- @classmod core.graphics.ShaderProgram
--- Shader programs are used to define how models are rendered.
--
-- They consist of multiple @{core.graphics.Shader} objects, which must provide
-- an entry point for each mandatory rendering stage: Vertex and fragment shader.
--
-- This is just a brief summary, the complete documentation is available at
-- http://www.opengl.org/wiki/GLSL_Object
--
-- Includes @{core.Resource}.
local engine = require 'engine'
local class = require 'middleclass'
local Object = class.Object
local Scheduler = require 'core/Scheduler'
local Resource = require 'core/Resource'
local Shader = require 'core/graphics/Shader'
local ShaderVariableSet = require 'core/graphics/ShaderVariableSet'
local ShaderProgram = class('core/graphics/ShaderProgram')
ShaderProgram:include(Resource)
ShaderProgram.static.globalVariables =
ShaderVariableSet(Scheduler.awaitCall(engine.GetGlobalShaderVariableSet))
--- Creates a shader program by loading and linking the given shader sources.
--
-- @function static:load( ... )
--
-- @param[type=string] ...
-- Multiple shader sources that are then loaded, compiled and linked into the
-- program.
--
function ShaderProgram.static:_load( ... )
local shaders = {...}
for i,shader in ipairs(shaders) do
if type(shader) == 'string' then
shaders[i] = Shader:load(shader)
else
assert(Object.isInstanceOf(shader, Shader))
end
end
local shaderProgram = ShaderProgram(table.unpack(shaders))
return { value=shaderProgram, destructor=shaderProgram.destroy }
end
--- Links the given @{core.graphics.Shader}s into a shader program.
function ShaderProgram:initialize( ... )
local shaders = {...}
local shaderHandles = {}
for i,v in ipairs(shaders) do
shaderHandles[i] = v.handle
end
Scheduler.awaitCall(function()
self.handle = engine.LinkShaderProgram(table.unpack(shaderHandles))
self.variables =
ShaderVariableSet(engine.GetShaderProgramShaderVariableSet(self.handle))
end)
end
function ShaderProgram:destroy()
Scheduler.blindCall(engine.DestroyShaderProgram, self.handle)
self.handle = nil
self.variables:destroy()
self.variables = nil
end
return ShaderProgram
|
--[[
Copyright (c) 2011-2014 chukong-inc.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
--[[--
]]
local c = cc
local DrawNode = c.DrawNode
local drawPolygon = DrawNode.drawPolygon
function DrawNode:drawPolygon(points, params)
local segments = #points
fillColor = cc.c4f(1,1,1,1)
borderWidth = 0
borderColor = cc.c4f(0,0,0,1)
if params then
if params.fillColor then fillColor = params.fillColor end
if params.borderWidth then borderWidth = params.borderWidth end
if params.borderColor then borderColor = params.borderColor end
end
drawPolygon(self, points, #points, fillColor, borderWidth, borderColor)
return self
end
local drawDot = DrawNode.drawDot
function DrawNode:drawDot(point, radius, color)
drawDot(self, point, radius, color)
return self
end
|
--[[ I AM NOT RESPONSIBLE IF YOU GET BANNED WITH THE "A" SCRIPT ]]
require(5656254881)()
|
local setmetatable = setmetatable
local config = ngx.shared.config
local ngx = ngx
local tinsert = table.insert
local tconcat = table.concat
local pairs = pairs
local cjson = require "cjson"
local type = type
local resty_lock = require "resty.lock"
local _M = {}
_M._VERSION = '0.1'
local weixin_errcode = {
[-1] = '系统繁忙',
[40001] = '获取access_token时AppSecret错误,或者access_token无效',
[40002] = '不合法的凭证类型',
[40003] = '不合法的OpenID',
[40004] = '不合法的媒体文件类型',
[40005] = '不合法的文件类型',
[40006] = '不合法的文件大小',
[40007] = '不合法的媒体文件id',
[40008] = '不合法的消息类型',
[40009] = '不合法的图片文件大小',
[40010] = '不合法的语音文件大小',
[40011] = '不合法的视频文件大小',
[40012] = '不合法的缩略图文件大小',
[40013] = '不合法的APPID',
[40014] = '不合法的access_token',
[40015] = '不合法的菜单类型',
[40016] = '不合法的按钮个数',
[40017] = '不合法的按钮个数',
[40018] = '不合法的按钮名字长度',
[40019] = '不合法的按钮KEY长度',
[40020] = '不合法的按钮URL长度',
[40021] = '不合法的菜单版本号',
[40022] = '不合法的子菜单级数',
[40023] = '不合法的子菜单按钮个数',
[40024] = '不合法的子菜单按钮类型',
[40025] = '不合法的子菜单按钮名字长度',
[40026] = '不合法的子菜单按钮KEY长度',
[40027] = '不合法的子菜单按钮URL长度',
[40028] = '不合法的自定义菜单使用用户',
[40029] = '不合法的oauth_code',
[40030] = '不合法的refresh_token',
[40031] = '不合法的openid列表',
[40032] = '不合法的openid列表长度',
[40033] = '不合法的请求字符,不能包含\\uxxxx格式的字符',
[40035] = '不合法的参数',
[40038] = '不合法的请求格式',
[40039] = '不合法的URL长度',
[40050] = '不合法的分组id',
[40051] = '分组名字不合法',
[41001] = '缺少access_token参数',
[41002] = '缺少appid参数',
[41003] = '缺少refresh_token参数',
[41004] = '缺少secret参数',
[41005] = '缺少多媒体文件数据',
[41006] = '缺少media_id参数',
[41007] = '缺少子菜单数据',
[41008] = '缺少oauthcode',
[41009] = '缺少openid',
[42001] = 'access_token超时',
[42002] = 'refresh_token超时',
[42003] = 'oauth_code超时',
[43001] = '需要GET请求',
[43002] = '需要POST请求',
[43003] = '需要HTTPS请求',
[43004] = '需要接收者关注',
[43005] = '需要好友关系',
[44001] = '多媒体文件为空',
[44002] = 'POST的数据包为空',
[44003] = '图文消息内容为空',
[44004] = '文本消息内容为空',
[45001] = '多媒体文件大小超过限制',
[45002] = '消息内容超过限制',
[45003] = '标题字段超过限制',
[45004] = '描述字段超过限制',
[45005] = '链接字段超过限制',
[45006] = '图片链接字段超过限制',
[45007] = '语音播放时间超过限制',
[45008] = '图文消息超过限制',
[45009] = '接口调用超过限制',
[45010] = '创建菜单个数超过限制',
[45015] = '回复时间超过限制',
[45016] = '系统分组,不允许修改',
[45017] = '分组名字过长',
[45018] = '分组数量超过上限',
[46001] = '不存在媒体数据',
[46002] = '不存在的菜单版本',
[46003] = '不存在的菜单数据',
[46004] = '不存在的用户',
[47001] = '解析JSON/XML内容错误',
[48001] = 'api功能未授权',
[50001] = '用户未授权该api'
}
local mt = { __index = _M }
function _M.new(self)
local appid, secret, tokenkey = config:get("appid"), config:get("secret"), config:get("tokenkey")
if not appid or not secret or not tokenkey then
ngx.log(ngx.ERR, "init client with appid: ", appid, " and secret ", secret, " and tokenkey ", tokenkey)
return nil, "init error"
end
return setmetatable({ appid = appid, secret = secret, tokenkey = tokenkey }, mt)
end
local function build_query(self, param)
if type(param) ~= 'table' then
return nil
end
local params = {}
for k, v in pairs(param) do
tinsert(params, tconcat({ k, v }, "="))
end
return tconcat(params, "&")
end
--optoken
local function fetch_optoken(self)
local token, err = config:get(self.tokenkey)
if token then
return token, nil
end
--mylock is the shared_dict defined in the nginx config file
local lock, err = resty_lock:new("mylock", { exptime = 10, timeout = 8, max_step = 0.1 })
local elapsed, err = lock:lock(self.tokenkey)
if not elapsed then
ngx.log(ngx.ERR, "fail to acquire the lock: ", err)
return nil, "fail to acquire the lock " .. err
end
--check again
token, err = config:get(self.tokenkey)
if token then
local ok, err = lock:unlock()
if not ok then
ngx.log(ngx.ERR, "fail to unlock after hit cache second time: ", err)
return nil, "fail to unlock: " .. err
end
return token, nil
end
--remote require
local val, err = self:get('cgi-bin/token', { grant_type = 'client_credential', appid = true, secret = true })
if not err then
token = val.access_token
local ttl = val.expires_in
--set cache
local ok, err = config:set(self.tokenkey, token, ttl - 200)
if not ok then
ngx.log(ngx.ERR, "fail to set ", self.tokenkey, " ", token)
local ok2, err2 = lock:unlock()
if not ok2 then
return nil, "fail to set cache and unlock"
end
return nil, "fail to set cache"
end
end
--unlock
local ok, err = lock:unlock()
if not ok then
ngx.log(ngx.ERR, "fail to unlock after set cache")
end
return token, nil
end
local function replace_key(self, param)
for k, mark in pairs(param) do
if mark then
if k == 'appid' then
param[k] = self.appid
elseif k == 'secret' then
param[k] = self.secret
elseif k == 'access_token' then
local token = fetch_optoken(self)
param[k] = token
end
end
end
return param
end
local function analyze(self, ret)
local rstatus = ret.status
local rheader = ret.rheader
local rbody = ret.body
if rstatus ~= ngx.HTTP_OK then
ngx.log(ngx.ERR, 'connect weixin error with: ', rstatus)
return nil, 'connect weixin error with http code ' .. rstatus
end
rbody = cjson.decode(rbody)
if rbody.errcode and 0 ~= rbody.errcode then
local errmsg = rbody.errmsg or ''
if weixin_errcode[rbody.errcode] then
errmsg = errmsg .. "," .. weixin_errorcode[rbody.errcode]
end
ngx.log(ngx.ERR, errmsg)
return nil, errmsg
end
return rbody, nil
end
local function set_header(self, header)
if not header then
return
end
for k, v in pairs(header) do
ngx.req.set_header(k, v)
end
end
local function request(self, ...)
local args = { ... }
local method = args[1]
local url = args[2]
local url_param = args[3] or {}
local post_param = args[4] or {}
local opts = args[5] or {}
local url = '/p2weixin/' .. url
url_param = replace_key(self, url_param)
if type(post_param) == 'table' then
post_param = build_query(replace_key(self, post_param))
end
local request_param = {}
request_param.method = method
if url_param then request_param.args = url_param end
if post_param then request_param.body = post_param end
--opts.header
if opts.header then set_header(self, opts.header) end
local ret = ngx.location.capture(
url, request_param
)
return analyze(self, ret)
end
function _M.get(self, ...)
local args = { ... }
local url = args[1] or nil
if not url then
ngx.log(ngx.ERR, "get error with args: ", ...)
return nil, 'get params error'
end
return request(self, ngx.HTTP_GET, ...)
end
function _M.post(self, ...)
local args = { ... }
local url = args[1] or nil
local post_params = args[3] or nil
if not url or not post_params then
ngx.log(ngx.ERR, "post error with args: ", ...)
return nil, 'post params error'
end
return request(self, ngx.HTTP_POST, ...)
end
return _M
|
for i=16, 100 do
surface.CreateFont( "ui."..i, { font = "Bebas Neue", size = i } )
end
function ScrWH()
return ScrW(), ScrH()
end scrwh=ScrWH; Scrwh=ScrWH; SCRWH=ScrWH;
function PlaySound( s )
surface.PlaySound( "vgui/" .. s .. ".ogg" )
end
local blur = Material( "pp/blurscreen" )
function draw.BlurPanel( panel, amount, color )
local x, y = panel:LocalToScreen(0, 0)
local w, h = ScrW(), ScrH()
surface.SetDrawColor(255, 255, 255)
surface.SetMaterial(blur)
amount = amount or 4
for i = 1, 5 do
blur:SetFloat("$blur", (i / 3) * amount)
blur:Recompute()
render.UpdateScreenEffectTexture()
surface.DrawTexturedRect( x*-1, y*-1, w, h )
end
if color then draw.RoundedBox( 0, 0, 0, w, h, color ) end
end
function addMaterial( m, t )
surface.SetMaterial( Material( m, t ) )
end
|
local helpers = require('test.functional.helpers')(after_each)
local Screen = require('test.functional.ui.screen')
local lfs = require('lfs')
local neq, eq, command = helpers.neq, helpers.eq, helpers.command
local clear, curbufmeths = helpers.clear, helpers.curbufmeths
local exc_exec, expect, eval = helpers.exc_exec, helpers.expect, helpers.eval
local insert, meth_pcall = helpers.insert, helpers.meth_pcall
local meths = helpers.meths
describe('eval-API', function()
before_each(clear)
it("work", function()
command("call nvim_command('let g:test = 1')")
eq(1, eval("nvim_get_var('test')"))
local buf = eval("nvim_get_current_buf()")
command("call nvim_buf_set_lines("..buf..", 0, -1, v:true, ['aa', 'bb'])")
expect([[
aa
bb]])
command("call nvim_win_set_cursor(0, [1, 1])")
command("call nvim_input('ax<esc>')")
expect([[
aax
bb]])
end)
it("throw errors for invalid arguments", function()
local err = exc_exec('call nvim_get_current_buf("foo")')
eq('Vim(call):E118: Too many arguments for function: nvim_get_current_buf', err)
err = exc_exec('call nvim_set_option("hlsearch")')
eq('Vim(call):E119: Not enough arguments for function: nvim_set_option', err)
err = exc_exec('call nvim_buf_set_lines(1, 0, -1, [], ["list"])')
eq('Vim(call):E5555: API call: Wrong type for argument 4, expecting Boolean', err)
err = exc_exec('call nvim_buf_set_lines(0, 0, -1, v:true, "string")')
eq('Vim(call):E5555: API call: Wrong type for argument 5, expecting ArrayOf(String)', err)
err = exc_exec('call nvim_buf_get_number("0")')
eq('Vim(call):E5555: API call: Wrong type for argument 1, expecting Buffer', err)
err = exc_exec('call nvim_buf_line_count(17)')
eq('Vim(call):E5555: API call: Invalid buffer id', err)
end)
it("use buffer numbers and windows ids as handles", function()
local screen = Screen.new(40, 8)
screen:attach()
local bnr = eval("bufnr('')")
local bhnd = eval("nvim_get_current_buf()")
local wid = eval("win_getid()")
local whnd = eval("nvim_get_current_win()")
eq(bnr, bhnd)
eq(wid, whnd)
command("new") -- creates new buffer and new window
local bnr2 = eval("bufnr('')")
local bhnd2 = eval("nvim_get_current_buf()")
local wid2 = eval("win_getid()")
local whnd2 = eval("nvim_get_current_win()")
eq(bnr2, bhnd2)
eq(wid2, whnd2)
neq(bnr, bnr2)
neq(wid, wid2)
-- 0 is synonymous to the current buffer
eq(bnr2, eval("nvim_buf_get_number(0)"))
command("bn") -- show old buffer in new window
eq(bnr, eval("nvim_get_current_buf()"))
eq(bnr, eval("bufnr('')"))
eq(bnr, eval("nvim_buf_get_number(0)"))
eq(wid2, eval("win_getid()"))
eq(whnd2, eval("nvim_get_current_win()"))
end)
it("get_lines and set_lines use NL to represent NUL", function()
curbufmeths.set_lines(0, -1, true, {"aa\0", "b\0b"})
eq({'aa\n', 'b\nb'}, eval("nvim_buf_get_lines(0, 0, -1, 1)"))
command('call nvim_buf_set_lines(0, 1, 2, v:true, ["xx", "\\nyy"])')
eq({'aa\0', 'xx', '\0yy'}, curbufmeths.get_lines(0, -1, 1))
end)
it("that are FUNC_ATTR_NOEVAL cannot be called", function()
-- Deprecated vim_ prefix is not exported.
local err = exc_exec('call vim_get_current_buffer("foo")')
eq('Vim(call):E117: Unknown function: vim_get_current_buffer', err)
-- Deprecated buffer_ prefix is not exported.
err = exc_exec('call buffer_line_count(0)')
eq('Vim(call):E117: Unknown function: buffer_line_count', err)
-- Functions deprecated before the api functions became available
-- in vimscript are not exported.
err = exc_exec('call buffer_get_line(0, 1)')
eq('Vim(call):E117: Unknown function: buffer_get_line', err)
-- some api functions are only useful from a msgpack-rpc channel
err = exc_exec('call nvim_subscribe("fancyevent")')
eq('Vim(call):E117: Unknown function: nvim_subscribe', err)
end)
it('have metadata accessible with api_info()', function()
local api_keys = eval("sort(keys(api_info()))")
eq({'error_types', 'functions', 'types',
'ui_events', 'ui_options', 'version'}, api_keys)
end)
it('are highlighted by vim.vim syntax file', function()
if lfs.attributes("build/runtime/syntax/vim/generated.vim",'uid') == nil then
pending("runtime was not built, skipping test")
return
end
local screen = Screen.new(40, 8)
screen:attach()
screen:set_default_attr_ids({
[1] = {bold = true, foreground = Screen.colors.Brown},
[2] = {foreground = Screen.colors.DarkCyan},
[3] = {foreground = Screen.colors.SlateBlue},
[4] = {foreground = Screen.colors.Fuchsia},
[5] = {bold = true, foreground = Screen.colors.Blue},
})
command("set ft=vim")
command("let &rtp='build/runtime/,'.&rtp")
command("syntax on")
insert([[
call bufnr('%')
call nvim_input('typing...')
call not_a_function(42)]])
screen:expect([[
{1:call} {2:bufnr}{3:(}{4:'%'}{3:)} |
{1:call} {2:nvim_input}{3:(}{4:'typing...'}{3:)} |
{1:call} not_a_function{3:(}{4:42}{3:^)} |
{5:~ }|
{5:~ }|
{5:~ }|
{5:~ }|
|
]])
screen:detach()
end)
it('cannot be called from sandbox', function()
eq({false, 'Vim(call):E48: Not allowed in sandbox'},
meth_pcall(command, "sandbox call nvim_input('ievil')"))
eq({''}, meths.buf_get_lines(0, 0, -1, true))
end)
end)
|
workspace "REV"
architecture "x64"
preferredtoolarchitecture "x86_64"
configurations { "debug", "release", "nsight" }
location "../.."
startproject "sandbox"
include "premake_engine.lua"
include "premake_sandbox.lua"
|
local Color1 = color(Var "Color1")
local Color2 = color(Var "Color2")
local a1 =
LoadActor(Var "File1") ..
{
OnCommand = function(self)
self:cropto(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2):diffuse(Color1):effectclock("music")
-- Explanation in StretchNoLoop.lua.
if self.GetTexture then
self:GetTexture():rate(self:GetParent():GetUpdateRate())
end
end,
GainFocusCommand = function(self)
self:play()
end,
LoseFocusCommand = function(self)
self:pause()
end
}
local a2 =
LoadActor(Var "File2") ..
{
OnCommand = function(self)
self:cropto(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2):diffuse(Color2):effectclock("music")
-- Explanation in StretchNoLoop.lua.
if self.GetTexture then
self:GetTexture():rate(self:GetParent():GetUpdateRate())
end
end,
GainFocusCommand = function(self)
self:play()
end,
LoseFocusCommand = function(self)
self:pause()
end
}
local t =
Def.ActorFrame {
a1 ..
{
OnCommand = function(self)
self:x(scale(1, 0, 4, SCREEN_LEFT, SCREEN_RIGHT)):y(scale(1, 0, 4, SCREEN_TOP, SCREEN_BOTTOM))
end
},
a2 ..
{
OnCommand = function(self)
self:x(scale(3, 0, 4, SCREEN_LEFT, SCREEN_RIGHT)):y(scale(1, 0, 4, SCREEN_TOP, SCREEN_BOTTOM))
end
},
a2 ..
{
OnCommand = function(self)
self:x(scale(1, 0, 4, SCREEN_LEFT, SCREEN_RIGHT)):y(scale(3, 0, 4, SCREEN_TOP, SCREEN_BOTTOM))
if self.SetDecodeMovie then
self:SetDecodeMovie(false)
end
end
},
a1 ..
{
OnCommand = function(self)
self:x(scale(3, 0, 4, SCREEN_LEFT, SCREEN_RIGHT)):y(scale(3, 0, 4, SCREEN_TOP, SCREEN_BOTTOM))
if self.SetDecodeMovie then
self:SetDecodeMovie(false)
end
end
}
}
return t
|
require 'accuracy/generateTest'
require 'accuracy/runTest'
require 'gap/utils'
require 'gap/constants'
-- return a list of files/folder in a directory
function scandir(directory)
local i, t, popen = 0, {}, io.popen
local pfile = popen('ls -a "'..directory..'"')
for filename in pfile:lines() do
i = i + 1
if i > 2 then
table.insert(t, filename)
end
end
pfile:close()
return t
end
-- read all the txt files in a test_set_group folder for n times
-- return a list of accuracy (one element = one running time)
-- report is a csv file
function runTestGroup(path_to_test_set_group, model, no_of_run_times, path_to_report_file)
local timebefore = os.time()
local gap_char = find_char_to_represent_gap(model)
local test_files = scandir(path_to_test_set_group)
-- writing to txt file
local report = io.open(path_to_report_file, "w")
report:write('run_id,correct,incorrect\n')
local trueCount = 0
local wrongCount = 0
for j = 1, no_of_run_times do
print ("Interation no. " .. j)
for i = 1,#test_files do
test_set = generateTestSet(path_to_test_set_group .. test_files[i], 'testset', gap_char)
test_result = runSingleTest(test_set, model)
trueCount = trueCount + test_result.trueCount
wrongCount = wrongCount + test_result.wrongCount
end
report:write(j .. "," .. trueCount .. "," .. wrongCount .. "\n")
trueCount = 0
wrongCount = 0
end
report:close()
local timeafter = os.time()
print ("Report for test group at: " .. path_to_test_set_group .. " generated.")
print ("Total running time: " .. (timeafter - timebefore)/60 .. " minutes")
end
--[[
Run generated test set group on a model
]]
function runGeneratedTestGroup(path_to_test_set_group, model, no_of_run_times, path_to_report_file, naive, opt, lookforward_length, path_to_time_report)
if (opt == nil) then
opt = {}
opt.threshold = THRESHOLD
opt.cutoffprobs = CUT_OFF_PROBS
end
-- print ('in runGeneratedTestGroup')
-- print (opt)
local timebefore = os.time()
local gap_char = find_char_to_represent_gap(model)
local test_files = scandir(path_to_test_set_group)
local report = io.open(path_to_report_file, "w")
report:write('test_id,correct,incorrect\n')
for i = 1, math.min(no_of_run_times,#test_files) do
print('Running test no. ' .. i)
-- print (path_to_test_set_group .. test_files[i])
test_set = table.load(path_to_test_set_group .. test_files[i])
local test_result
if naive ~= nil then
test_result = runSingleTest(test_set, model, naive, opt, lookforward_length)
else
test_result = runSingleTest(test_set, model, false, opt, lookforward_length)
end
report:write(i .. "," .. test_result.trueCount .. "," .. test_result.wrongCount .. "\n")
end
report:close()
local timeafter = os.time()
if (path_to_time_report ~= nil) then
local time_report = io.open(path_to_time_report, "a")
time_report:write((timeafter - timebefore) .. " seconds\n")
time_report:close()
end
print ("Report for test group at: " .. path_to_test_set_group .. " generated.")
print ("Total running time: " .. (timeafter - timebefore)/60 .. " minutes")
end
--[[
read all the txt files in a test_set_group folder, generate test based the text
result is detail of each gap
]]
function runTestGroup2(path_to_test_set_group, model, path_to_report_group)
local gap_char = find_char_to_represent_gap(model)
local test_files = scandir(path_to_test_set_group)
os.execute("mkdir " .. path_to_report_group)
for i = 1,#test_files do
testCase = generateTestSet(path_to_test_set_group .. test_files[i], 'testset', gap_char)
generateSingleDetailReport(testCase, path_to_report_group .. test_files[i], model)
print ('report for ' .. path_to_test_set_group .. test_files[i] .. ' generated')
end
end
function runGeneratedTestOnMultipleModels(model_paths, test_cases_path, test_run_no, report_paths, naive)
for i=1, #model_paths do
local model = get_model_by_path(model_paths[i])
runGeneratedTestGroup(test_cases_path, model, test_run_no, report_paths[i], naive)
end
end
function runGeneratedTestOnMultipleModelsWithGPU(model_paths, test_cases_path, test_run_no, report_paths)
for i=1, #model_paths do
local model = get_model_by_path_with_GPU(model_paths[i])
runGeneratedTestGroup(test_cases_path, model, test_run_no, report_paths[i])
end
end
function testChangingThresholdWithGPU(model_path, test_cases_path, test_run_no, report_path, thresholds)
local model = get_model_by_path(model_path)
for i=1,#thresholds do
local report = report_path .. 'thresholds_' .. thresholds[i] .. '_.csv'
local opt = {}
opt.threshold = thresholds[i]
opt.cutoffprobs = CUT_OFF_PROBS
runGeneratedTestGroup(test_cases_path, model, test_run_no, report, false, opt)
end
end
function testChangingLookForwardLength(model_path, test_cases_path, test_run_no, report_path, lookforward_lens, time_report_path)
local model = get_model_by_path(model_path)
for i=1,#lookforward_lens do
local report = report_path .. 'lookforward_len_' .. lookforward_lens[i] .. '_.csv'
runGeneratedTestGroup(test_cases_path, model, test_run_no, report, false, nil, lookforward_lens[i], time_report_path)
end
end
-----------------------------------------------
-- GENERATE TEST AND STORE
-----------------------------------------------
-- CHECKPOINT_PATH = 'models/sherlock_holmes_3_128/sherlock_holmes_3_128_103800.t7'
--
-- local model = get_model_by_path(CHECKPOINT_PATH)
-- generateTestSetAndStore('accuracy/rawTestFiles/harrypotter_alpha5.txt', 'accuracy/generatedTestCases/harrypotter_alpha5/', model, 100)
-- CHECKPOINT_PATH = 'models/sherlock_holmes_3_128/sherlock_holmes_3_128_103800.t7'
--
-- local model = get_model_by_path(CHECKPOINT_PATH)
-- generateTestSetAndStore('accuracy/rawTestFiles/harrypotter2.txt', 'accuracy/generatedTestCases/gapsize3/', model, 100)
-----------------------------------------------
-- THRESHOLD TESTING
-----------------------------------------------
-- thresholds = {0.6,0.7,0.8,0.9,1}
-- testChangingThresholdWithGPU('models/sherlock_holmes_3_128/sherlock_holmes_3_128_103800.t7', 'accuracy/generatedTestCases/harrypotter/', 100, 'accuracy/visualization/report-data/changing-threshold/', thresholds)
-----------------------------------------------
-- LOOK FORWARD LENGTH TESTING
-----------------------------------------------
-- lookforward_lens = {0,1,100}
-- testChangingLookForwardLength('models/sherlock_holmes_3_128/sherlock_holmes_3_128_103800.t7', 'accuracy/generatedTestCases/harrypotter/', 2, 'accuracy/visualization/report-data/changing-lookforwardlen/', lookforward_lens, 'accuracy/visualization/report-data/changing-lookforwardlen/timereport.txt')
-----------------------------------------------
-- METHOD OF ACCUMULATING PROBS
-----------------------------------------------
-- local model_path = 'models/sherlock_holmes_3_128/sherlock_holmes_3_128_103800.t7'
-- local model = get_model_by_path(model_path)
-- local path_to_report_file = 'accuracy/visualization/report-data/changing-method-of-accum-prob/sum_decay.csv'
-- local test_cases_path = 'accuracy/generatedTestCases/harrypotter/'
-- runGeneratedTestGroup(test_cases_path, model, 2, path_to_report_file, false)
-----------------------------------------------
-- DECAY FACTOR
-----------------------------------------------
-- local model_path = 'models/sherlock_holmes_3_128/sherlock_holmes_3_128_103800.t7'
-- local model = get_model_by_path(model_path)
--
-- local path_to_report_folder = 'accuracy/visualization/report-data/changing-decay-factor/'
-- local test_cases_path = 'accuracy/generatedTestCases/harrypotter/'
--
-- product_decay_factors = {0.02,0.04,0.06,0.08,0.1,0.12,0.14,0.16,0.18,0.2}
-- -- product_decay_factors = {0.02,0.1,0.3}
--
-- for i=1,#product_decay_factors do
-- PRODUCT_DECAY_FACTOR = product_decay_factors[i]
-- path_to_report_file = path_to_report_folder .. 'decay_' .. PRODUCT_DECAY_FACTOR .. '.csv'
-- runGeneratedTestGroup(test_cases_path, model, 2, path_to_report_file, false, nil, 6)
-- end
-----------------------------------------------
-- RELEVANCE OF TESTSET
-----------------------------------------------
-- model_path = 'models/sherlock_holmes_3_128/sherlock_holmes_3_128_103800.t7'
-- local model = get_model_by_path(model_path)
--
-- local path_to_report1 = 'accuracy/visualization/report-data/relevance-of-testsets/ntu_news.csv'
-- local test_cases_path1 = 'accuracy/generatedTestCases/ntu_news/'
--
-- local path_to_report2 = 'accuracy/visualization/report-data/relevance-of-testsets/resubtitution.csv'
-- local test_cases_path2 = 'accuracy/generatedTestCases/resubtitution/'
--
-- runGeneratedTestGroup(test_cases_path1, model, 2, path_to_report1, false, nil, 6)
-- runGeneratedTestGroup(test_cases_path2, model, 2, path_to_report2, false, nil, 6)
-----------------------------------------------
-- PYTHON & INDONESIAN
-----------------------------------------------
-- python
-- model_path = 'models/python_code_3_128/python_code_3_128_20000.t7'
-- local model = get_model_by_path(model_path)
-- local path_to_report = 'accuracy/visualization/report-data/different-sequence-type/python.csv'
-- local test_cases_path = 'accuracy/generatedTestCases/python_test_django/'
-- runGeneratedTestGroup(test_cases_path, model, 2, path_to_report, false, nil, 6)
--
-- -- indonesian
-- model_path = 'models/indonesian_3_128/indonesian_cleaned_11000.t7'
-- local model = get_model_by_path(model_path)
-- local path_to_report = 'accuracy/visualization/report-data/different-sequence-type/indonesian.csv'
-- local test_cases_path = 'accuracy/generatedTestCases/indonesian_test/'
-- runGeneratedTestGroup(test_cases_path, model, 2, path_to_report, false, nil, 6)
-----------------------------------------------
-- VOCAB SIZE
-----------------------------------------------
-- alphabet 4
model_path = 'models/sherlock_holmes_alpha4/sherlock_holmes_alpha4_38000.t7'
local model = get_model_by_path(model_path)
local path_to_report = 'accuracy/visualization/report-data/varying-vocab-size/alphabet4_53.csv'
local test_cases_path = 'accuracy/generatedTestCases/harrypotter_alpha4/'
runGeneratedTestGroup(test_cases_path, model, 2, path_to_report, false, nil, 6)
-- alphabet 4
model_path = 'models/sherlock_holmes_alpha4/sherlock_holmes_alpha4_38000.t7'
local model = get_model_by_path(model_path)
local path_to_report = 'accuracy/visualization/report-data/varying-vocab-size/alphabet5_27.csv'
local test_cases_path = 'accuracy/generatedTestCases/harrypotter_alpha5/'
runGeneratedTestGroup(test_cases_path, model, 2, path_to_report, false, nil, 6)
-----------------------------------------------
-- GAP SIZE
-----------------------------------------------
-- model_path = 'models/sherlock_holmes_3_128/sherlock_holmes_3_128_103800.t7'
-- local model = get_model_by_path(model_path)
-- local path_to_time_report = 'accuracy/visualization/report-data/changing-gapsize/timereport.csv'
-- local path_to_report = 'accuracy/visualization/report-data/changing-gapsize/gapsize_1.csv'
-- local test_cases_path = 'accuracy/generatedTestCases/gapsize1/'
-- runGeneratedTestGroup(test_cases_path, model, 1, path_to_report, false, nil, 6, path_to_time_report)
--
-- path_to_report = 'accuracy/visualization/report-data/changing-gapsize/gapsize_2.csv'
-- test_cases_path = 'accuracy/generatedTestCases/gapsize2/'
-- runGeneratedTestGroup(test_cases_path, model, 1, path_to_report, false, nil, 6, path_to_time_report)
--
-- path_to_report = 'accuracy/visualization/report-data/changing-gapsize/gapsize_3.csv'
-- test_cases_path = 'accuracy/generatedTestCases/gapsize3/'
-- runGeneratedTestGroup(test_cases_path, model, 1, path_to_report, false, nil, 6, path_to_time_report)
SHERLOCK_HOLMES__VARYING_SIZE_MODEL_PATHS = {
'models/sherlock_holmes_1_128/sherlock_holmes_1_128_100000.t7',
'models/sherlock_holmes_1_256/sherlock_holmes_1_256_103800.t7',
'models/sherlock_holmes_1_512/sherlock_holmes_1_512_103800.t7',
'models/sherlock_holmes_2_128/sherlock_holmes_2_128_103800.t7',
'models/sherlock_holmes_2_256/sherlock_holmes_2_256_103800.t7',
'models/sherlock_holmes_2_512/sherlock_holmes_2_512_103800.t7',
'models/sherlock_holmes_3_128/sherlock_holmes_3_128_103800.t7',
'models/sherlock_holmes_3_256/sherlock_holmes_3_256_103800.t7',
'models/sherlock_holmes_3_512/sherlock_holmes_3_512_100000.t7',
}
SHERLOCK_HOLMES_REPORT_PATHS = {
'accuracy/visualization/report-data/varying-size-iter-100000-devil-foot/sherlock_holmes_1_128.csv',
'accuracy/visualization/report-data/varying-size-iter-100000-devil-foot/sherlock_holmes_1_256.csv',
'accuracy/visualization/report-data/varying-size-iter-100000-devil-foot/sherlock_holmes_1_512.csv',
'accuracy/visualization/report-data/varying-size-iter-100000-devil-foot/sherlock_holmes_2_128.csv',
'accuracy/visualization/report-data/varying-size-iter-100000-devil-foot/sherlock_holmes_2_256.csv',
'accuracy/visualization/report-data/varying-size-iter-100000-devil-foot/sherlock_holmes_2_512.csv',
'accuracy/visualization/report-data/varying-size-iter-100000-devil-foot/sherlock_holmes_3_128.csv',
'accuracy/visualization/report-data/varying-size-iter-100000-devil-foot/sherlock_holmes_3_256.csv',
'accuracy/visualization/report-data/varying-size-iter-100000-devil-foot/sherlock_holmes_3_512.csv',
}
-- runGeneratedTestOnMultipleModels(SHERLOCK_HOLMES__VARYING_SIZE_MODEL_PATHS,'accuracy/generatedTestCases/devil_foot/', 2, SHERLOCK_HOLMES_REPORT_PATHS)
-----------------------------------------------
-- NAIVE TESTING
-----------------------------------------------
-- local model = get_model_by_path('models/sherlock_holmes_3_128/sherlock_holmes_3_128_103800.t7')
-- runGeneratedTestGroup('accuracy/generatedTestCases/harrypotter/', model, 100, 'accuracy/visualization/report-data/naive/harrypotter_3_128.csv', true)
-----------------------------------------------
-- NORMAL RUN TEST GROUP
-----------------------------------------------
-- CHECKPOINT_PATH = 'models/sherlock_holmes_1_128/sherlock_holmes_1_128_10000.t7'
-- local model = get_model_by_path(CHECKPOINT_PATH)
-- runGeneratedTestGroup('accuracy/generatedTestCases/harrypotter2/', model, 100, 'accuracy/visualization/report-data/changing-iteration-1-128-double-check/sherlock_holmes_1_128_ITER_10000.csv')
-- runTestGroup2('accuracy/rawTestFiles/harrypotter_onefile/', model, 'accuracy/reports/sherlock_holmes_2_256_tested_with_harry_potter_new_engine/')
-- CHECKPOINT_PATH = 'models/vietnamese_cleaned_3_128/vietnamese_cleaned_3_128_30300.t7'
-- local model = get_model_by_path(CHECKPOINT_PATH)
-- runGeneratedTestGroup('accuracy/generatedTestCases/gonewiththewind/', model, 2, 'accuracy/visualization/report-data/different-sequence-type/vietnamese_cleaned_3_128.csv')
function iteration_testing(testrunno)
testrunno = testrunno or 100
CHECKPOINT_PATH = 'models/sherlock_holmes_1_128/sherlock_holmes_1_128_10000.t7'
local model = get_model_by_path(CHECKPOINT_PATH)
runGeneratedTestGroup('accuracy/generatedTestCases/harrypotter2/', model, testrunno, 'accuracy/visualization/report-data/changing-iteration-1-128-double-check/sherlock_holmes_1_128_ITER_10000.csv')
CHECKPOINT_PATH = 'models/sherlock_holmes_1_128/sherlock_holmes_1_128_20000.t7'
local model = get_model_by_path(CHECKPOINT_PATH)
runGeneratedTestGroup('accuracy/generatedTestCases/harrypotter2/', model, testrunno, 'accuracy/visualization/report-data/changing-iteration-1-128-double-check/sherlock_holmes_1_128_ITER_20000.csv')
CHECKPOINT_PATH = 'models/sherlock_holmes_1_128/sherlock_holmes_1_128_30000.t7'
local model = get_model_by_path(CHECKPOINT_PATH)
runGeneratedTestGroup('accuracy/generatedTestCases/harrypotter2/', model, testrunno, 'accuracy/visualization/report-data/changing-iteration-1-128-double-check/sherlock_holmes_1_128_ITER_30000.csv')
CHECKPOINT_PATH = 'models/sherlock_holmes_1_128/sherlock_holmes_1_128_40000.t7'
local model = get_model_by_path(CHECKPOINT_PATH)
runGeneratedTestGroup('accuracy/generatedTestCases/harrypotter2/', model, testrunno, 'accuracy/visualization/report-data/changing-iteration-1-128-double-check/sherlock_holmes_1_128_ITER_40000.csv')
CHECKPOINT_PATH = 'models/sherlock_holmes_1_128/sherlock_holmes_1_128_50000.t7'
local model = get_model_by_path(CHECKPOINT_PATH)
runGeneratedTestGroup('accuracy/generatedTestCases/harrypotter2/', model, testrunno, 'accuracy/visualization/report-data/changing-iteration-1-128-double-check/sherlock_holmes_1_128_ITER_50000.csv')
CHECKPOINT_PATH = 'models/sherlock_holmes_1_128/sherlock_holmes_1_128_60000.t7'
local model = get_model_by_path(CHECKPOINT_PATH)
runGeneratedTestGroup('accuracy/generatedTestCases/harrypotter2/', model, testrunno, 'accuracy/visualization/report-data/changing-iteration-1-128-double-check/sherlock_holmes_1_128_ITER_60000.csv')
CHECKPOINT_PATH = 'models/sherlock_holmes_1_128/sherlock_holmes_1_128_70000.t7'
local model = get_model_by_path(CHECKPOINT_PATH)
runGeneratedTestGroup('accuracy/generatedTestCases/harrypotter2/', model, testrunno, 'accuracy/visualization/report-data/changing-iteration-1-128-double-check/sherlock_holmes_1_128_ITER_70000.csv')
CHECKPOINT_PATH = 'models/sherlock_holmes_1_128/sherlock_holmes_1_128_80000.t7'
local model = get_model_by_path(CHECKPOINT_PATH)
runGeneratedTestGroup('accuracy/generatedTestCases/harrypotter2/', model, testrunno, 'accuracy/visualization/report-data/changing-iteration-1-128-double-check/sherlock_holmes_1_128_ITER_80000.csv')
CHECKPOINT_PATH = 'models/sherlock_holmes_1_128/sherlock_holmes_1_128_90000.t7'
local model = get_model_by_path(CHECKPOINT_PATH)
runGeneratedTestGroup('accuracy/generatedTestCases/harrypotter2/', model, testrunno, 'accuracy/visualization/report-data/changing-iteration-1-128-double-check/sherlock_holmes_1_128_ITER_90000.csv')
CHECKPOINT_PATH = 'models/sherlock_holmes_1_128/sherlock_holmes_1_128_100000.t7'
local model = get_model_by_path(CHECKPOINT_PATH)
runGeneratedTestGroup('accuracy/generatedTestCases/harrypotter2/', model, testrunno, 'accuracy/visualization/report-data/changing-iteration-1-128-double-check/sherlock_holmes_1_128_ITER_100000.csv')
end
-- iteration_testing()
-- CHECKPOINT_PATH = 'models/sherlock_holmes_1_128/sherlock_holmes_1_128_10000.t7'
-- local model = get_model_by_path_with_GPU(CHECKPOINT_PATH)
-- runGeneratedTestGroup('accuracy/generatedTestCases/harrypotter/', model, 10, 'accuracyTestResult/sherlock_holmes_1_128_ITER_10000.csv')
|
local values = {};
local i = 1;
local j = 1;
local width = 720
local height = 400
-- The statements in the setup() function
-- execute once when the program begins
-- The array is filled with random values in setup() function.
function setup()
--createCanvas(720, 400);
for idx = 1,(width/8) do
table.insert(values,random(height));
end
end
-- The bubbleSort() function sorts taking 8 elements of the array
-- per frame. The algorithm behind this function is bubble sort.
local function bubbleSort(chunkSize)
chunkSize = chunkSize or 8
-- sort 8 elements at a time
for k = 1,chunkSize do
--print("k: ", k)
if(i < #values-1) then
local temp = values[j];
if (values[j] > values[j+1]) then
values[j] = values[j+1];
values[j+1] = temp;
end
j = j + 1;
if (j >= #values) then
j = 1;
i = i + 1;
end
else
noLoop();
end
end
end
-- The simulateSorting() function helps in animating
-- the whole bubble sort algorithm
-- by drawing the rectangles using values
-- in the array as the length of the rectangle.
function simulateSorting()
stroke(100, 143, 143);
fill(50);
for idx = 1,#values do
--rect(i*8 , height, 8, values[i],20);
rect((idx-1)*8 , height, 8, -values[idx]);
end
end
-- The statements in draw() function are executed until the
-- program is stopped. Each statement is executed in
-- sequence and after the last line is read, the first
-- line is executed again.
function draw()
background(220);
bubbleSort(16);
simulateSorting();
end
go({width = 720, height = 400})
|
vr_info_table = {}
vr_info_table[1] = {}
vr_info_table[1].field_name = "vr_info_h_op"
vr_info_table[1].ProtoField = ProtoField.int8
vr_info_table[1].base = base.DEC
vr_info_table[1].append_value = {
branch = {
prepend = ": ",
value = function (val) return sandesh_op[val] end
},
subtree = {
prepend = ", Operation: ",
value = function (val) return sandesh_op[val] end
}}
vr_info_table[1].info_col = {prepend = "Operation: "}
vr_info_table[1].show_when_zero = true
vr_info_table[2] = {}
vr_info_table[2].field_name = "vdu_rid"
vr_info_table[2].ProtoField = ProtoField.int16
vr_info_table[2].base = base.DEC
vr_info_table[3] = {}
vr_info_table[3].field_name = "vdu_index"
vr_info_table[3].ProtoField = ProtoField.int16
vr_info_table[3].base = base.DEC
vr_info_table[3].info_col = {prepend = "ID: "}
vr_info_table[3].show_when_zero = true
vr_info_table[3].append_value = {
subtree = {
prepend = ", ID: ",
value = function (val) return tostring(val) end
}}
vr_info_table[4] = {}
vr_info_table[4].field_name = "vdu_buff_table_id"
vr_info_table[4].ProtoField = ProtoField.int16
vr_info_table[4].base = base.DEC
vr_info_table[5] = {}
vr_info_table[5].field_name = "vdu_marker"
vr_info_table[5].ProtoField = ProtoField.int16
vr_info_table[5].base = base.DEC
vr_info_table[6] = {}
vr_info_table[6].field_name = "vdu_msginfo"
vr_info_table[6].ProtoField = ProtoField.int16
vr_info_table[6].base = base.DEC
vr_info_table[7] = {}
vr_info_table[7].field_name = "vdu_outbufsz"
vr_info_table[7].ProtoField = ProtoField.int32
vr_info_table[7].base = base.DEC
vr_info_table[8] = {}
vr_info_table[8].field_name = "vdu_inbuf"
vr_info_table[8].ProtoField = ProtoField.string
vr_info_table[9] = {}
vr_info_table[9].field_name = "vdu_proc_info"
vr_info_table[9].ProtoField = ProtoField.string
|
-----------------------------------
-- Area: RuAun Gardens
-- NM: Despot
-----------------------------------
function onMobSpawn(mob)
local ph = GetMobByID(mob:getLocalVar("ph"))
if ph then
local pos = ph:getPos()
mob:setPos(pos.x, pos.y, pos.z, pos.r)
local killerId = ph:getLocalVar("killer")
if killerId ~= 0 then
local killer = GetPlayerByID(killerId)
if not killer:isEngaged() and killer:checkDistance(mob) <= 50 then
mob:updateClaim(killer)
end
end
end
end
function onMobWeaponSkill(target, mob, skill)
if skill:getID() == 536 then
local panzerfaustCounter = mob:getLocalVar("panzerfaustCounter")
local panzerfaustMax = mob:getLocalVar("panzerfaustMax")
if panzerfaustCounter == 0 and panzerfaustMax == 0 then
panzerfaustMax = math.random(2, 5)
mob:setLocalVar("panzerfaustMax", panzerfaustMax)
end
panzerfaustCounter = panzerfaustCounter + 1
mob:setLocalVar("panzerfaustCounter", panzerfaustCounter)
if panzerfaustCounter > panzerfaustMax then
mob:setLocalVar("panzerfaustCounter", 0)
mob:setLocalVar("panzerfaustMax", 0)
else
mob:useMobAbility(536)
end
end
end
function onMobDeath(mob, player, isKiller)
end
function onMobDespawn(mob)
mob:removeListener("PH_VAR")
end
|
-----------------------------------------
-- ID: 5728
-- Item: serving_of_zaru_soba_+1
-- Food Effect: 60min, All Races
-----------------------------------------
-- Agility 4
-- HP % 12 (cap 185)
-- Resist Sleep +10
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(tpz.effect.FOOD) or target:hasStatusEffect(tpz.effect.FIELD_SUPPORT_FOOD) then
result = tpz.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(tpz.effect.FOOD, 0, 0, 3600, 5728)
end
function onEffectGain(target, effect)
target:addMod(tpz.mod.AGI, 4)
target:addMod(tpz.mod.FOOD_HPP, 12)
target:addMod(tpz.mod.FOOD_HP_CAP, 185)
target:addMod(tpz.mod.SLEEPRES, 10)
end
function onEffectLose(target, effect)
target:delMod(tpz.mod.AGI, 4)
target:delMod(tpz.mod.FOOD_HPP, 12)
target:delMod(tpz.mod.FOOD_HP_CAP, 185)
target:delMod(tpz.mod.SLEEPRES, 10)
end
|
require("alua")
function spawncb(reply)
local cmd = [[ print("Hello from " .. alua.id .. "!"); alua.exit() ]]
for p in pairs(reply.processes) do
alua.send(p, cmd)
end
end
function opencb(reply)
alua.spawn(7, spawncb)
end
alua.open({addr="127.0.0.1", port=6080}, opencb)
alua.loop()
|
local InterruptTable = _G.InterruptTable
-- Black Rook Hold
InterruptTable["Ghostly Councilor"] = {
["Dark Mending"] = true
}
InterruptTable["Ghostly Protector"] = {
["Sacrifice Soul"] = true
}
InterruptTable["Lord Etheldrin Ravencrest"] = {
["Spirit Blast"] = true
}
InterruptTable["Risen Arcanist"] = {
["Arcane Blitz"] = true
}
InterruptTable["Felspite Dominator"] = {
["Felfrenzy"] = true
}
-- Court of Stars
InterruptTable["Duskwatch Sentry"] = {
["Sound Alarm"] = true
}
InterruptTable["Arcane Manifestation"] = {
["Drain Magic"] = true
}
InterruptTable["Duskwatch Arcanist"] = {
["Seal Magic"] = true
}
InterruptTable["Guardian Construct"] = {
["Suppress"] = true,
["Charging Station"] = true
}
InterruptTable["Watchful Oculus"] = {
["Searing Glare"] = true
}
InterruptTable["Shadow Mistress"] = {
["Bewitch"] = true
}
InterruptTable["Blazing Imp"] = {
["Drifting Embers"] = true
}
InterruptTable["Talixae Flamewreath"] = {
["Withering Soul"] = true
}
InterruptTable["Vigilant Duskwatch"] = {
["Hinder"] = true
}
InterruptTable["Watchful Inquisitor"] = {
["Eye Storm"] = true
}
-- Darkheart Thicket
InterruptTable["Dreadsoul Ruiner"] = {
["Star Shower"] = true
}
InterruptTable["Mindshattered Screecher"] = {
["Unnerving Screech"] = true
}
InterruptTable["Nightmare Dweller"] = {
["Tormenting Fear"] = true
}
InterruptTable["Nightmare Dweller"] = {
["Tormenting Fear"] = true
}
InterruptTable["Dreadfire Imp"] = {
["Dread Inferno"] = true
}
-- Eye of Azshara
InterruptTable["Hatecoil Stormweaver"] = {
["Storm"] = true,
["Arc Lightning"] = true
}
InterruptTable["Hatecoil Crusher"] = {
["Thundering Stomp"] = true
}
InterruptTable["Hatecoil Oracle"] = {
["Rejuvenating Waters"] = true
}
InterruptTable["Hatecoil Crestrider"] = {
["Restoration"] = true,
["Bellowing Roar"] = true
}
InterruptTable["Hatecoil Shellbreaker"] = {
["Bellowing Roar"] = true
}
InterruptTable["Hatecoil Arcanist"] = {
["Aqua Spout"] = true,
["Polymorph: Fish"] = true
}
InterruptTable["Mak'rana Hardshell"] = {
["Armorshell"] = true
}
InterruptTable["Serpentrix"] = {
["Rampage"] = true
}
InterruptTable["Blazing Hydra Spawn"] = {
["Blazing Nova"] = true
}
InterruptTable["Arcane Hydra Spawn"] = {
["Arcane Blast"] = true
}
InterruptTable["Ritualist Lesha"] = {
["Aqua Spout"] = true
}
InterruptTable["Channeler Varisz"] = {
["Polymorph: Fish"] = true
}
InterruptTable["Mystic Ssa'veh"] = {
["Storm"] = true
}
-- Halls of Valor
InterruptTable["Valarjar Thundercaller"] = {
["Thunderous Bolt"] = true
}
InterruptTable["Valarjar Mystic"] = {
["Healing Light"] = true,
["Rune of Healing"] = true
}
InterruptTable["Valarjar Runecarver"] = {
["Shattered Rune"] = true,
["Etch"] = true
}
InterruptTable["Valarjar Purifier"] = {
["Cleansing Flames"] = true
}
InterruptTable["Olmyr the Enlightened"] = {
["Searing Light"] = true
}
InterruptTable["King Ranulf"] = {
["Unruly Yell"] = true
}
InterruptTable["King Bjorn"] = {
["Unruly Yell"] = true
}
InterruptTable["King Haldor"] = {
["Unruly Yell"] = true
}
InterruptTable["King Tor"] = {
["Unruly Yell"] = true
}
InterruptTable["Stormforged Obliterator"] = {
["Surge"] = true
}
-- Maw of Souls
InterruptTable["Waterlogged Soul Guard"] = {
["Soul Siphon"] = true
}
InterruptTable["Seacursed Mistmaiden"] = {
["Torrent of Souls"] = true
}
InterruptTable["Helarjar Champion"] = {
["Bone Chilling Scream"] = true
}
InterruptTable["Harbaron"] = {
["Void Snap"] = true
}
InterruptTable["Shackled Servitor"] = {
["Void Snap"] = true
}
InterruptTable["Skjal"] = {
["Debilitating Shout"] = true
}
InterruptTable["Skeletal Sorcerer"] = {
["Necrotic Bolt"] = true
}
InterruptTable["Helya"] = {
["Torrent"] = true
}
-- Neltharion's Lair
InterruptTable["Rockback Gnasher"] = {
["Stone Gaze"] = true
}
InterruptTable["Rockbound Trapper"] = {
["Bound"] = true
}
InterruptTable["Blightshard Shaper"] = {
["Stone Bolt"] = true
}
InterruptTable["Understone Drummers"] = {
["War Drums"] = true
}
-- The Arcway
InterruptTable["Withered Manawraith"] = {
["Siphon Essence"] = true
}
InterruptTable["Forgotten Spirit"] = {
["Torment"] = true
}
InterruptTable["Nightborne Reclaimer"] = {
["Eye of the Vortex"] = true
}
InterruptTable["Eredar Chaosbringer"] = {
["Portal: Argus"] = true,
["Demonic Ascension"] = true
}
InterruptTable["Arcane Anomaly"] = {
["Arcane Reconstitution"] = true
}
InterruptTable["Warp Shade"] = {
["Phase Breach"] = true
}
InterruptTable["Ivanyr"] = {
["Overcharge Mana"] = true
}
InterruptTable["Advisor Vandros"] = {
["Accelerating Blast"] = true
}
InterruptTable["Timeless Wraith"] = {
["Time Lock"] = true
}
-- The Arcway
InterruptTable["Felsworn Infester"] = {
["Nightmares"] = true
}
InterruptTable["Tirathon Saltheril"] = {
["Furious Blast"] = true
}
InterruptTable["Fel Fury"] = {
["Scorch"] = true,
["Fel Emission"] = true
}
InterruptTable["Fel Scorcher"] = {
["Inferno Blast"] = true
}
InterruptTable["Inquisitor Tormentorum"] = {
["Sapped Soul"] = true
}
InterruptTable["Deranged Mindflayer"] = {
["Frightening Shout"] = true
}
-- Violet Hold
InterruptTable["Portal Guardian"] = {
["Shield of Eyes"] = true,
["Carrion Swarm"] = true,
["Vampiric Cleave"] = true,
["Fel Destruction"] = true
}
InterruptTable["Portal Keeper"] = {
["Shield of Eyes"] = true,
["Carrion Swarm"] = true,
["Vampiric Cleave"] = true,
["Fel Destruction"] = true
}
InterruptTable["Acolyte of Sael'orn"] = {
["Lob Poison"] = true
}
InterruptTable["Venomhide Shadowspinner"] = {
["Venom Nova"] = true
}
InterruptTable["Thorium Rocket Chicken"] = {
["Rocket Chicken Rocket"] = true
}
InterruptTable["Mindflayer Kaahrj"] = {
["Hysteria"] = true
}
InterruptTable["Lord Malgath"] = {
["Shadow Bolt Volley"] = true
}
InterruptTable["Blazing Infernal"] = {
["Blazing Hellfire"] = true
}
-- Return to Karazhan
InterruptTable["Forlorn Spirit"] = {
["Soul Leech"] = true
}
InterruptTable["Ancient Tome"] = {
["Consume Magic"] = true
}
InterruptTable["Mana Confluence"] = {
["Arcane Barrage"] = true
}
InterruptTable["Infused Pyromancer"] = {
["Fel Fireball"] = true
}
InterruptTable["Shrieking Terror"] = {
["Terrifying Wail"] = true
}
InterruptTable["Luminore"] = {
["Burning Blaze"] = true,
["Heat Wave"] = true
}
InterruptTable["Coggleston"] = {
["Dinner Bell!"] = true
}
InterruptTable["Mrs. Cauldrons"] = {
["Leftovers"] = true
}
InterruptTable["Shoreline Tidespeaker"] = {
["Bubble Blast"] = true
}
InterruptTable["Galindre"] = {
["Flashy Bolt"] = true
}
InterruptTable["Ghostly Understudy"] = {
["Poetry Slam"] = true
}
InterruptTable["Backup Singer"] = {
["Firelands Portal"] = true
}
InterruptTable["Spectral Attendant"] = {
["Shadow Rejuvenation"] = true
}
InterruptTable["Spectral Retainer"] = {
["Oath of Fealty"] = true
}
InterruptTable["Undying Servant"] = {
["Shackles of Servitude"] = true
}
InterruptTable["Virtuous Lady"] = {
["Shadow Bolt Volley"] = true
}
InterruptTable["Wholesome Hostess"] = {
["Banshee Wail"] = true
}
InterruptTable["Maiden of Virtue"] = {
["Holy Shock"] = true,
["Holy Wrath"] = true
}
InterruptTable["Baroness Dorothea Millstipe"] = {
["Mana Drain"] = true
}
InterruptTable["Lady Keira Berrybuck"] = {
["Empowered Arms"] = true
}
InterruptTable["Lady Catriona"] = {
["Healing Stream"] = true,
["Smite"] = true
}
InterruptTable["Spectral Stable Hand"] = {
["Healing Touch"] = true
}
InterruptTable["Nightbane"] = {
["Reverberating Shadows"] = true
}
InterruptTable["Shade of Medivh"] = {
["Piercing Missiles"] = true,
["Frostbite"] = true
}
InterruptTable["Viz'aduum the Watcher"] = {
["Stabilize Rift"] = true,
["Burning Blast"] = true
}
-- Vault of the Wardens
InterruptTable["Fel-Infused Fury"] = {
["Unleash Fury"] = true
}
InterruptTable["Tirathon Saltheril"] = {
["Furious Blast"] = true
}
InterruptTable["Deranged Mindflayer"] = {
["Frightening Shout"] = true
}
InterruptTable["Ember"] = {
["Sear"] = true
}
InterruptTable["Malignant Defiler"] = {
["Drain"] = true
}
-- Cathedral of Eternal Night
InterruptTable["Felguard Destroyer"] = {
["Shadow Wall"] = true
}
InterruptTable["Hellblaze Soulmender"] = {
["Demonic Mending"] = true
}
InterruptTable["Hellblaze Temptress"] = {
["Alluring Aroma"] = true
}
InterruptTable["Felborne Botanist"] = {
["Blistering Rain"] = true,
["Fel Rejuvenation"] = true
}
InterruptTable["Hellblaze Imp"] = {
["Fel Blast"] = true
}
-- Seat of the Triumvirate
InterruptTable["Famished Broken"] = {
["Consume Essence"] = true
}
InterruptTable["Rift Warden"] = {
["Stygian Blast"] = true
}
InterruptTable["Shadewing"] = {
["Dread Screech"] = true
}
InterruptTable["Viceroy Nezhar"] = {
["Howling Dark"] = true,
["Eternal Twilight"] = true
}
|
local SoraRouter = {}
local util = require "sora.util"
local routes = ngx.shared.routes
function SoraRouter.new(o, req)
o = o or {}
local base = require "sora.base"
local parent = base:new(req)
setmetatable(
o,
{
__index = parent
}
)
return o
end
function SoraRouter:getControllerUri()
local replacedUri = self.req:path():gsub(self.config.uri.base, "")
local replacedUris = util.split(replacedUri, "%?")
local controllerUri = replacedUris[1] or "/"
-- rescue extension(s)
local action,extension = controllerUri:match("([^/%.]+)%.([^/]+)$")
if extension then
controllerUri = controllerUri:gsub("%." .. extension .. "$", "")
self.req.format = extension
end
return controllerUri
end
--
-- parts = { "", "user", "list", "nobody", "over20", "true" } -- because split "/", "/user/list/nobody"...
-- if exists controller/user/list.lua then
-- return {
-- requirePath : "controller.user.list",
-- action : "nobody",
-- params : { "over20", "true" },
-- }
-- end
--
function SoraRouter:searchTheLongestController(parts)
local path, requirePath, action
local params = {}
local partsNum = #parts
local controllersDir = ngx.var.baseDir .. "/" ..
self.config.dir.ownLibs .. "/" ..
self.config.dir.controller .. "/"
for i=1, partsNum do
path = controllersDir .. table.concat(parts, "/") .. ".lua"
if util.fileExists(path) then
local controller = require(self.config.dir.controller .. "." .. table.concat(parts, ".")):new()
action = params[#params]
if controller[action] then
if not controller._cannotAccess(controller, action) then
table.remove(params, #params)
requirePath = self.config.dir.controller .. "." .. table.concat(parts, ".")
break
end
elseif controller["index"] then
action = "index"
if not controller._cannotAccess(controller, action) then
requirePath = self.config.dir.controller .. "." .. table.concat(parts, ".")
break
end
end
end
table.insert(params, table.remove(parts, #parts))
end
if requirePath then
util.reverse(params)
return {
requirePath = requirePath:lower(),
action = action,
params = params,
}
end
end
function SoraRouter:getCache(path)
local json = routes:get(path)
return util.fromJSON(json)
end
function SoraRouter:setCache(path, object)
local json = util.toJSON(object)
routes:set(path, json)
end
function SoraRouter:deleteCache(path)
routes:delete(path)
end
function SoraRouter:autoRouteCache()
local controllerUri = self:getControllerUri()
local controllerInfo = self:getCache(controllerUri)
if not controllerInfo then return end
local controller = require(controllerInfo.requirePath):new(self.req)
return controller, controllerInfo.action, controllerInfo.params
end
-- local controller, action, params, authType, controllerRole = this:autoRoute()
--
-- 1. 最長マッチでControllerファイル file1.lua を探し
-- 2. 次の文字列param1をメソッド評価
-- 2-1. function param1があればparam1(param2, param3)
-- 2-2. function param1がなければindex(param1, param2, param3)
-- 2-3. indexも無ければ404
--
function SoraRouter:autoRouteDyn()
local controllerUri = self:getControllerUri()
local parts = util.split(controllerUri, "/")
table.remove(parts,1) -- shift
-- set controller/index.lua if requested "/"
if #parts < 1 then parts = { "index" } end
local controllerInfo = self:searchTheLongestController(parts)
if not controllerInfo then return end
-- /file/list/example : {"params":["example"],"requirePath":"controllers.file","action":"list"}
self:setCache(controllerUri, controllerInfo)
local controller = require(controllerInfo.requirePath):new(self.req)
return controller, controllerInfo.action, controllerInfo.params
end
function SoraRouter:autoRoute()
local controller, action, params = self:autoRouteCache()
if not controller then
controller, action, params = self:autoRouteDyn()
end
if controller then
return controller, action, params
end
return
end
return SoraRouter
|
require "stategraphs/SGbigfoot"
local assets =
{
Asset("ANIM", "anim/foot_build.zip"),
Asset("ANIM", "anim/foot_basic.zip"),
Asset("ANIM", "anim/foot_print.zip"),
Asset("ANIM", "anim/foot_shadow.zip"),
}
local prefabs =
{
"groundpound_fx",
"groundpoundring_fx",
}
local ShadowWarnTime = 2
local function DoStep(inst)
local player = GetPlayer()
local distToPlayer = inst:GetPosition():Dist(player:GetPosition())
local power = Lerp(3, 1, distToPlayer/180)
player.components.playercontroller:ShakeCamera(player, "VERTICAL", 0.5, 0.03, power, 40)
inst.components.groundpounder:GroundPound()
inst:SpawnPrint()
inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/glommer/foot_ground")
GetWorld():PushEvent("bigfootstep")
end
local function roundToNearest(numToRound, multiple)
local half = multiple/2
return numToRound+half - (numToRound+half) % multiple
end
local function GetRotation(inst)
local rotationTranslation =
{
["0"] = 180, -- "right"
["1"] = 135, -- "up"
["2"] = 0, -- "left"
["3"] = -135, --"down"
}
local cameraVec = TheCamera:GetDownVec()
local cameraAngle = math.atan2(cameraVec.z, cameraVec.x)
cameraAngle = cameraAngle * (180/math.pi)
cameraAngle = roundToNearest(cameraAngle, 45)
local rot = inst.AnimState:GetCurrentFacing()
return rotationTranslation[tostring(rot)] - cameraAngle
end
local function SpawnPrint(inst)
local footprint = SpawnPrefab("bigfootprint")
footprint.Transform:SetPosition(inst:GetPosition():Get())
footprint.Transform:SetRotation(GetRotation(inst))
end
local function SimulateStep(inst)
inst:DoTaskInTime(ShadowWarnTime, function(inst)
inst:DoStep()
inst:Remove()
end)
end
local function StartStep(inst)
local shadow = SpawnPrefab("bigfootshadow")
shadow.Transform:SetPosition(inst:GetPosition():Get())
shadow.Transform:SetRotation(GetRotation(inst))
inst:Hide()
inst:DoTaskInTime(ShadowWarnTime - (5*FRAMES), function(inst) inst.sg:GoToState("stomp") end)
end
local function foot_fn()
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
local sound = inst.entity:AddSoundEmitter()
trans:SetFourFaced()
anim:SetBank("foot")
anim:SetBuild("foot_build")
inst:SetStateGraph("SGbigfoot")
inst:AddComponent("groundpounder")
inst.components.groundpounder.destroyer = true
inst:AddComponent("combat")
inst.components.combat:SetDefaultDamage(1000)
inst:AddComponent("inspectable")
inst.SpawnPrint = SpawnPrint
inst.DoStep = DoStep
inst.SimulateStep = SimulateStep -- For really far away steps.
inst.StartStep = StartStep
return inst
end
local function footprint_fn()
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
local sound = inst.entity:AddSoundEmitter()
anim:SetBank("foot_print")
anim:SetBuild("foot_print")
anim:PlayAnimation("idle")
anim:SetOrientation( ANIM_ORIENTATION.OnGround )
anim:SetLayer( LAYER_BACKGROUND )
anim:SetSortOrder( 3 )
trans:SetRotation( 0 )
inst:AddTag("scarytoprey")
inst:AddComponent("colourtweener")
inst.components.colourtweener:StartTween({0,0,0,0}, 15, function(inst) inst:Remove() end)
inst.persists = false
return inst
end
local easing = require("easing")
local function LerpOut(inst)
local timeToLeave = 1.33
if not inst.sizeTask then
inst.LeaveTime = inst:GetTimeAlive() + timeToLeave
inst.sizeTask = inst:DoPeriodicTask(FRAMES, LerpOut)
inst.components.colourtweener:StartTween({0,0,0,0}, timeToLeave, function() inst:Remove() end)
end
local t = timeToLeave - (inst.LeaveTime - inst:GetTimeAlive())
local s = easing.outCirc(t, 1, inst.StartingScale - 1, timeToLeave)
inst.Transform:SetScale(s,s,s)
end
local function LerpIn(inst)
local s = easing.inExpo(inst:GetTimeAlive(), inst.StartingScale, 1 - inst.StartingScale, inst.TimeToImpact)
inst.Transform:SetScale(s,s,s)
if s <= 1 then
inst.sizeTask:Cancel()
inst.sizeTask = nil
end
end
local function shadow_fn()
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
anim:SetBank("foot_shadow")
anim:SetBuild("foot_shadow")
anim:PlayAnimation("idle")
anim:SetOrientation( ANIM_ORIENTATION.OnGround )
anim:SetLayer( LAYER_BACKGROUND )
anim:SetSortOrder( 3 )
inst.persists = false
local s = 2
inst.StartingScale = s
inst.Transform:SetScale(s,s,s)
inst.TimeToImpact = ShadowWarnTime
inst:AddComponent("colourtweener")
inst.AnimState:SetMultColour(0,0,0,0)
inst.components.colourtweener:StartTween({0,0,0,1}, inst.TimeToImpact, function() inst:DoTaskInTime(45*FRAMES, LerpOut) end)
inst.sizeTask = inst:DoPeriodicTask(FRAMES, LerpIn)
return inst
end
return Prefab("common/bigfoot", foot_fn, assets, prefabs),
Prefab("common/bigfootprint", footprint_fn, assets, prefabs),
Prefab("common/bigfootshadow", shadow_fn, assets, prefabs)
|
--- @module class
-- Utility for working with idiomatic Lua object-oriented patterns
local class = {}
--- Given an `object`, return its class
function class.classOf(object)
return getmetatable(object)
end
--- Given an `object` and a `class`, return if that object is an instance of another class/superclass
-- Equivalent to @{class.extends}(@{class.classOf}(object), `cls`)
function class.instanceOf(object, cls)
return class.extends(getmetatable(object), cls)
end
--- Get the superclass of a class
function class.getSuperclass(theClass)
local meta = getmetatable(theClass)
return meta and meta.__index
end
--- Check if one class extends another class
function class.extends(subclass, superclass)
assert(type(subclass) == "table")
assert(type(superclass) == "table")
local c = subclass
repeat
if c == superclass then
return true
end
c = class.getSuperclass(c)
until not c
return false
end
return class
|
UIMenuItem = setmetatable({}, UIMenuItem)
UIMenuItem.__index = UIMenuItem
UIMenuItem.__call = function() return "UIMenuItem", "UIMenuItem" end
function UIMenuItem.New(Text, Description)
_UIMenuItem = {
Rectangle = UIResRectangle.New(0, 0, 431, 38, 255, 255, 255, 20),
Text = UIResText.New(tostring(Text) or "", 8, 0, 0.33, 245, 245, 245, 255, 0),
_Description = tostring(Description) or "";
SelectedSprite = Sprite.New("commonmenu", "gradient_nav", 0, 0, 431, 38),
LeftBadge = { Sprite = Sprite.New("commonmenu", "", 0, 0, 40, 40), Badge = 0},
RightBadge = { Sprite = Sprite.New("commonmenu", "", 0, 0, 40, 40), Badge = 0},
Label = {
Text = UIResText.New("", 0, 0, 0.35, 245, 245, 245, 255, 0, "Right"),
MainColour = {R = 255, G = 255, B = 255, A = 255},
HighlightColour = {R = 0, G = 0, B = 0, A = 255},
},
_Selected = false,
_Hovered = false,
_Enabled = true,
_Offset = {X = 0, Y = 0},
ParentMenu = nil,
Panels = {},
Activated = function(_, _) end,
ActivatedPanel = function(_, _, _, _) end,
}
return setmetatable(_UIMenuItem, UIMenuItem)
end
function UIMenuItem:SetParentMenu(Menu)
if Menu ~= nil and Menu() == "UIMenu" then
self.ParentMenu = Menu
else
return self.ParentMenu
end
end
function UIMenuItem:Selected(bool)
if bool ~= nil then
self._Selected = tobool(bool)
else
return self._Selected
end
end
function UIMenuItem:Hovered(bool)
if bool ~= nil then
self._Hovered = tobool(bool)
else
return self._Hovered
end
end
function UIMenuItem:Enabled(bool)
if bool ~= nil then
self._Enabled = tobool(bool)
else
return self._Enabled
end
end
function UIMenuItem:Description(str)
if tostring(str) and str ~= nil then
self._Description = tostring(str)
else
return self._Description
end
end
function UIMenuItem:Offset(X, Y)
if tonumber(X) or tonumber(Y) then
if tonumber(X) then
self._Offset.X = tonumber(X)
end
if tonumber(Y) then
self._Offset.Y = tonumber(Y)
end
else
return self._Offset
end
end
function UIMenuItem:Position(Y)
if tonumber(Y) then
self.Rectangle:Position(self._Offset.X, Y + 144 + self._Offset.Y)
self.SelectedSprite:Position(0 + self._Offset.X, Y + 144 + self._Offset.Y)
self.Text:Position(8 + self._Offset.X, Y + 147 + self._Offset.Y)
self.LeftBadge.Sprite:Position(0 + self._Offset.X, Y + 142 + self._Offset.Y)
self.RightBadge.Sprite:Position(385 + self._Offset.X, Y + 142 + self._Offset.Y)
self.Label.Text:Position(420 + self._Offset.X, Y + 148 + self._Offset.Y)
end
end
function UIMenuItem:RightLabel(Text, MainColour, HighlightColour)
if tostring(Text) and Text ~= nil then
if type(MainColour) == "table" then
self.Label.MainColour = MainColour
end
if type(HighlightColour) == "table" then
self.Label.HighlightColour = HighlightColour
end
self.Label.Text:Text(tostring(Text))
else
return self.Label.Text:Text()
end
end
function UIMenuItem:SetLeftBadge(Badge)
if tonumber(Badge) then
self.LeftBadge.Badge = tonumber(Badge)
end
end
function UIMenuItem:SetRightBadge(Badge)
if tonumber(Badge) then
self.RightBadge.Badge = tonumber(Badge)
end
end
function UIMenuItem:Text(Text)
if tostring(Text) and Text ~= nil then
self.Text:Text(tostring(Text))
else
return self.Text:Text()
end
end
function UIMenuItem:AddPanel(Panel)
if Panel() == "UIMenuPanel" then
table.insert(self.Panels, Panel)
Panel:SetParentItem(self)
end
end
function UIMenuItem:RemovePanelAt(Index)
if tonumber(Index) then
if self.Panels[Index] then
table.remove(self.Panels, tonumber(Index))
end
end
end
function UIMenuItem:FindPanelIndex(Panel)
if Panel() == "UIMenuPanel" then
for Index = 1, #self.Panels do
if self.Panels[Index] == Panel then
return Index
end
end
end
return nil
end
function UIMenuItem:FindPanelItem()
for Index = #self.Items, 1, -1 do
if self.Items[Index].Panel then
return Index
end
end
return nil
end
function UIMenuItem:Draw()
self.Rectangle:Size(431 + self.ParentMenu.WidthOffset, self.Rectangle.Height)
self.SelectedSprite:Size(431 + self.ParentMenu.WidthOffset, self.SelectedSprite.Height)
if self._Hovered and not self._Selected then
self.Rectangle:Draw()
end
if self._Selected then
self.SelectedSprite:Draw()
end
if self._Enabled then
if self._Selected then
self.Text:Colour(0, 0, 0, 255)
self.Label.Text:Colour(self.Label.HighlightColour.R, self.Label.HighlightColour.G, self.Label.HighlightColour.B, self.Label.HighlightColour.A)
else
self.Text:Colour(245, 245, 245, 255)
self.Label.Text:Colour(self.Label.MainColour.R, self.Label.MainColour.G, self.Label.MainColour.B, self.Label.MainColour.A)
end
else
self.Text:Colour(163, 159, 148, 255)
self.Label.Text:Colour(163, 159, 148, 255)
end
if self.LeftBadge.Badge == BadgeStyle.None then
self.Text:Position(8 + self._Offset.X, self.Text.Y)
else
self.Text:Position(35 + self._Offset.X, self.Text.Y)
self.LeftBadge.Sprite.TxtDictionary = GetBadgeDictionary(self.LeftBadge.Badge, self._Selected)
self.LeftBadge.Sprite.TxtName = GetBadgeTexture(self.LeftBadge.Badge, self._Selected)
self.LeftBadge.Sprite:Colour(GetBadgeColour(self.LeftBadge.Badge, self._Selected))
self.LeftBadge.Sprite:Draw()
end
if self.RightBadge.Badge ~= BadgeStyle.None then
self.RightBadge.Sprite:Position(385 + self._Offset.X + self.ParentMenu.WidthOffset, self.RightBadge.Sprite.Y)
self.RightBadge.Sprite.TxtDictionary = GetBadgeDictionary(self.RightBadge.Badge, self._Selected)
self.RightBadge.Sprite.TxtName = GetBadgeTexture(self.RightBadge.Badge, self._Selected)
self.RightBadge.Sprite:Colour(GetBadgeColour(self.RightBadge.Badge, self._Selected))
self.RightBadge.Sprite:Draw()
end
if self.Label.Text:Text() ~= "" and string.len(self.Label.Text:Text()) > 0 then
self.Label.Text:Position(420 + self._Offset.X + self.ParentMenu.WidthOffset, self.Label.Text.Y)
self.Label.Text:Draw()
end
self.Text:Draw()
end
|
AddCSLuaFile()
ENT.Type = "anim"
ENT.PrintName = "Door Breach"
ENT.Category = "HL2 RP"
ENT.Spawnable = true
ENT.AdminOnly = true
ENT.PhysgunDisable = true
ENT.bNoPersist = true
if (SERVER) then
function ENT:GetLockPosition(door, normal)
local index = door:LookupBone("handle")
local position = door:GetPos()
normal = normal or door:GetForward():Angle()
if (index and index >= 1) then
position = door:GetBonePosition(index)
end
position = position + normal:Forward() * 4 + normal:Up() * 8 + normal:Right()
if (IsValid(door.ixLock)) then
position = position + normal:Forward() * 6 + normal:Up() * 8 + normal:Right() * -1
end
normal:RotateAroundAxis(normal:Up(), 180)
normal:RotateAroundAxis(normal:Forward(), 180)
normal:RotateAroundAxis(normal:Right(), 180)
return position, normal
end
function ENT:SetDoor(door, position, angles)
if (!IsValid(door) or !door:IsDoor()) then
return
end
local doorPartner = door:GetDoorPartner()
self.door = door
self.door:DeleteOnRemove(self)
door.ixBreach = self
if (IsValid(doorPartner)) then
self.doorPartner = doorPartner
self.doorPartner:DeleteOnRemove(self)
doorPartner.ixBreach = self
end
self:SetPos(position)
self:SetAngles(angles)
self:SetParent(door)
end
function ENT:SpawnFunction(client, trace)
local door = trace.Entity
if (!IsValid(door) or !door:IsDoor() or IsValid(door.ixBreach)) then
return client:NotifyLocalized("dNotValid")
end
local normal = client:GetEyeTrace().HitNormal:Angle()
local position, angles = self:GetLockPosition(door, normal)
local entity = ents.Create("ix_doorbreach")
entity:SetPos(trace.HitPos)
entity:Spawn()
entity:Activate()
entity:SetDoor(door, position, angles)
return entity
end
function ENT:OnRemove()
if (IsValid(self)) then
self:SetParent(nil)
end
if (IsValid(self.door)) then
self.door:Fire("unlock")
self.door.ixBreach = nil
end
if (IsValid(self.doorPartner)) then
self.doorPartner:Fire("unlock")
self.doorPartner.ixBreach = nil
end
end
function ENT:Initialize()
self:SetModel("models/props_wasteland/prison_padlock001a.mdl")
self:SetSolid(SOLID_VPHYSICS)
self:PhysicsInit(SOLID_VPHYSICS)
self:SetCollisionGroup(COLLISION_GROUP_WEAPON)
self:SetUseType(SIMPLE_USE)
self.nextUseTime = 0
end
function ENT:Explode( )
local eff = EffectData( )
eff:SetStart( self:GetPos( ) )
eff:SetOrigin( self:GetPos( ) )
eff:SetScale( 6 )
util.Effect( "Explosion", eff, true, true )
-- This determines if and how much damage the surrounding entities (namely, players) take from the blast.
util.BlastDamage( self, self, self:GetPos(), 40, 15)
self:EmitSound( "physics/wood/wood_furniture_break" .. math.random( 1, 2 ) .. ".wav" )
end
function ENT:Use(client)
if (self.nextUseTime > CurTime()) then
return
end
self:SetNWBool("beep", true)
self:EmitSound("buttons/blip1.wav")
timer.Simple(1, function()
self:EmitSound("buttons/blip1.wav")
timer.Simple(1, function()
self:EmitSound("buttons/blip1.wav")
timer.Simple(0.8, function()
self:EmitSound("buttons/blip1.wav")
timer.Simple(0.6, function()
self:EmitSound("buttons/blip1.wav")
timer.Simple(0.4, function()
self:EmitSound("buttons/blip1.wav")
timer.Simple(0.4, function()
self:EmitSound("buttons/blip1.wav")
timer.Simple(0.3, function()
self:EmitSound("buttons/blip1.wav")
timer.Simple(0.3, function()
self:EmitSound("buttons/blip1.wav")
timer.Simple(0.2, function()
self:EmitSound("buttons/blip1.wav")
timer.Simple(0.2, function()
self:EmitSound("buttons/blip1.wav")
timer.Simple(0.1, function()
self:EmitSound("buttons/blip1.wav")
timer.Simple(0.1, function()
if (IsValid(self.door)) then
self:EmitSound("buttons/blip1.wav")
self:EmitSound("weapons/explode3.wav")
self:Explode()
self.door:Fire("unlock")
self.door:Fire("open")
self:Remove()
if (IsValid(self.doorPartner)) then
self.doorPartner:Fire("unlock")
self.doorPartner:Fire("open")
end
end
end )
end )
end )
end )
end )
end )
end )
end )
end )
end )
end )
end )
self.nextUseTime = CurTime() + 10
end
else
local glowMaterial = ix.util.GetMaterial("sprites/glow04_noz")
local color_green = Color(0, 255, 0, 255)
local color_blue = Color(0, 100, 255, 255)
local color_red = Color(255, 50, 50, 255)
function ENT:Draw()
self:DrawModel()
local color = color_green
if (self:GetNWBool("beep", false)) then
color = color_red
else
color = color_green
end
local position = self:GetPos() + self:GetForward() * 1.5 + self:GetUp() * 3
render.SetMaterial(glowMaterial)
render.DrawSprite(position, 10, 10, color)
end
end
|
require('luacov')
local testcase = require('testcase')
function testcase.before_all()
-- install hello and world module
local f = assert(io.popen(table.concat({
'cd testdata',
'luarocks make hello-scm-1.rockspec',
'luarocks make world-scm-1.rockspec',
}, ' && ')))
for line in f:lines() do
print(line)
end
f:close()
end
function testcase.hello()
-- test that check module is declared with metamodule
local hello
assert(pcall(function()
hello = require('hello')
end))
local h = hello.new()
assert.equal(h._NAME, 'hello')
assert.equal(h._PACKAGE, 'hello')
assert.match(h, '^hello: ', false)
assert.equal(h.val, 'hello-value')
-- test that return a module name
assert.equal(h:instanceof(), 'hello')
-- test that call method
assert.equal(h:say(), 'hello hello-value')
end
function testcase.world_based_on_hello()
-- test that check module is declared with metamodule
local hello
local world
assert(pcall(function()
world = require('world')
hello = require('hello')
end))
local w = world.new()
assert.equal(w._NAME, 'world.World')
assert.equal(w._PACKAGE, 'world')
assert.match(w, '^world%.World: ', false)
assert.equal(w.val, 'world-value')
local h = hello.new()
assert.equal(w.say, h.say)
-- test that contains a base module methods
assert.equal(w.hello, {
init = h.init,
say = h.say,
instanceof = h.instanceof,
})
-- test that return a module name
assert.equal(w:instanceof(), 'world.World')
-- test that call method
assert.equal(w:say(), 'world.World world-value')
-- test that call method
assert.equal(w:say2(), 'world.World say2 world-value')
end
|
local class = require "com/class"
local CollectibleGeneratorManager = class:derive("CollectibleGeneratorManager")
local CollectibleGeneratorEntry = require("src/CollectibleGenerator/Entry")
function CollectibleGeneratorManager:new()
self.generators = {}
local generatorList = loadJson(parsePath("config/collectible_generators.json"))
for i, name in ipairs(generatorList) do
self.generators[name] = CollectibleGeneratorEntry(self, name)
end
end
function CollectibleGeneratorManager:getEntry(name)
return self.generators[name]
end
return CollectibleGeneratorManager
|
springs = {}
local modpath = minetest.get_modpath("springs")
dofile(modpath.."/pipes.lua")
dofile(modpath.."/sluice.lua")
dofile(modpath.."/pump.lua")
dofile(modpath.."/wells.lua")
--[[
TODO:
water filters
pipe inlet/outlet pressure checks
broken outlet sharing
non-connected pipes and splitters
fix wells
better springs texture
optimize static water
pumps
fix spout and intake nodeboxes
crafts
galvanized-ish pipes (coat in tin)
]]
minetest.register_node("springs:spring", {
description = "Spring",
tiles = {"default_cobble.png^default_river_water.png"},
--paramtype = "light",
--leveled = 64,
--alpha = 160,
drop = "default:cobble",
--drowning = 1,
walkable = true, -- because viscosity doesn't work for regular nodes, and the liquid hack can't be leveled
-- post_effect_color = {a = 103, r = 30, g = 76, b = 120},
groups = { puts_out_fire = 1, cracky = 1, is_ground_content = 1, cools_lava = 1},
sounds = default.node_sound_water_defaults(),
})
minetest.register_node("springs:water", {
description = "node ",
drawtype = "nodebox",
paramtype = "light",
tiles = {
{
name = "default_river_water_source_animated.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 2.0,
},
},
},
special_tiles = {
{
name = "default_river_water_source_animated.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 2.0,
},
backface_culling = false,
},
},
leveled = 64,
alpha = 160,
drop = "",
drowning = 1,
walkable = false, -- because viscosity doesn't work for regular nodes, and the liquid hack can't be leveled
climbable = true, -- because viscosity doesn't work for regular nodes, and the liquid hack can't be leveled
pointable = false,
diggable = false,
buildable_to = true,
-- liquid_viscosity = 14,
-- liquidtype = "source",
-- liquid_alternative_flowing = "springs:water",
-- liquid_alternative_source = "springs:water",
-- liquid_renewable = false,
-- liquid_range = 0,
-- groups = {crumbly=3,soil=1,falling_node=1},
post_effect_color = {a = 103, r = 30, g = 76, b = 90},
groups = { puts_out_fire = 1, liquid = 3, cools_lava = 1, fresh_water=1},
sounds = default.node_sound_water_defaults(),
node_box = {
type = "leveled",
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0.5, 0.5}, -- NodeBox1
}
}
})
-- this is a special node used to optimize large pools of water
-- its flowing abm runs much less frequently
minetest.register_node("springs:water_full", {
description = "node ",
drawtype = "nodebox",
paramtype = "light",
tiles = {
{
name = "default_river_water_source_animated.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 2.0,
},
},
},
special_tiles = {
{
name = "default_river_water_source_animated.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 2.0,
},
backface_culling = false,
},
},
leveled = 64,
alpha = 160,
drop = "",
drowning = 1,
walkable = false, -- because viscosity doesn't work for regular nodes, and the liquid hack can't be leveled
climbable = true, -- because viscosity doesn't work for regular nodes, and the liquid hack can't be leveled
pointable = false,
diggable = false,
buildable_to = true,
-- liquid_viscosity = 14,
-- liquidtype = "source",
-- liquid_alternative_flowing = "springs:water",
-- liquid_alternative_source = "springs:water",
-- liquid_renewable = false,
-- liquid_range = 0,
-- groups = {crumbly=3,soil=1,falling_node=1},
post_effect_color = {a = 103, r = 30, g = 76, b = 90},
groups = { puts_out_fire = 1, liquid = 3, cools_lava = 1, fresh_water=1},
sounds = default.node_sound_water_defaults(),
node_box = {
type = "leveled",
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0.5, 0.5}, -- NodeBox1
}
}
})
-- spring
minetest.register_abm({
nodenames = {"springs:spring"},
neighbors = {"group:fresh_water", "air"},
interval = 5,
chance = 60,
action = function(pos)
-- local mylevel = minetest.get_node_level(pos)
-- print("spring at: "..pos.x..","..pos.y..","..pos.z)
local air_nodes = minetest.find_nodes_in_area(
{x=pos.x - 1, y=pos.y - 1, z=pos.z - 1},
{x=pos.x + 1, y=pos.y, z=pos.z + 1},
{"group:fresh_water", "air"}
)
if nil == air_nodes or #air_nodes == 0 then
return
end
local tpos = air_nodes[math.random(#air_nodes)]
-- calculate flow rate based on absolute location
local prate = (minetest.hash_node_position(pos) % 48)
local amount = math.random(1, 16) + prate
local t = minetest.get_node(tpos)
if t.name == "air" then
minetest.set_node(tpos, {name = "springs:water"})
minetest.set_node_level(tpos, amount)
else -- it's group:fresh_water
local tlevel = minetest.get_node_level(tpos)
minetest.set_node_level(tpos, math.min(64, tlevel + amount))
end
end
})
-- evaporation
minetest.register_abm({
nodenames = {"group:fresh_water"},
neighbors = {"air"},
interval = 5,
chance = 10,
action = function(pos)
local mylevel = minetest.get_node_level(pos)
if math.random(16 - minetest.get_node_light(pos)) == 1 then
if mylevel > 1 then
minetest.set_node_level(pos, mylevel - 1)
else
minetest.set_node(pos, {name = "air"})
end
end
end
})
local soak = {
["default:cobble"] = 10,
["default:desert_cobble"] = 10,
["default:mossycobble"] = 9,
["default:dirt"] = 2,
["default:dirt_with_grass"] = 2,
["default:dirt_with_grass_footsteps"] = 2,
["default:dirt_with_dry_grass"] = 2,
["default:dirt_with_coniferous_litter"] = 2,
["default:dirt_with_rainforest_litter"] = 1,
["default:gravel"] = 8,
["default:coral_orange"] = 6,
["default:coral_brown"] = 6,
["default:coral_skeleton"] = 6,
["default:sand"] = 6,
["default:sand_with_kelp"] = 6,
["default:desert_sand"] = 7,
["default:silver_sand"] = 7,
["default:snow"] = 4,
["default:snowblock"] = 4,
["default:leaves"] = 60,
["default:bush_leaves"] = 60,
["default:jungleleaves"] = 60,
["default:pine_needles"] = 60,
["default:acacia_leaves"] = 60,
["default:acacia_bush_leaves"] = 60,
["default:aspen_leaves"] = 60,
-- dilution
["default:water_source"] = 65,
["default:water_flowing"] = 65,
["default:river_water_source"] = 65,
["default:river_water_flowing"] = 65,
-- boiling -- TODO: steam effect
["default:lava_source"] = 65,
["default:lava_flowing"] = 65,
-- no ladder hacks
["default:ladder_wood"] = 65,
-- ["default:ladder_steel"] = 65, -- need to figure out a way for water to flow through ladders
["default:sign_wall_wood"] = 65,
["default:sign_wall_steel"] = 65,
["default:fence_wood"] = 65,
["default:fence_acacia_wood"] = 65,
["default:fence_junglewood"] = 65,
["default:fence_pine_wood"] = 65,
["default:fence_aspen_wood"] = 65,
["default:torch"] = 65,
["carts:rail"] = 65,
["carts:brakerail"] = 65,
["carts:powerrail"] = 65,
}
local soak_names = {}
for n,_ in pairs(soak) do
table.insert(soak_names, n)
end
-- soaking sideways
minetest.register_abm({
nodenames = {"group:fresh_water"},
neighbors = soak_names,
interval = 4,
chance = 10,
action = function(pos)
-- print("\nsoak ")
local soak_nodes = minetest.find_nodes_in_area(
{x=pos.x - 1, y=pos.y, z=pos.z - 1},
{x=pos.x + 1, y=pos.y, z=pos.z + 1},
soak_names
)
local mylevel = minetest.get_node_level(pos)
local total_loss = 0
for _,spos in ipairs(soak_nodes) do
local sn = minetest.get_node(spos)
total_loss = total_loss + soak[sn.name]
if 1 == math.random(120 / mylevel) then
minetest.set_node(spos, {name = "air"})
end
end
if total_loss == 0 then
return
end
--print("loss: ".. total_loss)
local remain = mylevel - (total_loss * (mylevel / 64))
if remain > 0 then
minetest.set_node_level(pos, remain)
else
minetest.set_node(pos, {name="air"})
end
end
})
-- de-stagnation (faster flowing)
minetest.register_abm({
nodenames = {"springs:water_full"},
neighbors = {"air"},
interval = 6,
chance = 1,
action = function(pos)
-- if it's near air it might flow
minetest.set_node(pos, {name = "springs:water"})
end
})
-- flowing
minetest.register_abm({
nodenames = {"springs:water"},
neighbors = {"group:fresh_water", "air"},
interval = 2,
chance = 2,
action = function(pos)
local mylevel = minetest.get_node_level(pos)
-- print("\n mylevel ".. mylevel)
-- falling
local below = {x=pos.x, y=pos.y - 1, z=pos.z}
local nbelow = minetest.get_node(below).name
if nbelow == "air" then
minetest.set_node(below, {name="springs:water"})
minetest.set_node_level(below, mylevel)
minetest.set_node(pos, {name="air"})
return
elseif nbelow == "springs:water" then
local blevel = minetest.get_node_level(below)
if blevel < 64 then
local sum = mylevel + blevel
minetest.set_node_level(below, math.min(64, sum))
if sum > 64 then
mylevel = sum - 64
minetest.set_node_level(pos, mylevel)
-- keep flowing the liquid. this speeds up cascades
else
minetest.set_node(pos, {name="air"})
return
end
end
else -- check soaking
local rate = soak[nbelow]
if rate ~= nil then
local remains = mylevel - rate
if remains > 0 then
minetest.set_node_level(pos, remains)
else
minetest.set_node(pos, {name="air"})
end
if 1 == math.random(120 / mylevel) then
minetest.set_node(below, {name = "air"})
end
mylevel = remains
--return -- keep the fluid mechanics
end
end
local air_nodes = minetest.find_nodes_in_area(
{x=pos.x - 1, y=pos.y - 1, z=pos.z - 1},
{x=pos.x + 1, y=pos.y, z=pos.z + 1},
"air"
)
-- print("x: "..pos.x.." y: "..pos.y.." z: "..pos.z)
-- print("air list len ".. #air_nodes)
local off = math.random(#air_nodes)
for i = 1,#air_nodes do
--local theirlevel = minetest.get_node_level(fp)
local fp = air_nodes[((i + off) % #air_nodes) + 1]
if mylevel >= 2 then
local half = math.ceil(mylevel / 2)
minetest.set_node_level(pos, mylevel - half)
minetest.set_node(fp, {name= "springs:water"})
minetest.set_node_level(fp, half)
-- minetest.check_for_falling(fp)
return
end
end
local flow_nodes = minetest.find_nodes_in_area(
{x=pos.x - 1, y=pos.y , z=pos.z - 1},
{x=pos.x + 1, y=pos.y, z=pos.z + 1},
"group:fresh_water"
)
-- print("x: "..pos.x.." y: "..pos.y.." z: "..pos.z)
-- print("list len ".. #flow_nodes)
local off = math.random(#flow_nodes)
for i = 1,#flow_nodes do
local fp = flow_nodes[((i + off) % #flow_nodes) + 1]
local theirlevel = minetest.get_node_level(fp)
-- print("theirlevel "..theirlevel)
if mylevel - theirlevel >= 2 then
local diff = (mylevel - theirlevel)
local half = math.ceil(diff / 2)
minetest.set_node_level(pos, mylevel - half)
minetest.set_node_level(fp, theirlevel + (diff - half))
return
end
end
-- local n = minetest.get_node(fp);
-- -- check above to make sure it can get here
-- local na = minetest.get_node({x=fp.x, y=fp.y+1, z=fp.z})
--
-- -- print("name: " .. na.name .. " l: " ..g)
-- if na.name == "default:river_water_flowing" or na.name == "default:river_water_flowing" then
-- minetest.set_node(fp, {name=node.name})
-- minetest.set_node(pos, {name=n.name})
-- return
-- end
-- end
-- stagnation: this may not work
if mylevel == 64 then
--print("stagnating ".. pos.x .. ","..pos.y..","..pos.z)
minetest.set_node(pos, {name = "springs:water_full"})
end
end
})
-- surface water
minetest.register_ore({
ore_type = "scatter",
ore = "springs:spring",
wherein = {"default:dirt_with_grass", "default:dirt_with_coniferous_litter", "default:dirt_with_rainforest_litter"},
clust_scarcity = 64 * 64 * 64,
clust_num_ores = 1,
clust_size = 1,
y_min = -20,
y_max = 200,
})
minetest.register_ore({
ore_type = "scatter",
ore = "springs:spring",
wherein = "default:dirt",
clust_scarcity = 48 * 48 * 48,
clust_num_ores = 1,
clust_size = 1,
y_min = -20,
y_max = 200,
})
-- ground water
minetest.register_ore({
ore_type = "scatter",
ore = "springs:spring",
wherein = "default:stone",
clust_scarcity = 16 * 16 * 16,
clust_num_ores = 3,
clust_size = 3,
y_min = -50,
y_max = -10,
})
minetest.register_ore({
ore_type = "scatter",
ore = "springs:spring",
wherein = "default:stone",
clust_scarcity = 8 * 8 * 8,
clust_num_ores = 5,
clust_size = 4,
y_min = -50,
y_max = -25,
})
-- deep water - rare but bountiful
minetest.register_ore({
ore_type = "scatter",
ore = "springs:spring",
wherein = "default:stone",
clust_scarcity = 64 * 64 * 64,
clust_num_ores = 12,
clust_size = 6,
y_min = -32000,
y_max = -100,
})
-- minetest.register_ore({
-- ore_type = "scatter",
-- ore = "springs:spring",
-- wherein = "default:stone",
-- clust_scarcity = 8 * 8 * 8,
-- clust_num_ores = 16,
-- clust_size = 5,
-- y_min = -50,
-- y_max = -40,
-- })
-- TODO: desert stone, sandstone
|
local M = {}
--#region Global data
local mod_data
---@type table <number, LuaEntity>
local players_opened_compile
---@type table <number, function>
local compiled = {}
---@type table <number, string>
local compilers_text
---@type table <number, string>
local players_copyboard
--#endregion
--#region Constants
local sub = string.sub
local RED_COLOR = {1, 0, 0}
local DEFAULT_TEXT = "local compiler, player = ...\nplayer.print(compiler.name)"
--#endregion
if script.mod_name ~= "lua-compiler" then
remote.remove_interface("disable-lua-compiler")
remote.add_interface("disable-lua-compiler", {})
end
--#region utils
local function destroy_GUI(player)
local element = player.gui.screen.zLua_compiler
if element then
element.destroy()
end
end
local function on_click_on_compiler(player, entity)
local unit_number = entity.unit_number
local screenGui = player.gui.screen
if screenGui.zLua_compiler then
local player_index = player.index
local text = screenGui.zLua_compiler.flow.scroll_pane["zLua_program-input"].text
if text ~= '' then
compilers_text[unit_number] = text
compiled[unit_number] = load(text)
players_opened_compile[player_index] = nil
else
compilers_text[unit_number] = nil
compiled[unit_number] = nil
end
screenGui.zLua_compiler.destroy()
return false
end
local compiler_text = compilers_text[unit_number]
local main_frame = screenGui.add{type = "frame", name = "zLua_compiler", direction = "vertical"}
local flow = main_frame.add{type = "flow"}
flow.add{
type = "label",
style = "frame_title",
caption = {"item-name.zLua-compiler"},
ignored_by_interaction = true
}
local drag_handler = flow.add{type = "empty-widget", style = "draggable_space"}
drag_handler.drag_target = main_frame
drag_handler.style.right_margin = 0
drag_handler.style.horizontally_stretchable = true
drag_handler.style.height = 32
flow.add{
type = "sprite-button",
name = "zLua_close-compiler",
style = "frame_action_button",
sprite = "utility/close_white",
hovered_sprite = "utility/close_black",
clicked_sprite = "utility/close_black"
}
local is_have_errors = false
-- Data of the lowest element
local error_element_data = {type = "label", name = "error_message", caption = "", style = "bold_red_label"}
if compiler_text then
if compiled[unit_number] == nil then
is_have_errors = true
error_element_data.caption = {"lua-compiler.cant-compile"}
end
end
local buttons_row = main_frame.add{type = "table", name = "buttons_row", column_count = 8}
local content = {type = "sprite-button"}
if compiler_text then
content.name = "zLua_run"
content.sprite = "microcontroller-play-sprite"
buttons_row.add(content)
else
content.name = "zLua_refresh"
content.sprite = "refresh"
buttons_row.add(content)
end
content.name = "zLua_power-off"
content.sprite = "power-off"
if entity.rotatable then
if is_have_errors then
entity.rotatable = false
else
content.name = "zLua_power-on"
content.sprite = "power-on"
end
end
buttons_row.add(content)
content.name = "zLua_copy"
content.sprite = "microcontroller-copy-sprite"
buttons_row.add(content)
content.name = "zLua_paste"
content.sprite = "microcontroller-paste-sprite"
buttons_row.add(content)
local scroll_pane = main_frame.add{type = "scroll-pane", name = "scroll_pane"}
local textbox = scroll_pane.add{type = "text-box", name = "zLua_program-input", style = "lua_program_input"}
if entity.destructible then
textbox.text = compiler_text or DEFAULT_TEXT
else
textbox.text = compiler_text or ''
end
main_frame.add(error_element_data)
main_frame.force_auto_center()
return main_frame
end
local function clear_compiler_data(event)
local unit_number = event.entity.unit_number
compiled[unit_number] = nil
compilers_text[unit_number] = nil
end
--#endregion
--#region Events
local function left_mouse_click(event)
local player = game.get_player(event.player_index)
local entity = player.selected
if entity.name == "zLua-compiler" then
local is_destructible = entity.destructible
if is_destructible == false then
if entity.rotatable then
local f = compiled[entity.unit_number]
if f then
local is_ok, error = pcall(f, entity, player)
if not is_ok then
player.print(error, RED_COLOR)
end
return
end
end
else
entity.minable = false
entity.rotatable = false
entity.operable = false
end
if not player.admin then
entity.operable = false
player.print({"command-output.parameters-require-admin"})
return
end
local gui = on_click_on_compiler(player, entity)
if gui then
players_opened_compile[player.index] = entity
else
players_opened_compile[player.index] = nil
end
if is_destructible then
entity.destructible = false
end
end
end
local function on_gui_text_changed(event)
local element = event.element
if element.name ~= "zLua_program-input" then return end
local button = element.parent.parent.buttons_row.zLua_run
if button then
button.name = "zLua_refresh"
button.sprite = "refresh"
end
end
local function on_entity_settings_pasted(event)
local player = game.get_player(event.player_index)
if not player.admin then return end
local source = event.source
local destination = event.destination
if destination.name ~= source.name then return end
if source.name == "zLua-compiler" then
local sun = source.unit_number
local dun = destination.unit_number
compilers_text[dun] = compilers_text[sun]
compiled[dun] = compiled[sun]
end
end
local function on_player_removed(event)
players_opened_compile[event.player_index] = nil
end
local function on_player_far_from_compiler(event)
local player_index = event.player_index
local player = game.get_player(player_index)
destroy_GUI(player)
players_opened_compile[player_index] = nil
end
local function on_player_left_game(event)
local player_index = event.player_index
players_copyboard[player_index] = nil
players_opened_compile[player_index] = nil
end
local function on_player_joined_game(event)
local player_index = event.player_index
players_copyboard[player_index] = nil
destroy_GUI(game.get_player(player_index))
end
local function on_player_rotated_entity(event)
local entity = event.entity
if entity.name ~= "zLua-compiler" then return end
local player = game.get_player(event.player_index)
if not player.admin then return end
local gui = on_click_on_compiler(player, entity)
if gui then
players_opened_compile[player.index] = entity
else
players_opened_compile[player.index] = nil
end
end
local GUIS = {
["zLua_paste"] = function(element, player)
local text = players_copyboard[player.index]
if text == nil then return end
local parent = element.parent
parent.parent.scroll_pane["zLua_program-input"].text = text
local unit_number = players_opened_compile[player.index].unit_number
if text ~= '' then
local f = load(text)
local error_message_GUI = parent.parent.error_message
compilers_text[unit_number] = text
compiled[unit_number] = f
if type(f) == "function" then
local refresh_element = parent.buttons_row.zLua_refresh
if refresh_element then
refresh_element.name = "zLua_run"
refresh_element.sprite = "microcontroller-play-sprite"
end
else
error_message_GUI.caption = {"lua-compiler.cant-compile"}
players_opened_compile[player.index].rotatable = false
local power_element = parent.parent.buttons_row["zLua_power-on"]
if power_element then
power_element.name = "zLua_power-off"
power_element.sprite = "power-off"
end
end
else
compilers_text[unit_number] = nil
compiled[unit_number] = nil
end
--TODO: add undo, self destruction
end,
["zLua_copy"] = function(element, player)
players_copyboard[player.index] = element.parent.parent.scroll_pane["zLua_program-input"].tex
end,
["zLua_power-off"] = function(element, player)
local entity = players_opened_compile[player.index]
element.name = "zLua_power-on"
element.sprite = "power-on"
entity.rotatable = true
player.print({"lua-compiler.rotate-hint"})
end,
["zLua_power-on"] = function(element, player)
local entity = players_opened_compile[player.index]
element.name = "zLua_power-off"
element.sprite = "power-off"
entity.rotatable = false
end,
["zLua_close-compiler"] = function(element, player)
local entity = players_opened_compile[player.index]
local zLua_compiler = player.gui.screen.zLua_compiler
local buttons_row = zLua_compiler.buttons_row
if entity and entity.valid and buttons_row.zLua_refresh then
local text = zLua_compiler.scroll_pane["zLua_program-input"].text
local unit_number = entity.unit_number
if text ~= '' and text ~= DEFAULT_TEXT then
local f = load(text)
compilers_text[unit_number] = text
compiled[unit_number] = f
else
compilers_text[unit_number] = nil
compiled[unit_number] = nil
end
end
zLua_compiler.destroy()
end,
["zLua_refresh"] = function(element, player)
local unit_number = players_opened_compile[player.index].unit_number
local parent = element.parent
local text = parent.parent.scroll_pane["zLua_program-input"].text
if text ~= '' then
local f = load(text)
compilers_text[unit_number] = text
compiled[unit_number] = f
local error_message_GUI = parent.parent.error_message
if type(f) == "function" then
element.name = "zLua_run"
element.sprite = "microcontroller-play-sprite"
else
error_message_GUI.caption = {"lua-compiler.cant-compile"}
end
else
compilers_text[unit_number] = nil
compiled[unit_number] = nil
player.print({"lua-compiler.no-code"})
local power_element = parent.parent.buttons_row["zLua_power-on"]
if power_element then
power_element.name = "zLua_power-off"
power_element.sprite = "power-off"
players_opened_compile[player.index].rotatable = false
end
end
end,
["zLua_run"] = function(element, player)
local entity = players_opened_compile[player.index]
local error_message_GUI = element.parent.parent.error_message
local is_ok, error = pcall(compiled[entity.unit_number], entity, player)
if not is_ok then
error_message_GUI.caption = error
local power_element = element.parent.buttons_row["zLua_power-on"]
if power_element then
power_element.name = "zLua_power-off"
power_element.sprite = "power-off"
entity.rotatable = false
end
else
error_message_GUI.caption = ""
end
end
}
local function on_gui_click(event)
local element = event.element
local f = GUIS[element.name]
if f then f(element, game.get_player(event.player_index)) end
end
--#endregion
--#region Pre-game stage
local function check_all_compilers()
for unit_number, text in pairs(compilers_text) do
compiled[unit_number] = load(text)
end
end
local function link_data()
mod_data = global["lua-compiler"]
players_opened_compile = mod_data.players_opened_compile
compilers_text = mod_data.compilers_text
players_copyboard = mod_data.players_copyboard
end
local function set_filters()
local filters = {{filter = "name", name = "zLua-compiler"}}
script.set_event_filter(defines.events.on_player_mined_entity, filters)
script.set_event_filter(defines.events.on_entity_died, filters)
script.set_event_filter(defines.events.on_robot_mined_entity, filters)
script.set_event_filter(defines.events.script_raised_destroy, filters)
end
local function update_global_data()
global["lua-compiler"] = global["lua-compiler"] or {}
mod_data = global["lua-compiler"]
mod_data.compilers_text = mod_data.compilers_text or {}
mod_data.players_opened_compile = {}
mod_data.players_copyboard = {}
link_data()
for _, player in pairs(game.players) do
destroy_GUI(player)
end
for unit_number, entity in pairs(compilers_text) do
if not (entity and entity.valid) then
compilers_text[unit_number] = nil
compiled[unit_number] = nil
end
end
set_filters()
check_all_compilers()
end
M.on_init = update_global_data
M.on_configuration_changed = update_global_data
M.on_load = function()
link_data()
set_filters()
check_all_compilers()
end
M.add_remote_interface = function()
-- https://lua-api.factorio.com/latest/LuaRemote.html
remote.remove_interface("lua-compiler") -- For safety
remote.add_interface("lua-compiler", {
get_source = function()
return script.mod_name
end,
get_mod_data = function()
return mod_data
end,
execute_compiler = function(entity, player)
local f = compiled[entity.unit_number]
if f ~= nil then
f(entity, player)
end
end,
add_compiler = function(entity, text)
local unit_number = entity.unit_number
local f = load(text)
compiled[unit_number] = f
if type(f) == "function" then
compilers_text[unit_number] = text
entity.destructible = false
entity.minable = false
entity.rotatable = false
entity.operable = true
end
return f
end,
change_text = function(entity, text)
local unit_number = entity.unit_number
local f = load(text)
compiled[unit_number] = f
if type(f) == "function" then
compilers_text[unit_number] = text
end
return f
end,
get_function = function(entity)
return compiled[entity.unit_number]
end,
close_complier_gui = destroy_GUI,
open_complier_gui = function(player, entity)
destroy_GUI(player)
local gui = on_click_on_compiler(player, entity)
if gui then
players_opened_compile[player.index] = entity
else
players_opened_compile[player.index] = nil
end
end
})
end
--#endregion
M.events = {
[defines.events.on_gui_click] = function(event)
pcall(on_gui_click, event)
end,
[defines.events.on_entity_settings_pasted] = function(event)
pcall(on_entity_settings_pasted, event)
end,
["open-gui"] = function(event)
pcall(left_mouse_click, event)
end,
[defines.events.on_gui_text_changed] = function(event)
pcall(on_gui_text_changed, event)
end,
[defines.events.on_player_joined_game] = on_player_joined_game,
[defines.events.on_player_removed] = on_player_removed,
[defines.events.on_player_respawned] = function(event)
pcall(on_player_far_from_compiler, event)
end,
[defines.events.on_player_respawned] = function(event)
pcall(on_player_far_from_compiler, event)
end,
[defines.events.on_player_left_game] = function(event)
pcall(on_player_left_game, event)
end,
[defines.events.on_player_rotated_entity] = function(event)
pcall(on_player_rotated_entity, event)
end,
[defines.events.on_player_demoted] = function(event)
pcall(destroy_GUI, game.get_player(event.player_index))
end,
[defines.events.on_player_mined_entity] = clear_compiler_data,
[defines.events.on_entity_died] = clear_compiler_data,
[defines.events.on_robot_mined_entity] = clear_compiler_data,
[defines.events.script_raised_destroy] = clear_compiler_data,
}
return M
|
object_mobile_dressed_padawan_wke_03 = object_mobile_shared_dressed_padawan_wke_03:new {
}
ObjectTemplates:addTemplate(object_mobile_dressed_padawan_wke_03, "object/mobile/dressed_padawan_wke_03.iff")
|
function xAdmin.Core.RegisterCommandInternal(cmd, dsc, pwr, fnc)
xAdmin.Commands[cmd] = {
command = cmd,
desc = dsc or "n/a",
power = xAdmin.Config.PowerlevelPermissions[cmd] or xAdmin.Config.PowerLevelDefault,
func = fnc
}
end
function xAdmin.Core.RegisterCommand(command, desc, power, func, alias)
if not command then
return
end
if not func then
return
end
// xAdmin.Commands[command] = {
// command = command,
// desc = desc or "n/a",
// power = xAdmin.Config.PowerlevelPermissions[command] or xAdmin.Config.PowerLevelDefault,
// func = func
// }
print("[xAdmin] Loading command " .. command .. ".")
xAdmin.Core.RegisterCommandInternal(command, desc, power, func)
if alias then
if not istable(alias) then return end
for k, v in pairs(alias) do
xAdmin.Core.RegisterCommandInternal(v, desc, power, func)
print("", "Alias Registered: " .. v)
end
end
end
function xAdmin.Core.IsCommand(arg)
return xAdmin.Commands[arg] or false
end
for _, files in SortedPairs(file.Find("xadmin/commands/*.lua", "LUA"), true) do
print("[xAdmin] Loading commands located in: " .. files)
include("xadmin/commands/" .. files)
end
concommand.Add("xadmin", function(ply, cmd, args, argStr)
if not args[1] then
return
end
if ply == NULL then
ply = xAdmin.Console
end
local comTbl = xAdmin.Commands[string.lower(args[1])]
if not comTbl then
return
end
if not ply:HasPower(comTbl.power) then
return
end
local formattedArgs = xAdmin.Core.FormatArguments(string.Explode(" ", argStr))
table.remove(formattedArgs, 1)
if hook.Run("xAdminCanRunCommand", ply, string.lower(args[1]), formattedArgs, true) == false then
return
end
comTbl.func(ply, formattedArgs)
end)
hook.Add("PlayerSay", "xAdminChatCommands", function(ply, msg)
if string.sub(msg, 1, #xAdmin.Config.Prefix) == xAdmin.Config.Prefix then
local args = xAdmin.Core.FormatArguments(string.Explode(" ", msg))
args[1] = string.sub(args[1], #xAdmin.Config.Prefix + 1)
local command = xAdmin.Core.IsCommand(string.lower(args[1]))
if command and ply:HasPower(command.power) then
local cmdName = args[1]
table.remove(args, 1)
if hook.Run("xAdminCanRunCommand", ply, command.command, args, false) == false then
return
end
command.func(ply, args)
--print("[xAdmin] " .. ply:Nick() .. " [" .. ply:SteamID() .. "] ran command " .. args[1] .. ": " .. msg)
return ""
end
end
end)
|
local p = peripheral.find("manaPool")
test.assert(p, "Pool not found")
test.eq(500000, p.getMana(), "Problem with mana")
test.eq(1000000, p.getMaxMana(), "Max mana")
test.eq(false, p.isFull(), "is full")
test.eq(false, p.isEmpty(), "is empty")
|
local script = [[
git clone https://github.com/microsoft/vscode-node-debug2.git
cd vscode-node-debug2
npm install
npx gulp build
]]
return {
install_script = function()
return script
end,
path = function()
local resolve = require("installer/utils/fs").resolve
local server_path = require("installer/utils/fs").module_path("da", "node2")
return resolve(server_path, "vscode-node-debug2/out/src/nodeDebug.js")
end,
}
|
require("msa/Core")
local AnimAction = require("msa/Animating/AnimAction")
local Animation = {}
Animation.__index = Animation
setmetatable(Animation, {__call = function (cls, ...) return cls.New(...) end })
--##################################################################
-- constructor
--##################################################################
function Animation.New(params)
local self = setmetatable({}, Animation)
-- constructor
self.animationArray = {};
self.stepCount = 0;
self.currentStep = 0;
return self
end
--##################################################################
-- special functions
--##################################################################
--- Wait for all previous animations to finish
function Animation:Await(onCompleteFunc)
print("TODO : Animation:Await")
return self
end
--- Delay current animation
function Animation:Delay(seconds)
print("TODO : Animation:Delay")
return self
end
--- function to execute then all previous commands are finished. (function gets array of animated objects as parameter.)
function Animation:Execute(onCompleteFunc)
print("TODO : Animation:Execute")
return self
end
--##################################################################
-- Functions to prepare items for chaining
--##################################################################
--- Take one or many Items (for chaining)
function Animation:Take(...)
print("TODO : Animation:Take")
return self
end
--- Take items from container (for chaining)
function Animation:TakeFrom(container, amount)
print("TODO : Animation:TakeFrom")
return self
end
--- Clone one or many Items (for chaining)
function Animation:Clone(target, amount)
--print("TODO : Animation:Clone")
--PrintObject(target, "clone")
if type(target) == "string" then target = getObjectFromGUID(target) end
if target == nil then PrintError("Animation:Clone parameter target can't be nil.") return self end
amount = amount or 1
for i = 1, amount do
self.stepCount = self.stepCount + 1
self.animationArray[self.stepCount] = {
action = AnimAction.Clone,
target = target,
amount = amount,
targetInteractable = target.interactable
}
end
target.interactable = false;
return self
end
--##################################################################
-- Single action chaining functions
--##################################################################
--- Move items To new position
function Animation:Move(position)
--print("TODO : Animation:Move")
if type(position) ~= "table" then PrintError("Animation:Move position must be table."); return self; end
local x = position["x"] or position[1]
local y = position["y"] or position[2]
local z = position["z"] or position[3]
if type(x) ~= "number" then PrintError("Animation:Move position must have x number in table."); return self; end
if type(y) ~= "number" then PrintError("Animation:Move position must have y number in table."); return self; end
if type(z) ~= "number" then PrintError("Animation:Move position must have z number in table."); return self; end
self.stepCount = self.stepCount + 1
self.animationArray[self.stepCount] = {
action = AnimAction.Move,
target = {x, y, z}
}
return self
end
--- Move items To object
function Animation:MoveTo(target)
--print("TODO : Animation:MoveTo target : "..type(target))
if type(target) == "string" then
target = GetObject(target)
end
if type(target) ~= "userdata" then PrintError("Animation:MoveTo target must be valid object."); return self; end
self.stepCount = self.stepCount + 1
self.animationArray[self.stepCount] = {
action = AnimAction.MoveTo,
target = target,
targetInteractable = target.interactable
}
target.interactable = false;
return self
end
--- Rotate item/items To new rotation
function Animation:Rotate(x, y, z)
print("TODO : Animation:Rotate")
return self
end
--- Scale item/items To new scale
function Animation:Scale(scale)
print("TODO : Animation:Scale")
return self
end
--- Transform item/items To new position AND rotation AND scale
function Animation:Transform(position, rotation, scale)
print("TODO : Animation:Transform")
return self
end
--- Teleport item/items instantly To new position AND rotation AND scale
function Animation:Teleport(position, rotation, scale)
print("TODO : Animation:Teleport")
return self
end
--- Flip item/items
function Animation:Flip()
print("TODO : Animation:Flip")
return self
end
--- Sort item/items using custom sort function
function Animation:Sort(sortFunc)
print("TODO : Animation:Sort")
return self
end
--- Shuffle items in container
function Animation:Shuffle()
print("TODO : Animation:Shuffle")
return self
end
--- Lock item/items
function Animation:Lock()
print("TODO : Animation:Lock")
return self
end
--- Unlock item/items
function Animation:Unlock()
print("TODO : Animation:Unlock")
return self
end
--- Delete item/items
function Animation:Delete()
print("TODO : Animation:Delete")
return self
end
--- Draw to player
function Animation:Draw(player, amount)
print("TODO : Animation:Draw")
return self
end
--- Deal to all players
function Animation:Deal(amount)
print("TODO : Animation:Deal")
return self
end
--##################################################################
-- Inner works
--##################################################################
--- Move items To new position
function Animation:GetObjectCount()
return self.stepCount;
end
return Animation
|
--- The Lemur test runner script.
-- This script can run with Lemur to perform automated tests.
--
-- @script LemurTestRunner
-- @release 0.2.0
-- @license MIT
-- Add init.lua to path allowing Lemur (and other dependencies) to load
package.path = package.path .. ";?/init.lua"
local Lemur = require("lemur")
local Habitat = Lemur.Habitat.new()
--- The source locations to load in lemur
local Source = { -- This can potentially be loaded from a project.json
{ "src/client/", "StarterPlayer.StarterPlayerScripts" },
{ "src/loading/", "ReplicatedFirst" },
{ "src/server/", "ServerScriptService" },
{ "src/shared/", "ReplicatedStorage" },
{ "Packages/", "ReplicatedStorage.Packages" },
{ "tests/integration/", "ReplicatedStorage.Tests.Integration" },
{ "tests/runners/", "ReplicatedStorage.Tests.Runners" },
{ "tests/unit/", "ReplicatedStorage.Tests.Unit" },
{ "modules/testez/", "ReplicatedStorage.Modules.TestEZ" },
}
--- Tokenizes a habitat path.
-- @param path the path to tokenize
-- @return a table of the tokens
local function tokenizePath(path)
local tokens = {}
for token in string.gmatch(path, "[^%.]+") do
table.insert(tokens, token)
end
return tokens
end
-- Build the project in Lemur
for _, pair in ipairs(Source) do
local source = Habitat:loadFromFs(pair[1])
local tokens = tokenizePath(pair[2])
local container = Habitat.game:GetService(tokens[1])
local containerExists = false
-- Find the object we're placing this source in
if #tokens == 1 then
containerExists = true
else
for i = 2, #tokens - 1 do
local found = container:FindFirstChild(tokens[i])
if not found then
found = Habitat.Instance.new("Folder")
found.Name = tokens[i]
found.Parent = container
end
container = found
end
local object = container:FindFirstChild(tokens[#tokens])
if object then
container = object
containerExists = true
end
end
-- If the final container exists place everything inside.
if containerExists then
for _, object in ipairs(source:GetChildren()) do
object.Parent = container
end
source:Destroy()
else -- If it doesn't, replace it
source.Name = tokens[#tokens]
source.Parent = container
end
end
-- Load variables dependent on the build
local ReplicatedStorage = Habitat.game:GetService("ReplicatedStorage")
local Tests = Habitat:require(
ReplicatedStorage
:WaitForChild("Tests")
:WaitForChild("Runners")
:WaitForChild("Tests")
)
local Roots = { ReplicatedStorage.Tests }
-- Run tests and set up exit status
local completed, result = Tests(Roots)
local status = 0
-- Determine and report results
if completed then
if not result then
print("Tests have failed.")
status = 1
end
else
print(result)
status = 2
end
os.exit(status)
|
-- Generated from template
local MANIAC_TEAM = DOTA_TEAM_BADGUYS
local SURVIVORS_TEAM = DOTA_TEAM_GOODGUYS
local GENERATORS_TEAM = DOTA_TEAM_CUSTOM_1
local generator_building
scoreFirstTeam = 0
scoreSecondTeam = 0
if CAddonTemplateGameMode == nil then
CAddonTemplateGameMode = class({})
end
function Precache( context )
--[[
Precache things we know we'll use. Possible file types include (but not limited to):
PrecacheResource( "model", "*.vmdl", context )
PrecacheResource( "soundfile", "*.vsndevts", context )
PrecacheResource( "particle", "*.vpcf", context )
PrecacheResource( "particle_folder", "particles/folder", context )
]]
end
-- Create the game mode when we activate
function Activate()
GameRules.AddonTemplate = CAddonTemplateGameMode()
GameRules.AddonTemplate:InitGameMode()
end
function CAddonTemplateGameMode:InitGameMode()
print( "Template addon is loaded." )
-- GameRules:GetGameModeEntity():SetThink( "OnThink", self, "GlobalThink", 2 )
ListenToGameEvent('entity_killed', Dynamic_Wrap( CAddonTemplateGameMode, 'test' ) , self )
ListenToGameEvent('dota_player_pick_hero', Dynamic_Wrap(CAddonTemplateGameMode, 'OnPlayerPickHero'), self)
ListenToGameEvent('entity_killed', Dynamic_Wrap( CAddonTemplateGameMode, 'onGewneratorKilled' ) , self )
end
function CAddonTemplateGameMode:onGewneratorKilled(event)
local killedUnit = EntIndexToHScript( event.entindex_killed )
print(killedUnit == generator_building)
if killedUnit == generator_building then
CAddonTemplateGameMode:generatePortal()
end
end
function CAddonTemplateGameMode:generatePortal()
local pos2 = Vector(1000, 128, 128)
generator_building = CreateUnitByName("npc_dota_creature_gnoll_portal", pos2, true, nil, nil, GENERATORS_TEAM)
generator_building:SetAbsOrigin(pos2)
generator_building:RemoveModifierByName("modifier_invulnerable")
end
function CAddonTemplateGameMode:test(event)
local killedUnit = EntIndexToHScript( event.entindex_killed )
if killedUnit and killedUnit:IsRealHero() then
if killedUnit:GetTeamNumber() == 3 then
scoreFirstTeam = scoreFirstTeam + 1
if scoreFirstTeam >= 1 then
GameRules:MakeTeamLose(3)
end
end
if killedUnit:GetTeamNumber() == 2 then
scoreSecondTeam = scoreSecondTeam + 1
if scoreSecondTeam >= 1 then
GameRules:MakeTeamLose(2)
end
end
end
end
function CAddonTemplateGameMode:OnPlayerPickHero(keys)
CAddonTemplateGameMode:GenerateGenerator(128, 128, 128)
end
function CAddonTemplateGameMode:GenerateGenerator(x, y, z)
local pos2 = Vector(x, y, z)
-- Spawning
generator_building = CreateUnitByName("npc_dota_creature_gnoll_generator", pos2, true, nil, nil, GENERATORS_TEAM)
generator_building:SetAbsOrigin(pos2)
generator_building:RemoveModifierByName("modifier_invulnerable")
end
-- Evaluate the state of the game
function CAddonTemplateGameMode:OnThink()
if GameRules:State_Get() == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
--print( "Template addon script is running." )
elseif GameRules:State_Get() >= DOTA_GAMERULES_STATE_POST_GAME then
return nil
end
return 1
end
|
collisions = {}
collisions.point = hc.circle(0, 0, 5) -- this collider is used to probe for objects at locations
function collisions.handleShip(ship)
for shape, delta in pairs(hc.collisions(ship.collider)) do
if shape.class == 'land' or shape.class == 'spawn' then
collisions.resolve(ship, delta, 1, 0.2)
if shape.class == 'spawn' and game.mode == game.captureTheFlag then
spawns.stealFlag(shape.parent, ship)
end
elseif shape.class == 'border' then
collisions.resolve(ship, delta, 0.03, 0.9)
end
if not ship.invulnerable then
if shape.class == 'ship' then
if not shape.parent.invulnerable then
ships.ram(ship, shape.parent, delta)
end
elseif shape.class == 'powerup' then
powerups.remove(shape.parent)
sounds.woodBreak()
sounds.splash()
if ship.powerup == 'none' then ship.powerup = powerups.get(ship) end
elseif shape.class == 'mine' then
mines.detonate(shape.parent)
ships.damageByAndScore(ship, shape.parent.ship, config.powerups.mineDamage / 4)
elseif shape.class == 'shockwave' then
ships.damageByAndScore(ship, shape.parent.ship, config.powerups.mineDamage / 4)
elseif shape.class == 'tornado' then
local tornado = shape.parent
ships.damageByAndScore(ship, tornado.ship, tornado.dmg)
end
end
end
end
function collisions.handleShockwave(shockwave)
for shape, dleta in pairs(hc.collisions(shockwave.collider)) do
if shape.class == 'mine' then mines.detonate(shape.parent) end
end
end
function collisions.isLand(xPos, yPos)
collisions.point:moveTo(xPos, yPos)
for shape, delta in pairs(hc.collisions(collisions.point)) do
if shape.class == 'land' then return true end
end
collisions.point:moveTo(bounds.dim, bounds.dim)
return false
end
function collisions.handleFlag(flag)
for shape, delta in pairs(hc.collisions(flag.collider)) do
if shape.class == 'ship' then
local ship = shape.parent
if ship.powerup == 'none' then
flags.remove(flag)
ships.setPowerup(ship, flag.color .. 'Flag')
end
end
end
end
function collisions.handleBullet(bullet)
for shape, delta in pairs(hc.collisions(bullet.collider)) do
local class = shape.class
if collisions.isTransparentForBullets(class) then
-- do nothing
else
bullets.remove(bullet)
explosions.new(bullet.x, bullet.y)
if class == 'mine' then mines.detonate(shape.parent) end
if class == 'ship' or class == 'powerup' then
sounds.impact()
else
sounds.impactSand()
end
if class == 'ship' then
if not shape.parent.invulnerable then
ships.damageByAndScore(shape.parent, bullet.ship, config.bullets.damage)
end
elseif class == 'powerup' then
powerups.remove(shape.parent)
end
end
end
end
function collisions.handlePowerup(powerup)
for shape, delta in pairs(hc.collisions(powerup.collider)) do
if shape.class == 'land' or shape.class == 'spawn' then
powerups.remove(powerup)
elseif shape.class == 'tornado' or shape.class == 'shockwave' then
sounds.woodBreak()
powerups.remove(powerup)
end
end
end
function collisions.resolve(object, delta, hardness, restitution)
object.x = object.x + delta.x * hardness
object.y = object.y + delta.y * hardness
object.vx = object.vx * restitution
object.vy = object.vy * restitution
end
function collisions.isTransparentForBullets(class)
if class == 'bullet' or class == 'border' or class == 'shockwave' then return true
elseif class == 'tornado' or class == 'center' or class =='land' then return true
elseif class == 'flag' or class == 'spawn' then return true
end
return false
end
|
local leader = nil
local level = nil
os.loadAPI("AIBUT/config")
local mode = config.type
os.unloadAPI("AIBUT/config")
local stack = {
admin_control = {
action = function(params)
local code = nil
local i = 0
for v in ipairs(params) do
i++
if i ~= 1 then
code = code .. " "
end
code = code .. v
end
end,
level = 4,--4 = admin, 3 = trade, 2 = leader, 1 = self
expires = -1--How long the world has been running in seconds.
}
}
function locateByGPS()
function establishLead(id)
rednet.broadcast("getLeader " .. os.getComputerID())
local id, msg = rednet.receive("herd", 10)
_, _, leader, level = string.find(msg, "^giveLeader (%d+) level (%d+)$")
if not (leader and level) then
return establishLead(id)
end
end
function findID(herdIDs, findID)
|
local sqlite3 = require("lsqlite3")
local db = assert( sqlite3:open_memory() )
assert( db:exec[[
CREATE TABLE customer (
id INTEGER PRIMARY KEY,
name VARCHAR(40)
);
CREATE TABLE invoice (
id INTEGER PRIMARY KEY,
customer INTEGER NOT NULL,
title VARCHAR(80) NOT NULL,
article1 VARCHAR(40) NOT NULL,
price1 REAL NOT NULL,
article2 VARCHAR(40),
price2 REAL
);
CREATE TABLE invoice_overflow (
id INTEGER PRIMARY KEY,
invoice INTEGER NOT NULL,
article VARCHAR(40) NOT NULL,
price REAL NOT NULL
);
INSERT INTO customer VALUES(
1, "Michael" );
INSERT INTO invoice VALUES(
1, 1, "Computer parts", "harddisc", 89.90, "floppy", 9.99 );
INSERT INTO customer VALUES(
2, "John" );
INSERT INTO invoice VALUES(
2, 2, "Somme food", "apples", 2.79, "pears", 5.99 );
INSERT INTO invoice_overflow VALUES(
NULL, 2, "grapes", 6.34 );
INSERT INTO invoice_overflow VALUES(
NULL, 2, "strawberries", 4.12 );
INSERT INTO invoice_overflow VALUES(
NULL, 2, "tomatoes", 6.17 );
INSERT INTO invoice VALUES(
3, 2, "A new car", "Cybercar XL-1000", 65000.00, NULL, NULL );
]] )
local function customer_name(id)
local stmt = db:prepare("SELECT name FROM customer WHERE id = ?")
stmt:bind_values(id)
stmt:step()
local r = stmt:get_uvalues()
stmt:finalize()
return r
end
local function all_invoices()
return db:nrows("SELECT id, customer, title FROM invoice")
end
local function all_articles(invoice)
local function iterator()
local stmt, row
-- Get the articles that are contained in the invoice table itself.
stmt = db:prepare("SELECT article1, price1, article2, price2 FROM invoice WHERE id = ?")
stmt:bind_values(invoice)
stmt:step()
row = stmt:get_named_values()
-- Every Invoice has at least one article.
coroutine.yield(row.article1, row.price1)
-- Maybe the Invoice has a second article?
if row.article2 then
-- Yes, there is a second article, so return it.
coroutine.yield(row.article2, row.price2)
-- When there was an second article, maybe there are even
-- more articles in the overflow table? We will see...
stmt = db:prepare("SELECT article, price FROM invoice_overflow WHERE invoice = ? ORDER BY id")
stmt:bind_values(invoice)
for row in stmt:nrows() do
coroutine.yield(row.article, row.price)
end
end
end
return coroutine.wrap(iterator)
end
for invoice in all_invoices() do
local id = invoice.id
local name = customer_name(invoice.customer)
local title = invoice.title
print()
print("Invoice #"..id..", "..name..": '"..title.."'")
print("----------------------------------------")
for article, price in all_articles(id) do
print( string.format("%20s %8.2f", article, price) )
end
print()
end
|
-- @Author: Administrator
-- @Date: 2016-11-21 19:15:01
-- @Last Modified by: Administrator
-- @Last Modified time: 2016-11-21 20:32:55
local CLIENT_LANG = select(3, GetVersion())
local JH_CALL_AJAX = {}
local JH_AJAX_TAG = "JH_AJAX#" -- event CURL_REQUEST_RESULT arg0
local tinsert, tconcat = table.insert, table.concat
local Curl = {}
Curl.__index = Curl
local function console_log(message)
Log("[JH] " .. message)
end
local conf_default = {
charset = 'utf8',
type = 'post',
data = {},
dataType = "text",
ssl = false,
timeout = 3,
-- done
success = function(szContent, dwBufferSize, option)
console_log("Curl " .. option.url .. " - success")
end,
error = function(szContent, dwBufferSize, option)
console_log("Curl " .. option.url .. " - error")
end,
}
local function ConvertToUTF8(data)
if type(data) == "table" then
local t = {}
for k, v in pairs(data) do
if type(k) == "string" then
t[ConvertToUTF8(k)] = ConvertToUTF8(v)
else
t[k] = ConvertToUTF8(v)
end
end
return t
elseif type(data) == "string" then
return AnsiToUTF8(data)
else
return data
end
end
local function EncodePostData(data, t, prefix)
if type(data) == "table" then
local first = true
for k, v in pairs(data) do
if first then
first = false
else
tinsert(t, "&")
end
if prefix == "" then
EncodePostData(v, t, k)
else
EncodePostData(v, t, prefix .. "[" .. k .. "]")
end
end
else
if prefix ~= "" then
tinsert(t, prefix)
tinsert(t, "=")
end
tinsert(t, data)
end
end
local function serialize(data)
local t = {}
EncodePostData(data, t, "")
local text = tconcat(t)
return text
end
-- constructor
function Curl:ctor(option)
assert(option and option.url)
local oo = {}
setmetatable(oo, self)
setmetatable(option, { __index = conf_default })
local szKey = GetTickCount() * 100
while JH_CALL_AJAX[JH_AJAX_TAG .. szKey] do
szKey = szKey + 1
end
szKey = JH_AJAX_TAG .. szKey
JH_CALL_AJAX[szKey] = option
local url, data = option.url, option.data
if option.charset:lower() == "utf8" then
url = ConvertToUTF8(url)
data = ConvertToUTF8(data)
end
if string.sub(url, 1, 6) == "https:" then
option.ssl = true
end
if option.type:lower() == "post" then
CURL_HttpPost(szKey, url, data, option.ssl, option.timeout)
elseif option.type:lower() == "get" then
data = serialize(data)
if not url:find("?") then
url = url .. "?"
elseif url:sub(-1) ~= "&" then
url = url .. "&"
end
url = url .. data
CURL_HttpRqst(szKey, url, option.ssl, option.timeout)
end
oo.szKey = szKey
return oo
end
function Curl:done(success)
local option = JH_CALL_AJAX[self.szKey]
if option then
option.success = success
end
return self
end
function Curl:fail(error)
local option = JH_CALL_AJAX[self.szKey]
if option then
option.error = error
end
return self
end
function Curl:always(complete)
local option = JH_CALL_AJAX[self.szKey]
if option then
option.complete = complete
end
return self
end
JH.RegisterEvent("CURL_REQUEST_RESULT.AJAX", function()
local szKey = arg0
local bSuccess = arg1
local szContent = arg2
local dwBufferSize = arg3
if JH_CALL_AJAX[szKey] then
local option = JH_CALL_AJAX[szKey]
local fnError = option.error
local bError = not bSuccess
if option.complete then
local status, err = pcall(option.complete, szContent, dwBufferSize, option)
if not status then
JH.Debug("CURL # " .. option.url .. ' - complete - PCALL ERROR - ' .. err)
end
end
if bSuccess then
if option.charset:lower() == "utf8" and szContent ~= nil and CLIENT_LANG == "zhcn" then
szContent = UTF8ToAnsi(szContent)
end
if option.dataType == "json" then
local result, err = JH.JsonDecode(szContent)
if result then
szContent = result
else
JH.Debug("CURL # JsonDecode ERROR")
bError = true
end
end
local status, err = pcall(option.success, szContent, dwBufferSize, option)
if not status then
JH.Debug("CURL # " .. option.url .. ' - success - PCALL ERROR - ' .. err)
end
end
if bError then
local status, err = pcall(fnError, "failed", dwBufferSize, option)
if not status then
JH.Debug("CURL # " .. option.url .. ' - error - PCALL ERROR - ' .. err)
end
end
JH_CALL_AJAX[szKey] = nil
end
end)
JH.Curl = setmetatable({}, { __call = function(me, ...) return Curl:ctor( ... ) end, __newindex = function() end, __metatable = true })
-- function JH.Get()
-- end
-- function JH.Post()
-- end
|
--Client-side script: Taximeter
--Created by Exciter, anumaz, 04.05.2014
--Last updated 05.05.2014 by Exciter
--Released as open source. This header should remain intact. Otherwise no use restrictions.
-- configuration
taxiModels = {[420]=true, [438]=true} -- Vehicle models
defaultfare = 21 -- Default taxi fare
syncInterval = 30000 --ms
minFare, maxFare = 15, 30
|
function dofile(filename)
local f = assert(loadfile(filename))
return f()
end
|
local Area = require("api.Area")
local TestUtil = require("api.test.TestUtil")
local Item = require("api.Item")
local Assert = require("api.test.Assert")
local Map = require("api.Map")
local World = require("api.World")
function test_home_preserves_items_on_renew()
local north_tyris_area = Area.create_unique("elona.north_tyris", "root")
local ok, north_tyris_map = assert(north_tyris_area:load_or_generate_floor(north_tyris_area:starting_floor()))
local your_home_area = Area.create_unique("elona.your_home", north_tyris_area)
local ok, first_floor = assert(your_home_area:load_or_generate_floor(your_home_area:starting_floor()))
TestUtil.set_player(north_tyris_map)
Map.set_map(north_tyris_map)
local item = Item.create("elona.putitoro", 10, 10, {}, first_floor)
local item_count = Item.iter(first_floor):length()
Assert.is_truthy(Map.travel_to(first_floor))
Assert.is_truthy(Map.travel_to(north_tyris_map))
World.pass_time_in_seconds(60 * 60 * 24 * 31 * 2)
Assert.gt(first_floor.renew_major_date, World.date_hours())
Assert.is_truthy(Map.travel_to(first_floor))
Assert.eq(item_count, Item.iter(first_floor):length())
Assert.is_truthy(item.location)
end
function test_town_removes_items_on_renew()
local north_tyris_area = Area.create_unique("elona.north_tyris", "root")
local ok, north_tyris_map = assert(north_tyris_area:load_or_generate_floor(north_tyris_area:starting_floor()))
local vernis_area = Area.create_unique("elona.vernis", north_tyris_area)
local ok, vernis = assert(vernis_area:load_or_generate_floor(vernis_area:starting_floor()))
TestUtil.set_player(north_tyris_map)
Map.set_map(north_tyris_map)
local item = Item.create("elona.putitoro", 10, 10, {}, vernis)
Assert.is_truthy(Map.travel_to(vernis))
Assert.is_truthy(Map.travel_to(north_tyris_map))
World.pass_time_in_seconds(60 * 60 * 24 * 31 * 2)
Assert.gt(vernis.renew_major_date, World.date_hours())
Assert.is_truthy(Map.travel_to(vernis))
Assert.eq(nil, item.location)
end
|
function onSay(cid, words, param, channel)
if(param == '') then
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Command requires param.")
return true
end
local tid = cid
local t = string.explode(param, ",")
if(t[2]) then
tid = getPlayerByNameWildcard(t[2])
if(not tid or (isPlayerGhost(tid) and getPlayerGhostAccess(tid) > getPlayerGhostAccess(cid))) then
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Player " .. t[2] .. " not found.")
return true
end
end
local tmp = t[1]
if(not tonumber(tmp)) then
tmp = getTownId(tmp)
if(not tmp) then
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Town " .. t[1] .. " does not exists.")
return true
end
end
local pos = getTownTemplePosition(tmp, false)
if(not pos or isInArray({pos.x, pos.y}, 0)) then
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Town " .. t[1] .. " does not exists or has invalid temple position.")
return true
end
pos = getClosestFreeTile(tid, pos)
if(not pos or isInArray({pos.x, pos.y}, 0)) then
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Destination not reachable.")
return true
end
tmp = getCreaturePosition(tid)
if(doTeleportThing(tid, pos, true) and not isPlayerGhost(tid)) then
doSendMagicEffect(tmp, CONST_ME_POFF)
doSendMagicEffect(pos, CONST_ME_TELEPORT)
end
return true
end
|
if x then
print("guard")
if y then
if z then
print("z")
else
print("not z")
end
end
elseif a then
print("a")
end
|
print(pcall(require))
--> ~^false\t.*value needed
print(pcall(require, {}))
--> ~^false\t.*must be a string
print(require "testlib.foo") -- points at testlib/foo.lua
--> =foo
--> =bar
-- Second time, the module is already loaded so no side effects.
print(require "testlib.foo")
--> =bar
print(package.loaded["testlib.foo"])
--> =bar
print(require "testlib.bar") -- points at testlib/bar/init.lua
--> =42
|
------------------------------------------------------------------------
-- Signal.lua
-- @version v1.0.0
------------------------------------------------------------------------
-- private types
type fn = (...any) -> ...any
type table = {any}
type array<T> = {T}
-- Complex
export type Complex = {
X: number,
Y: number,
Magnitude: (Complex) -> number,
AbsSquare: (Complex) -> number,
Conjugate: (Complex) -> Complex,
ToPolar: (Complex) -> (number, number),
Orbit: (Complex, c: Complex, maxIter: number, escapeOrbit: number?) -> number
-- no way to define operator overloads?
}
-- List
export type List = {
[number]: ListNode,
Push: (List, v: any) -> nil,
Pop: (List) -> any,
Front: (List) -> any,
Back: (List) -> any,
Size: (List) -> number,
ToArray: (List) -> (array<any>, number)
}
export type ListNode = {any | ListNode?}
-- Signal
export type Connection = {
[number]: Connection | fn,
IsActive: (Connection) -> boolean,
Disconnect: (Connection) -> nil
}
export type Signal = {
Connect: (Signal, callback: fn) -> Connection,
Wait: (Signal) -> ...any,
Fire: (Signal, ...any) -> nil,
DisconnectAll: (Signal) -> nil
}
return nil
|
local class = require 'EasyLD.lib.middleclass'
local SFX = class('SFX')
function SFX:initialize(name)
end
return SFX
|
local class = require "lib.lua-oop"
Timer = class("Timer")
function Timer:constructor(timeOutSecs, oneShoot, start)
self.timeOutSecs = timeOutSecs
self.oneShoot = oneShoot
self.started = false
self.hasTimeOuted = false
self.timeout = false
self.onTimeouts = {}
self.resetRequested = false
if start then
self:start()
end
end
function Timer:start()
if not (self.started) then
self.started = true
self.endSecs = os.time() + self.timeOutSecs
end
end
function Timer:update(dt)
if not self.started then
return
end
-- check if reset is requested (for security)
if self.resetRequested then
self.resetRequested = false
self:reset(self.reqResetStart)
end
if os.time() >= self.endSecs then
if self.oneShoot then
if self.hasTimeOuted then
self.timeout = false;
else
self.timeout = true;
self:executeOnTimeouts()
end
else
self.timeout = true;
self:executeOnTimeouts()
end
self.hasTimeOuted = true;
end
end
function Timer:doTimer(dt)
self:start()
self:update(dt)
end
function Timer:onTimeout(func)
assert(type(func) == "function", "Parameter is not a function (Timer)")
table.insert(self.onTimeouts, func)
end
function Timer:reset(start)
if start == nil then
start = true
end
self.started = false
self.hasTimeOuted = false
self.timeout = false
if start then
self:start()
end
end
function Timer:requestReset(start)
self.resetRequested = true
self.reqResetStart = start
end
function Timer:executeOnTimeouts()
for key, func in pairs(self.onTimeouts) do
func()
end
end
return Timer
|
-- Copyright (c) 2021 Kirazy
-- Part of Artisanal Reskins: Compatibility
--
-- See LICENSE in the project directory for license information.
-- Check to see if reskinning needs to be done.
if not mods["NauvisDay"] then return end
if not (reskins.bobs and reskins.bobs.triggers.greenhouse.entities) then return end
-- Set input parameters
local inputs = {
type = "assembling-machine",
icon_name = "dead-greenhouse",
base_entity = "lab",
mod = "compatibility",
group = "nauvisday",
icon_layers = 1,
}
-- Fetch entity
local entity = data.raw["assembling-machine"]["dead-greenhouse"]
-- Check if entity exists, if not, return
if not entity then return end
reskins.lib.setup_standard_entity("dead-greenhouse", 0, inputs)
local dead_greenhouse_base = reskins.lib.make_4way_animation_from_spritesheet({
-- Base
filename = reskins.compatibility.directory.."/graphics/entity/nauvisday/dead-greenhouse/dead-greenhouse-base.png",
width = 97,
height = 96,
shift = util.by_pixel(0, 0),
hr_version = {
filename = reskins.compatibility.directory.."/graphics/entity/nauvisday/dead-greenhouse/hr-dead-greenhouse-base.png",
width = 194,
height = 192,
shift = util.by_pixel(0, 0),
scale = 0.5
},
})
local dead_greenhouse_integration_patch = {
filename = "__base__/graphics/entity/lab/lab-integration.png",
width = 122,
height = 81,
shift = util.by_pixel(0, 15.5),
hr_version = {
filename = "__base__/graphics/entity/lab/hr-lab-integration.png",
width = 242,
height = 162,
shift = util.by_pixel(0, 15.5),
scale = 0.5
}
}
local dead_greenhouse_shadow = {
filename = "__base__/graphics/entity/lab/lab-shadow.png",
width = 122,
height = 68,
shift = util.by_pixel(13, 11),
draw_as_shadow = true,
hr_version = {
filename = "__base__/graphics/entity/lab/hr-lab-shadow.png",
width = 242,
height = 136,
shift = util.by_pixel(13, 11),
scale = 0.5,
draw_as_shadow = true
}
}
-- Reskin the entity
entity.animation = {
north = {
layers = {
dead_greenhouse_base.north,
dead_greenhouse_integration_patch,
dead_greenhouse_shadow
}
},
east = {
layers = {
dead_greenhouse_base.east,
dead_greenhouse_integration_patch,
dead_greenhouse_shadow
}
},
south = {
layers = {
dead_greenhouse_base.south,
dead_greenhouse_integration_patch,
dead_greenhouse_shadow
}
},
west = {
layers = {
dead_greenhouse_base.west,
dead_greenhouse_integration_patch,
dead_greenhouse_shadow
}
},
}
entity.idle_animation = nil
local dead_greenhouse_working = reskins.lib.make_4way_animation_from_spritesheet({
layers = {
-- Light Underlayer
{
filename = reskins.compatibility.directory.."/graphics/entity/nauvisday/dead-greenhouse/dead-greenhouse-lit.png",
width = 97,
height = 96,
shift = util.by_pixel(0, 0),
hr_version = {
filename = reskins.compatibility.directory.."/graphics/entity/nauvisday/dead-greenhouse/hr-dead-greenhouse-lit.png",
width = 194,
height = 192,
shift = util.by_pixel(0, 0),
scale = 0.5
}
},
-- Light
{
filename = reskins.compatibility.directory.."/graphics/entity/nauvisday/dead-greenhouse/dead-greenhouse-light.png",
width = 97,
height = 96,
shift = util.by_pixel(0, 0),
draw_as_light = true,
hr_version = {
filename = reskins.compatibility.directory.."/graphics/entity/nauvisday/dead-greenhouse/hr-dead-greenhouse-light.png",
width = 194,
height = 192,
shift = util.by_pixel(0, 0),
draw_as_light = true,
scale = 0.5
}
},
}
})
entity.working_visualisations = {
{
fadeout = true,
north_animation = dead_greenhouse_working.north,
east_animation = dead_greenhouse_working.east,
west_animation = dead_greenhouse_working.west,
south_animation = dead_greenhouse_working.south,
},
-- Pipe shadow fixes
{
always_draw = true,
north_animation = reskins.lib.vertical_pipe_shadow{0, -1},
south_animation = reskins.lib.vertical_pipe_shadow{0, 1},
}
}
entity.fluid_boxes[1].pipe_picture = nil
entity.fluid_boxes[1].secondary_draw_orders = {east = 3, west = 3, south = 3}
-- Disable burner energy source light
entity.energy_source.light_flicker = {
color = {0, 0, 0},
minimum_light_size = 0,
light_intensity_to_size_coefficient = 0,
}
|
describe('#list', function()
local list
setup(function()
list = require"novus.util.list"
end)
describe('map', function()
it('transforms a table by the given function', function()
local t = {1,2,3,4,5}
local t2 = {2,4,6,8,10}
local by2 = function(x) return 2 * x end
assert.are.same(
list.map(by2, t),
t2
)
end)
it('leaves the old table alone', function()
local t = {1,2,3,4,5}
local tsf = function(x) return x end
assert.not_equals(
list.map(tsf, t),
t
)
end)
it('can operate over mixed tables, ignoring hash parts', function()
local t = {foo = "bar"; 1, 2, 3}
local tt ={2, 4, 6}
local by2 = function(x) return 2 * x end
assert.are.same(
list.map(by2, t),
tt
)
end)
end)
describe('filter', function()
it('filters an array by a given predicate', function()
local t = {1,2,3,4,5,6}
local e = {2,4,6}
local fl = function(x) return x % 2 == 0 end
assert.are.same(
list.filter(fl, t),
e
)
end)
it('doesnt leave holes', function()
local t = {1,2,3,4}
local r = list.filter(function(x) return x ~= 2 and x ~= 3 end, t)
assert.is_not_nil(
r[2]
)
end)
end)
describe('zip', function()
it('zips together two lists using the given function on each pair', function()
local t1 = {1,1,1}
local t2 = {2,2,2}
local function agrt(x,y) return x..y end
assert.are.same(
list.zip(agrt, t1,t2),
{'12','12','12'}
)
end)
end)
describe('fold', function()
it('accumulates/reduces elements in an array', function()
local t = {1,2,3}
local rdr = function(a, x) a[x] = x return a end
assert.are.same(
t,
list.fold(rdr, {}, t)
)
end)
end)
describe('reverse', function()
it('reverses a list', function()
local t = {1,2,3}
local j = list.reverse(t)
for i, v in ipairs(j) do
assert.are.equal(v, t[4 - i])
end
end)
end)
describe('shuffle', function()
it('shuffles a list', function()
local t = {1,2,3}
local ts = list.shuffle(t)
assert.not_equal(t, ts)
end)
end)
end)
|
Editor = class()
function Editor:init()
-- you can accept and set parameters here
end
|
function RemoveDotDirs(aTable)
if aTable == nil or type(aTable) ~= 'table' then
return aTable
end
--remove the two directories "." , ".."
local i = 1
while i <= #aTable do
while aTable[i] ~= nil and aTable[i]:sub(1,1) == '.' do
aTable[i] = aTable[#aTable]
aTable[#aTable] = nil
end
i = i + 1
end
end
function getTableSize(aTable)
local numItems = 0
for k,v in pairs(aTable) do
numItems = numItems + 1
end
return numItems
end
function GetRandomValue(aTable)
local values = {}
for key, value in pairs(aTable) do
values[ #values+1 ] = value
end
return values[ torch.random(#values) ]
end
function GetValuesSum(aTable)
local total = 0
for key, value in pairs(aTable) do
total = total + value
end
return total
end
function loadImageOrig(path)
-----------------------------------------------------------------
-- Reads an image
-- inputs:
-- "path": path to the image
-- output:
-- "im": the image
-----------------------------------------------------------------
local im = image.load(path)
if im:dim() == 2 then -- 1-channel image loaded as 2D tensor
im = im:view(1,im:size(1), im:size(2)):repeatTensor(3,1,1)
elseif im:dim() == 3 and im:size(1) == 1 then -- 1-channel image
im = im:repeatTensor(3,1,1)
elseif im:dim() == 3 and im:size(1) == 3 then -- 3-channel image
elseif im:dim() == 3 and im:size(1) == 4 then -- image with alpha
im = im[{{1,3},{},{}}]
else
error("image structure not compatible")
end
return im
end
function loadImage(path, imH, imW)
-----------------------------------------------------------------
-- Reads an image and rescales it
-- inputs:
-- "path": path to the image
-- "imH" and "imW": the image is rescaled to imH x imW
-- output:
-- "im": the rescaled image
-----------------------------------------------------------------
local im = loadImageOrig(path)
im = image.scale(im, imW, imH)
return im
end
function normalizeImage(im, mean, std)
-----------------------------------------------------------------
-- Normalizes image "im" by subtracting the "mean" and dividing by "std"
-----------------------------------------------------------------
for channel=1,3 do
im[{channel,{},{}}]:add(-mean[channel]);
im[{channel,{},{}}]:div(std[channel]);
end
return im;
end
function LoadRandomSamples(nSamples, allfiles, imH, imW);
-----------------------------------------------------------------
-- Loads "nSamples" images from the "allfiles" and rescaled them to imH x imW
-- inputs:
-- nSamples: # of images that is sampled
-- allfiles: an array of paths of the images in the dataset
-- imH, imW: size of the rescaled image
-- outputs:
-- images: 4D Tensor that includes "nSamples" number of imHximW images
-----------------------------------------------------------------
local images = torch.Tensor(nSamples, 3, imH, imW);
local randnums = torch.randperm(#allfiles);
local idx = randnums[{{1,nSamples}}];
for i = 1,nSamples do
local fname = allfiles[idx[i]];
local im = loadImage(fname, imH, imW);
images[{{i},{},{},{}}] = im;
end
return images;
end
function ComputeMeanStd(nSample, allfiles, imH, imW)
-----------------------------------------------------------------
-- Computes the mean and std of randomly sampled images
-- inputs:
-- nSample: # of images that is sampled
-- allfiles: an array of paths of the images in the dataset
-- imH, imW: size of the rescaled image
-- outputs:
-- mean: a 3-element array (the mean for each channel)
-- std: a 3-element array (the std for each channel)
-----------------------------------------------------------------
local images = LoadRandomSamples(nSample, allfiles, imH, imW);
local mean = {};
local std = {};
mean[1] = torch.mean(images[{{},1,{},{}}]);
mean[2] = torch.mean(images[{{},2,{},{}}]);
mean[3] = torch.mean(images[{{},3,{},{}}]);
std[1] = torch.std(images[{{},1,{},{}}]);
std[2] = torch.std(images[{{},2,{},{}}]);
std[3] = torch.std(images[{{},3,{},{}}]);
return mean, std;
end
function MakeListTrainFrames(dataset, trainDir, image_type)
allfiles = {};
for category, subdataset in pairs(dataset) do
if category ~= 'config' then
for angles, subsubdataset in pairs(subdataset) do
for dirs, files in pairs(subsubdataset) do
for _, f in pairs(files) do
fname = string.sub(f, 1, -11) .. "." .. image_type;
table.insert(allfiles, paths.concat(trainDir, category, dirs, fname));
end
end
end
end
end
return allfiles;
end
function MakeListGEFrames(dataset, data_type)
local geDir = config.GE.dir;
allfiles = {};
for categories, subdataset in pairs(dataset) do
for angles, subsubdataset in pairs(subdataset) do
for dirs, files in pairs(subsubdataset) do
for _, f in pairs(files) do
table.insert(allfiles, paths.concat(geDir, categories, categories .. "_" .. angles .. "_" .. data_type, dirs, f));
end
end
end
end
return allfiles;
end
function shuffleList(list, deterministic)
local rand
if deterministic then -- shuffle! but deterministicly.
math.randomseed(2)
rand = math.random
else
rand = torch.random
end
for i = #list, 2, -1 do
local j = rand(i)
list[i], list[j] = list[j], list[i]
end
end
function GetPhysicsCategory(category)
return category:match("[^-]+")
end
function MakeShuffledTuples(dataset, deterministic)
-- tuple: category, physics category, angle, folder
local trainDir = config.trainDir;
tuples = {};
for category, subdataset in pairs(dataset) do
if category ~= 'config' then
local physicsCategory = GetPhysicsCategory(category)
for angles, subsubdataset in pairs(subdataset) do
for dirs, _ in pairs(subsubdataset) do
table.insert(tuples, {category, physicsCategory, angles, dirs});
end
end
end
end
shuffleList(tuples, deterministic);
return tuples;
end
function isExcluded(excluded_categories, category)
for _, ecat in pairs(excluded_categories) do
if category:find(ecat) then
return true
end
end
return false
end
function removeExcludedCategories(categories, excluded_categories)
local result = {};
for k,v in pairs(categories) do
if not isExcluded(excluded_categories, v) then
table.insert(result, v);
end
end
assert(#result + #excluded_categories <= #categories, "At least one category" ..
"should be removed per excluded_categories.")
assert(#result > 0, "Cannot exclude all categories.")
return result;
end
function getAllCategoriesandAngles(dataset)
physics_category_list = {};
category_list = {};
angle_list = {};
for k,v in pairs(dataset) do
table.insert(physics_category_list, GetPhysicsCategory(k))
table.insert(category_list, k);
table.insert(angle_list, getTableSize(dataset[k]));
end
return physics_category_list, category_list, angle_list;
end
function GetNNParamsToCPU(nnModel)
-- Convert model into FloatTensor and save.
local params, gradParams = nnModel:parameters()
if params ~= nill then
paramsCPU = pl.tablex.map(function(param) return param:float() end, params)
else
paramsCPU = {};
end
return paramsCPU
end
function LoadNNlParams(current_model,saved_params)
local params, gradparams = current_model:parameters()
if params ~= nill then
assert(#params == #saved_params,
string.format('#layer != #saved_layers (%d vs %d)!',
#params, #saved_params));
for i = 1,#params do
assert(params[i]:nDimension() == saved_params[i]:nDimension(),
string.format("Layer %d: dimension mismatch (%d vs %d).",
i, params[i]:nDimension(), saved_params[i]:nDimension()))
for j = 1, params[i]:nDimension() do
assert(params[i]:size(j) == saved_params[i]:size(j),
string.format("Layer %d, Dim %d: size does not match (%d vs %d).",
i, j, params[i]:size(j), saved_params[i]:size(j)))
end
params[i]:copy(saved_params[i]);
end
end
end
function rand_initialize(layer)
local tn = torch.type(layer)
if tn == "cudnn.SpatialConvolution" then
local c = math.sqrt(10.0 / (layer.kH * layer.kW * layer.nInputPlane));
layer.weight:copy(torch.randn(layer.weight:size()) * c)
layer.bias:fill(0)
elseif tn == "cudnn.VolumetricConvolution" then
local c = math.sqrt(10.0 / (layer.kH * layer.kW * layer.nInputPlane));
layer.weight:copy(torch.randn(layer.weight:size()) * c)
layer.bias:fill(0)
elseif tn == "nn.Linear" then
local c = math.sqrt(10.0 / layer.weight:size(2));
layer.weight:copy(torch.randn(layer.weight:size()) * c)
layer.bias:fill(0)
end
end
function GetCategoryViewPointId(physicsCategory, viewpoint)
local offset = 0;
for i, class in ipairs(config.classes) do
if class == physicsCategory then
return offset + viewpoint
end
offset = offset + config.class_angles[i];
end
error("failed to find the physicsCategory:" .. physicsCategory);
return -1; -- invalid physics category
end
function DecryptCategoryViewPointId(categoryId)
assert(categoryId > 0, "Invalid categoryId " .. tostring(categoryId))
local offset = 0;
for i, class in ipairs(config.classes) do
if offset + config.class_angles[i] >= categoryId then
return class, categoryId - offset
end
offset = offset + config.class_angles[i];
end
error("Invalid categoryId " .. tostring(categoryId));
end
function GetCategoryId(physicsCategory)
for i, class in pairs(config.classes) do
if class == physicsCategory then
return i
end
end
error("failed to find the physicsCategory:" .. physicsCategory);
return -1; -- invalid physics category
end
function CategoryViewPointId2CategoryId(categoryId)
assert(categoryId > 0, "Invalid categoryId " .. tostring(categoryId))
local offset = 0;
for i, class in ipairs(config.classes) do
if offset + config.class_angles[i] >= categoryId then
return i
end
offset = offset + config.class_angles[i];
end
error("Invalid categoryId " .. tostring(categoryId));
end
function GetUniformRandomElement(data)
local result = {}
while type(data) == 'table' do
local keys = {}
for key, value in pairs(data) do
if key ~= 'config' and (type(value) ~= 'table' or next(value) ~= nil) then
keys[ #keys+1 ] = key
end
end
local randomKey = keys[torch.random(#keys)]
data = data[randomKey]
result[#result+1] = randomKey
end
result[#result+1] = data
return result
end
function GetUniformRandomCategory(dataset, physicsCategory, angle)
local keys = {}
for key, value in pairs(dataset) do
if string.sub(key,1,string.len(physicsCategory)) == physicsCategory then
if value[angle] and next(value[angle]) then
keys[ #keys+1 ] = key
end
end
end
if next(keys) then
return keys[torch.random(#keys)]
else
return nil
end
end
function GetUniformRandomData(dataset)
local randomData = GetUniformRandomElement(dataset)
local category = randomData[1]
local physicsCategory = GetPhysicsCategory(category)
local angle = randomData[2]
local folder = randomData[3]
return {category, physicsCategory, angle, folder}
end
function log(...)
-- Log to file:
io.output(config.logFile)
print(...)
-- Log to stdout:
io.output(io.stdout)
print(...)
end
function GetEnableInputTypes(input_config)
local result = {}
for input_type, conf in pairs(input_config) do
if type(conf) == 'table' and conf.enable then
if config.w_crop and conf.croppable then
result[ input_type ] = conf.nChannels * 5
else
result[ input_type ] = conf.nChannels
end
end
end
return result
end
function GetPerClassAccuracy(predictions, labels)
local per_class = torch.Tensor(config.nCategories, 2):fill(0)
local nAccurate = 0
labels = labels:clone()
predictions = predictions:clone()
for i=1,labels:size(1) do
if labels[i] == predictions[i] then
nAccurate = nAccurate + 1
per_class[ labels[i] ][1] = per_class[ labels[i] ][1] + 1
end
per_class[ labels[i] ][2] = per_class[ labels[i] ][2] + 1
end
local acc = nAccurate / labels:size(1)
return acc, per_class
end
function GetAnimationFeatures(model, convLayer)
local n = GetValuesSum(config.class_angles) -- Total number of classes
local feats
local labels = {}
for i=1,n do
local featsDir = paths.concat(config.GE.featsDir, i)
local featFiles = paths.dir(featsDir)
RemoveDotDirs( featFiles )
if not featFiles or #featFiles==0 then
log("Animation vectors for category " .. tostring(i) .. " not found.")
os.execute('mkdir -p ' .. featsDir)
local category, angle = DecryptCategoryViewPointId(i)
local gameEngineVideos = LoadGEPerCategory(category, angle, dataset_GE):transpose(2, 3):cuda()
log("Feed-forward animation to get features.")
for j=1,gameEngineVideos:size(1) do
local cur = model:forward( gameEngineVideos[ {{j}, {}, {}, {}, {}} ] )
if feats then
feats = torch.cat(feats, cur, 3)
else
feats = cur
end
for k=1,cur:size(1) do
labels[ #labels+1 ] = i
end
-- Cache for future use:
torch.save( paths.concat(featsDir, tostring(j) .. '.t7'), cur)
end
else
for j, v in pairs(featFiles) do
local cur = torch.load( paths.concat(featsDir, v) )
if feats then
feats = torch.cat(feats, cur, 3)
else
feats = cur
end
for k=1,cur:size(1) do
labels[ #labels+1 ] = i
end
end
end
end
feats = feats:transpose(2, 3):transpose(1, 2)
if convLayer then
feats = convLayer:forward(feats):reshape(config.nClasses, 10, 4096)
torch.save(paths.concat( config.DataRootPath, 'all.t7'), feats)
end
return feats, labels
end
function GetPairwiseCosine(M1, M2)
assert(M1:size(2) == M2:size(2), "ERROR: dimensions mismatch!")
local smooth = 1e-5
local M1rownorms = torch.cmul(M1, M1):sum(2):sqrt():view(M1:size(1))
local M2rownorms = torch.cmul(M2, M2):sum(2):sqrt():view(M2:size(1))
local pairwiseNorms = torch.ger(M1rownorms, M2rownorms)
local dot = M1 * M2:t()
return torch.cdiv(dot, pairwiseNorms + smooth)
end
function GetVideoCount(dataset)
local total = 0
for _1, cat in pairs(dataset) do
if _1 ~= 'config' then
for _2, view in pairs(cat) do
for _3, fold in pairs(view) do
total = total + 1
end
end
end
end
return total
end
function Choose(tensor, indices)
assert(tensor:size(1) == indices:size(1), "Dimension mismatch")
local result = torch.Tensor( indices:size() )
for i = 1, indices:size(1) do
result[i] = tensor[i][ indices[i] ]
end
return result:cuda()
end
function ContainsValue(dict, value)
for k,v in pairs(dict) do
if v == value then
return true
end
end
return false
end
function GetGaussianTarget(target)
local result = torch.CudaTensor(target:size(1), config.nClasses):fill(0)
local frames = target - (torch.floor((target-1) / 10) * 10)
for i=1,target:size(1) do
local sigma = 1
for j = target[i]-frames[i]+1,target[i]-frames[i]+10 do
result[i][j] = torch.exp( -(target[i] - j)^2 / sigma)
end
result[i] = result[i] / result[i]:sum()
end
return result
end
|
local AS = unpack(AddOnSkins)
function AS:Blizzard_EncounterJournal(event, addon)
if addon ~= 'Blizzard_EncounterJournal' then return end
AS:SkinBackdropFrame(EncounterJournal)
AS:SkinBackdropFrame(EncounterJournal.navBar, nil, nil, true)
EncounterJournal.navBar.Backdrop:SetPoint("TOPLEFT", -2, 0)
EncounterJournal.navBar.Backdrop:SetPoint("BOTTOMRIGHT")
AS:StripTextures(EncounterJournal.navBar.overlay, true)
AS:SkinButton(EncounterJournal.navBar.homeButton, true)
EncounterJournal.navBar.homeButton.xoffset = 1
AS:SkinEditBox(EncounterJournal.searchBox)
AS:SkinCloseButton(EncounterJournal.CloseButton)
AS:CreateBackdrop(EncounterJournal.encounter.info)
for _, Tab in pairs({ EncounterJournal.encounter.info.bossTab, EncounterJournal.encounter.info.lootTab, EncounterJournal.encounter.info.modelTab, EncounterJournal.encounter.info.overviewTab }) do
Tab:GetNormalTexture():SetTexture(nil)
Tab:GetPushedTexture():SetTexture(nil)
Tab:GetDisabledTexture():SetTexture(nil)
Tab:GetHighlightTexture():SetTexture(nil)
AS:SkinBackdropFrame(Tab, nil, true)
Tab.Backdrop:SetPoint('TOPLEFT', 11, -8)
Tab.Backdrop:SetPoint('BOTTOMRIGHT', -6, 8)
Tab:HookScript('OnEnter', function(self) self.Backdrop:SetBackdropBorderColor(unpack(AS.Color)) end)
Tab:HookScript('OnLeave', function(self) self.Backdrop:SetBackdropBorderColor(unpack(AS.BorderColor)) end)
end
EncounterJournal.encounter.info.overviewTab:SetPoint('TOPLEFT', EncounterJournal.encounter.info, 'TOPRIGHT', AS.PixelPerfect and -2 or 0, -35)
EncounterJournal.encounter.info.overviewTab.SetPoint = AS.Noop
AS:StripTextures(EncounterJournal.instanceSelect)
AS:SkinFrame(EncounterJournal.suggestFrame)
AS:SkinFrame(EncounterJournal.instanceSelect.scroll)
AS:SkinScrollBar(EncounterJournal.instanceSelect.scroll.ScrollBar)
AS:SkinButton(EncounterJournal.instanceSelect.dungeonsTab, true)
AS:SkinButton(EncounterJournal.instanceSelect.raidsTab, true)
AS:SkinButton(EncounterJournal.instanceSelect.suggestTab, true)
AS:SkinButton(EncounterJournal.instanceSelect.LootJournalTab, true)
AS:SkinScrollBar(EncounterJournal.encounter.info.lootScroll.scrollBar)
AS:SkinScrollBar(EncounterJournal.encounter.info.detailsScroll.ScrollBar)
AS:SkinScrollBar(EncounterJournal.encounter.info.bossesScroll.ScrollBar)
AS:SkinScrollBar(EncounterJournal.encounter.instance.loreScroll.ScrollBar)
AS:StripTextures(EncounterJournal.encounter.info)
EncounterJournal.encounter.instance.loreScroll.child.lore:SetTextColor(1, 1, 1)
EncounterJournal.encounter.info.detailsScroll.child.description:SetTextColor(1, 1, 1)
EncounterJournal.encounter.info.overviewScroll.child.loreDescription:SetTextColor(1, 1, 1)
EncounterJournal.encounter.info.overviewScroll.child.header:Hide()
_G.EncounterJournalEncounterFrameInfoOverviewScrollFrameScrollChildTitle:SetFontObject("GameFontNormalLarge")
_G.EncounterJournalEncounterFrameInfoOverviewScrollFrameScrollChildTitle:SetTextColor(1, 1, 1)
EncounterJournal.instanceSelect.suggestTab:SetPoint('BOTTOMLEFT', '$parent', 'TOPLEFT', 25, -49)
EncounterJournal.encounter.info.overviewScroll.child.overviewDescription.Text:SetTextColor(1, 1, 1)
AS:SkinFrame(EncounterJournal.LootJournal)
AS:StripTextures(EncounterJournal.LootJournal.ItemSetsFrame.ClassButton)
AS:SkinButton(EncounterJournal.LootJournal.ItemSetsFrame.ClassButton, true)
AS:SkinScrollBar(EncounterJournal.LootJournal.ItemSetsFrame.scrollBar)
EncounterJournal.instanceSelect.bg:SetAlpha(0)
AS:Delay(0, function() AS:SkinDropDownBox(EncounterJournalInstanceSelectTierDropDown) end) -- Apparently Spawned but not all elements until the frame is shown.
for i = 1, AJ_MAX_NUM_SUGGESTIONS do
local suggestion = EncounterJournal.suggestFrame["Suggestion"..i]
local centerDisplay = suggestion.centerDisplay
local reward = suggestion.reward
suggestion.bg:SetAlpha(0)
AS:CreateBackdrop(suggestion.bg)
AS:CreateBackdrop(suggestion.icon)
centerDisplay.title.text:SetTextColor(1, 1, 1)
centerDisplay.description.text:SetTextColor(.9, .9, .9)
AS:CreateBackdrop(reward.icon)
reward.iconRing:Hide()
reward.iconRingHighlight:SetTexture("")
if i == 1 then
reward.text:SetTextColor(.9, .9, .9)
suggestion.icon:SetPoint("TOPLEFT", 135, -15)
AS:SkinButton(suggestion.button)
AS:SkinArrowButton(suggestion.prevButton)
AS:SkinArrowButton(suggestion.nextButton)
else
reward:SetFrameLevel(suggestion:GetFrameLevel() + 3)
AS:SkinButton(suggestion.centerDisplay.button)
suggestion.bg:SetPoint('TOPLEFT', -16, 4)
end
end
AS:SkinButton(EncounterJournal.encounter.info.lootScroll.lootSlotFilter, true)
AS:SkinButton(EncounterJournal.encounter.info.lootScroll.filter, true)
AS:SkinButton(EncounterJournal.encounter.info.lootScroll.slotFilter, true)
AS:StripTextures(EncounterJournal.encounter.info.lootScroll.classClearFilter, true)
EncounterJournal.encounter.info.lootScroll.classClearFilter.text:SetTextColor(1, 1, 1)
AS:SkinButton(EncounterJournal.encounter.info.reset)
AS:SkinButton(EncounterJournal.encounter.info.difficulty, true)
for i, Button in pairs(EncounterJournal.encounter.info.lootScroll.buttons) do
Button.bossTexture:SetAlpha(0)
Button.bosslessTexture:SetAlpha(0)
Button.icon:SetSize(32, 32)
Button.icon:Point("TOPLEFT", AS.PixelPerfect and 3 or 4, -(AS.PixelPerfect and 7 or 8))
Button.icon:SetDrawLayer("ARTWORK")
AS:SkinTexture(Button.icon, true)
Button.name:SetPoint("TOPLEFT", Button.icon, "TOPRIGHT", 6, -2)
Button.boss:SetTextColor(1, 1, 1)
Button.boss:SetPoint("BOTTOMLEFT", 4, 6)
Button.slot:SetPoint("TOPLEFT", Button.name, "BOTTOMLEFT", 0, -3)
Button.slot:SetTextColor(1, 1, 1)
Button.armorType:SetTextColor(1, 1, 1)
Button.armorType:SetPoint("RIGHT", Button, "RIGHT", -10, 0)
hooksecurefunc(Button.IconBorder, "SetVertexColor", function(self, r, g, b)
self:GetParent().icon.Backdrop:SetBackdropBorderColor(r, g, b)
self:SetTexture("")
end)
AS:CreateBackdrop(Button)
Button.Backdrop:Point("TOPLEFT", 0, -4)
Button.Backdrop:Point("BOTTOMRIGHT", 0, AS.PixelMode and 3 or 0)
if i == 1 then
Button:ClearAllPoints()
Button:Point("TOPLEFT", EncounterJournal.encounter.info.lootScroll.scrollChild, "TOPLEFT", 5, 0)
end
end
AS:SkinTooltip(EncounterJournalTooltip)
hooksecurefunc('AdventureJournal_Reward_OnEnter', function(self)
local rewardData = self.data
if ( rewardData ) then
local frame = EncounterJournalTooltip
if ( rewardData.itemLink or rewardData.currencyType ) then
local _, _, quality = GetItemInfo(rewardData.itemLink)
AS:SkinTexture(frame.Item1.icon, true)
frame.Item1.icon.Backdrop:SetBackdropBorderColor(GetItemQualityColor(quality))
frame.Item1.IconBorder:SetAlpha(0)
frame.Item1.tooltip:SetBackdrop(nil)
end
end
end)
hooksecurefunc("EncounterJournal_ListInstances", function()
local instanceSelect = EncounterJournal.instanceSelect
local scrollFrame = instanceSelect.scroll.child
local index = 1
local Button = scrollFrame["instance"..index]
while Button do
AS:SkinButton(Button)
scrollFrame["instance"..index].bgImage:SetTexCoord(.08, .6, .08, .6)
scrollFrame["instance"..index].bgImage:SetDrawLayer('ARTWORK')
scrollFrame["instance"..index].bgImage:SetInside()
index = index + 1
Button = scrollFrame["instance"..index]
end
end)
hooksecurefunc("EncounterJournal_DisplayInstance", function()
local bossIndex = 1
local bossButton = _G["EncounterJournalBossButton"..bossIndex]
while bossButton do
AS:SkinButton(bossButton)
bossButton.creature:ClearAllPoints()
bossButton.creature:SetPoint("TOPLEFT", 1, -4)
bossIndex = bossIndex + 1
bossButton = _G["EncounterJournalBossButton"..bossIndex]
end
end)
hooksecurefunc("EncounterJournal_SetUpOverview", function(self, _, index)
local header = self.overviews[index]
if not header.isSkinned then
header.descriptionBG:SetAlpha(0)
AS:CreateBackdrop(header.descriptionBG)
header.descriptionBG.Backdrop:SetAllPoints()
header.descriptionBGBottom:SetAlpha(0)
for i = 4, 18 do
select(i, header.button:GetRegions()):SetTexture("")
end
AS:SkinButton(header.button)
header.button.title:SetTextColor(unpack(AS.Color))
header.button.title.SetTextColor = AS.Noop
header.button.expandedIcon:SetTextColor(1, 1, 1)
header.button.expandedIcon.SetTextColor = AS.Noop
header.isSkinned = true
end
end)
hooksecurefunc("EncounterJournal_SetBullets", function(object)
local parent = object:GetParent()
if parent.Bullets then
for _, bullet in pairs(parent.Bullets) do
if not bullet.styled then
bullet.Text:SetTextColor(1, 1, 1)
bullet.styled = true
end
end
end
end)
hooksecurefunc("EncounterJournal_ToggleHeaders", function()
local index = 1
local header = _G["EncounterJournalInfoHeader"..index]
while header do
if not header.isSkinned then
header.flashAnim.Play = AS.Noop
header.descriptionBG:SetAlpha(0)
header.descriptionBGBottom:SetAlpha(0)
for i = 4, 18 do
select(i, header.button:GetRegions()):SetTexture("")
end
header.description:SetTextColor(1, 1, 1)
header.button.title:SetTextColor(unpack(AS.Color))
header.button.title.SetTextColor = AS.Noop
header.button.expandedIcon:SetTextColor(1, 1, 1)
header.button.expandedIcon.SetTextColor = AS.Noop
AS:SkinButton(header.button)
AS:SkinTexture(header.button.abilityIcon, true)
header.isSkinned = true
end
index = index + 1
header = _G["EncounterJournalInfoHeader"..index]
end
end)
hooksecurefunc("EJSuggestFrame_RefreshDisplay", function()
for i = 1, 3 do
local Suggestion = EncounterJournal.suggestFrame['Suggestion'..i]
local Data = EncounterJournal.suggestFrame.suggestions[i]
if Suggestion and Data then
Suggestion.iconRing:Hide()
Suggestion.icon:SetMask("")
Suggestion.icon:SetTexture(Data.iconPath or QUESTION_MARK_ICON)
AS:SkinTexture(Suggestion.icon)
end
end
end)
hooksecurefunc("EJSuggestFrame_UpdateRewards", function(suggestion)
local rewardData = suggestion.reward.data
if rewardData then
local texture = rewardData.itemIcon or rewardData.currencyIcon or [[Interface\Icons\achievement_guildperk_mobilebanking]]
suggestion.reward.icon:SetMask("")
suggestion.reward.icon:SetTexture(texture)
AS:SkinTexture(suggestion.reward.icon)
local r, g, b = unpack(AS.BorderColor)
if rewardData.itemID then
local quality = select(3, GetItemInfo(rewardData.itemID))
if quality and quality > 1 then
r, g, b = GetItemQualityColor(quality)
end
end
suggestion.reward.icon.Backdrop:SetBackdropBorderColor(r, g, b)
end
end)
hooksecurefunc(EncounterJournal.LootJournal.ItemSetsFrame, "UpdateList", function(self)
for _, Button in pairs(self.buttons) do
Button.ItemLevel:SetTextColor(1, 1, 1)
Button.Background:Hide()
AS:SkinFrame(Button)
for _, Item in pairs(Button.ItemButtons) do
Item.Border:Hide()
Item.Icon:SetPoint("TOPLEFT", 1, -1)
AS:SkinTexture(Item.Icon, true)
end
end
end)
hooksecurefunc(EncounterJournal.LootJournal.ItemSetsFrame, 'ConfigureItemButton', function(self, button)
local r, g, b = unpack(AS.BorderColor)
if button.itemID then
local _, _, itemQuality = GetItemInfo(button.itemID)
if itemQuality and itemQuality > 1 then
r, g, b = GetItemQualityColor(itemQuality)
end
end
if button.Icon.Backdrop then
button.Icon.Backdrop:SetBackdropBorderColor(r, g, b)
end
end)
AS:UnregisterSkinEvent(addon, event)
end
AS:RegisterSkin("Blizzard_EncounterJournal", AS.Blizzard_EncounterJournal, 'ADDON_LOADED')
|
require("animation/animBase");
require("common/uiFactory");
AnimBtnMessage = class(AnimBase);
AnimBtnMessage.load = function (view)
AnimBtnMessage.root = view;
end
AnimBtnMessage.play = function (view)
if not view then
return;
end
AnimBtnMessage.stop();
AnimBtnMessage.load(view);
AnimBtnMessage.move();
end
AnimBtnMessage.move = function()
local _, animMove = AnimBtnMessage.root:addPropTranslate(1, kAnimLoop, 800, 0, nil, nil, 0,10);--上移
animMove:setDebugName("PropTranslate|AnimBtnMessage.move");
end
AnimBtnMessage.stop = function()
if AnimBtnMessage.root and not AnimBtnMessage.root:checkAddProp(1) then
AnimBtnMessage.root:removeProp(1);
end
end
AnimBtnMessage.release = function()
AnimBtnMessage.stop();
end
|
local dump = require "dump"
local msg = require "msg"
local engine = require "dependencies/mpvcontextmenu/menu-engine"
local mp = require 'mp'
local utils = require 'mp.utils'
local Menu = {}
function Menu:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
o.menu_list = { context_menu = {} }
return o
end
local function add_menu(menu, add)
local first_elem = true
for k,v in pairs(add) do
if type(k) == 'number' then
if first_elem and menu[1] then
table.insert(menu,{'separator'})
end
first_elem = false
table.insert(menu,v)
elseif menu[k] then
add_menu(menu[k],v)
else
menu[k] = v
end
end
end
function Menu:append(menu)
add_menu(self.menu_list, menu)
end
function Menu:menu_action(vx, vy)
engine.createMenu(self.menu_list, 'context_menu', -1, -1, 'tk')
end
return Menu
|
collision_callback_test = {}
collision_callback_test.msgCount = 0
collision_callback_test.dt = 0
collision_callback_test.ran = false
-- process message function
collision_callback_test.RecieveMessage = function (logicComponent, msg, msgType)
if msgType == "COLLISION" then
collision_callback_test.dt = collision_callback_test.dt + msg.dt
--print("delta time: " .. collision_callback_test.dt)
if collision_callback_test.ran == false then
collision_callback_test.msgCount = collision_callback_test.msgCount+1
print(collision_callback_test.msgCount)
collision_callback_test.ran = true
elseif collision_callback_test.dt > 0.25 then
collision_callback_test.ran = false
collision_callback_test.dt = 0
end
end
end
|
-- basic.lua
local basic = {}
package.loaded[...] = basic
function basic.index(table, item)
for k, v in pairs(table) do
if v == item then return k end
end
end
function basic.map(table, func)
local t = {}
for k, v in pairs(table) do
t[k] = func(v)
end
return t
end
function basic.matchstr(str, pat)
local t = {}
for i in str:gmatch(pat) do
t[#t + 1] = i
end
return t
end
function basic.utf8chars(str, ...)
local chars = {}
for pos, code in utf8.codes(str) do
chars[#chars + 1] = utf8.char(code)
end
return chars
end
function basic.utf8sub(str, first, ...)
local last = ...
if last == nil or last > utf8.len(str) then
last = utf8.len(str)
elseif last < 0 then
last = utf8.len(str) + 1 + last
end
local fstoff = utf8.offset(str, first)
local lstoff = utf8.offset(str, last + 1)
if fstoff == nil then fstoff = 1 end
if lstoff ~= nil then lstoff = lstoff - 1 end
return string.sub(str, fstoff, lstoff)
end
|
------------------------------------------------------------
------------------------- yrp_hud --------------------------
------------------------------------------------------------
--------------------- Created by Flap ----------------------
------------------------------------------------------------
----------------- YourRolePlay Development -----------------
--------------- Thank you for using this hud ---------------
----- Regular updates and lots of interesting scripts ------
--------- discord -> https://discord.gg/hqZEXc8FSE ---------
------------------------------------------------------------
description 'YourRolePlay Development HUD inspirated by poggu_hud'
author 'YourRolePlay Development // discord -> https://discord.gg/uSv9sWwhE9'
version '1.0'
client_scripts {
'config/config.lua',
'client/client.lua'
}
server_scripts {
'config/config.lua',
'server/server.lua',
'config/server_config.lua'
}
ui_page 'html/index.html'
files {
'html/index.html',
'html/main.js',
'html/main.css'
}
dependencies {
'es_extended',
'esx_identity'
}
|
if Config.initialised then
Config.print()
end
|
local SpriteSheet = {}
function SpriteSheet:new(imagePath, hFrames, vFrames)
newSheet = {
_imageData = {source = nil, rows = 0, cols = 0},
frameWidth = 0,
frameHeight = 0
}
if type(imagePath) == 'string' then
newSheet._imageData.source = love.graphics.newImage(imagePath)
else
newSheet._imageData.source = imagePath
end
if newSheet._imageData.source == nil then
error('could not open animation source.')
end
-- set spritesheet grid dimensions
local width, height = newSheet._imageData.source:getDimensions()
newSheet.frameWidth = width / hFrames
newSheet.frameHeight = height / vFrames
newSheet._imageData.cols = width / newSheet.frameWidth
newSheet._imageData.rows = height / newSheet.frameHeight
-- set of all the quads that can be accessed by indexing
newSheet._frames = {}
local r, c = newSheet._imageData.rows, newSheet._imageData.cols
for i = 1, r do
for j = 1, c do
newSheet._frames[(i - 1) * c + j] =
love.graphics.newQuad(newSheet.frameWidth * (j - 1),
newSheet.frameHeight * (i - 1),
newSheet.frameWidth, newSheet.frameHeight,
newSheet._imageData.source:getDimensions())
end
end
self.__index = self
return setmetatable(newSheet, self)
end
function SpriteSheet:showFrame(frameIndex, x, y, r, sx, sy)
if frameIndex > table.getn(self._frames) or frameIndex <= 0 then
return nil
end
love.graphics.draw(self._imageData.source, self._frames[frameIndex], x, y,
r, sx, sy)
end
-- The animation table contains data about the the 'Frame set' which is a
-- collection of frames in a spritesheet.
local Animation = {}
function Animation:new(spriteSheet, s, e, t, l)
newAnim = {
sheet = spriteSheet,
startIndex = s,
endIndex = e,
duration = t,
loop = l,
currentIndex = s,
frameCount = e - s + 1,
timeElapsed = 0
}
assert(newAnim.frameCount > 0, 'animation must have at least 1 frame')
self.__index = self
return setmetatable(newAnim, self)
end
function Animation.newSpriteSheet(path, hFrames, vFrames)
return SpriteSheet:new(path, hFrames, vFrames)
end
function Animation:update(dt)
self.timeElapsed = self.timeElapsed + dt
if self.timeElapsed >= self.duration then
if self.currentIndex + 1 >= self.startIndex + self.frameCount then
if self.loop then self.currentIndex = self.startIndex end
else
self.currentIndex = self.currentIndex + 1
end
self.timeElapsed = 0
end
end
function Animation:show(x, y, r, sx, sy)
self.sheet:showFrame(self.currentIndex, x, y, r, sx, sy)
end
return Animation
|
local function SendFriendStatus()
local friends = {}
for _,ply in ipairs(player.GetHumans()) do
if ply:GetFriendStatus() == "friend" then
table.insert(friends, ply:EntIndex())
end
end
RunConsoleCommand("wire_expression2_friend_status", table.concat(friends, ","))
end
if CanRunConsoleCommand() then
SendFriendStatus()
end
hook.Add("OnEntityCreated", "wire_expression2_extension_player", function(ent)
if not IsValid(ent) then return end
if not ent:IsPlayer() then return end
SendFriendStatus()
end)
-- isTyping
hook.Add("StartChat","E2_IsTyping_Start",function() RunConsoleCommand("E2_StartChat") end)
hook.Add("FinishChat","E2_IsTyping_Finish",function() RunConsoleCommand("E2_FinishChat") end)
|
---
-- @module drawing
local types = require("lualife.types")
local typeutils = require("typeutils")
local Size = require("lualife.models.size")
local Point = require("lualife.models.point")
local Field = require("lualife.models.field")
local ClassifiedGame = require("biohazardcore.classifiedgame")
local Rectangle = require("models.rectangle")
local DrawingSettings = require("models.drawingsettings")
local Color = require("models.color")
local drawing = {}
---
-- @tparam Rectangle screen
-- @tparam biohazardcore.ClassifiedGame game
function drawing.draw_game(screen, game)
assert(types.is_instance(screen, Rectangle))
assert(types.is_instance(game, ClassifiedGame))
local grid_step = screen:height() / game.settings.field.size.height
local field_offset = screen.minimum
:translate(Point:new(
(screen:width() - grid_step * game.settings.field.size.width) / 2,
0
))
drawing._draw_rectangle(
"fill",
field_offset,
typeutils.scale_size(game.settings.field.size, grid_step),
0,
Color:new(1, 1, 1)
)
local classification = game:classify_cells()
for cell_kind, cells in pairs(classification) do
local settings = DrawingSettings:new(field_offset, grid_step, cell_kind)
drawing._draw_field(cells, settings)
end
drawing._draw_rectangle(
"line",
DrawingSettings:new(field_offset, grid_step)
:map_point(game:offset()),
typeutils.scale_size(game.settings.field_part.size, grid_step),
grid_step / 10,
Color:new(0.75, 0.75, 0)
)
end
---
-- @tparam lualife.models.Field field
-- @tparam DrawingSettings settings
function drawing._draw_field(field, settings)
assert(types.is_instance(field, Field))
assert(types.is_instance(settings, DrawingSettings) and settings.cell_kind)
field:map(function(point, contains)
if contains then
drawing._draw_cell(point, settings)
end
end)
end
---
-- @tparam lualife.models.Point point
-- @tparam DrawingSettings settings
function drawing._draw_cell(point, settings)
assert(types.is_instance(point, Point))
assert(types.is_instance(settings, DrawingSettings) and settings.cell_kind)
local cell_color
if settings.cell_kind == "old" then
cell_color = Color:new(0, 0, 1)
elseif settings.cell_kind == "new" then
cell_color = Color:new(0, 0.66, 0)
elseif settings.cell_kind == "intersection" then
cell_color = Color:new(0.85, 0, 0)
end
drawing._draw_rectangle(
"fill",
settings:map_point(point),
Size:new(settings.grid_step, settings.grid_step),
settings.grid_step / 4,
cell_color
)
end
---
-- @tparam "line"|"fill" rectangle_kind
-- @tparam lualife.models.Point position
-- @tparam lualife.models.Size size
-- @tparam int border [0, ∞) width (for the line rectangle kind)
-- / radius (for the fill rectangle kind)
-- @tparam Color color
function drawing._draw_rectangle(
rectangle_kind,
position,
size,
border,
color
)
assert(rectangle_kind == "line" or rectangle_kind == "fill")
assert(types.is_instance(position, Point))
assert(types.is_instance(size, Size))
assert(types.is_number_with_limits(border, 0))
assert(types.is_instance(color, Color))
local border_width, border_radius = 0, 0
if rectangle_kind == "line" then
border_width = border
elseif rectangle_kind == "fill" then
border_radius = border
end
love.graphics.setLineWidth(border_width)
love.graphics.setColor(color:channels())
love.graphics.rectangle(
rectangle_kind,
position.x,
position.y,
size.width,
size.height,
border_radius
)
end
return drawing
|
-- Place Bison -- Author: Neirai -- DateCreated: 5/12/2014 9:35:31 AM
function buildABison(pPlayer, pCity)
for pCityPlot = 1, pCity:GetNumCityPlots() - 1, 1 do
local pSpecificPlot = pCity:GetCityIndexPlot(pCityPlot)
if pSpecificPlot:GetTerrainType() == TerrainTypes.TERRAIN_PLAINS then
if pSpecificPlot:GetFeatureType() == (-1) and not pSpecificPlot:IsMountain() then
if pSpecificPlot:GetResourceType(-1) == (-1) then
pSpecificPlot:SetResourceType(GameInfoTypes.RESOURCE_BISON, 1)
pSpecificPlot:SetImprovementType(GameInfoTypes.IMPROVEMENT_CAMP)
print("Bison Placed on Plains")
return true
end
end
elseif
pSpecificPlot:GetTerrainType() == TerrainTypes.TERRAIN_GRASS then
if pSpecificPlot:GetFeatureType() == (-1) and not pSpecificPlot:IsMountain() then
if pSpecificPlot:GetResourceType(-1) == (-1) then
pSpecificPlot:SetResourceType(GameInfoTypes.RESOURCE_BISON, 1)
pSpecificPlot:SetImprovementType(GameInfoTypes.IMPROVEMENT_CAMP)
print("Bison Placed on Grasslands")
return true
end
end
elseif
pSpecificPlot:GetTerrainType() == TerrainTypes.TERRAIN_TUNDRA then
if pSpecificPlot:GetFeatureType() == (-1) and not pSpecificPlot:IsMountain() then
if pSpecificPlot:GetResourceType(-1) == (-1) then
pSpecificPlot:SetResourceType(GameInfoTypes.RESOURCE_BISON, 1)
pSpecificPlot:SetImprovementType(GameInfoTypes.IMPROVEMENT_CAMP)
print("Bison Placed on Tundra")
return true
end
end
end
end
return false
end
function PutBisonSomewhere(player, city, building)
print(building)
print(GameInfoTypes.BUILDING_3BUFFALOPOUND)
if building == GameInfoTypes.BUILDING_3BUFFALOPOUND then
local pPlayer = Players[player]
local pCity = pPlayer:GetCityByID(city)
if buildABison(pPlayer, pCity) == false then
print("No place to place a Bison place.")
end
end
end
GameEvents.CityConstructed.Add(PutBisonSomewhere)
|
-- put user settings here
-- this module will be loaded after everything else when the application starts
-- it will be automatically reloaded when saved
local core = require "core"
local keymap = require "core.keymap"
local config = require "core.config"
local style = require "core.style"
local common = require "core.common"
local lsp = require "plugins.lsp"
-- local font = require "font"
-- local fontconfig = require "plugins.fontconfig"
local path = system.absolute_path -- shorthand to normalise path
------------------------------ Themes ----------------------------------------
-- light theme:
core.reload_module("colors.nightfly")
--------------------------- Key bindings -------------------------------------
-- key binding:
-- keymap.add { ["ctrl+escape"] = "core:quit" }
------------------------------- Fonts ----------------------------------------
-- customize fonts:
style.font = renderer.font.load(DATADIR .. "/fonts/FiraSans-Regular.ttf", 12 * SCALE)
-- style.code_font = renderer.font.load(DATADIR .. "/fonts/JetBrainsMono-Regular.ttf", 13 * SCALE)
-- style.code_font = renderer.font.load(USERDIR .. "/fonts/VictorMono-Regular.ttf", 14 * SCALE)
renderer.font.group {
"/usr/share/fonts/TTF/Iosevka Nerd Font Complete Mono.ttf",
"/usr/share/fonts/joypixels/JoyPixels.ttf"
}
-- font names used by lite:
-- style.font : user interface
-- style.big_font : big text in welcome screen
-- style.icon_font : icons
-- style.icon_big_font : toolbar icons
-- style.code_font : code
style.lint = {
error = { common.color "#eb6772" },
warning = { common.color "#db9d63" },
info = { common.color "#9acc76" },
hint = { common.color "#3e4550" },
}
-- the function to load the font accept a 3rd optional argument like:
--
-- {antialiasing="grayscale", hinting="full"}
--
-- possible values are:
-- antialiasing: grayscale, subpixel
-- hinting: none, slight, full
-- fontconfig.use {
-- font = { name = 'sans', size = 13 * SCALE },
-- code_font = { name = 'monospace', size = 13 * SCALE },
-- }
config.fallback_fonts = {}
config.fallback_fonts.enable = false
config.fallback_fonts.preload_range = { lower = 0, upper = 0xFF }
config.fallback_fonts.fontmap_file = path(USERDIR .. "/fontmap.bin")
config.fallback_fonts.fonts = {
{ path = path("/usr/share/fonts/joypixels/JoyPixels.ttf"), size = 13 },
}
config.tab_type = "soft" -- soft for spaces, hard for real tabs (\t)
config.indent_size = 2 -- 2 spaces
-- 😀
------------------------------ Plugins ----------------------------------------
-- enable or disable plugin loading setting config entries:
-- enable plugins.trimwhitespace, otherwise it is disable by default:
-- config.plugins.trimwhitespace = true
--
-- disable detectindent, otherwise it is enabled by default
-- config.plugins.detectindent = false
config.vibe = {}
config.vibe.clipboard_ring_max = 10
config.vibe.debug_str_max = 0
config.vibe.misc_str_max_depth = 8
config.vibe.misc_str_max_list = 4
config.vibe.max_stroke_sugg = 10
config.vibe.stroke_sug_delay = 0.500
-- set this to nil to stop showing. Or to sth else)
config.vibe.permanent_status_tooltip = nil
-- max line difference to join jumplist events
config.vibe.history_max_dline_to_join = 5
-- max time difference to join jumplist events
config.vibe.history_max_dt_to_join = 0.5
-- max number of inline project search items to show
config.vibe.inline_search_maxN = 100
-------------------LSP--------------------------------
lsp.add_server {
name = "svelteserver",
language = "svelte",
file_patterns = {"%.svelte$"},
command = { "svelteserver", "--stdio" },
verbose = false
}
lsp.add_server {
name = "rust-analyzer",
language = "rust",
file_patterns = {"%.rs$"},
command = { "rust-analyzer" },
verbose = false
}
lsp.add_server {
name = "clangd",
language = "c/cpp",
file_patterns = {
"%.c$", "%.h$", "%.inl$", "%.cpp$", "%.hpp$",
"%.cc$", "%.C$", "%.cxx$", "%.c++$", "%.hh$",
"%.H$", "%.hxx$", "%.h++$", "%.objc$", "%.objcpp$"
},
command = { "clangd", "-background-index" },
verbose = false
}
lsp.add_server {
name = "lua-language-server",
language = "lua",
file_patterns = {"%.lua$"},
command = { "lua-language-server" },
verbose = false,
settings = {
Lua = {
completion = {
enable = true,
keywordSnippet = "Disable"
},
develop = {
enable = false,
debuggerPor = 11412,
debuggerWait = false
},
diagnostics = {
enable = true,
},
hover = {
enable = true,
viewNumber = true,
viewString = true,
viewStringMax = 1000
},
runtime = {
version = 'Lua 5.4',
path = {
"?.lua",
"?/init.lua",
"?/?.lua",
"/usr/share/5.4/?.lua",
"/usr/share/lua/5.4/?/init.lua"
}
},
signatureHelp = {
enable = true
},
workspace = {
maxPreload = 2000,
preloadFileSize = 1000
},
telemetry = {
enable = false
}
}
}
}
|
function sysCall_info()
return {autoStart=false}
end
function sysCall_init()
sim.addLog(sim.verbosity_scriptinfos,"This tool will display the custom data blocks attached to the selected object, or the custom data blocks attached to the scene, if no object is selected. Custom data blocks can be written and read with simWriteCustomDataBlock and simReadCustomDataBlock.")
object=-1
selectedDecoder=1
end
function sysCall_addOnScriptSuspend()
return {cmd='cleanup'}
end
decoders={
{
name='auto',
f=function(tag,data)
local t=getTagType(tag)
if t then
local d=getDecoderForType(t)
if d then
return d.f(tag,data)
else
error('unknown type: '..t)
end
end
return '<font color=#b75501>For automatic selection of decoder, there must be an \'__info__\' block with type information, e.g.: {myTagName={type=\'table\'}}</font>'
end,
},
{
name='binary',
f=function(tag,data)
return '<tt>'..data:gsub('(.)',function(y)
return string.format('%02X ',string.byte(y))
end)..'</tt>'
end,
},
{
name='string',
f=function(tag,data)
return data
end,
},
{
name='table',
f=function(tag,data)
local status,data=pcall(function() return sim.unpackTable(data) end)
if status then
return getAsString(data):gsub('[\n ]',{['\n']='<br/>',[' ']=' '})
end
end,
},
{
name='float[]',
f=function(tag,data)
return getAsString(sim.unpackFloatTable(data))
end,
},
{
name='double[]',
f=function(tag,data)
return getAsString(sim.unpackDoubleTable(data))
end,
},
{
name='int32[]',
f=function(tag,data)
return getAsString(sim.unpackInt32Table(data))
end,
},
{
name='uint8[]',
f=function(tag,data)
return getAsString(sim.unpackUInt8Table(data))
end,
},
{
name='uint16[]',
f=function(tag,data)
return getAsString(sim.unpackUInt16Table(data))
end,
},
{
name='uint32[]',
f=function(tag,data)
return getAsString(sim.unpackUInt32Table(data))
end,
},
}
function getTagType(tag)
-- standard tags that have known types:
if tag=='__info__' or tag=='__config__' or tag=='__schema__' then
return 'table'
elseif tag=='__type__' then
return 'string'
end
if info and info.blocks and info.blocks[tag] then
return info.blocks[tag]['type']
end
end
function getDecoderForType(t)
for i,decoder in ipairs(decoders) do
if decoder.name~='auto' and decoder.name==t then
return decoder
end
end
end
function sysCall_cleanup()
hideDlg()
end
function sysCall_beforeSimulation()
hideDlg()
end
function sysCall_beforeInstanceSwitch()
hideDlg()
end
function onDecoderChanged()
local index=simUI.getComboboxSelectedIndex(ui,700)
selectedDecoder=index+1
if selectedDecoder>0 then
local decoder=decoders[selectedDecoder]
if selectedTag then
local html=decoder.f(selectedTag,content[selectedTag])
if html then
simUI.setText(ui,800,html)
else
simUI.setText(ui,800,string.format('<font color=red>Not %s data</font>',decoder.name))
end
end
else
simUI.setText(ui,800,'')
end
end
function onSelectionChange(ui,id,row,column)
if row==-1 then
selectedTag=nil
else
selectedTag=simUI.getItem(ui,id,row,0)
end
local e=selectedTag and true or false
simUI.setEnabled(ui,20,e)
simUI.setEnabled(ui,700,e)
onDecoderChanged()
end
function onClearClicked(ui,id)
if selectedTag then
sim.writeCustomDataBlock(object,selectedTag,'')
hideDlg()
end
end
function onCloseClicked()
leaveNow=true
end
function showDlg()
if not ui then
local pos='position="-30,160" placement="relative"'
if uiPos then
pos='position="'..uiPos[1]..','..uiPos[2]..'" placement="absolute"'
end
local title="Custom data blocks in scene:"
if object~=sim.handle_scene then
title="Custom data blocks in object '<b>"..sim.getObjectAlias(object,0).."</b>':"
end
if not ui then
xml='<ui title="Custom Data Block Explorer" activate="false" closeable="true" on-close="onCloseClicked" resizable="false" '..pos..'>'
xml=xml..'<group flat="true"><label text="'..title..'" /></group>'
xml=xml..'<table id="600" selection-mode="row" editable="false" on-selection-change="onSelectionChange">'
xml=xml..'<header><item>Tag name</item><item>Size (bytes)</item><item>Type</item></header>'
local selectedIndex,i=-1,0
for tag,data in pairs(content) do
if tag==selectedTag then selectedIndex=i end
xml=xml..'<row>'
xml=xml..'<item>'..tag..'</item>'
xml=xml..'<item>'..#data..'</item>'
local t=getTagType(tag)
if t then xml=xml..'<item>'..t..'</item>' end
xml=xml..'</row>'
i=i+1
end
xml=xml..'</table>'
xml=xml..'<group flat="true" layout="grid">'
xml=xml..'<label text="Decode as:" />'
xml=xml..'<combobox id="700" on-change="onDecoderChanged">'
for i,decoder in ipairs(decoders) do
xml=xml..'<item>'..decoder.name..'</item>'
end
xml=xml..'</combobox>'
xml=xml..'</group>'
xml=xml..'<text-browser id="800" read-only="true" />'
xml=xml..'<button id="20" enabled="false" text="Clear selected tag" on-click="onClearClicked" />'
xml=xml..'</ui>'
ui=simUI.create(xml)
if selectedIndex~=-1 then
simUI.setTableSelection(ui,600,selectedIndex,0,false)
end
simUI.setComboboxSelectedIndex(ui,700,selectedDecoder-1)
end
end
end
function hideDlg()
if ui then
uiPos={}
uiPos[1],uiPos[2]=simUI.getPosition(ui)
simUI.destroy(ui)
ui=nil
end
end
function sysCall_nonSimulation()
if leaveNow then
return {cmd='cleanup'}
end
local s=sim.getObjectSelection()
local previousObject,previousContent=object,content
content=nil
object=-1
info=nil
local tags=nil
if s then
if #s>=1 then
if s[#s]>=0 then
object=s[#s]
end
end
else
object=sim.handle_scene
end
if object~=-1 then
tags=sim.readCustomDataBlockTags(object)
info=sim.readCustomDataBlock(object,'__info__')
if info then info=sim.unpackTable(info) end
end
if previousObject~=object then
hideDlg()
end
if tags then
content={}
for i,tag in ipairs(tags) do
content[tag]=sim.readCustomDataBlock(object,tag)
end
local _=function(x) return x~=nil and sim.packTable(x) or nil end
if _(content)~=_(previousContent) then
hideDlg()
end
showDlg()
else
hideDlg()
end
end
|
local FAQ = {}
setmetatable(FAQ, {__index = _G})
-- Exported function
-- Returns the factory object
-- Optional callback param that is passed the factory object
function getFactory(cb)
if cb then
cb(FAQ)
end
return FAQ
end
-- Replicate the following functions in the FAQ table, so we can use them in the export
local REPLICATES = {
"Node","Nodes",
"Icon","TextIcon","AlertLink","AlertHeading",
"Badge","Breadcrumb","Button","ButtonGroup",
"ButtonToolbar","Callout","Card","CardList",
"CardBase","CardBody","CardTitle","CardSubtitle",
"CardText","CardLink","CardHeader","CardFooter",
"Carousel","Dropdown","DropdownButton","FormInputText",
"FormInputPassword","FormInputCheckbox","FormInputRadio",
"Footer","FormInputTextGroup","NavList","NavItem",
"NavLink","Navbar","NavbarBrand","NavbarNav",
"NavbarText","Pagination","PageItem","PageLink",
"ProgressBar","ProgressGroup","Switch","TableSmall",
"TableBase","TableHead","TableBody","Form",
}
for _, replicate in next, REPLICATES do
FAQ[replicate] = _G[replicate]
end
FAQ.BuildPage = function(cb, data)
local html = ""
data = FAQ.PatchData(data)
local ok, msg = cb(FAQ, data, function(input)
html = html .. input
end)
if not ok then
return FAQ.Alert("warning", (msg or "Failed to build page"))
end
return html
end
FAQ.ReadableNumber = function(num, places)
local ret
local placeValue = ("%%.%df"):format(places or 0)
if not num then
return 0
elseif num >= 1000000000000 then
ret = placeValue:format(num / 1000000000000) .. "T" -- trillion
elseif num >= 1000000000 then
ret = placeValue:format(num / 1000000000) .. "B" -- billion
elseif num >= 1000000 then
ret = placeValue:format(num / 1000000) .. "M" -- million
elseif num >= 1000 then
ret = placeValue:format(num / 1000) .. "k" -- thousand
else
ret = placeValue:format(num) -- hundreds
end
return ret
end
-- Generate a paginator widget to navigate between pages
FAQ.GeneratePaginator = function(pageName, currentPage, maxPages, align)
local paginatorList = {}
if maxPages > 0 then
if currentPage > maxPages or currentPage < 0 then currentPage = 1 end
table.insert(paginatorList, {"Previous", FAQ.GenerateDataUrl(pageName, {page = math.max(currentPage - 1, 1)}), false, currentPage == 1})
for i = 1, maxPages do
table.insert(paginatorList, {i, FAQ.GenerateDataUrl(pageName, {page = i}), i == currentPage})
end
table.insert(paginatorList, {"Next", FAQ.GenerateDataUrl(pageName, {page = math.min(currentPage + 1, maxPages)}), false, currentPage == maxPages})
return Pagination(paginatorList, align or "center")
end
return Pagination({
{"Previous", "#", false, true},
{"-", "#", true, true},
{"Next", "#", false, true},
}, "center")
end
-- Get the plugin url with extra parameters
FAQ.GenerateDataUrl = function(name, data)
local url = exports["webadmin"]:getPluginUrl(name)
for get, val in next, data do
if get ~= 'name' then
url = url .. ("&%s=%s"):format(get, val)
end
end
return url
end
-- Show a button in the sidebar
-- page, string, name of page
-- icon, string, font awesome icon to represent page
-- name, string, title of page
-- badge, string, badge content (optional)
-- badgetype, string, badge type (optional, defaults to warning)
-- active, bool, highlight button as if it's the current page (optional)
FAQ.SidebarOption = function(page, icon, name, badge, badgetype, active)
return Node("li", {class = "nav-item" .. (active and " open" or "")}, Node("a", {class = "nav-link" .. (active and " active" or ""), href = FAQ.GenerateDataUrl(page, {})}, {
Node("i", {class = "nav-icon fa fa-" .. icon}, ""),
" " .. name,
badge and Badge(badgetype or "warning", badge) or "",
}))
end
-- Simply turns a table of tables into a key value pair
-- Yes, it breaks if you have multiple of the same key, but who the fuck does that anyways?
FAQ.PatchData = function(data)
local returnData = {}
for k, v in next, data do
returnData[k] = v[1]
-- Convert string numbers to real numbers
if tostring(tonumber(v[1])) == v[1] then
returnData[k] = tonumber(v[1])
end
end
return returnData
end
--[[
Arguments:
table headers*
list of header titles
table data*
list of rows, each row is a list of each column
function datafunc(rowdata, n)
advanced function ran for every row, return formatted row data
string style
extra table css style
string headstyle
extra table head css style
]]
FAQ.Table = function(headers, data, datafunc, style, headstyle)
local rows = {}
if datafunc then
for n, row in next, data do
table.insert(rows, datafunc(row, n))
end
else
rows = data
end
return TableBase({
TableHead(headers, headstyle),
TableBody(rows, true)
}, style)
end
FAQ.PageTitle = function(title)
return Node("h1", {}, title)
end
FAQ.InfoCard = function(title, data)
local innerData = ""
for _, entry in next, data do
innerData = innerData .. Node("dt", {class = "col-sm-2"}, entry[1])
innerData = innerData .. Node("dd", {class = "col-sm-10"}, entry[2])
end
innerData = Node("dl", {class = "row my-0"}, innerData)
return CardBase({
CardHeader(title),
CardBody(innerData),
})
end
FAQ.UserCard = function(title, subtitle, data)
local innerData = ""
for _, entry in next, data do
innerData = innerData .. Callout(entry[1], entry[2], "primary", true)
end
return CardBase({
CardHeader({TextIcon("user"), title}),
CardBody({
CardSubtitle(subtitle),
innerData,
}),
})
end
local ALERT_ICON_TYPES = {
["warning"] = [[<i class="fa fa-exclamation-triangle"></i> ]],
["danger"] = [[<i class="fa fa-exclamation-circle"></i> ]],
["info"] = [[<i class="fa fa-info-circle"></i> ]],
}
FAQ.Alert = function(alert, message, important, no_icon)
return [[<div class="alert alert-]]..alert..[[" role="alert">]]..(important and "<strong>" or "")..(no_icon and "" or (ALERT_ICON_TYPES[alert] or ""))..message..(important and "</strong>" or "")..[[</div>]]
end
|
local function lol(gfx)
local items = newItemList()
items:add(newEItem('spawn',5,3,gfx))
items:add(newEItem('score',9,21,gfx))
items:add(newEItem('score',13,21,gfx))
items:add(newEItem('score',17,21,gfx))
items:add(newEItem('goal',15,4,gfx))
local decs = {}
decs[1] = {1, 6, 4}
decs[2] = {1, 7, 4}
decs[3] = {1, 8, 4}
decs[4] = {1, 16, 4}
decs[5] = {1, 16, 15}
decs[6] = {1, 17, 15}
decs[7] = {1, 18, 15}
decs[8] = {1, 8, 15}
decs[9] = {1, 19, 15}
decs[10] = {1, 15, 15}
decs[11] = {1, 9, 23}
decs[12] = {1, 10, 23}
decs[13] = {1, 11, 23}
decs[14] = {1, 13, 23}
decs[15] = {1, 14, 23}
decs[16] = {1, 16, 23}
decs[17] = {1, 17, 23}
decs[18] = {1, 18, 23}
local nmys = {}
nmys[1] = {5, 14, 7}
nmys[2] = {5, 14, 8}
nmys[3] = {5, 14, 9}
nmys[4] = {5, 14, 10}
nmys[5] = {5, 14, 11}
nmys[6] = {5, 14, 12}
nmys[7] = {5, 14, 13}
nmys[8] = {5, 14, 14}
nmys[9] = {5, 9, 8}
nmys[10] = {5, 9, 9}
nmys[11] = {5, 9, 10}
nmys[12] = {5, 9, 11}
nmys[13] = {5, 9, 12}
nmys[14] = {5, 9, 14}
nmys[15] = {5, 9, 13}
nmys[16] = {5, 9, 7}
nmys[17] = {5, 14, 16}
nmys[18] = {5, 14, 15}
nmys[19] = {5, 9, 15}
nmys[20] = {5, 9, 16}
nmys[21] = {4, 13, 26}
local lvl = {}
lvl[1] = {}
lvl[2] = {}
lvl[3] = {}
lvl[4] = {}
lvl[4][4] = 1
lvl[4][5] = 4
lvl[4][6] = 7
lvl[5] = {}
lvl[5][4] = 2
lvl[5][5] = 5
lvl[5][6] = 8
lvl[6] = {}
lvl[6][4] = 2
lvl[6][5] = 5
lvl[6][6] = 8
lvl[6][15] = 1
lvl[6][16] = 4
lvl[6][17] = 4
lvl[6][18] = 4
lvl[6][19] = 4
lvl[6][20] = 4
lvl[6][21] = 4
lvl[6][22] = 4
lvl[6][23] = 4
lvl[6][24] = 4
lvl[6][25] = 7
lvl[7] = {}
lvl[7][4] = 2
lvl[7][5] = 5
lvl[7][6] = 8
lvl[7][15] = 2
lvl[7][16] = 5
lvl[7][17] = 5
lvl[7][18] = 5
lvl[7][19] = 5
lvl[7][20] = 5
lvl[7][21] = 5
lvl[7][22] = 5
lvl[7][23] = 5
lvl[7][24] = 5
lvl[7][25] = 8
lvl[8] = {}
lvl[8][4] = 2
lvl[8][5] = 5
lvl[8][6] = 8
lvl[8][15] = 2
lvl[8][16] = 5
lvl[8][17] = 86
lvl[8][18] = 6
lvl[8][19] = 6
lvl[8][20] = 6
lvl[8][21] = 6
lvl[8][22] = 6
lvl[8][23] = 62
lvl[8][24] = 5
lvl[8][25] = 8
lvl[9] = {}
lvl[9][4] = 2
lvl[9][5] = 5
lvl[9][6] = 8
lvl[9][15] = 2
lvl[9][16] = 5
lvl[9][17] = 8
lvl[9][23] = 2
lvl[9][24] = 5
lvl[9][25] = 8
lvl[10] = {}
lvl[10][4] = 3
lvl[10][5] = 6
lvl[10][6] = 9
lvl[10][15] = 3
lvl[10][16] = 6
lvl[10][17] = 9
lvl[10][23] = 2
lvl[10][24] = 5
lvl[10][25] = 8
lvl[11] = {}
lvl[11][23] = 2
lvl[11][24] = 5
lvl[11][25] = 8
lvl[12] = {}
lvl[12][23] = 2
lvl[12][24] = 5
lvl[12][25] = 8
lvl[13] = {}
lvl[13][4] = 1
lvl[13][5] = 4
lvl[13][6] = 7
lvl[13][15] = 1
lvl[13][16] = 4
lvl[13][17] = 7
lvl[13][23] = 2
lvl[13][24] = 5
lvl[13][25] = 8
lvl[14] = {}
lvl[14][4] = 2
lvl[14][5] = 5
lvl[14][6] = 8
lvl[14][15] = 2
lvl[14][16] = 5
lvl[14][17] = 8
lvl[14][23] = 2
lvl[14][24] = 5
lvl[14][25] = 8
lvl[15] = {}
lvl[15][4] = 2
lvl[15][5] = 5
lvl[15][6] = 8
lvl[15][15] = 2
lvl[15][16] = 5
lvl[15][17] = 8
lvl[15][23] = 2
lvl[15][24] = 5
lvl[15][25] = 8
lvl[16] = {}
lvl[16][4] = 2
lvl[16][5] = 5
lvl[16][6] = 8
lvl[16][15] = 2
lvl[16][16] = 5
lvl[16][17] = 8
lvl[16][23] = 2
lvl[16][24] = 5
lvl[16][25] = 8
lvl[17] = {}
lvl[17][4] = 2
lvl[17][5] = 5
lvl[17][6] = 8
lvl[17][15] = 2
lvl[17][16] = 5
lvl[17][17] = 8
lvl[17][23] = 2
lvl[17][24] = 5
lvl[17][25] = 8
lvl[18] = {}
lvl[18][4] = 3
lvl[18][5] = 6
lvl[18][6] = 9
lvl[18][15] = 2
lvl[18][16] = 5
lvl[18][17] = 8
lvl[18][23] = 2
lvl[18][24] = 5
lvl[18][25] = 8
lvl[19] = {}
lvl[19][15] = 2
lvl[19][16] = 5
lvl[19][17] = 48
lvl[19][18] = 4
lvl[19][19] = 4
lvl[19][20] = 4
lvl[19][21] = 4
lvl[19][22] = 4
lvl[19][23] = 24
lvl[19][24] = 5
lvl[19][25] = 8
lvl[20] = {}
lvl[20][15] = 2
lvl[20][16] = 5
lvl[20][17] = 5
lvl[20][18] = 5
lvl[20][19] = 5
lvl[20][20] = 5
lvl[20][21] = 5
lvl[20][22] = 5
lvl[20][23] = 5
lvl[20][24] = 5
lvl[20][25] = 8
lvl[21] = {}
lvl[21][15] = 3
lvl[21][16] = 6
lvl[21][17] = 6
lvl[21][18] = 6
lvl[21][19] = 6
lvl[21][20] = 6
lvl[21][21] = 6
lvl[21][22] = 6
lvl[21][23] = 6
lvl[21][24] = 6
lvl[21][25] = 9
lvl[22] = {}
lvl[23] = {}
lvl[24] = {}
lvl[25] = {}
lvl[26] = {}
lvl[27] = {}
lvl[28] = {}
lvl[29] = {}
lvl[30] = {}
lvl[31] = {}
lvl[32] = {}
lvl[33] = {}
lvl[34] = {}
lvl[35] = {}
lvl[36] = {}
lvl[37] = {}
lvl[38] = {}
lvl[39] = {}
lvl[40] = {}
lvl[41] = {}
lvl[42] = {}
lvl[43] = {}
lvl[44] = {}
lvl[45] = {}
lvl[46] = {}
lvl[47] = {}
lvl[48] = {}
lvl[49] = {}
lvl[50] = {}
lvl[51] = {}
lvl[52] = {}
lvl[53] = {}
lvl[54] = {}
lvl[55] = {}
lvl[56] = {}
lvl[57] = {}
lvl[58] = {}
lvl[59] = {}
lvl[60] = {}
lvl[61] = {}
lvl[62] = {}
lvl[63] = {}
lvl[64] = {}
lvl[65] = {}
lvl[66] = {}
lvl[67] = {}
lvl[68] = {}
lvl[69] = {}
lvl[70] = {}
lvl[71] = {}
lvl[72] = {}
lvl[73] = {}
lvl[74] = {}
lvl[75] = {}
lvl[76] = {}
lvl[77] = {}
lvl[78] = {}
lvl[79] = {}
lvl[80] = {}
lvl[81] = {}
lvl[82] = {}
lvl[83] = {}
lvl[84] = {}
lvl[85] = {}
lvl[86] = {}
lvl[87] = {}
lvl[88] = {}
lvl[89] = {}
lvl[90] = {}
lvl[91] = {}
lvl[92] = {}
lvl[93] = {}
lvl[94] = {}
lvl[95] = {}
lvl[96] = {}
lvl[97] = {}
lvl[98] = {}
lvl[99] = {}
lvl[100] = {}
return lvl,items,decs,nmys
end
return lol
|
object_tangible_component_structure_turbo_fluidic_drilling_pumping_unit_advanced = object_tangible_component_structure_shared_turbo_fluidic_drilling_pumping_unit_advanced:new {
}
ObjectTemplates:addTemplate(object_tangible_component_structure_turbo_fluidic_drilling_pumping_unit_advanced, "object/tangible/component/structure/turbo_fluidic_drilling_pumping_unit_advanced.iff")
|
-- @Author:pandayu
-- @Version:1.0
-- @DateTime:2018-09-09
-- @Project:pandaCardServer CardGame
-- @Contact: QQ:815099602
local model = require "game.model.role_model"
local config = require "game.template.replica"
local timetool = require "include.timetool"
local bconfig = require "game.config"
local task_config = require "game.template.task"
local vip_config = require "game.template.vip"
local open_config = require "game.template.open"
local max = math.max
local _M = model:extends()
_M.class = "role.replica"
_M.push_name = "replica"
_M.changed_name_in_role = "replica"
_M.virtual_id = 24
_M.attrs = {
llist ={},
hlist={},
bl={0,0,0,0},
bls ={0,0,0,0},
at = 0,
en = config.replica_energy_max,
n = config.replica_l_cout_max,
rn = 0,
bpost = 0,
rf =0,
}
function _M:__up_version()
_M.super.__up_version(self)
if not self.vip then
self.vip = 0
end
if not self.data.bl then self.data.bl ={0,0,0,0}end
if not self.data.bls then self.data.bls ={0,0,0,0}end
if not self.data.bpost then self.data.bpost = 0 end
if not self.data.rf then self.data.rf = 0 end
self:get_llist_post()
end
function _M:on_time_up()
self.data.en = config.replica_energy_max
self.data.at = timetool:now() -1
self:changed("en")
self:changed("at")
self.data.n = config.replica_l_cout_max
self:changed("n")
self.data.rn =0
self:changed("rn")
self.data.rf =0
self:changed("rn")
if self.data.bl[1] > 0 then
self.data.bpost = self.data.bpost -3
self.data.bpost = max(self.data.bpost,0)
self.data.bl[1] = 0
end
self.data.bls[1] = 0
self.refresh_llist = false
--[[for i,v in ipairs(self.data.llist) do
v.fs = {0,0,0,0}
v.ps = {0,0,0,0}
v.g =0
end]]--
for i,v in ipairs(self.data.hlist) do
--v.fs = {0,0,0,0}
--v.ps = {0,0,0,0}
v.ns = {config.replica_l_cout_max,config.replica_l_cout_max,config.replica_l_cout_max,config.replica_l_cout_max}
--v.ss ={0,0,0,0}
--v.gl = 0
v.rn ={0,0,0,0}
end
self:changed("llist")
self:changed("hlist")
self:changed("bl")
self:changed("bls")
end
function _M:update()
local ltime = timetool:now()
if self.data.en < config.replica_energy_max and ltime - self.data.at >= config.replica_add_energy_interval then
self.data.at = ltime + config.replica_add_energy_interval
self.data.en = self.data.en + 1
self:changed("en")
self:changed("at")
end
self:is_boss_refresh(ltime)
end
function _M:init()
if #self.data.llist == 0 and not self.get_llist and open_config:check_level(self.role,open_config.need_level.replica) then
self.data.llist = config:create_l_list()
self:changed("llist")
self.get_llist = true
end
if #self.data.hlist == 0 and not self.get_hlist and open_config:check_level(self.role,open_config.need_level.replica) then
self.data.hlist = config:create_h_list()
self:changed("hlist")
self.get_hlist = true
end
end
function _M:virtula_add_count(num)
self.data.en = self.data.en + num
self:changed("en")
end
function _M:on_level_up()
self:init()
end
function _M:on_vip_up()
--self:refresh()
end
function _M:is_boss_refresh(ltime)
local hour = timetool:get_hour(ltime)
local lv = self.role:get_level()
local send = false
if hour >= 6 and self.data.bls[1] == 0 and lv >= config.replica_l_need_lv and not self.refresh_llist then
local id =self:get_max_llist_id()
if self:boss_refresh_stage(id) then send = true end
self.refresh_llist = true
elseif hour >= 6 and self.data.bls[2] == 0 and lv >= config.replica_h_need_lv then
self.data.bl[2] = config:boss_refresh(2)
self.data.bls[2] = 1
send = true
elseif hour >= 12 and self.data.bls[3] == 0 and lv >= config.replica_h_need_lv then
self.data.bl[3] = config:boss_refresh(2)
self.data.bls[3] = 1
send = true
elseif hour >= 18 and self.data.bls[4] == 0 and lv >= config.replica_h_need_lv then
self.data.bl[4] = config:boss_refresh(2)
self.data.bls[4] = 1
send = true
end
if hour == 3 and self.data.bl[1] >0 then
self.data.bl={0,0,0,0}
self.data.bls={0,0,0,0}
send = true
end
if send then
self:changed("bl")
self:changed("bls")
end
end
function _M:get_max_llist_id()
local id =1
for i,v in ipairs(self.data.llist) do
if v.fs[1] <= 0 then break end
id = v.id
end
return id
end
function _M:check_stage(id,stage,num)
if id > 100 then
id = id % 100
if not self.data.hlist[id] or not self.data.hlist[id].ns[stage] or self.data.hlist[id].ns[stage] - num < 0 then return false end
if self.data.en - config.replica_stage_cost_energy * num < 0 then return false end
if stage >1 and self.data.hlist[id].fs[stage-1] == 0 then return false end
if id > 1 and self.data.hlist[id-1].fs[4] == 0 then return false end
else
if not self.data.llist[id] or self.data.n - num < 0 then return false end
if stage >1 and self.data.llist[id].fs[stage-1] == 0 then return false end
if id > 1 and self.data.llist[id-1].fs[4] == 0 then return false end
end
return true
end
function _M:get_stage_profit(id,stage,win,num)
local f = 0
if id > 100 and self.data.hlist[id - 100].fs[stage] == 0 then f =1
elseif id >0 and id < 100 and self.data.llist[id].fs[stage] == 0 then f =1 end
return config:get_stage_profit(f,id,stage,win,num)
end
function _M:get_all_str()
self.all_str = 0
for i,v in ipairs(self.data.hlist) do
for i1,v1 in ipairs(v.ss) do
if v1 >0 then self.all_str = self.all_str + v1 end
end
end
return self.all_str
end
function _M:is_all_win(id)
local pass = true
for i,v in ipairs(self.data.hlist[id].ps) do
if v ~= 1 then
pass =false
break
end
end
return pass
end
function _M:set_stage(id,stage,win,star,num,f)
if id > 100 then
id = id % 100
self.data.hlist[id].ns[stage] = self.data.hlist[id].ns[stage] - num
if win == 1 then
local last_str = self.data.hlist[id].ss[stage]
local last_ps = self.data.hlist[id].ps[stage]
self.data.hlist[id].ss[stage] = max(self.data.hlist[id].ss[stage] , star )
self.data.hlist[id].fs[stage] = 1
self.data.hlist[id].ps[stage] = 1
if last_str ~= star then
self:get_all_str()
self.role.tasklist:trigger(task_config.trigger_type.replica_high_starnum,self.all_str)
end
self.role.tasklist:trigger(task_config.trigger_type.replica_high_part_pass,num)
if last_ps ==0 and self:is_all_win(id) then self.role.tasklist:trigger(task_config.trigger_type.replica_high_pass,1) end
end
self:changed("hlist")
self.data.en = self.data.en - config.replica_stage_cost_energy * num
self.data.at = timetool:now() + config.replica_add_energy_interval
self:changed("en")
self:use_virtaul(config.replica_stage_cost_energy * num)
else
self.data.n = self.data.n - num
if win == 1 then
self.data.llist[id].fs[stage] = 1
self.data.llist[id].ps[stage] = 1
end
self:changed("llist")
self:changed("n")
self:boss_refresh_stage(id)
end
end
function _M:can_get_box(id,pos)
if id > 100 then
if not self.data.hlist[id-100] or self.data.hlist[id-100].gl >= pos then return false end
return config:check_hlist_box(self.data.hlist[id-100],id,pos)
else
if not self.data.llist[id] or self.data.llist[id].g ~= 0 then return false end
return config:check_llist_box(self.data.llist[id],id,pos)
end
return true
end
function _M:get_box_profit(id,pos)
return config:get_box_profit(id,pos)
end
function _M:set_box(id,pos)
if id > 100 then
id = id % 100
self.data.hlist[id].gl = pos
self:changed("hlist")
else
self.data.llist[id].g = 1
self:changed("llist")
end
end
function _M:can_reset(id ,pos )
if id < 100 then return false end
if not self.data.hlist[id % 100] or not self.data.hlist[id % 100].rn[pos] then return false end
if self.data.hlist[id % 100].rn[pos] + 1 > vip_config:get_fun_itmes(self.role,vip_config.type.bw_num) then return false end
return true
end
function _M:get_reset_cost()
return config:get_reset_cost()
end
function _M:set_reset(id,pos)
self.data.hlist[id % 100].rn[pos] = self.data.hlist[id % 100].rn[pos] + 1
self.data.hlist[id % 100].ns[pos] = config.replica_l_cout_max
--self.data.rn = self.data.rn +1
self:changed("hlist")
self:changed("rn")
end
function _M:check_boss(pos)
if not self.data.bl[pos] or self.data.bls[pos] ~= 1 then return false end
if self.data.en - config:get_boss_consume(self.data.bl[pos]) < 0 then return false end
return true
end
function _M:get_boss_profit(pos)
return config:get_boss_profit(self.data.bl[pos])
end
function _M:set_boss(pos,win)
if win == 1 then
self.data.bls[pos] = 2
self:changed("bls")
end
self.data.en = self.data.en - config:get_boss_consume(self.data.bl[pos])
self.data.at = timetool:now() + config.replica_add_energy_interval
self:changed("en")
self:use_virtaul( config:get_boss_consume(self.data.bl[pos]))
self:changed("at")
end
function _M:get_llist_post()
self.lpost = 0
for k,v in pairs(self.data.llist) do
if v.ps and v.ps[1] == 1 and v.ps[4] ~= 1 then
self.lpost = k
break
end
end
end
function _M:boss_refresh_stage(id)
if id > self.data.bpost + 3 and self.data.rf == 0 then
self.data.bl[1] = config:boss_refresh(1)
self.data.bls[1] = 1
self.data.rf = 1
self.data.bpost = (self.data.bpost or 0 ) + 3
self:changed("rf")
self:changed("bl")
self:changed("bls")
self:changed("bpost")
return true
end
return false
end
return _M
|
local view3 = nil
local M = {}
M.init = function(view_mngr)
view3 = view_mngr.addView("view3")
-- Callback function when one of the buttons in the grid is selected
local function onSelected(choice)
dumpTable(choice)
end
-- Specific callback function for view1 button
local function onView1Clicked(choice)
view3.leave("view1", {fromView="view3"})
end
-- Specific callback function for view2 button
local function onView2Clicked(choice)
view3.leave("view2", {fromView="view3"})
end
-------------------------------------------
-- Override callbacks
--[[
function view2.onLeave()
print("Leaving view2")
end
]]
local dynspan = 1
local grid = nil
function view3.onLeave()
grid.clear()
end
function view3.onStart(vstage, params)
dynspan = dynspan % 3
dynspan = dynspan + 1
print('view3.onStart ')
dumpTable(params)
local appwidth = application:getDeviceWidth()
local appheight = application:getDeviceHeight()
-- Create a button grid with:
-- Width and height of the screen
-- 3 rows, 1 column
-- cell padding of 10%
grid = ButtonGrid(appwidth, appheight, 3, 4, 0.10)
grid.setBtnParams({font_file = 'Vera.ttf'})
-- Add the following buttons. The optimal unified font size for all
-- the buttons is calculated when the button grid is rendered
local params1 = { disp_params = { xspan = 4, keep_max_font = true } }
grid.addButton(1, 1, "In view3", nil, params1)
local params2 = { disp_params = { xspan = dynspan } }
grid.addButton(3, 1, "To View1", onView1Clicked, params2)
local params3 = { disp_params = { xspan = 4-dynspan+1 } }
grid.addButton(3, dynspan+1, "To View2", onView2Clicked, params3)
-- Set the button grid callback handler
grid.setHandler( onSelected )
grid.render(vstage)
end
end
return M
|
object_tangible_loot_npc_loot_shisa_generic = object_tangible_loot_npc_loot_shared_shisa_generic:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_npc_loot_shisa_generic, "object/tangible/loot/npc/loot/shisa_generic.iff")
|
-- File: telescope.lua
-- Author: Zakhary Kaplan <https://zakharykaplan.ca>
-- Created: 06 Aug 2021
-- SPDX-License-Identifier: MIT
-- Require module setup
require('telescope').setup {
defaults = {
-- Default configuration for telescope goes here:
-- config_key = value,
mappings = {
i = {
-- map actions.which_key to <C-h> (default: <C-/>)
-- actions.which_key shows the mappings for your picker,
-- e.g. git_{create, delete, ...}_branch for the git_branches picker
-- ['<C-h>'] = 'which_key',
},
},
},
pickers = {
-- Default configuration for builtin pickers goes here:
-- picker_name = {
-- picker_config_key = value,
-- ...
-- }
-- Now the picker_config_key will be applied every time you call this
-- builtin picker
},
extensions = {
-- Your extension configuration goes here:
-- extension_name = {
-- extension_config_key = value,
-- }
-- please take a look at the readme of the extension you want to configure
},
}
-- Configure mappings
do
local function map(...) vim.api.nvim_set_keymap(...) end
local opts = { noremap = true, silent = true }
-- Prefix mappings
local prefix = '<C-h>'
map('n', prefix .. '<CR>', '<Cmd>Telescope<CR>', opts)
map('n', prefix .. 'a', '<Cmd>lua require("telescope.builtin").find_files({ hidden = true })<CR>', opts)
map('n', prefix .. 'b', '<Cmd>lua require("telescope.builtin").buffers()<CR>', opts)
map('n', prefix .. 'f', '<Cmd>lua require("telescope.builtin").find_files()<CR>', opts)
map('n', prefix .. 'g', '<Cmd>lua require("telescope.builtin").live_grep()<CR>', opts)
map('n', prefix .. 'h', '<Cmd>lua require("telescope.builtin").help_tags()<CR>', opts)
map('n', prefix .. 'o', '<Cmd>lua require("telescope.builtin").oldfiles()<CR>', opts)
map('n', prefix .. 's', '<Cmd>lua require("telescope.builtin").git_status()<CR>', opts)
-- Shortcuts
map('n', prefix, prefix .. '<CR>', { silent = true }) -- Telescope
map('n', '<C-p>', prefix .. 'f', { silent = true }) -- find_files
map('n', 'gb', prefix .. 'b', { silent = true }) -- buffers
end
-- To get extensions loaded and working with telescope, you need to call
-- load_extension, somewhere after setup function:
require('telescope').load_extension('fzf')
require('telescope').load_extension('notify')
|
local c = require("load_conf")
local config = c.get_conf("/etc/wpt/conf.json")
local hosts = ngx.shared.hosts
local len = 0
local ch = config["hosts"]
for host in ipairs(ch) do
hosts:set(ch[host]["id"], ch[host]["host"])
hosts:set(host, ch[host]["host"])
len=1+len
end
-- set length of hosts
hosts:set(0, len)
|
local brave = require "telescope._extensions.bookmarks.brave"
describe("brave", function()
describe("collect_bookmarks", function()
it("should parse bookmarks file", function()
local bookmarks = brave.collect_bookmarks(
{ os_name = "Darwin", os_homedir = "spec/fixtures" },
{ selected_browser = "brave" }
)
assert.are.same(bookmarks, {
{
name = "Brave",
path = "Brave",
url = "https://brave.com/",
},
})
end)
end)
end)
|
Set = {}
local mt = {} -- 集合的元表
-- 根据参数列表中的值创建一个新的集合
function Set.new(l)
local set = {}
setmetatable(set, mt)
for _, v in pairs(l) do set[v] = true end
mt.__metatable = "You cannot get the metatable" -- 设置完的元表以后,不让其他人再设置
return set
end
-- 并集操作
function Set.union(a, b)
local retSet = Set.new{} -- 此处相当于Set.new({})
for v in pairs(a) do retSet[v] = true end
for v in pairs(b) do retSet[v] = true end
return retSet
end
-- 交集操作
function Set.intersection(a, b)
local retSet = Set.new{}
for v in pairs(a) do retSet[v] = b[v] end
return retSet
end
-- 打印集合的操作
function Set.tostring(set)
local tb = {}
for e in pairs(set) do
tb[#tb + 1] = e
end
return "{" .. table.concat(tb, ", ") .. "}"
end
function Set.print(s)
print(Set.toString(s))
end
mt.__add = Set.union
mt.__tostring = Set.toString
-- test set
local set1 = Set.new({10, 20, 30})
local set2 = Set.new({1, 2})
print(getmetatable(set1)) -- 获取的都是同一个 matetable
print(getmetatable(set2))
assert(getmetatable(set1) == getmetatable(set2))
local set12= set1 + set2
print("set1 + set2: ",Set.tostring(set12))
-----------------------
--[[
print_dump是一个用于调试输出数据的函数,能够打印出nil,boolean,number,string,table类型的数据,以及table类型值的元表
参数data表示要输出的数据
参数showMetatable表示是否要输出元表
参数lastCount用于格式控制,用户请勿使用该变量
]]
function print_dump(data, showMetatable, lastCount)
if type(data) ~= "table" then
--Value
if type(data) == "string" then
io.write("\"", data, "\"")
else
io.write(tostring(data))
end
else
--Format
local count = lastCount or 0
count = count + 1
io.write("{\n")
--Metatable
if showMetatable then
for i = 1,count do io.write("\t") end
local mt = getmetatable(data)
io.write("\"__metatable\" = ")
print_dump(mt, showMetatable, count) -- 如果不想看到元表的元表,可将showMetatable处填nil
io.write(",\n") --如果不想在元表后加逗号,可以删除这里的逗号
end
--Key
for key,value in pairs(data) do
for i = 1,count do io.write("\t") end
if type(key) == "string" then
io.write("\"", key, "\" = ")
elseif type(key) == "number" then
io.write("[", key, "] = ")
else
io.write(tostring(key))
end
print_dump(value, showMetatable, count) -- 如果不想看到子table的元表,可将showMetatable处填nil
io.write(",\n") --如果不想在table的每一个item后加逗号,可以删除这里的逗号
end
--Format
for i = 1,lastCount or 0 do io.write("\t") end
io.write("}")
end
--Format
if not lastCount then
io.write("\n")
end
end
t1 = {}
tm = {}
db = {k=1}
tm.__newindex = db
setmetatable(t1,tm)
print_dump(t1,true)
t1.k2 = 2
print_dump(t1,true)
|
function onStepHit()
if curStep == 544 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 547 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 552 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 555 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 560 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 563 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 568 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 704 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 707 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 712 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 715 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 720 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 723 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 728 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 732 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 768 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 771 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 776 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 779 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 784 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 787 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 792 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 796 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 832 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 835 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 840 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 843 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 848 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 851 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 856 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 860 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 928 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 931 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 936 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 939 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 944 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 947 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 952 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 956 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1216 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1219 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1224 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1227 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1232 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1235 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1240 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1244 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1280 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1283 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1288 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1291 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1296 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1299 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1304 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1308 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1344 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1347 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1352 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1355 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1360 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1363 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1368 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1372 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1440 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1443 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1448 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1451 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1456 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1459 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1464 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
if curStep == 1468 then
doTweenAlpha('dient', 'gradient1', 0, 0.4, 'linear')
setProperty('gradient1.alpha', 1)
doTweenAlpha('dient1', 'gradient', 0, 0.4, 'linear')
setProperty('gradient.alpha', 1)
end
end
--FUUUUUUUUUUUUUUUU AHHHHHHHHHHHHHHHHHHHHHH
|
-- 消息窗
local MsgBox = LDeclare("MsgBox", LClass("MsgBox"))
function MsgBox:Start()
print("MsgBox Start")
self.btn_close = self.gameObject.transform:Find("btn_close"):GetComponent(Button)
self.btn_close.onClick:AddListener(function()
self.gameObject:GetComponent(Image).sprite = nil
LWindowManager.GetInstance():popWindow("Prefabs/MsgBox.prefab")
end)
end
function MsgBox:OnDestroy()
LLoadBundle.GetInstance():UnloadBundles({
"atlas-face_png.ab",
"scenes-first_unity.ab",
"prefabs-msgbox_prefab.ab"})
end
return MsgBox
|
module ('mock')
function loadAssetDataTable(filename) --lua or json?
-- _stat( 'loading json data table', filename )
if not filename then return nil end
local f = io.open( filename, 'r' )
if not f then
error( 'data file not found:' .. tostring( filename ),2 )
end
local text=f:read('*a')
f:close()
local data = MOAIJsonParser.decode(text)
if not data then _error( 'json file not parsed: '..filename ) end
return data
end
function loadTextData( filename )
local fp = io.open( filename, 'r' )
local text = fp:read( '*a' )
return text
end
---------------------basic loaders
local basicLoaders = {}
function basicLoaders.text( node )
return loadTextData( node.filePath )
end
----------REGISTER the loaders
for assetType, loader in pairs(basicLoaders) do
registerAssetLoader( assetType, loader )
end
|
math.randomseed(os.time())
local max = 1000
local N = math.random(max)
print("Welcome to the number guessing game!")
print("I am thinking of a number between 1 and " .. max)
local tries = 0
while true do
print("Take a guess:")
local input = io.read()
local guess = tonumber(input)
if guess == nil then
print("Hey, " .. input .. " is not a number!")
else
tries = tries + 1
if guess < N then
print("Too small!")
elseif guess == N then
print("You got it, in " .. tries .. " tries!")
break
else
print("Too big!")
end
end
end
print("Thanks for playing!")
|
-- some constant
return {
luals_repos = vim.loop.os_homedir()..'/repos/lua-language-server/',
lsp_condaenv_bin = vim.loop.os_homedir()..'/miniconda3/envs/dev_env_ansible/bin/',
pses_bundle_path = vim.env.HOME..'/repos/PowerShellEditorServices/module'
}
-- vim:et ts=2 sw=2
|
ITEM.Name = 'TV Head'
ITEM.Price = 100
ITEM.Model = 'models/props_c17/tv_monitor01.mdl'
ITEM.Attachment = 'eyes'
function ITEM:OnEquip(ply, modifications)
ply:PS_AddClientsideModel(self.ID)
end
function ITEM:OnHolster(ply)
ply:PS_RemoveClientsideModel(self.ID)
end
function ITEM:ModifyClientsideModel(ply, model, pos, ang)
model:SetModelScale(0.8, 0)
pos = pos + (ang:Right() * -2) + (ang:Forward() * -3) + (ang:Up() * 0.5)
return model, pos, ang
end
|
local narrator = require('narrator.narrator')
local book = narrator.parseFile('stories/main', { save = true })
|
gd = require "gd"
im = gd.createTrueColor(160, 50)
red = im:colorAllocate(255, 0, 0)
green = im:colorAllocate(0, 255, 0)
blue = im:colorAllocate(0, 0, 255)
white = im:colorAllocate(255, 255, 255)
black = im:colorAllocate(0, 0, 0)
im:filledRectangle(0, 0, 160, 50, white)
im:filledRectangle(1, 2, 48, 13, red)
im:filledRectangle(1, 19, 48, 30, green)
im:filledRectangle(1, 36, 48, 47, blue)
im:string(gd.FONT_GIANT, 61, 6, "Powered by", black)
im:string(gd.FONT_GIANT, 60, 5, "Powered by", white)
im:string(gd.FONT_GIANT, 61, 26, "libmodjpeg", black)
im:string(gd.FONT_GIANT, 60, 25, "libmodjpeg", white)
im:png("unmaskeddropon.png")
im:jpeg("dropon.jpg", 90)
im:filledRectangle(0, 0, 160, 50, black)
im:filledRectangle(1, 2, 48, 13, white)
im:filledRectangle(1, 19, 48, 30, white)
im:filledRectangle(1, 36, 48, 47, white)
gray = im:colorAllocate(64, 64, 64)
im:string(gd.FONT_GIANT, 61, 6, "Powered by", gray)
im:string(gd.FONT_GIANT, 60, 5, "Powered by", white)
im:string(gd.FONT_GIANT, 61, 26, "libmodjpeg", gray)
im:string(gd.FONT_GIANT, 60, 25, "libmodjpeg", white)
im:png("mask.png")
im:jpeg("mask.jpg", 90)
-- gm composite -compose CopyOpacity mask.png unmaskeddropon.png dropon.png
|
ys = ys or {}
slot1 = singletonClass("BattleNPCCharacterFactory", ys.Battle.BattleEnemyCharacterFactory)
ys.Battle.BattleNPCCharacterFactory = slot1
slot1.__name = "BattleNPCCharacterFactory"
slot1.Ctor = function (slot0)
slot0.super.Ctor(slot0)
slot0.HP_BAR_NAME = slot0.super.Ctor.Battle.BattleHPBarManager.HP_BAR_FOE
end
slot1.CreateCharacter = function (slot0, slot1)
slot4 = slot0:MakeCharacter()
slot4:SetFactory(slot0)
slot4:SetUnitData(slot1.unit)
if slot1.extraInfo.modleID then
slot4:SetModleID(slot2.modleID)
end
if slot2.HPColor then
slot4:SetHPColor(slot2.HPColor)
end
if slot2.isUnvisible then
slot4:SetUnvisible()
end
slot0:MakeModel(slot4)
return slot4
end
slot1.MakeModel = function (slot0, slot1)
slot2 = slot1:GetUnitData()
function slot3(slot0)
slot0:AddModel(slot0)
slot1 = slot0.AddModel:GetSceneMediator()
slot0:CameraOrthogonal(slot2.Battle.BattleCameraUtil.GetInstance():GetCamera())
slot1:AddEnemyCharacter(slot0)
slot1:MakeUIComponentContainer(slot0)
slot1:MakeFXContainer(slot0)
slot1:MakePopNumPool(slot0)
slot1:MakeBloodBar(slot0)
slot1:MakeWaveFX(slot0)
slot1:MakeSmokeFX(slot0)
slot1:MakeArrowBar(slot0)
for slot6, slot7 in ipairs(slot2) do
slot0:AddFX(slot7)
end
slot0:MakeVisible()
end
slot0.GetCharacterPool(slot0):InstCharacter(slot1:GetModleID(), function (slot0)
slot0(slot0)
end)
end
slot1.MakeCharacter = function (slot0)
return slot0.Battle.BattleNPCCharacter.New()
end
slot1.MakeBloodBar = function (slot0, slot1)
slot3 = slot0:GetHPBarPool():GetHPBar(slot0.HP_BAR_NAME).transform
if slot1:GetHPColor() then
slot3:Find("blood"):GetComponent(typeof(Image)).color = slot4
end
slot1:AddHPBar(slot2)
slot1:UpdateHPBarPostition()
end
return
|
-- Copyright (c) 2021 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
describe("moonpie.tables.map_keys", function()
local tables = require "moonpie.tables"
it("works with keyed sets", function()
local key_set = {
a = 1, b = 2, c = 3
}
local mapped = tables.mapKeys(key_set, function(n, k) return k .. tostring(n) end)
assert.array_includes_all({ "a1", "b2", "c3" }, mapped)
end)
end)
|
while true do
white = color.new(255, 255, 255)
black = color.new(0, 0, 0)
sound.stop(menumusic)
office1:blit(0, 0)
--blackfullscreen:blit(0, 0, whatnight_tr[1])
--screen.print(240, 128, "whatnight_txt", 1, white, black, __ACENTER)
if night == 1 then
nightnum = nightnum_1
end
nightnum:blit(0, 0, whatnight_tr[1])
blackfullscreen:blit(0, 0, whatnight_tr[2])
if whatnight_tr[2] > 0 then
whatnight_tr[2] = whatnight_tr[2] - 2
end
if whatnight_tr[2] < 0 then
whatnight_timer = whatnight_timer + 1
if whatnight_timer == 30 then
whatnight_tr[3] = true
end
end
if whatnight_tr[3] == true then
if whatnight_tr[1] > 0 then
whatnight_tr[1] = whatnight_tr[1] - 2
elseif whatnight_tr[1] < 0 then
j2_assets("nil", "whatnight")
j2_assets("load", "gameprocess")
j2_assets("load", "ai")
dofile("scripts/gameprocessre.lua")
end
end
--[[if timer == 300 then
dofile("scripts/gameprocessre.lua")
end]]
screen.flip()
end
|
-- $Id: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/LandMode/BuildBarracksLand.lua#2 $
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- (C) Petroglyph Games, Inc.
--
--
-- ***** ** * *
-- * ** * * *
-- * * * * *
-- * * * * * * * *
-- * * *** ****** * ** **** *** * * * ***** * ***
-- * ** * * * ** * ** ** * * * * ** ** ** *
-- *** ***** * * * * * * * * ** * * * *
-- * * * * * * * * * * * * * * *
-- * * * * * * * * * * ** * * * *
-- * ** * * ** * ** * * ** * * * *
-- ** **** ** * **** ***** * ** *** * *
-- * * *
-- * * *
-- * * *
-- * * * *
-- **** * *
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
-- C O N F I D E N T I A L S O U R C E C O D E -- D O N O T D I S T R I B U T E
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- $File: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/LandMode/BuildBarracksLand.lua $
--
-- Original Author: James Yarrow
--
-- $Author: James_Yarrow $
--
-- $Change: 46090 $
--
-- $DateTime: 2006/06/13 15:02:25 $
--
-- $Revision: #2 $
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
require("pgevents")
function Definitions()
Category = "Tactical_Multiplayer_Build_Barracks"
IgnoreTarget = true
TaskForce = {
{
"MainForce"
,"UC_E_Ground_Barracks | UC_R_Ground_Barracks | UC_U_Ground_Merc_Outpost = 1"
}
}
AllowFreeStoreUnits = false
end
function MainForce_Thread()
BlockOnCommand(MainForce.Build_All())
MainForce.Set_Plan_Result(true)
ScriptExit()
end
|
-- credit to atom0s for help with decompiling
-- Decompiled using luadec 2.2 rev: for Lua 5.1 from https://github.com/viruscamp/luadec
return {
Const = { Currency = 1001017, DailyFreeTimes = 1, Infinite = {
{ 1, 4 },
{ 2, 0 },
}, OnceCost = 1 },
PoolCfg = {
{
{ 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 },
},
},
RewardCfg = {
{ Id = 1, ItemId = 1012114, Number = 1, PoolId = 1, Rare = true, RewardNumber = 30, SubId = 1, Weight = 1 },
{ Id = 2, ItemId = 1021305, Number = 1, PoolId = 1, Rare = true, RewardNumber = 1, SubId = 1, Weight = 1 },
{ Id = 3, ItemId = 1021304, Number = 1, PoolId = 1, Rare = true, RewardNumber = 1, SubId = 1, Weight = 1 },
{ Id = 4, ItemId = 1022210, Number = 1, PoolId = 1, RewardNumber = 70, SubId = 1, Weight = 2 },
{ Id = 5, ItemId = 1021021, Number = 1, PoolId = 1, RewardNumber = 28, SubId = 1, Weight = 2 },
{ Id = 6, ItemId = 1025001, Number = 1, PoolId = 1, RewardNumber = 10, SubId = 1, Weight = 2 },
{ Id = 7, ItemId = 1021005, Number = 1, PoolId = 1, RewardNumber = 40, SubId = 1, Weight = 2 },
{ Id = 8, ItemId = 1013103, Number = 1, PoolId = 1, RewardNumber = 20, SubId = 1, Weight = 2 },
{ Id = 9, ItemId = 1012114, Number = 1, PoolId = 2, Rare = true, RewardNumber = 40, SubId = 1, Weight = 1 },
{ Id = 10, ItemId = 1021306, Number = 1, PoolId = 2, Rare = true, RewardNumber = 1, SubId = 1, Weight = 1 },
{ Id = 11, ItemId = 1021316, Number = 1, PoolId = 2, Rare = true, RewardNumber = 1, SubId = 1, Weight = 1 },
{ Id = 12, ItemId = 1022210, Number = 1, PoolId = 2, RewardNumber = 70, SubId = 1, Weight = 2 },
{ Id = 13, ItemId = 1021021, Number = 1, PoolId = 2, RewardNumber = 28, SubId = 1, Weight = 2 },
{ Id = 14, ItemId = 1025001, Number = 1, PoolId = 2, RewardNumber = 10, SubId = 1, Weight = 2 },
{ Id = 15, ItemId = 1021005, Number = 1, PoolId = 2, RewardNumber = 30, SubId = 1, Weight = 2 },
{ Id = 16, ItemId = 1013103, Number = 1, PoolId = 2, RewardNumber = 20, SubId = 1, Weight = 2 },
{ Id = 17, ItemId = 6211416, Number = 1, PoolId = 3, Rare = true, RewardNumber = 1, SubId = 1, Weight = 1 },
{ Id = 18, ItemId = 1012114, Number = 1, PoolId = 3, Rare = true, RewardNumber = 80, SubId = 1, Weight = 1 },
{ Id = 19, ItemId = 1021234, Number = 1, PoolId = 3, Rare = true, RewardNumber = 1, SubId = 1, Weight = 1 },
{ Id = 20, ItemId = 1021238, Number = 1, PoolId = 3, Rare = true, RewardNumber = 1, SubId = 1, Weight = 1 },
{ Id = 21, ItemId = 1022210, Number = 1, PoolId = 3, RewardNumber = 60, SubId = 1, Weight = 2 },
{ Id = 22, ItemId = 1021021, Number = 1, PoolId = 3, RewardNumber = 17, SubId = 1, Weight = 2 },
{ Id = 23, ItemId = 1025001, Number = 1, PoolId = 3, RewardNumber = 10, SubId = 1, Weight = 2 },
{ Id = 24, ItemId = 1021005, Number = 1, PoolId = 3, RewardNumber = 20, SubId = 1, Weight = 2 },
{ Id = 25, ItemId = 1013103, Number = 1, PoolId = 3, RewardNumber = 10, SubId = 1, Weight = 2 },
{ Id = 26, ItemId = 1011144, Number = 1, PoolId = 4, Rare = true, RewardNumber = 1, SubId = 1, Weight = 1 },
{ Id = 27, ItemId = 1012114, Number = 1, PoolId = 4, Rare = true, RewardNumber = 90, SubId = 1, Weight = 1 },
{ Id = 28, ItemId = 1022210, Number = 1, PoolId = 4, RewardNumber = 50, SubId = 1, Weight = 2 },
{ Id = 29, ItemId = 1021021, Number = 1, PoolId = 4, RewardNumber = 20, SubId = 1, Weight = 2 },
{ Id = 30, ItemId = 1025001, Number = 1, PoolId = 4, RewardNumber = 10, SubId = 1, Weight = 2 },
{ Id = 31, ItemId = 1021005, Number = 1, PoolId = 4, RewardNumber = 19, SubId = 1, Weight = 2 },
{ Id = 32, ItemId = 1013103, Number = 1, PoolId = 4, RewardNumber = 10, SubId = 1, Weight = 2 },
{ Id = 33, ItemId = 1001043, Number = 2, PoolId = 1, Rare = true, RewardNumber = 1, SubId = 2, Weight = 1 },
{ Id = 34, ItemId = 1001058, Number = 2, PoolId = 1, Rare = true, RewardNumber = 1, SubId = 2, Weight = 1 },
{ Id = 35, ItemId = 1013114, Number = 3, PoolId = 1, Rare = true, RewardNumber = 1, SubId = 2, Weight = 1 },
{ Id = 36, ItemId = 1021023, Number = 3, PoolId = 1, Rare = true, RewardNumber = 1, SubId = 2, Weight = 1 },
{ Id = 37, ItemId = 1001043, Number = 1, PoolId = 1, RewardNumber = 1, SubId = 2, Weight = 1 },
{ Id = 38, ItemId = 1001058, Number = 1, PoolId = 1, RewardNumber = 1, SubId = 2, Weight = 1 },
{ Id = 39, ItemId = 1001024, Number = 100, PoolId = 1, RewardNumber = 1, SubId = 2, Weight = 1 },
},
__maketime = 1611822194,
__md5 = "e543e4d44505ca5385eccb34e3413cf2",
__version = 11,
}
|
function gmod.BroadcastLua(lua)
for _, pl in pairs(player.GetAll()) do
pl:SendLua(lua)
end
end
function net.Quick( msg, rf )
net.Start( msg )
if( not rf ) then
net.Broadcast()
else
net.Send( rf )
end
end
function GM:PosInWater(Pos)
return bit.band(util.PointContents(Pos), CONTENTS_WATER) == CONTENTS_WATER
end
function GM:MaxEntLimitReached()
return #ents.GetAll() >= SA.MAX_ENTITIES
end
|
local ReplicatedStorage = game:GetService('ReplicatedStorage')
local Modules = ReplicatedStorage:WaitForChild('Modules')
local src = Modules:WaitForChild('src')
local logger = require(src.utils.Logger)
local InventoryObjects = require(src.objects.InventoryObjects)
local PET_TYPES = InventoryObjects.PET_TYPES
local Pet = require(src:WaitForChild('Pet', 30))
local Print = require(src.utils.Print)
local M = require(Modules.M)
local SlotManager = {}
local PetManager = {}
local characterPets = {}
local characterSlots = {}
local defaultSpeed = 16
function SlotManager:initSlots(character, playerSlotsCount)
if not characterSlots[character] then
characterSlots[character] = {}
for i = 0, playerSlotsCount do
characterSlots[character][i] = false
end
end
end
function SlotManager:findSlot(character)
local slot = M.find(characterSlots[character], false) or 1
characterSlots[character][slot] = true
return slot
end
function SlotManager:clearSlot(character, slot)
characterSlots[character][slot] = false
return slot
end
function PetManager:checkAbilities(character)
local humanoid = character:FindFirstChild('Humanoid')
function getMaxSpeed(petDeployed)
if petDeployed.petObject.ability == PET_TYPES.SPEED then
return petDeployed.petObject.speed
else
return defaultSpeed
end
end
local maxSpeed = M.max(M.map(characterPets[character], getMaxSpeed))
logger:d('Adding speed ability to player', character.Name, maxSpeed)
humanoid.WalkSpeed = maxSpeed or defaultSpeed
end
function PetManager:addToCharacter(petObjects, character, playerSlotsCount)
if not character then
logger:d('No Character found')
return
end
if not characterPets[character] then
characterPets[character] = {}
SlotManager:initSlots(character, playerSlotsCount)
end
function getPetObject(pet)
return pet.petObject
end
local characterPetObjects = M.map(characterPets[character], getPetObject)
local deleteObjects = M.difference(characterPetObjects, petObjects)
local addObjects = M.difference(petObjects, characterPetObjects)
function deletePet(petObject)
if characterPets[character][petObject] then
logger:d('deleting pet' .. petObject.id)
SlotManager:clearSlot(character, characterPets[character][petObject].slot)
characterPets[character][petObject]:delete()
characterPets[character][petObject] = nil
end
end
M.each(deleteObjects, deletePet)
function addPet(petObject)
local slotNr = SlotManager:findSlot(character)
characterPets[character][petObject] = Pet:create(petObject, character, slotNr)
characterPets[character][petObject]:init()
end
M.each(addObjects, addPet)
PetManager:checkAbilities(character)
end
return PetManager
|
IncludeDir = {}
IncludeDir["GLFW"] = "../Engine/vendor/glfw/include/"
IncludeDir["Glad"] = "../Engine/vendor/glad/include/"
IncludeDir["ImGui"] = "../Engine/vendor/imgui/"
IncludeDir["spdlog"] = "../Engine/vendor/spdlog/include"
IncludeDir["cereal"] = "../Engine/vendor/cereal/include"
IncludeDir["stb"] = "../Engine/vendor/stb/"
IncludeDir["Razix"] = "../Engine/src"
IncludeDir["vendor"] = "../Engine/vendor/"
IncludeDir["Vendor"] = "../Engine/vendor/"
project "Sandbox"
kind "ConsoleApp"
language "C++"
files
{
"src/**.h",
"src/**.cpp"
}
sysincludedirs
{
"%{IncludeDir.GLFW}",
"%{IncludeDir.Glad}",
"%{IncludeDir.stb}",
"%{IncludeDir.ImGui}",
"%{IncludeDir.spdlog}",
"%{IncludeDir.cereal}",
"%{IncludeDir.Razix}",
"%{IncludeDir.external}",
"%{IncludeDir.External}"
}
includedirs
{
"../Engine/src/Razix",
"%{IncludeDir.GLFW}",
"%{IncludeDir.Glad}",
"%{IncludeDir.stb}",
"%{IncludeDir.ImGui}",
"%{IncludeDir.spdlog}",
"%{IncludeDir.cereal}",
"%{IncludeDir.Razix}"
}
links
{
"Razix",
"imgui",
"spdlog"
}
defines
{
"SPDLOG_COMPILED_LIB"
}
filter { "files:vendor/**"}
warnings "Off"
filter "system:windows"
cppdialect "C++17"
staticruntime "On"
systemversion "latest"
-- entrypoint "WinMainCRTStartup"
defines
{
"RAZIX_PLATFORM_WINDOWS",
"RAZIX_RENDER_API_OPENGL",
"WIN32_LEAN_AND_MEAN",
"_CRT_SECURE_NO_WARNINGS",
"_DISABLE_EXTENDED_ALIGNED_STORAGE",
"_SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING",
"RAZIX_ROOT_DIR=" .. root_dir,
}
libdirs
{
}
links
{
"glfw",
"OpenGL32",
}
disablewarnings { 4307 }
filter "configurations:Debug"
defines { "RAZIX_DEBUG", "_DEBUG" }
symbols "On"
runtime "Debug"
optimize "Off"
filter "configurations:Release"
defines { "RAZIX_RELEASE"}
optimize "Speed"
symbols "On"
runtime "Release"
filter "configurations:Distribution"
defines "RAZIX_DISTRIBUTION"
symbols "Off"
optimize "Full"
|
do
local Nil = { __tag = "Nil" };
(nil)({
{ _1 = 1, _2 = { { _1 = 2, _2 = { { _1 = 3, _2 = Nil }, __tag = "Cons" } }, __tag = "Cons" } },
__tag = "Cons"
});
(nil)(1);
(nil)({ { _1 = 2, _2 = Nil }, __tag = "Cons" })
local function k(xss)
if xss.__tag ~= "Cons" then return Nil end
local tmp = xss[1]
local x, xs = tmp._1, tmp._2
local function o(xss0)
if xss0.__tag ~= "Cons" then return k(xs) end
local tmp0 = xss0[1]
return { { _2 = o(tmp0._2), _1 = { _1 = x, _2 = tmp0._1 } }, __tag = "Cons" }
end
return o({
{ _1 = 4, _2 = { { _1 = 5, _2 = { { _1 = 6, _2 = Nil }, __tag = "Cons" } }, __tag = "Cons" } },
__tag = "Cons"
})
end
(nil)(k({
{ _1 = 1, _2 = { { _1 = 2, _2 = { { _1 = 3, _2 = Nil }, __tag = "Cons" } }, __tag = "Cons" } },
__tag = "Cons"
}))
local function s(xss)
if xss.__tag ~= "Cons" then return Nil end
local tmp = xss[1]
local x, xs = tmp._1, tmp._2
local b = x + 1
local function w(xss0)
if xss0.__tag == "Cons" then
return { { _2 = w(xss0[1]._2), _1 = { _1 = x, _2 = b } }, __tag = "Cons" }
end
return s(xs)
end
return w({ { _1 = b, _2 = { { _1 = x, _2 = Nil }, __tag = "Cons" } }, __tag = "Cons" })
end
(nil)(s({
{ _1 = 1, _2 = { { _1 = 2, _2 = { { _1 = 3, _2 = Nil }, __tag = "Cons" } }, __tag = "Cons" } },
__tag = "Cons"
}))
end
|
local composer = require( "composer" )
local colors = require('classes.colors-rgb')
local scene = composer.newScene()
local widget = require("widget")
widget.setTheme ( "widget_theme_ios" )
local screenLeft = display.screenOriginX
local screenWidth = display.viewableContentWidth - screenLeft * 2
local screenRight = screenLeft + screenWidth
local screenTop = display.screenOriginY
local screenHeight = display.viewableContentHeight - screenTop * 2
local screenBottom = screenTop + screenHeight
local function switchScene(event)
local sceneID = event.target.id
local options = {effect = "crossFade", time = 300}
composer.gotoScene( sceneID, options )
-- Show Options & About buttons in the Menu --
if sceneID == "scenes.menu" then
if game_version ~= nil then game_version.isVisible = false end
if (optionsBtn ~= nil) and (aboutBtn ~= nil) then
optionsBtn.isVisible = true
aboutBtn.isVisible = true
end
background.isVisible = false
helptext.isVisible = false
helpShade.alpha = 0
end
end
local function setUpDisplay(grp)
local xPos = screenLeft + 10
local yPos = screenBottom - 10
local backBtn = widget.newButton ({label = "Back", id = "scenes.menu", onRelease = switchScene})
backBtn.anchorX = 0
backBtn.anchorY = 1
backBtn.x = xPos
backBtn.y = yPos
backBtn:scale(0.5, 0.5)
grp:insert(backBtn)
local helpText = [[
* GAME INFORMATION COMING SOON!
~ Food Icons designed by Freepik <https://www.freepik.com/>
]]
local paragraphs = {}
local paragraph
local tmpString = helpText
-- Help Scene background
background = display.newImageRect( "images/backgrounds/background.png", display.contentWidth + 550, display.contentHeight + 1000)
background.alpha = 0.50
-- Text Options
local options = {
text = "",
width = display.contentWidth,
fontSize = 10,
align = "left",
}
local yOffset = 10
helpShade = display.newRect( 0, 0, display.contentWidth, display.contentHeight)
helpShade.x = display.viewableContentWidth / 2
helpShade.y = display.viewableContentHeight / 2
helpShade:setFillColor ( colorsRGB.RGB("blue") )
helpShade.alpha = 0.50
repeat
local b, e = string.find(tmpString, "\r\n")
if b then
paragraph = string.sub(tmpString, 1, b - 1)
tmpString = string.sub(tmpString, e + 1)
else
paragraph = tmpString
tmpString = ""
end
options.text = paragraph
paragraphs[#paragraphs + 1] = display.newText( options )
paragraphs[#paragraphs].anchorX = 0
paragraphs[#paragraphs].anchorY = 0
paragraphs[#paragraphs].x = 10
paragraphs[#paragraphs].y = yOffset
paragraphs[#paragraphs]:setFillColor( colorsRGB.RGB("white") )
paragraphs[#paragraphs].alpha = 1
helptext = paragraphs[#paragraphs]
yOffset = yOffset + paragraphs[#paragraphs].height
until tmpString == nil or string.len( tmpString ) == 0
-- Create Copyright Notice
local copyright = display.newText( grp, "Copyright © 2018, Particle Plex, Jericho Crosby <jericho.crosby227@gmail.com>", 0, 0, native.systemFontBold, 8 )
local spacing = 100
copyright.x = xPos + spacing
copyright.y = yPos
copyright.anchorX = 0
copyright.anchorY = 1
copyright:setFillColor( colorsRGB.RGB("white") )
copyright.alpha = 1
end
-- "scene:create()"
function scene:create( event )
local sceneGroup = self.view
-- Initialize the scene here.
-- Example: add display objects to "sceneGroup", add touch listeners, etc.
setUpDisplay(sceneGroup)
end
-- "scene:show()"
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
-- Called when the scene is still off screen (but is about to come on screen).
elseif ( phase == "did" ) then
-- Called when the scene is now on screen.
-- Insert code here to make the scene come alive.
-- Example: start timers, begin animation, play audio, etc.
end
end
-- "scene:hide()"
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
-- Called when the scene is on screen (but is about to go off screen).
-- Insert code here to "pause" the scene.
-- Example: stop timers, stop animation, stop audio, etc.
elseif ( phase == "did" ) then
-- Called immediately after scene goes off screen.
end
end
-- "scene:destroy()"
function scene:destroy( event )
local sceneGroup = self.view
-- Called prior to the removal of scene's view ("sceneGroup").
-- Insert code here to clean up the scene.
-- Example: remove display objects, save state, etc.
end
-- -------------------------------------------------------------------------------
-- Listener setup
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
-- -------------------------------------------------------------------------------
return scene
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf/protobuf"
local ATTRIBUTEINFO_PB = require("AttributeInfo_pb")
module('FashionData_pb')
FASHIONDATA = protobuf.Descriptor();
local FASHIONDATA_ITEMID_FIELD = protobuf.FieldDescriptor();
local FASHIONDATA_LEVEL_FIELD = protobuf.FieldDescriptor();
local FASHIONDATA_UID_FIELD = protobuf.FieldDescriptor();
local FASHIONDATA_TIMELEFT_FIELD = protobuf.FieldDescriptor();
local FASHIONDATA_POS_FIELD = protobuf.FieldDescriptor();
local FASHIONDATA_ATTRS_FIELD = protobuf.FieldDescriptor();
local FASHIONDATA_TIMEEND_FIELD = protobuf.FieldDescriptor();
FASHIONDATA_ITEMID_FIELD.name = "itemID"
FASHIONDATA_ITEMID_FIELD.full_name = ".KKSG.FashionData.itemID"
FASHIONDATA_ITEMID_FIELD.number = 1
FASHIONDATA_ITEMID_FIELD.index = 0
FASHIONDATA_ITEMID_FIELD.label = 1
FASHIONDATA_ITEMID_FIELD.has_default_value = false
FASHIONDATA_ITEMID_FIELD.default_value = 0
FASHIONDATA_ITEMID_FIELD.type = 13
FASHIONDATA_ITEMID_FIELD.cpp_type = 3
FASHIONDATA_LEVEL_FIELD.name = "level"
FASHIONDATA_LEVEL_FIELD.full_name = ".KKSG.FashionData.level"
FASHIONDATA_LEVEL_FIELD.number = 2
FASHIONDATA_LEVEL_FIELD.index = 1
FASHIONDATA_LEVEL_FIELD.label = 1
FASHIONDATA_LEVEL_FIELD.has_default_value = false
FASHIONDATA_LEVEL_FIELD.default_value = 0
FASHIONDATA_LEVEL_FIELD.type = 13
FASHIONDATA_LEVEL_FIELD.cpp_type = 3
FASHIONDATA_UID_FIELD.name = "uid"
FASHIONDATA_UID_FIELD.full_name = ".KKSG.FashionData.uid"
FASHIONDATA_UID_FIELD.number = 3
FASHIONDATA_UID_FIELD.index = 2
FASHIONDATA_UID_FIELD.label = 1
FASHIONDATA_UID_FIELD.has_default_value = false
FASHIONDATA_UID_FIELD.default_value = 0
FASHIONDATA_UID_FIELD.type = 4
FASHIONDATA_UID_FIELD.cpp_type = 4
FASHIONDATA_TIMELEFT_FIELD.name = "timeleft"
FASHIONDATA_TIMELEFT_FIELD.full_name = ".KKSG.FashionData.timeleft"
FASHIONDATA_TIMELEFT_FIELD.number = 4
FASHIONDATA_TIMELEFT_FIELD.index = 3
FASHIONDATA_TIMELEFT_FIELD.label = 1
FASHIONDATA_TIMELEFT_FIELD.has_default_value = false
FASHIONDATA_TIMELEFT_FIELD.default_value = 0
FASHIONDATA_TIMELEFT_FIELD.type = 13
FASHIONDATA_TIMELEFT_FIELD.cpp_type = 3
FASHIONDATA_POS_FIELD.name = "pos"
FASHIONDATA_POS_FIELD.full_name = ".KKSG.FashionData.pos"
FASHIONDATA_POS_FIELD.number = 5
FASHIONDATA_POS_FIELD.index = 4
FASHIONDATA_POS_FIELD.label = 1
FASHIONDATA_POS_FIELD.has_default_value = false
FASHIONDATA_POS_FIELD.default_value = 0
FASHIONDATA_POS_FIELD.type = 13
FASHIONDATA_POS_FIELD.cpp_type = 3
FASHIONDATA_ATTRS_FIELD.name = "attrs"
FASHIONDATA_ATTRS_FIELD.full_name = ".KKSG.FashionData.attrs"
FASHIONDATA_ATTRS_FIELD.number = 6
FASHIONDATA_ATTRS_FIELD.index = 5
FASHIONDATA_ATTRS_FIELD.label = 3
FASHIONDATA_ATTRS_FIELD.has_default_value = false
FASHIONDATA_ATTRS_FIELD.default_value = {}
FASHIONDATA_ATTRS_FIELD.message_type = ATTRIBUTEINFO_PB.ATTRIBUTEINFO
FASHIONDATA_ATTRS_FIELD.type = 11
FASHIONDATA_ATTRS_FIELD.cpp_type = 10
FASHIONDATA_TIMEEND_FIELD.name = "timeend"
FASHIONDATA_TIMEEND_FIELD.full_name = ".KKSG.FashionData.timeend"
FASHIONDATA_TIMEEND_FIELD.number = 7
FASHIONDATA_TIMEEND_FIELD.index = 6
FASHIONDATA_TIMEEND_FIELD.label = 1
FASHIONDATA_TIMEEND_FIELD.has_default_value = false
FASHIONDATA_TIMEEND_FIELD.default_value = 0
FASHIONDATA_TIMEEND_FIELD.type = 13
FASHIONDATA_TIMEEND_FIELD.cpp_type = 3
FASHIONDATA.name = "FashionData"
FASHIONDATA.full_name = ".KKSG.FashionData"
FASHIONDATA.nested_types = {}
FASHIONDATA.enum_types = {}
FASHIONDATA.fields = {FASHIONDATA_ITEMID_FIELD, FASHIONDATA_LEVEL_FIELD, FASHIONDATA_UID_FIELD, FASHIONDATA_TIMELEFT_FIELD, FASHIONDATA_POS_FIELD, FASHIONDATA_ATTRS_FIELD, FASHIONDATA_TIMEEND_FIELD}
FASHIONDATA.is_extendable = false
FASHIONDATA.extensions = {}
FashionData = protobuf.Message(FASHIONDATA)
|
require "x_functions";
if not x_requires then
-- Sanity check. If they require a newer version, let them know.
timer = 1;
while (true) do
timer = timer + 1;
for i = 0, 32 do
gui.drawbox( 6, 28 + i, 250, 92 - i, "#000000");
end;
gui.text( 10, 32, string.format("This Lua script requires the x_functions library."));
gui.text( 53, 42, string.format("It appears you do not have it."));
gui.text( 39, 58, "Please get the x_functions library at");
gui.text( 14, 69, "http://xkeeper.shacknet.nu/");
gui.text(114, 78, "emu/nes/lua/x_functions.lua");
warningboxcolor = string.format("%02X", math.floor(math.abs(30 - math.fmod(timer, 60)) / 30 * 0xFF));
gui.drawbox(7, 29, 249, 91, "#ff" .. warningboxcolor .. warningboxcolor);
FCEU.frameadvance();
end;
else
x_requires(4);
end;
-- Things to be done every frame, so that the main emulation loop can be passed off to other parts
function frame()
-- Infinite health.
memory.writebyte(0x04a2, 0x0F);
forcepos();
FCEU.frameadvance();
if showhud then
hud();
end;
movetimeout = movetimeout - 1;
playerx = memory.readword(0x0485);
playery = memory.readword(0x0488);
camerax = memory.readword(0x0457);
cameray = memory.readword(0x045a);
stage = memory.readbyte(0x062b);
inkeyp = table.clone(inkey);
inkey = input.get();
if inkey['delete'] and not inkeyp['delete'] then
playercontrol = not playercontrol;
end;
if inkey['insert'] and not inkeyp['insert'] then
screenshotmode = not screenshotmode;
lolx = math.random(0, 0x0F00);
loly = math.random(0, 0x0F00);
end;
if inkey['left'] then
playerfx = math.max(playerfx - 16, 0);
end;
if inkey['right'] then
playerfx = math.min(playerfx + 16, 0x0FFF);
end;
if inkey['up'] then
playerfy = math.max(playerfy - 16, 0);
end;
if inkey['down'] then
playerfy = math.min(playerfy + 16, 0x0FFF);
end;
end;
function hud()
text( 188, 218, "Force:");
if playercontrol == true then
text( 223, 218, "ON ");
else
text( 223, 218, "OFF");
end;
text( 188, 226, string.format("%04X %04X", playerfx, playerfy));
text( 8, 218, string.format("%04X %04X", playerx, playery));
text( 8, 226, string.format("%04X %04X", camerax, cameray));
if screenshotmode == true then
text( 93, 218, "Automove ON ");
else
text( 93, 218, "Automove OFF");
end;
text( 98, 226, string.format("%04X %04X", desiredx, desiredy));
-- text(8, 100, stage);
end;
-- Moves the player by the max amount possible.
-- Returns false if there is still more movement to be done.
-- returns true if movement is done (camera may not be centered yet)
-- dx, dy are camera.
function moveplayer(dx, dy)
desiredx = dx;
desiredy = dy;
dx = dx + 0x80;
dy = dy + 0x70;
if dx - playerfx ~= 0 then
if lastdir ~= 0 and movetimeout > 0 then
text( 80, 8, string.format("H-Wait: %2d", movetimeout));
return false;
end;
lastdir = 0;
movetimeout = 50;
if dx < playerfx then
text( 80, 8, string.format("Move left:\n%4Xpx", math.abs(dx - playerfx)));
playerfx = playerfx - math.min(8, math.abs(dx - playerfx));
else
text( 80, 8, string.format("Move right:\n%4Xpx", math.abs(dx - playerfx)));
playerfx = playerfx + math.min(8, math.abs(dx - playerfx));
end;
elseif dy - playerfy ~= 0 then
if lastdir ~= 1 and movetimeout > 0 then
text( 80, 8, string.format("V-Wait: %2d", movetimeout));
return false;
end;
lastdir = 1;
movetimeout = 50;
if dy < playerfy then
text( 80, 8, string.format("Move up:\n%4Xpx", math.abs(dy - playerfy)));
playerfy = playerfy - math.min(8, math.abs(dy - playerfy));
else
text( 80, 8, string.format("Move down:\n%4Xpx", math.abs(dy - playerfy)));
playerfy = playerfy + math.min(8, math.abs(dy - playerfy));
end;
else
return true;
end;
return false;
end;
function forcepos()
if playercontrol == true then
memory.writeword(0x0485, playerfx);
memory.writeword(0x0488, playerfy);
end;
end;
memory.register(0x0485, forcepos);
function cartded()
memory.writebyte(0x07FE, 0);
end;
memory.register(0x07FE, cartded);
desiredx = 0x0000;
desiredy = 0x0000;
playercontrol = true;
screenshotmode = true;
inkey = {};
inkeyp = {};
playerx = memory.readword(0x0485);
playery = memory.readword(0x0488);
camerax = memory.readword(0x0457);
cameray = memory.readword(0x045a);
stage = memory.readbyte(0x062b);
playerfx = math.floor(playerx / 8) * 8;
playerfy = math.floor(playery / 8) * 8;
movetimeout = 30;
lolx = 0;
loly = 0;
showhud = true;
function makemap()
for sy = 0x0000, 0x1000, 0xC0 do
for sx = 0x0000, 0x1000, 0xE0 do
while not moveplayer(sx, sy) do
frame();
end;
for delay = 1, 90 do
frame();
end;
FCEU.setrenderplanes(false, true);
frame();
frame();
screenshot = gui.gdscreenshot()
f = io.open(string.format("stage%d/bfamap-%04x-%04x.gd", stage, sx, sy), "wb");
f:write(screenshot);
f:close();
frame();
frame();
FCEU.setrenderplanes(true, true);
if sx > 0x0900 then
sx = 0xFFFF;
end;
end;
if sy > 0x0900 then
sy = 0xFFFF;
end;
end;
end;
makemap();
while true do
text(8, 8, "DONE");
-- if screenshotmode then
-- done =;
-- if done then
-- text(8, 8, "OK");
-- end;
-- end;
frame();
end;
|
function OrgImports(wait_ms)
local params = vim.lsp.util.make_range_params()
params.context = {only = {"source.organizeImports"}}
local result = vim.lsp.buf_request_sync(0, "textDocument/codeAction", params, wait_ms)
for _, res in pairs(result or {}) do
for _, r in pairs(res.result or {}) do
if r.edit then
vim.lsp.util.apply_workspace_edit(r.edit)
else
vim.lsp.buf.execute_command(r.command)
end
end
end
end
|
EditorOptionsMenu = EditorOptionsMenu or class()
local Options = EditorOptionsMenu
function Options:init()
local O = BLE.Options
local EMenu = BLE.Menu
local icons = BLE.Utils.EditorIcons
local page = EMenu:make_page("Options", nil, {scrollbar = false})
ItemExt:add_funcs(self, page)
local w = page:ItemsWidth(2, 0)
local h = page:ItemsHeight(2, 6)
local main = self:divgroup("Main", {w = w / 2, auto_height = false, h = h * 1/2})
main:GetToolbar():tb_imgbtn("ResetMainOptions", ClassClbk(self, "show_reset_dialog", main), nil, icons.reset_settings, {img_scale = 0.7, help = "Reset main settings"})
main:button("ResetAllOptions", ClassClbk(self, "show_reset_dialog", page))
main:button("ReloadEditor", ClassClbk(self, "reload"), {help = "A reload button if you wish to see your changes in effect faster. Pleae don't use this when actually working on a project."})
main:button(FileIO:Exists("mods/saves/BLEDisablePhysicsFix") and "EnablePhysicsFix" or "DisablePhysicsFix", ClassClbk(self, "show_disable_physics_fix_dialog"))
main:separator()
main:numberbox("AutoSaveMinutes", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/AutoSaveMinutes"), {help = "Set the time for auto saving"})
main:tickbox("AutoSave", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/AutoSave"), {help = "Saves your map automatically, unrecommended for large maps."})
main:tickbox("SaveBeforePlayTesting", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/SaveBeforePlayTesting"), {help = "Saves your map as soon as you playtest your map"})
main:tickbox("SaveMapFilesInBinary", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/SaveMapFilesInBinary"), {
help = "Saving your map files in binary cuts down in map file size which is highly recommended for release!"
})
main:tickbox("BackupMaps", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/BackupMaps"))
main:tickbox("SaveWarningAfterGameStarted", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/SaveWarningAfterGameStarted"), {
help = "Show a warning message when trying to save after play testing started the heist, where you can allow or disable saving for that session"
})
main:separator()
main:tickbox("KeepMouseActiveWhileFlying", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/KeepMouseActiveWhileFlying"))
main:tickbox("QuickAccessToolbar", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/QuickAccessToolbar"))
main:tickbox("ShowHints", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/ShowHints"), {help = "Shows hints in the main tab of the world menu"})
main:tickbox("RotationInfo", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/RotationInfo"), {help = "Shows how much you are rotating the current selection by"})
main:tickbox("RemoveOldLinks", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/RemoveOldLinks"), {
text = "Remove Old Links Of Copied Elements",
help = "Should the editor remove old links(ex: elements inside the copied element's on_executed list that are not part of the copy) when copy pasting elements"
})
main:separator()
main:numberbox("UndoHistorySize", ClassClbk(self, "set_clbk"), O:GetValue("UndoHistorySize"), {min = 1, max = 100000})
main:numberbox("InstanceIndexSize", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/InstanceIndexSize"), {max = 100000, floats = 0, min = 1, help = "Sets the default index size for instances."})
main:numberbox("Scrollspeed", ClassClbk(self, "set_clbk"), O:GetValue("Scrollspeed"), {max = 100, floats = 1, min = 1})
local visual = self:divgroup("Visual", {w = w / 2, auto_height = false, h = h * 1/2})
visual:GetToolbar():tb_imgbtn("ResetVisualOptions", ClassClbk(self, "show_reset_dialog", visual), nil, icons.reset_settings, {img_scale = 0.7, help = "Reset visual settings"})
visual:tickbox("GUIOnRight", ClassClbk(self, "set_clbk"), O:GetValue("GUIOnRight"), {text = "Place Editor GUI on the right side"})
visual:combobox("ToolbarPosition", ClassClbk(self, "set_clbk"), {"Top Corner", "Top Middle", "Bottom Middle"}, O:GetValue("ToolbarPosition"))
visual:slider("MapEditorPanelWidth", ClassClbk(self, "set_clbk"), O:GetValue("MapEditorPanelWidth"), {min = 300, max = 1600})
visual:slider("MapEditorFontSize", ClassClbk(self, "set_clbk"), O:GetValue("MapEditorFontSize"), {min = 8, max = 42})
visual:slider("ParticleEditorPanelWidth", ClassClbk(self, "set_clbk"), O:GetValue("ParticleEditorPanelWidth"), {min = 300, max = 1600})
visual:slider("QuickAccessToolbarSize", ClassClbk(self, "set_clbk"), O:GetValue("QuickAccessToolbarSize"), {min = 18, max = 38})
visual:slider("BoxesXOffset", ClassClbk(self, "set_clbk"), O:GetValue("BoxesXOffset"), {min = 0, max = 16})
visual:slider("BoxesYOffset", ClassClbk(self, "set_clbk"), O:GetValue("BoxesYOffset"), {min = 0, max = 16})
visual:slider("ItemsXOffset", ClassClbk(self, "set_clbk"), O:GetValue("ItemsXOffset"), {min = 0, max = 16})
visual:slider("ItemsYOffset", ClassClbk(self, "set_clbk"), O:GetValue("ItemsYOffset"), {min = 0, max = 16})
visual:colorbox("AccentColor", ClassClbk(self, "set_clbk"), O:GetValue("AccentColor"))
visual:colorbox("BackgroundColor", ClassClbk(self, "set_clbk"), O:GetValue("BackgroundColor"))
visual:colorbox("ItemsHighlight", ClassClbk(self, "set_clbk"), O:GetValue("ItemsHighlight"))
visual:colorbox("ContextMenusBackgroundColor", ClassClbk(self, "set_clbk"), O:GetValue("ContextMenusBackgroundColor"))
visual:colorbox("BoxesBackgroundColor", ClassClbk(self, "set_clbk"), O:GetValue("BoxesBackgroundColor"))
visual:colorbox("ToolbarBackgroundColor", ClassClbk(self, "set_clbk"), O:GetValue("ToolbarBackgroundColor"))
visual:colorbox("ToolbarButtonsColor", ClassClbk(self, "set_clbk"), O:GetValue("ToolbarButtonsColor"))
visual:separator()
visual:colorbox("ElementsColor", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/ElementsColor"))
visual:tickbox("UniqueElementIcons", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/UniqueElementIcons"))
visual:tickbox("RandomizedElementsColor", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/RandomizedElementsColor"))
visual:slider("ElementsSize", ClassClbk(self, "set_map_clbk"), O:GetValue("Map/ElementsSize"), {max = 64, min = 16, floats = 0})
local input = self:divgroup("Input", {w = w / 2, h = page:ItemsHeight(1, 6), auto_height = false, position = function(item)
if alive(main) then
local panel = main:Panel()
item:Panel():set_position(panel:right() + 12, panel:y())
end
end})
local function keybind(setting, supports_mouse, text, help)
return input:keybind("Input/"..setting, ClassClbk(self, "set_clbk"), O:GetValue("Input/"..setting), {text = text or string.pretty2(setting), help = help, supports_mouse = supports_mouse, supports_additional = true})
end
input:GetToolbar():tb_imgbtn("ResetInputOptions", ClassClbk(self, "show_reset_dialog", input), nil, icons.reset_settings, {img_scale = 0.7, help = "Reset input settings"})
keybind("TeleportToSelection")
keybind("CopyUnit")
keybind("PasteUnit")
keybind("SaveMap")
keybind("ToggleMoveWidget")
keybind("ToggleRotationWidget")
keybind("ToggleTransformOrientation")
keybind("DeleteSelection")
keybind("LinkManaged", nil, "Link To Element Managed List")
keybind("OpenManageList", nil, "Open Element Managed List")
keybind("OpenOnExecutedList", nil, "Open Element On Executed List")
keybind("ToggleMapEditor", nil, "Toggle Playtesting")
keybind("IncreaseCameraSpeed")
keybind("DecreaseCameraSpeed")
keybind("IncreaseGridSize")
keybind("DecreaseGridSize")
keybind("ToggleLight")
keybind("HideUnits", nil, "Hide Selected Units", "+alt to unhide all, +shift to hide not selected")
keybind("ToggleGUI")
keybind("ToggleRuler")
keybind("SpawnUnit")
keybind("SpawnElement")
keybind("SelectUnit")
keybind("SelectElement")
keybind("SpawnInstance")
keybind("SpawnPrefab")
keybind("SelectInstance")
keybind("SelectGroup")
keybind("RotateSpawnDummyYaw")
keybind("RotateSpawnDummyPitch")
keybind("RotateSpawnDummyRoll")
keybind("SettleUnits")
end
function Options:show_disable_physics_fix_dialog()
local file = "mods/saves/BLEDisablePhysicsFix"
local disabled = FileIO:Exists(file)
BLE.Utils:YesNoQuestion(string.format([[
Since the editor requires an edit to the physics settings of the game, and such edit can lead to crashing other players (or cause unwanted bugs), the editor also disables online play.
Do note however, the editor will not work properly without said fixes. So once you're done playing and wish to continue using the editor, please turn on this option.
Clicking 'Yes' will %s the physics settings fix and close the game. After opening the game again, online play will be %s.
]], disabled and "enable" or "disable", disabled and "disabled" or "enabled")
, function()
if disabled then
FileIO:Delete(file)
else
FileIO:WriteTo(file, "", "w")
end
setup:quit()
end)
end
function Options:show_reset_dialog(menu)
BLE.Utils:YesNoQuestion("Do you want to reset the selected options?", ClassClbk(self, "reset_options", menu))
end
function Options:Load(data)
end
function Options:Destroy()
return {}
end
function Options:set_item_value(name, value)
self:GetItem(name):SetValue(value, true)
end
function Options:set_theme(item)
local theme = item.name
if theme == "Dark" then
self:set_item_value("AccentColor", Color('4272d9'))
self:set_item_value("BackgroundColor", Color(0.6, 0.2, 0.2, 0.2))
else
self:set_item_value("AccentColor", Color('4272d9'))
self:set_item_value("BackgroundColor", Color(0.6, 0.62, 0.62, 0.62))
end
BLE.Utils:Notify("Theme has been set, please restart")
end
function Options:reset_options(menu)
for _, item in pairs(menu:Items()) do
if item.menu_type then
self:reset_options(item)
else
local opt = BLE.Options:GetOption(item.name)
if opt then
local value = BLE.Options:GetOptionDefaultValue(opt)
if value then
self:set(item.name, value)
item:SetValue(value)
end
end
end
end
end
function Options:set_clbk(item)
self:set(item.name, NotNil(item:Value(), ""))
end
function Options:set_map_clbk(item)
local name = item.name
local value = item:Value()
self:set("Map/"..item.name, NotNil(value, ""))
if name == "QuickAccessToolbar" then
managers.editor:set_use_quick_access(value)
elseif name == "AutoSave" or name == "AutoSaveMinutes" then
managers.editor.parts.opt:toggle_autosaving()
end
end
function Options:set(option, value)
BLE.Options:SetValue(option, value)
BLE.Options:Save()
end
function Options:reload()
BeardLib:AddDelayedCall("SettingsReloadBLE", 0.1, function()
BLE:MapEditorCodeReload()
end)
end
|
-- =========
-- LOAD FILE
-- =========
--- Load file contents
---@param fileName string FilePath
---@param context string PathContext. 'data' for modData. 'user' or nil for osirisData
---@return table file Parsed file contents
---@return string fileContents Stringified file contents
function LoadFile(fileName, context)
local file
local _, fileContents = pcall(Ext.LoadFile, fileName, context)
if string.match(fileName, '.json') then
if ValidString(fileContents) then file = Ext.JsonParse(fileContents); Destringify(file)
else file = {} end
else file = fileContents end
return file, fileContents
end
-- =========
-- SAVE FILE
-- =========
--- Save file
---@param fileName string FilePath
---@param contents any File Contents to save
function SaveFile(fileName, contents)
if ValidString(fileName) then
local fileContents = type(contents) == 'table' and Ext.JsonStringify(Rematerialize(contents)) or tostring(contents) or ""
Ext.SaveFile(fileName, fileContents)
end
end
-- ===================
-- LOAD MULTIPLE FILES
-- ===================
---Loads multiple files
---@param fileNames table Array of fileNames
---@param context string Path-Context
---@return table files Table of files
function LoadFiles(fileNames, context)
local files = {}
if type(fileNames) ~= 'table' then return end
for _, fileName in ipairs(fileNames) do
local _, fileContents = pcall(Ext.LoadFile, fileName, context)
if string.match(fileName, '.json') then
if ValidString(fileContents) then files[fileName] = Ext.JsonParse(fileContents); Destringify(files[fileName])
else files[fileName] = {} end
else files[fileName] = fileContents end
end
return files
end
|
--[[
* Configuration for <archive.lua> script.
*
]]
-- ----------------------------------------------------------------------------
--
local tConfiguration =
{
sCfgVersion = "0.0.2",
bUseMove = false, -- move files instead of copy
bUseCurDay = false, -- use todays' date or modification time of
-- newest file in source directory
sTargetFldr = "data/years",
sSourceFldr = "data/update",
sExtFilter = "*.json",
}
return tConfiguration
-- ----------------------------------------------------------------------------
-- ----------------------------------------------------------------------------
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.