content
stringlengths 5
1.05M
|
---|
local M = {}
local filetype = "cpp"
local function not_implemented()
error("Not yet implemented for cpp")
end
function M.remove_types()
-- TODO: Fix query issues for fried function, I want to keep the type
-- on which is applied the function.
return vim.treesitter.parse_query(filetype, [[
(parameter_list
(parameter_declaration
type: (qualified_identifier) @type6 (#offset! @type6)))
((type_qualifier) @type (#offset! @type))
((type_identifier) @type2 (#offset! @type2))
((primitive_type) @type3 (#offset! @type3))
((reference_declarator) @type4 (#offset! @type4))
((pointer_declarator) @type5 (#offset! @type5))
]])
-- TODO:
-- Add this & test in servers-drones-master/src/Window.cpp ((placeholder_type_specifier) @type6 (#offset! @type6))
-- Check reference_declarator also.
-- With toggle all & toggle for parenthesis.
end
function M.remove_for_parenthesis()
return vim.treesitter.parse_query(filetype, [[
(for_range_loop
type: (_) @for_range_left_side (#offset! @for_range_left_side)
right: (_) @for_range_right_side (#offset! @for_range_right_side))
(for_statement
initializer: (_) @for_range_left_side (#offset! @for_range_left_side)
update: (_) @for_range_right_side (#offset! @for_range_right_side))
]])
end
function M.remove_if_parenthesis()
return vim.treesitter.parse_query(filetype, [[
(if_statement
condition: (_) @condition (#offset! @condition))
]])
end
function M.remove_semicolons()
return vim.treesitter.parse_query(filetype, [[
((expression_statement) @expression1 (#offset! @expression1))
((return_statement) @expression2 (#offset! @expression2))
]])
end
return M
|
-- Dovecot authentication backend for Prosody
--
-- Copyright (C) 2011 Kim Alvefur
--
local log = require "util.logger".init("sasl_imap");
local setmetatable = setmetatable;
local s_match = string.match;
local t_concat = table.concat;
local tostring, tonumber = tostring, tonumber;
local socket = require "socket"
local ssl = require "ssl"
local x509 = require "util.x509";
local base64 = require "util.encodings".base64;
local b64, unb64 = base64.encode, base64.decode;
local _M = {};
local method = {};
method.__index = method;
-- For extracting the username.
local mitm = {
PLAIN = function(message)
return s_match(message, "^[^%z]*%z([^%z]+)%z[^%z]+");
end,
["SCRAM-SHA-1"] = function(message)
return s_match(message, "^[^,]+,[^,]*,n=([^,]*)");
end,
["DIGEST-MD5"] = function(message)
return s_match(message, "username=\"([^\"]*)\"");
end,
}
local function connect(host, port, ssl_params)
port = tonumber(port) or (ssl_params and 993 or 143);
log("debug", "connect() to %s:%s:%d", ssl_params and "ssl" or "tcp", host, tonumber(port));
local conn = socket.tcp();
-- Create a connection to imap socket
log("debug", "connecting to imap at '%s:%d'", host, port);
local ok, err = conn:connect(host, port);
conn:settimeout(10);
if not ok then
log("error", "error connecting to imap at '%s:%d': %s", host, port, err);
return false;
end
if ssl_params then
-- Perform SSL handshake
local ok, err = ssl.wrap(conn, ssl_params);
if ok then
conn = ok;
ok, err = conn:dohandshake();
end
if not ok then
log("error", "error initializing ssl connection to imap at '%s:%d': %s", host, port, err);
conn:close();
return false;
end
-- Verify certificate
if ssl_params.verify then
if not conn.getpeercertificate then
log("error", "unable to verify certificate, newer LuaSec required: https://prosody.im/doc/depends#luasec");
conn:close();
return false;
end
if not x509.verify_identity(host, nil, conn:getpeercertificate()) then
log("warn", "invalid certificate for imap service %s:%d, denying connection", host, port);
return false;
end
end
end
-- Parse IMAP handshake
local supported_mechs = {};
local line = conn:receive("*l");
if not line then
return false;
end
log("debug", "imap greeting: '%s'", line);
local caps = line:match("^%*%s+OK%s+(%b[])");
if not caps or not caps:match("^%[CAPABILITY ") then
conn:send("A CAPABILITY\r\n");
line = conn:receive("*l");
log("debug", "imap capabilities response: '%s'", line);
caps = line:match("^%*%s+CAPABILITY%s+(.*)$");
if not conn:receive("*l"):match("^A OK") then
log("debug", "imap capabilities command failed")
conn:close();
return false;
end
elseif caps then
caps = caps:sub(2,-2); -- Strip surrounding []
end
if caps then
for cap in caps:gmatch("%S+") do
log("debug", "Capability: %s", cap);
local mech = cap:match("AUTH=(.*)");
if mech then
log("debug", "Supported SASL mechanism: %s", mech);
supported_mechs[mech] = mitm[mech] and true or nil;
end
end
end
return conn, supported_mechs;
end
-- create a new SASL object which can be used to authenticate clients
function _M.new(realm, service_name, host, port, ssl_params, append_host)
log("debug", "new(%q, %q, %q, %d)", realm or "", service_name or "", host or "", port or 0);
local sasl_i = {
realm = realm;
service_name = service_name;
_host = host;
_port = port;
_ssl_params = ssl_params;
_append_host = append_host;
};
local conn, mechs = connect(host, port, ssl_params);
if not conn then
return nil, "Socket connection failure";
end
if append_host then
mechs = { PLAIN = mechs.PLAIN };
end
sasl_i.conn, sasl_i.mechs = conn, mechs;
return setmetatable(sasl_i, method);
end
-- get a fresh clone with the same realm and service name
function method:clean_clone()
if self.conn then
self.conn:close();
self.conn = nil;
end
log("debug", "method:clean_clone()");
return _M.new(self.realm, self.service_name, self._host, self._port, self._ssl_params, self._append_host)
end
-- get a list of possible SASL mechanisms to use
function method:mechanisms()
log("debug", "method:mechanisms()");
return self.mechs;
end
-- select a mechanism to use
function method:select(mechanism)
log("debug", "method:select(%q)", mechanism);
if not self.selected and self.mechs[mechanism] then
self.tag = tostring({}):match("0x(%x*)$");
self.selected = mechanism;
local selectmsg = t_concat({ self.tag, "AUTHENTICATE", mechanism }, " ");
log("debug", "Sending %d bytes: %q", #selectmsg, selectmsg);
local ok, err = self.conn:send(selectmsg.."\r\n");
if not ok then
log("error", "Could not write to socket: %s", err);
return "failure", "internal-server-error", err
end
local line, err = self.conn:receive("*l");
if not line then
log("error", "Could not read from socket: %s", err);
return "failure", "internal-server-error", err
end
log("debug", "Received %d bytes: %q", #line, line);
return line:match("^+")
end
end
-- feed new messages to process into the library
function method:process(message)
local username = mitm[self.selected](message);
if username then self.username = username; end
if self._append_host and self.selected == "PLAIN" then
message = message:gsub("^([^%z]*%z[^%z]+)(%z[^%z]+)$", "%1@"..self.realm.."%2");
end
log("debug", "method:process(%d bytes): %q", #message, message:gsub("%z", "."));
local ok, err = self.conn:send(b64(message).."\r\n");
if not ok then
log("error", "Could not write to socket: %s", err);
return "failure", "internal-server-error", err
end
log("debug", "Sent %d bytes to socket", ok);
local line, err = self.conn:receive("*l");
if not line then
log("error", "Could not read from socket: %s", err);
return "failure", "internal-server-error", err
end
log("debug", "Received %d bytes from socket: %s", #line, line);
while line and line:match("^%* ") do
line, err = self.conn:receive("*l");
end
if line:match("^%+") and #line > 2 then
local data = line:sub(3);
data = data and unb64(data);
return "challenge", unb64(data);
elseif line:sub(1, #self.tag) == self.tag then
local ok, rest = line:sub(#self.tag+1):match("(%w+)%s+(.*)");
ok = ok:lower();
log("debug", "%s: %s", ok, rest);
if ok == "ok" then
return "success"
elseif ok == "no" then
return "failure", "not-authorized", rest;
end
elseif line:match("^%* BYE") then
local err = line:match("BYE%s*(.*)");
return "failure", "not-authorized", err;
end
end
return _M;
|
local M = {}
--- Extends sub list of the table.
-- @param tbl table: A table of lists.
-- @param key any: A key of the sub list.
-- @param value any: A new value placed in the sub list.
function M.grow_sublist(tbl, key, value)
if tbl[key] == nil then
tbl[key] = { value }
else
table.insert(tbl[key], value)
end
end
return M;
|
data:define_type("god")
data:add_multi(
"core.god",
{
{
id = "mani",
legacy_id = 1,
},
{
id = "lulwy",
legacy_id = 2,
},
{
id = "itzpalt",
legacy_id = 3,
},
{
id = "ehekatl",
legacy_id = 4,
},
{
id = "opatos",
legacy_id = 5,
},
{
id = "jure",
legacy_id = 6,
},
{
id = "kumiromi",
legacy_id = 7,
},
})
|
#!/usr/bin/env lua
--- Tests on dumocks.ReceiverUnit.
-- @see dumocks.ReceiverUnit
-- set search path to include src directory
package.path = "src/?.lua;" .. package.path
local lu = require("luaunit")
local mru = require("dumocks.ReceiverUnit")
require("test.Utilities")
_G.TestReceiverUnit = {}
--- Verify constructor arguments properly handled and independent between instances.
function _G.TestReceiverUnit.testConstructor()
-- default element:
-- ["receiver xs"] = {mass = 13.27, maxHitPoints = 50.0, range = 100.0}
local receiver0 = mru:new()
local receiver1 = mru:new(nil, 1, "Receiver XS")
local receiver2 = mru:new(nil, 2, "invalid")
local receiver3 = mru:new(nil, 3, "receiver s")
local receiverClosure0 = receiver0:mockGetClosure()
local receiverClosure1 = receiver1:mockGetClosure()
local receiverClosure2 = receiver2:mockGetClosure()
local receiverClosure3 = receiver3:mockGetClosure()
lu.assertEquals(receiverClosure0.getId(), 0)
lu.assertEquals(receiverClosure1.getId(), 1)
lu.assertEquals(receiverClosure2.getId(), 2)
lu.assertEquals(receiverClosure3.getId(), 3)
-- prove default element is selected only where appropriate
local defaultMass = 13.27
lu.assertEquals(receiverClosure0.getMass(), defaultMass)
lu.assertEquals(receiverClosure1.getMass(), defaultMass)
lu.assertEquals(receiverClosure2.getMass(), defaultMass)
lu.assertNotEquals(receiverClosure3.getMass(), defaultMass)
end
--- Verify get range retrieves range properly.
function _G.TestReceiverUnit.testGetRange()
local mock = mru:new()
local closure = mock:mockGetClosure()
mock.range = 50.0
lu.assertEquals(closure.getRange(), 50.0)
mock.range = 100.0
lu.assertEquals(closure.getRange(), 100.0)
end
--- Verify receive calls all callbacks and propagates errors.
function _G.TestReceiverUnit.testReceiveError()
local mock = mru:new()
mock.channelList = "channel"
local calls = 0
local callback1Order, callback2Order
local callbackError = function(_, _)
calls = calls + 1
callback1Order = calls
error("I'm a bad callback.")
end
mock:mockRegisterReceive(callbackError, "*", "*")
local callback2 = function(_, _)
calls = calls + 1
callback2Order = calls
error("I'm a bad callback, too.")
end
mock:mockRegisterReceive(callback2, "*", "*")
-- both called, proper order, errors thrown
lu.assertErrorMsgContains("bad callback", mock.mockDoReceive, mock, "channel", "message")
lu.assertEquals(calls, 2)
lu.assertEquals(callback1Order, 1)
lu.assertEquals(callback2Order, 2)
end
--- Verify unfiltered receive gets all messages on channels the receiver is listening to.
function _G.TestReceiverUnit.testReceiveAll()
local mock = mru:new()
mock.channelList = "channel, blah"
local expectedChannel, actualChannel
local expectedMessage, actualMessage
local called
local callback = function(channel, message)
called = true
actualChannel = channel
actualMessage = message
end
mock:mockRegisterReceive(callback, "*", "*")
called = false
actualChannel = nil
actualMessage = nil
expectedChannel = "channel"
expectedMessage = "message"
mock:mockDoReceive(expectedChannel, expectedMessage)
lu.assertTrue(called)
lu.assertEquals(actualChannel, expectedChannel)
lu.assertEquals(actualMessage, expectedMessage)
called = false
actualChannel = nil
actualMessage = nil
expectedChannel = "blah"
expectedMessage = "new message"
mock:mockDoReceive(expectedChannel, expectedMessage)
lu.assertTrue(called)
lu.assertEquals(actualChannel, expectedChannel)
lu.assertEquals(actualMessage, expectedMessage)
called = false
expectedChannel = "filter"
expectedMessage = "message"
mock:mockDoReceive(expectedChannel, expectedMessage)
lu.assertFalse(called)
called = false
actualChannel = nil
actualMessage = nil
expectedChannel = "channel"
expectedMessage = "filter"
mock:mockDoReceive(expectedChannel, expectedMessage)
lu.assertTrue(called)
lu.assertEquals(actualChannel, expectedChannel)
lu.assertEquals(actualMessage, expectedMessage)
end
--- Verify filtering on channel works.
function _G.TestReceiverUnit.testReceiveFilterChannel()
local mock = mru:new()
mock.channelList = "channel, filter"
local expectedChannel, actualChannel
local expectedMessage, actualMessage
local called
local callback = function(channel, message)
called = true
actualChannel = channel
actualMessage = message
end
mock:mockRegisterReceive(callback, "channel", "*")
called = false
actualChannel = nil
actualMessage = nil
expectedChannel = "channel"
expectedMessage = "message"
mock:mockDoReceive(expectedChannel, expectedMessage)
lu.assertTrue(called)
lu.assertEquals(actualChannel, expectedChannel)
lu.assertEquals(actualMessage, expectedMessage)
-- in channel list but not in filter
called = false
expectedChannel = "filter"
expectedMessage = "message"
mock:mockDoReceive(expectedChannel, expectedMessage)
lu.assertFalse(called)
called = false
actualChannel = nil
actualMessage = nil
expectedChannel = "channel"
expectedMessage = "filter"
mock:mockDoReceive(expectedChannel, expectedMessage)
lu.assertTrue(called)
lu.assertEquals(actualChannel, expectedChannel)
lu.assertEquals(actualMessage, expectedMessage)
end
--- Verify filtering on messages works.
function _G.TestReceiverUnit.testReceiveFilterMessage()
local mock = mru:new()
mock.channelList = "channel"
local expectedChannel, actualChannel
local expectedMessage, actualMessage
local called
local callback = function(channel, message)
called = true
actualChannel = channel
actualMessage = message
end
mock:mockRegisterReceive(callback, "*", "message")
called = false
actualChannel = nil
actualMessage = nil
expectedChannel = "channel"
expectedMessage = "message"
mock:mockDoReceive(expectedChannel, expectedMessage)
lu.assertTrue(called)
lu.assertEquals(actualChannel, expectedChannel)
lu.assertEquals(actualMessage, expectedMessage)
called = false
expectedChannel = "channel"
expectedMessage = "filter"
mock:mockDoReceive(expectedChannel, expectedMessage)
lu.assertFalse(called)
end
--- Verify filtering on channel and message at the same time works.
function _G.TestReceiverUnit.testReceiveFilterBoth()
local mock = mru:new()
mock.channelList = "channel, filter"
local expectedChannel, actualChannel
local expectedMessage, actualMessage
local called
local callback = function(channel, message)
called = true
actualChannel = channel
actualMessage = message
end
mock:mockRegisterReceive(callback, "channel", "message")
called = false
actualChannel = nil
actualMessage = nil
expectedChannel = "channel"
expectedMessage = "message"
mock:mockDoReceive(expectedChannel, expectedMessage)
lu.assertTrue(called)
lu.assertEquals(actualChannel, expectedChannel)
lu.assertEquals(actualMessage, expectedMessage)
called = false
expectedChannel = "filter"
expectedMessage = "message"
mock:mockDoReceive(expectedChannel, expectedMessage)
lu.assertFalse(called)
called = false
expectedChannel = "channel"
expectedMessage = "filter"
mock:mockDoReceive(expectedChannel, expectedMessage)
lu.assertFalse(called)
end
--- Characterization test to determine in-game behavior, can run on mock and uses assert instead of luaunit to run
-- in-game.
--
-- Test setup:
-- 1. 1x Receiver XS, connected to Programming Board on slot1, default channel set to duMocks
-- 2. 1x Emitter XS, connected to Programming Board on slot2
--
-- Exercises: getElementClass, receive, getRange, setSignalOut, setChannels, getChannels
function _G.TestReceiverUnit.testGameBehavior()
local mock = mru:new(nil, 1)
local slot1 = mock:mockGetClosure()
-- stub this in directly to supress print in the unit test
local unit = {}
unit.getData = function()
return '"showScriptError":false'
end
unit.setTimer = function()
end
unit.exit = function()
end
local system = {}
system.print = function(msg)
end
local slot2 = {}
function slot2.send(channel, message)
mock:mockDoReceive(channel, message)
end
local tickEnd = function()
---------------
-- copy from here to unit.tick(timerId) stop
---------------
-- exit to report status
unit.exit()
---------------
-- copy to here to unit.tick(timerId) stop
---------------
end
local tickResume = function()
---------------
-- copy from here to unit.tick(timerId) resume
---------------
assert(_G.receiverCoroutine, "Coroutine must exist when resume is called.")
assert(coroutine.status(_G.receiverCoroutine) ~= "dead", "Coroutine should not be dead when resume is called.")
-- resume routine only when expected call has been received and processed
local ok, message = coroutine.resume(_G.receiverCoroutine)
assert(ok, string.format("Error resuming coroutine: %s", message))
---------------
-- copy to here to unit.tick(timerId) resume
---------------
end
local allCount, messageFilterCount, channelFilterCount
local receiveAllListener = function(channel, message)
---------------
-- copy from here to slot1.receive(channel,message) * *
---------------
allCount = allCount + 1
assert(slot1.getSignalOut("out") == 1.0)
---------------
-- copy to here to slot1.receive(channel,message) * *
---------------
end
mock:mockRegisterReceive(receiveAllListener, "*", "*")
local receiveChannelListener = function(channel, message)
---------------
-- copy from here to slot1.receive(channel,message) duMocks *
---------------
channelFilterCount = channelFilterCount + 1
assert(message == "filtered", "Received: " .. message)
---------------
-- copy to here to slot1.receive(channel,message) duMocks *
---------------
end
mock:mockRegisterReceive(receiveChannelListener, "duMocks", "*")
local receiveMessageListener = function(channel, message)
---------------
-- copy from here to slot1.receive(channel,message) * message
---------------
messageFilterCount = messageFilterCount + 1
assert(channel == "filtered", "Received on: " .. channel)
---------------
-- copy to here to slot1.receive(channel,message) * message
---------------
end
mock:mockRegisterReceive(receiveMessageListener, "*", "message")
---------------
-- copy from here to unit.start
---------------
-- verify expected functions
local expectedFunctions = {"getRange", "getChannels", "setChannels", "getSignalOut"}
for _, v in pairs(_G.Utilities.elementFunctions) do
table.insert(expectedFunctions, v)
end
_G.Utilities.verifyExpectedFunctions(slot1, expectedFunctions)
-- test element class and inherited methods
assert(slot1.getElementClass() == "ReceiverUnit")
assert(slot1.getMaxHitPoints() == 50.0)
assert(slot1.getMass() == 13.27)
_G.Utilities.verifyBasicElementFunctions(slot1, 3)
assert(slot1.getRange() == 1000.0)
allCount = 0
messageFilterCount = 0
channelFilterCount = 0
local channelList = "unexpected, filtered, duMocks"
slot1.setChannels(channelList)
assert(slot1.getChannels() == channelList,
string.format("Expected <%s> but got <%s>", channelList, slot1.getChannels()))
local function messagingTest()
slot2.send("unexpected", "unexpected") -- hits all listener only
coroutine.yield()
slot2.send("filtered", "message") -- filtered by message
coroutine.yield()
slot2.send("duMocks", "filtered") -- filtered by channel
coroutine.yield()
slot2.send("unlistened", "unexpected") -- receiver not registered for channel
coroutine.yield()
unit.exit()
end
_G.receiverCoroutine = coroutine.create(messagingTest)
coroutine.resume(_G.receiverCoroutine)
unit.setTimer("resume", 0.25)
-- all messages should be processed easily within 2 seconds
unit.setTimer("stop", 2)
---------------
-- copy to here to unit.start
---------------
-- listener function called synchronously, by the time yield is called all processing is finished, so just resume
tickResume()
tickResume()
tickResume()
tickResume()
---------------
-- copy from here to unit.stop()
---------------
assert(allCount == 3, allCount)
assert(messageFilterCount == 1, messageFilterCount)
assert(channelFilterCount == 1)
-- multi-part script, can't just print success because end of script was reached
if string.find(unit.getData(), '"showScriptError":false') then
system.print("Success")
else
system.print("Failed")
end
---------------
-- copy to here to unit.stop()
---------------
end
os.exit(lu.LuaUnit.run())
|
--[[
Useful functions to manipulate strings, based on similar implementations in other standard libraries.
]]
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local require = require(ReplicatedStorage:WaitForChild("Nevermore"))
local t = require("t")
local Functions = require(script.Parent.Functions)
local Tables = require(script.Parent.Tables)
local Strings = {}
local append = table.insert
local concat = table.concat
--[[
Convert `str` to camel-case.
@example _.camelCase('Pepperoni Pizza') --> 'pepperoniPizza'
@example _.camelCase('--pepperoni-pizza--') --> 'pepperoniPizza'
@example _.camelCase('__PEPPERONI_PIZZA') --> 'pepperoniPizza'
@trait Chainable
]]
--: string -> string
function Strings.camelCase(str)
assert(t.string(str))
return str:gsub(
"(%a)([%w]*)",
function(head, tail)
return head:upper() .. tail:lower()
end
):gsub("%A", ""):gsub("^%u", string.lower)
end
--[[
Convert `str` to kebab-case, making all letters lowercase.
@example _.kebabCase('strongStilton') --> 'strong-stilton'
@example _.kebabCase(' Strong Stilton ') --> 'strong-stilton'
@example _.kebabCase('__STRONG_STILTON__') --> 'strong-stilton'
@usage Chain with `:upper()` if you need an upper kebab-case string.
@trait Chainable
]]
--: string -> string
function Strings.kebabCase(str)
assert(t.string(str))
return str:gsub(
"(%l)(%u)",
function(a, b)
return a .. "-" .. b
end
):gsub("%A", "-"):gsub("^%-+", ""):gsub("%-+$", ""):lower()
end
--[[
Convert `str` to snake-case, making all letters uppercase.
@example _.snakeCase('sweetChickenCurry') --> 'SWEET_CHICKEN_CURRY'
@example _.snakeCase(' Sweet Chicken Curry ') --> 'SWEET_CHICKEN__CURRY'
@example _.snakeCase('--sweet-chicken--curry--') --> 'SWEET_CHICKEN__CURRY'
@usage Chain with `:lower()` if you need a lower snake-case string.
@trait Chainable
]]
function Strings.snakeCase(str)
assert(t.string(str))
return str:gsub(
"(%l)(%u)",
function(a, b)
return a .. "_" .. b
end
):gsub("%A", "_"):gsub("^_+", ""):gsub("_+$", ""):upper()
end
--[[
Convert `str` to title-case, where the first letter of each word is capitalized.
@example _.titleCase("jello world") --> "Jello World"
@example _.titleCase("yellow-jello with_sprinkles") --> "Yellow-jello With_sprinkles"
@example _.titleCase("yellow jello's don’t mellow") --> "Yellow Jello's Dont’t Mellow"
@usage Dashes, underscores and apostraphes don't break words.
@trait Chainable
]]
function Strings.titleCase(str)
assert(t.string(str))
return str:gsub(
"(%a)([%w_%-'’]*)",
function(head, tail)
return head:upper() .. tail
end
)
end
--[[
Capitalize the first letter of `str`.
@example _.capitalize("hello mould") --> "Hello mould"
@trait Chainable
]]
function Strings.capitalize(str)
assert(t.string(str))
return str:gsub("^%l", string.upper)
end
--[==[
Converts the characters `&<>"'` in `str` to their corresponding HTML entities.
@example _.encodeHtml([[Pease < Bacon > "Fish" & 'Chips']]) --> "Peas < Bacon > "Fish" & 'Chips'"
@trait Chainable
]==]
function Strings.encodeHtml(str)
assert(t.string(str))
local entities = {["<"] = "lt", [">"] = "gt", ["&"] = "amp", ['"'] = "quot", ["'"] = "apos"}
return str:gsub(
".",
function(char)
return entities[char] and ("&" .. entities[char] .. ";") or char
end
)
end
--[==[
The inverse of `_.encodeHtml`.
Converts any HTML entities in `str` to their corresponding characters.
@example _.decodeHtml("<b>"Smashed"</b> 'Avocado' 😏") --> [[<b>"Smashed"</b> 'Avocado' 😏]]
@trait Chainable
]==]
function Strings.decodeHtml(str)
assert(t.string(str))
local entities = {lt = "<", gt = ">", amp = "&", quot = '"', apos = "'"}
return str:gsub(
"(&(#?x?)([%d%a]+);)",
function(original, hashPrefix, code)
return (hashPrefix == "" and entities[code]) or
(hashPrefix == "#x" and tonumber(code, 16)) and utf8.char(tonumber(code, 16)) or
(hashPrefix == "#" and tonumber(code)) and utf8.char(code) or
original
end
)
end
--[[
Splits `str` into parts based on a pattern delimiter and returns a table of the parts.
@example _.splitByPattern("rice") --> {"r", "i", "c", "e"}
@example _.splitByPattern("one.two::flour", "[.:]") --> {"one", "two", "", "flour"}
@usage This method is useful only when you need a _pattern_ as a delimiter.
@usage Use the Roblox native `string.split` if you are splitting on a simple string.
@param delimiter (default = "")
@trait Chainable
]]
--: string, pattern -> string[]
function Strings.splitByPattern(str, delimiter)
assert(t.string(str))
assert(t.optional(t.string)(delimiter))
local result = {}
local from = 1
if (not delimiter) then
for i = 1, #str do
append(result, str:sub(i, i))
end
return result
end
local delim_from, delim_to = str:find(delimiter, from)
while delim_from do
append(result, str:sub(from, delim_from - 1))
from = delim_to + 1
delim_from, delim_to = str:find(delimiter, from)
end
append(result, str:sub(from))
return result
end
--[[
Removes any spaces from the start and end of `str`.
@example _.trim(" roast veg ") --> "roast veg"
@trait Chainable
]]
--: string -> string
function Strings.trim(str)
assert(t.string(str))
return str:match("^%s*(.-)%s*$")
end
--[[
Checks if `str` starts with the string `start`.
@example _.startsWith("Fun Roblox Games", "Fun") --> true
@example _.startsWith("Chess", "Fun") --> false
@trait Chainable
]]
--: string, string -> bool
function Strings.startsWith(str, prefix)
assert(t.string(str))
return str:sub(1, prefix:len()) == prefix
end
--[[
Checks if `str` ends with the string `suffix`.
@example _.endsWith("Fun Roblox Games", "Games") --> true
@example _.endsWith("Bad Roblox Memes", "Games") --> false
@trait Chainable
]]
--: string, string -> bool
function Strings.endsWith(str, suffix)
assert(t.string(str))
assert(t.string(suffix))
return str:sub(-suffix:len()) == suffix
end
--[[
Makes a string of `length` from `str` by repeating characters from `prefix` at the start of the string.
@example _.leftPad("toast", 6) --> " toast"
@example _.leftPad("2", 2, "0") --> "02"
@example _.leftPad("toast", 10, ":)") --> ":):):toast"
@param prefix (default = `" "`)
@trait Chainable
]]
--: string, number, string -> string
function Strings.leftPad(str, length, prefix)
assert(t.string(str))
assert(t.number(length))
assert(t.optional(t.string)(prefix))
prefix = prefix or " "
local padLength = length - #str
local remainder = padLength % #prefix
local repetitions = (padLength - remainder) / #prefix
return string.rep(prefix or " ", repetitions) .. prefix:sub(1, remainder) .. str
end
--[[
Makes a string of `length` from `str` by repeating characters from `suffix` at the end of the string.
@example _.rightPad("toast", 6) --> "toast "
@example _.rightPad("2", 2, "!") --> "2!"
@example _.rightPad("toast", 10, ":)") --> "toast:):):"
@param suffix (default = `" "`)
@trait Chainable
]]
--: string, number, string -> string
function Strings.rightPad(str, length, suffix)
assert(t.string(str))
assert(t.number(length))
assert(t.optional(t.string)(suffix))
suffix = suffix or " "
local padLength = length - #str
local remainder = padLength % #suffix
local repetitions = (padLength - remainder) / #suffix
return str .. string.rep(suffix or " ", repetitions) .. suffix:sub(1, remainder)
end
--[[
This function is a simpler & more powerful version of `string.format`, inspired by `format!` in Rust.
If an instance has a `:format()` method, this is used instead, passing the format arguments.
* `{}` prints the next variable using or `tostring`.
* `{:?}` prints using `_.serializeDeep`.
* `{:#?}` prints using `_.pretty`.
@param subject the format match string
]]
function Strings.format(subject, ...)
end
--[[
Pretty-prints the _subject_ and its associated metatable if _withMetatable_ is true
@param withMetatable (default = false)
]]
--: any, bool? -> string
function Strings.pretty(subject, withMetatable)
end
--[[
This function first calls `_.format` on the arguments provided and then outputs the response
to the debug target, set using `_.setDebug`. By default, this function does nothing, allowing
developers to leave the calls in the source code if that is beneficial.
@param subject the format match string
@usage A common pattern would be to `_.setDebug()` to alias to `print` during local development,
and call e.g. `_.setDebug(_.bind(HttpService.PostAsync, "https://example.com/log"))`
on a production build to allow remote debugging.
]]
function Strings.debug(subject, ...)
if Strings.debugTarget == nil then
return
end
Strings.debugTarget(Strings.format(...))
end
--[[
Hooks up any debug methods to invoke _fn_. By default, `_.debug` does nothing.
@param fn (default = `print`)
@usage Calling `_.setDebug()` will simply print all calls to `_.debug` with formatted arguments.
]]
function Strings.setDebug(fn)
Strings.debugTarget = fn
end
--[[
Converts _char_ into a hex representation
@param format (optional) a string passed to `_.format` which formats the hex value of each of the character's code points.
@param useBytes (default = false) whether to use the character's bytes, rather than UTF-8 code points.
@example _.charToHex("<") --> "3C"
@example _.charToHex("<", "&#{};") --> "C;"
@example _.charToHex("😏") --> "1F60F"
@example _.charToHex("😏", "0x{}") --> "0x1F60F"
@example _.charToHex("🤷🏼♀️", "&#x{};") --> "🤷🏼‍♀️"
@example _.charToHex("🤷🏼♀️", "%{}", true) --> "%F0%9F%A4%B7%F0%9F%8F%BC%E2%80%8D%E2%99%80%EF%B8%8F"
]]
--: char -> str, str?, boolean?
function Strings.charToHex(char, format, useBytes)
assert(t.string(char))
assert(utf8.len(char) == 1)
local values = {}
if useBytes then
for position, codePoint in utf8.codes(char) do
append(values, codePoint)
end
else
for i = 1, char:len() do
append(values, char:byte(i))
end
end
return concat(
Tables.map(
values,
function(value)
return format and Strings.format(format, string.format("%X", value))
end,
""
)
)
end
--[[
Generates a character from its _hex_ representation.
@example _.hexToChar("1F60F") --> "😏"
@example _.hexToChar("%1F60F") --> "😏"
@example _.hexToChar("#1F60F") --> "😏"
@example _.hexToChar("0x1F60F") --> "😏"
@throws _MalformedInput_ if _char_ is not a valid encoding.
]]
--: str -> char
function Strings.hexToChar(hex)
assert(t.string(hex))
if hex:sub(0, 1) == "%" or hex:sub(0, 1) == "#" then
hex = hex:sub(1)
elseif hex:sub(0, 2) == "0x" then
hex = hex:sub(2)
end
return utf8.char(tonumber(hex, 16)) or error("MalformedInput")
end
--[[
Encodes _str_ for use as a URL, for example as an entire URL.
@trait Chainable
@example
_.encodeUrl("https://example.com/Egg+Fried Rice!?🤷🏼♀️")
--> "https://example.com/Egg+Fried%20Rice!?%1F937%1F3FC%200D%2640%FE0F"
@usage
This method is designed to act like `encodeURI` in JavaScript.
]]
--: string -> string
function Strings.encodeUrl(str)
assert(t.string(str))
return str:gsub("[^%;%,%/%?%:%@%&%=%+%$%w%-%_%.%!%~%*%'%(%)%#]", Functions.bindTail(Strings.charToHex, "%{}", true))
end
--[[
Encodes _str_ for use in a URL, for example as a query parameter of a URL.
@trait Chainable
@example
_.encodeUrlComponent("https://example.com/Egg+Fried Rice!?🤷🏼♀️")
--> "https%3A%2F%2Fexample.com%2FEgg%2BFried%20Rice!%3F%1F937%1F3FC%200D%2640%FE0F"
@usage
This method is designed to act like `encodeURIComponent` in JavaScript.
@usage
This is very similar to `HttpService.EncodeUrl`, but is included for parity and conforms closer to the standard (e.g. EncodeUrl unnecessarily encodes `!`).
]]
--: string -> string
function Strings.encodeUrlComponent(str)
assert(t.string(str))
return str:gsub("[^%w%-_%.%!%~%*%'%(%)]", Functions.bindTail(Strings.charToHex, "%{}", true))
end
local calculateDecodeUrlExceptions =
Functions.once(
function()
local exceptions = {}
for char in ("#$&+,/:;=?@"):gmatch(".") do
exceptions[string.byte(char)] = true
end
return exceptions
end
)
--[[
The inverse of `_.encodeUrl`.
@trait Chainable
@example
_.decodeUrl("https://Egg+Fried%20Rice!?")
--> "https://Egg+Fried Rice!?"
@usage
This method is designed to act like `decodeURI` in JavaScript.
]]
--: string -> string
function Strings.decodeUrl(str)
assert(t.string(str))
local exceptions = calculateDecodeUrlExceptions()
return str:gsub(
"%%(%x%x)",
function(term)
local charId = tonumber(term, 16)
if not exceptions[charId] then
return utf8.char(charId)
end
end
)
end
--[[
The inverse of `_.encodeUrlComponent`.
@trait Chainable
@example
_.decodeUrlComponent("https%3A%2F%2FEgg%2BFried%20Rice!%3F")
--> "https://Egg+Fried Rice!?"
@usage This method is designed to act like `decodeURIComponent` in JavaScript.
@throws _MalformedInput_ if _str_ contains characters encoded incorrectly.
]]
--: string -> string
function Strings.decodeUrlComponent(str)
assert(t.string(str))
return str:gsub("%%(%x%x)", Strings.hexToChar)
end
--[[
Takes a _query_ dictionary of key-value pairs and builds a query string that can be concatenated
to the end of a url.
@example
_.encodeQueryString({
time = 11,
biscuits = "hob nobs",
chocolatey = true
})) --> "?biscuits=hob+nobs&time=11&chocolatey=true"
@usage A query string which contains duplicate keys with different values is technically valid, but this function doesn't provide a way to produce them.
]]
--: <K,V>(Iterable<K,V> -> string)
function Strings.encodeQueryString(query)
assert(t.table(query))
local fields =
Tables.mapValues(
query,
function(value, key)
return Strings.encodeUrlComponent(tostring(key)) .. "=" .. Strings.encodeUrlComponent(tostring(value))
end
)
return ("?" .. concat(fields, "&"))
end
return Strings
|
local class = require('opus.class')
local Event = require('opus.event')
local UI = require('opus.ui')
local Util = require('opus.util')
UI.StatusBar = class(UI.Window)
UI.StatusBar.defaults = {
UIElement = 'StatusBar',
backgroundColor = 'lightGray',
textColor = 'gray',
height = 1,
ey = -1,
}
function UI.StatusBar:layout()
UI.Window.layout(self)
-- Can only have 1 adjustable width
if self.columns then
local w = self.width - #self.columns - 1
for _,c in pairs(self.columns) do
if c.width then
c.cw = c.width -- computed width
w = w - c.width
end
end
for _,c in pairs(self.columns) do
if not c.width then
c.cw = w
end
end
end
end
function UI.StatusBar:setStatus(status)
if self.values ~= status then
self.values = status
self:draw()
end
end
function UI.StatusBar:setValue(name, value)
if not self.values then
self.values = { }
end
self.values[name] = value
end
function UI.StatusBar:getValue(name)
if self.values then
return self.values[name]
end
end
function UI.StatusBar:timedStatus(status, timeout)
self:write(2, 1, Util.widthify(status, self.width-2), self.backgroundColor)
Event.onTimeout(timeout or 3, function()
if self.enabled then
self:draw()
self:sync()
end
end)
end
function UI.StatusBar:getColumnWidth(name)
local c = Util.find(self.columns, 'key', name)
return c and c.cw
end
function UI.StatusBar:setColumnWidth(name, width)
local c = Util.find(self.columns, 'key', name)
if c then
c.cw = width
end
end
function UI.StatusBar:draw()
if not self.values then
self:clear()
elseif type(self.values) == 'string' then
self:write(1, 1, Util.widthify(' ' .. self.values, self.width))
else
local x = 2
self:clear()
for _,c in ipairs(self.columns) do
local s = Util.widthify(tostring(self.values[c.key] or ''), c.cw)
self:write(x, 1, s, c.bg, c.fg)
x = x + c.cw + 1
end
end
end
function UI.StatusBar.example()
return UI.Window {
status1 = UI.StatusBar { values = 'standard' },
status2 = UI.StatusBar {
ey = -3,
columns = {
{ key = 'field1' },
{ key = 'field2', width = 6 },
},
values = {
field1 = 'test',
field2 = '42',
}
}
}
end
|
--[[
Inital page for when the menu opens. Right now this is an empty page
]]
local CorePackages = game:GetService("CorePackages")
local InGameMenuDependencies = require(CorePackages.InGameMenuDependencies)
local Roact = InGameMenuDependencies.Roact
local InitalPage = Roact.PureComponent:extend("InitalPage")
function InitalPage:render()
end
return InitalPage
|
local Tables = require('Common.Tables')
local ModSpawns = require('Spawns.Priority')
local Test = {
UseReadyRoom = true,
UseRounds = true,
StringTables = {},
PlayerTeams = {
Blue = {
TeamId = 1,
Loadout = 'NoTeam',
},
},
Settings = {
RoundTime = {
Min = 5,
Max = 30,
Value = 10,
},
},
AiSpawns = nil,
Players = {}
}
Test.__index = Test
function Test:new()
local test = {}
setmetatable(self, test)
return test
end
--#region Initialization
---Method called right after the mission is loaded.
function Test:PreInit()
print('PreInit')
self.AiSpawns = ModSpawns:Create()
end
---Method called just before player gets control.
function Test:PostInit()
print('PostInit')
timer.Set(
'TestTimer1',
self,
self.TestTimer1,
10.0,
false
)
end
function Test:TestTimer1()
print('TestTimer1')
local players = gamemode.GetPlayerList(
1,
0,
false,
0,
true
)
print('Found ' .. #players .. ' players')
player.ShowGameMessage(
players[1],
'TestMessage1',
'Lower',
60.0
)
timer.Set(
'TestTimer2',
self,
self.TestTimer2,
5.0,
false
)
end
function Test:TestTimer2()
print('TestTimer2')
print('Clearing message')
timer.Clear(self, 'TestMessage1')
end
--#endregion
--#region Triggers
---Triggered when a round stage is set. Round stage can be anything set by the user
---using the gamemode.SetRoundStage(stage) function. Howver there are some predefined
---round stages.
---@param RoundStage string named of the set round stage
---| 'WaitingForReady'
---| 'ReadyCountdown'
---| 'PreRoundWait'
---| 'InProgress'
---| 'PostRoundWait'
function Test:OnRoundStageSet(RoundStage)
print('OnRoundStageSet ' .. RoundStage)
if RoundStage == 'PreRoundWait' then
self.AiSpawns:SelectSpawnPoints()
print('Stage time ' .. gamemode.GetRoundStageTime())
self.AiSpawns:Spawn(
4.0,
nil,
'OpFor'
)
elseif RoundStage == 'PostRoundWait' then
ai.CleanUp(self.AiTeams.OpFor.Tag)
end
end
---Triggered when a round stage time elapse. Round stage can be anything set by
---the user using the gamemode.SetRoundStage(stage) function. However there are some
---predefined round stages.
---@param RoundStage string Name of the elapsed round stage
---| 'WaitingForReady'
---| 'ReadyCountdown'
---| 'PreRoundWait'
---| 'InProgress'
---| 'PostRoundWait'
function Test:OnRoundStageTimeElapsed(RoundStage)
print('OnRoundStageTimeElapsed ' .. RoundStage)
end
---Triggered whenever any character dies (player or bot).
---@param Character any Character that died.
---@param CharacterController any Controller of the character that died.
---@param KillerController any Controller of the character that killed the character.
function Test:OnCharacterDied(Character, CharacterController, KillerController)
print('OnCharacterDied')
end
---Triggered whenever any actor ovelaps a trigger. Note: Extraction points act as
---triggers as well.
---@param GameTrigger any
---@param Player any
function Test:OnGameTriggerBeginOverlap(GameTrigger, Player)
print('OnGameTriggerBeginOverlap')
end
---Triggered whenever any actor ovelaps a trigger. Note: Extraction points act as
---triggers as well.
---@param GameTrigger any
---@param Player any
function Test:OnGameTriggerEndOverlap(GameTrigger, Player)
print('OnGameTriggerBeginOverlap')
end
--#endregion
--#region Player actions
---Method called when a player changes the selected insertion point.
---@param PlayerState any
---@param InsertionPoint any
function Test:PlayerInsertionPointChanged(PlayerState, InsertionPoint)
print('PlayerInsertionPointChanged')
end
---Method called when a player changes their ready status. If mission provides insertion
---points this is called at more or less the same time as PlayerInsertionPointChanged.
---@param PlayerState any
---@param ReadyStatus string
---| 'NotReady'
---| 'WaitingToReadyUp'
---| 'DeclaredReady'
function Test:PlayerReadyStatusChanged(PlayerState, ReadyStatus)
print('PlayerReadyStatusChanged ' .. ReadyStatus)
if ReadyStatus == 'WaitingToReadyUp' then
if not Tables.Index(self.Players, PlayerState) then
table.insert(self.Players, PlayerState)
end
elseif ReadyStatus == 'NotReady' then
local index = Tables.Index(self.Players, PlayerState)
if index then
table.remove(self.Players, index)
end
end
local RoundStage = gamemode.GetRoundStage()
if RoundStage ~= 'WaitingForReady' and RoundStage ~= 'ReadyCountdown' then
return
end
local readyPlayersCount = 0
local allPlayersCount = gamemode.GetPlayerCount(true)
for _, team in ipairs(gamemode.GetReadyPlayerTeamCounts(true)) do
readyPlayersCount = readyPlayersCount + team
end
print('readyPlayersCount ' .. readyPlayersCount .. ' allPlayersCount ' .. allPlayersCount)
if readyPlayersCount >= allPlayersCount then
gamemode.SetRoundStage('PreRoundWait')
elseif readyPlayersCount >= 1 and RoundStage == 'WaitingForReady' then
gamemode.SetRoundStage('ReadyCountdown')
elseif readyPlayersCount < 1 and RoundStage == 'ReadyCountdown' then
gamemode.SetRoundStage('WaitingForReady')
end
end
---Called by the game to check if the player should be allowed to enter play area.
---@param PlayerState any
---@return boolean PlayerCanEnterPlayArea whether or not should we allow users to enter
---play area.
function Test:PlayerCanEnterPlayArea(PlayerState)
print('PlayerCanEnterPlayArea')
return true
end
---Called when any player enters the play area.
---@param PlayerState any
function Test:PlayerEnteredPlayArea(PlayerState)
print('PlayerEnteredPlayArea')
end
---
---@param PlayerState any
---@param Request string
---| 'join'
function Test:PlayerGameModeRequest(PlayerState, Request)
print('PlayerGameModeRequest ' .. Request)
end
---Called when a player tries to enter play area in order to get a spawn point for
---the player. Has to return a spawn point in which the user will be spawned.
---@param PlayerState any
---@return any SpawnPoint the spawn point we want the user to spawn in.
function Test:GetSpawnInfo(PlayerState)
print('GetSpawnInfo')
return nil
end
---Triggered whenever a player leaves the game.
---@param Exiting any
function Test:LogOut(Exiting)
print('LogOut')
end
--#endregion
--#region Misc
---Whether or not we should check for team kills at this point.
---@return boolean ShouldCheckForTeamKills should we check for team kills.
function Test:ShouldCheckForTeamKills()
print('ShouldCheckForTeamKills')
return true
end
--#endregion
return Test
|
--
-- created with TexturePacker (http://www.codeandweb.com/texturepacker)
--
-- $TexturePacker:SmartUpdate:7e48340e56f3166be8728301312604eb:dcf7111b5d5c68d74a40afab3cbea017:82471236ac072b2a4b221f4904720680$
--
-- local sheetInfo = require("mysheet")
-- local myImageSheet = graphics.newImageSheet( "mysheet.png", sheetInfo:getSheet() )
-- local sprite = display.newSprite( myImageSheet , {frames={sheetInfo:getFrameIndex("sprite")}} )
--
local SheetInfo = {}
SheetInfo.sheet =
{
frames = {
{
-- bgSmall
x=1000,
y=0,
width=1000,
height=799,
},
{
-- bgTall
x=0,
y=0,
width=1000,
height=1500,
},
{
-- btnAllDone
x=0,
y=1679,
width=550,
height=139,
},
{
-- btnBack
x=0,
y=1818,
width=550,
height=139,
},
{
-- btnCancel
x=1550,
y=1377,
width=379,
height=139,
},
{
-- btnChallenge
x=0,
y=1500,
width=899,
height=179,
},
{
-- btnChallengeSomeone
x=1000,
y=1059,
width=1000,
height=139,
},
{
-- btnContinue
x=1000,
y=1377,
width=550,
height=139,
},
{
-- btnExit
x=899,
y=1516,
width=550,
height=139,
},
{
-- btnGo
x=899,
y=1655,
width=550,
height=139,
},
{
-- btnOk
x=1650,
y=1823,
width=159,
height=139,
},
{
-- btnPractice
x=1000,
y=1198,
width=899,
height=179,
},
{
-- btnRegister
x=1449,
y=1684,
width=550,
height=139,
},
{
-- btnResume
x=550,
y=1794,
width=550,
height=139,
},
{
-- btnStart
x=1100,
y=1823,
width=550,
height=139,
},
{
-- matchRow
x=1000,
y=799,
width=1000,
height=260,
},
{
-- pauseIcon
x=1899,
y=1198,
width=80,
height=79,
},
{
-- txtChallengeSomeone
x=1449,
y=1516,
width=464,
height=168,
},
{
-- txtGameOver
x=550,
y=1933,
width=479,
height=64,
},
{
-- txtPaused
x=550,
y=1679,
width=331,
height=66,
},
},
sheetContentWidth = 2000,
sheetContentHeight = 1997
}
SheetInfo.frameIndex =
{
["bgSmall"] = 1,
["bgTall"] = 2,
["btnAllDone"] = 3,
["btnBack"] = 4,
["btnCancel"] = 5,
["btnChallenge"] = 6,
["btnChallengeSomeone"] = 7,
["btnContinue"] = 8,
["btnExit"] = 9,
["btnGo"] = 10,
["btnOk"] = 11,
["btnPractice"] = 12,
["btnRegister"] = 13,
["btnResume"] = 14,
["btnStart"] = 15,
["matchRow"] = 16,
["pauseIcon"] = 17,
["txtChallengeSomeone"] = 18,
["txtGameOver"] = 19,
["txtPaused"] = 20,
}
function SheetInfo:getSheet()
return self.sheet;
end
function SheetInfo:getFrameIndex(name)
return self.frameIndex[name];
end
return SheetInfo
|
local class = require 'lib.30log'
local ImageCache = class('ImageCache')
function ImageCache:init()
self.images = {}
end
function ImageCache:load(file_name)
print(file_name)
self.images[file_name] = love.graphics.newImage(file_name)
end
function ImageCache:unload(file_name)
self.images[file_name]:release()
end
function ImageCache:unloadAll()
for _, image in pairs(self.images) do
image:release()
end
end
function ImageCache:get(file_name)
if not self.images[file_name] then
self:load(file_name)
end
return self.images[file_name]
end
function ImageCache:getBackground(name)
return self:get(string.format('assets/backgrounds/%s.png', name))
end
function ImageCache:getCharset(name)
return self:get(string.format('assets/charsets/%s.png', name))
end
function ImageCache:getControl(name)
return self:get(string.format('assets/controls/%s.png', name))
end
function ImageCache:getPanel(name)
return self:get(string.format('assets/panels/%s.png', name))
end
function ImageCache:getTileset(name)
return self:get(string.format('assets/tilesets/%s.png', name))
end
return ImageCache
|
--[[
The MIT License
Copyright (C) 2021 - 2022 Tony Wang
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 beClass = require 'libs/beGUI/beClass'
--[[
Helper structures.
]]
local Percent = beClass.class({
amount = 0,
-- Constructs a Percent structure.
-- `amount`: typically [0, 100]
ctor = function (self, amount)
self.amount = amount / 100
end,
__mul = function (self, num)
return self.amount * num
end
})
local function percent(amount)
return Percent.new(amount)
end
--[[
Exporting.
]]
return {
Percent = Percent,
percent = percent
}
|
--------------------------------
-- @module ImFontGlyph
-- @parent_module imgui
---@class imgui.ImFontGlyph
local ImFontGlyph = {}
imgui.ImFontGlyph = ImFontGlyph
--------------------------------
--- Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops)
---@type number
ImFontGlyph.Colored = nil
--------------------------------
--- 0x0000..0x10FFFF
---@type number
ImFontGlyph.Codepoint = nil
--------------------------------
--- Flag to indicate glyph has no visible pixels (e.g. space). Allow early out when rendering.
---@type number
ImFontGlyph.Visible = nil
--------------------------------
--- Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in)
---@type number
ImFontGlyph.AdvanceX = nil
--------------------------------
--- Glyph corners
---@type number
ImFontGlyph.X0 = nil
--------------------------------
--- Glyph corners
---@type number
ImFontGlyph.Y0 = nil
--------------------------------
--- Glyph corners
---@type number
ImFontGlyph.X1 = nil
--------------------------------
--- Glyph corners
---@type number
ImFontGlyph.Y1 = nil
--------------------------------
--- Texture coordinates
---@type number
ImFontGlyph.U0 = nil
--------------------------------
--- Texture coordinates
---@type number
ImFontGlyph.V0 = nil
--------------------------------
--- Texture coordinates
---@type number
ImFontGlyph.U1 = nil
--------------------------------
--- Texture coordinates
---@type number
ImFontGlyph.V1 = nil
return nil
|
--// Package Metadata
return {
Name = "System.Core";
Version = 1.0;
Description = [[ This package is responsible for the core functionality of Adonis. It provides core server & client loading and communication ]];
Author = "Sceleratis";
Package = script.Parent;
Dependencies = {
"System.Utilities"
};
Settings = {
};
}
|
local ffi = require("ffi")
local C = ffi.C
local foundation = require("foundation")
-- Window types and functions
ffi.cdef[[
typedef struct window_config_t window_config_t;
typedef struct window_t window_t;
typedef void (* window_draw_fn)(window_t*);
int window_module_initialize(const window_config_t);
void window_module_finalize(void);
bool window_module_is_initialized(void);
version_t window_module_version(void);
window_t* window_create(unsigned int, const char*, size_t, int, int, unsigned int);
window_t* window_allocate(void*);
void window_initialize(window_t*, void*);
void window_finalize(window_t*);
void window_deallocate(window_t*);
unsigned int window_adapter(window_t*);
void window_maximize(window_t*);
void window_minimize(window_t*);
void window_restore(window_t*);
void window_resize(window_t*, int, int);
void window_move(window_t*, int, int);
bool window_is_open(window_t*);
bool window_is_visible(window_t*);
bool window_is_maximized(window_t*);
bool window_is_minimized(window_t*);
bool window_has_focus(window_t*);
void window_show_cursor(window_t*, bool, bool);
void window_set_cursor_pos(window_t*, int, int);
bool window_is_cursor_locked(window_t*);
void window_set_title(window_t*, const char*, size_t);
int window_width(window_t*);
int window_height(window_t*);
int window_position_x(window_t*);
int window_position_y(window_t*);
void window_fit_to_screen(window_t*);
void* window_hwnd(window_t*);
void* window_hinstance(window_t*);
void* window_hdc(window_t*);
void window_release_hdc(void*, void*);
void* window_display(window_t*);
void* window_content_view(window_t*);
unsigned long window_drawable(window_t*);
void* window_visual(window_t*);
int window_screen(window_t*);
void* window_view(window_t*, unsigned int);
void* window_layer(window_t*, void*);
void window_add_displaylink(window_t*, window_draw_fn);
void window_show_keyboard(window_t*);
void window_hide_keyboard(window_t*);
int window_screen_width(unsigned int);
int window_screen_height(unsigned int);
int window_view_width(window_t*, void*);
int window_view_height(window_t*, void*);
]]
return {
-- Constants
WINDOWEVENT_CREATE = 1,
WINDOWEVENT_RESIZE = 2,
WINDOWEVENT_CLOSE = 3,
WINDOWEVENT_DESTROY = 4,
WINDOWEVENT_SHOW = 5,
WINDOWEVENT_HIDE = 6,
WINDOWEVENT_GOTFOCUS = 7,
WINDOWEVENT_LOSTFOCUS = 8,
WINDOWEVENT_REDRAW = 9,
WINDOW_ADAPTER_DEFAULT = -1
}
|
M = {}
function M.parse_csv_line(line, sep)
if not line then return nil end
if not sep then sep = ',' end
local values = {}
local pos = string.find(line, sep)
if string.sub(line, 1, 1) == '[' then
local arr_end_pos = string.find(line, ']')
if arr_end_pos then pos = arr_end_pos + 1 end
end
if not pos then pos = string.len(line) + 1 end
local v = string.sub(line, 1, pos - 1)
v = string.gsub(string.gsub(v, '^%s+', ''), '%s+$', '')
if string.sub(v, 1, 1) == '"' and string.sub(v, #v, #v) == '"' then
v = string.sub(v, 2, #v - 1)
end
if string.sub(v, 1, 1) == '\'' and string.sub(v, #v, #v) == '\'' then
v = string.sub(v, 2, #v - 1)
end
if v and string.len(v) > 0 then
-- print('found value: ' .. v)
table.insert(values, v)
end
local more = string.sub(line, pos + 1)
if #more > 0 then
local next_values = M.parse_csv_line(more)
if next_values and #next_values > 0 then
for i = 1, #next_values do
table.insert(values, next_values[i])
end
end
end
return values
end
function M.parse_file(path, sep)
print('LODING CONTENT...')
if not sep then sep = ',' end
-- PARSE LINES
local rows = {}
for line in io.lines(path) do
local vlist = M.parse_csv_line(line, sep)
if vlist and #vlist > 0 then table.insert(rows, vlist) end
end
-- CONVERT TO DICT ROWS
local tb, headers = {}, {}
if rows and #rows > 1 then headers = table.remove(rows, 1) end
for i = 1, #rows do
local d = {}
for j, v in pairs(headers) do
d[v] = rows[i][j]
end
if d and #d then table.insert(tb, d) end
end
print('DONE: LOADED CSV CONTENT...')
return tb
end
function M.parse_file_by_line(path, sep)
print('LODING CONTENT...')
if not sep then sep = ',' end
local i = 0
local iter = io.lines(path)
local headers = M.parse_csv_line(iter())
return function ()
i = i +1
local line = iter()
local vlist = M.parse_csv_line(line) or {}
if vlist and #vlist > 0 then
local d = {}
for j, col in pairs(headers) do
d[col] = vlist[j]
end
return i, d
else
print('DONE: LOADED CSV CONTENT...')
end
end
end
local path = 'dataset/student.csv'
-- inspect = require('inspect')
-- local tb = M.parse_file(path)
-- print( inspect(tb) )
for i, row in M.parse_file_by_line(path) do
i, row = i, row
-- print(i)
-- print(inspect(row))
end
-- print('[ OK. ]')
return M
|
--エクソシスター・ステラ
--
--Scripted by KillerDJ
function c100417014.initial_effect(c)
aux.AddCodeList(c,100417013)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(100417014,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_RECOVER)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,100417014)
e1:SetTarget(c100417014.efftg)
e1:SetOperation(c100417014.effop)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(100417014,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetProperty(EFFECT_FLAG_DELAY)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_MOVE)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,100417014+100)
e2:SetCondition(c100417014.spcon)
e2:SetTarget(c100417014.sptg)
e2:SetOperation(c100417014.spop)
c:RegisterEffect(e2)
end
function c100417014.effspfilter(c,e,tp)
return c:IsSetCard(0x271) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c100417014.efftg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c100417014.effspfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c100417014.cfilter(c)
return c:IsFaceup() and c:IsCode(100417013)
end
function c100417014.effop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c100417014.effspfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 and Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)~=0
and Duel.IsExistingMatchingCard(c100417014.cfilter,tp,LOCATION_ONFIELD,0,1,nil) then
Duel.BreakEffect()
Duel.Recover(tp,800,REASON_EFFECT)
end
end
function c100417014.filter(c)
return c:IsPreviousLocation(LOCATION_GRAVE)
end
function c100417014.spcon(e,tp,eg,ep,ev,re,r,rp)
return rp==1-tp and eg:IsExists(c100417014.filter,1,nil)
end
function c100417014.spfilter(c,e,tp,mc)
return c:IsSetCard(0x271) and c:IsType(TYPE_XYZ) and mc:IsCanBeXyzMaterial(c)
and c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_XYZ,tp,false,false) and Duel.GetLocationCountFromEx(tp,tp,mc,c)>0
end
function c100417014.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return aux.MustMaterialCheck(c,tp,EFFECT_MUST_BE_XMATERIAL)
and Duel.IsExistingMatchingCard(c100417014.spfilter,tp,LOCATION_EXTRA,0,1,nil,e,tp,c) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c100417014.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not aux.MustMaterialCheck(c,tp,EFFECT_MUST_BE_XMATERIAL) then return end
if c:IsFaceup() and c:IsRelateToEffect(e) and c:IsControler(tp) and not c:IsImmuneToEffect(e) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c100417014.spfilter,tp,LOCATION_EXTRA,0,1,1,nil,e,tp,c)
local sc=g:GetFirst()
if sc then
local mg=c:GetOverlayGroup()
if mg:GetCount()~=0 then
Duel.Overlay(sc,mg)
end
sc:SetMaterial(Group.FromCards(c))
Duel.Overlay(sc,Group.FromCards(c))
Duel.SpecialSummon(sc,SUMMON_TYPE_XYZ,tp,tp,false,false,POS_FACEUP)
sc:CompleteProcedure()
end
end
end
|
--====================================================================--
-- corovel/corona/network.lua
--
-- Documentation: http://docs.davidmccuskey.com/
--====================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2014-2015 David McCuskey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--====================================================================--
--== Corovel : Corona-esque Network Object
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.0"
--====================================================================--
--== Imports
local http = require 'socket.http'
local https = require 'ssl.https'
local ltn12 = require 'ltn12'
local urllib = require 'socket.url'
--====================================================================--
--== Setup, Constants
local DEFAULT_METHOD = 'GET'
local DEFAULT_TYPE = 'text'
local DEFAULT_TIMEOUT = 30 -- this is for raw http, default
local tconcat = table.concat
http.TIMEOUT = 30 -- this is for raw http
--====================================================================--
--== Support Functions
local Utils = {}
function Utils.propertyIn( list, property )
for i = 1, #list do
if list[i] == property then return true end
end
return false
end
local function makeHttpRequest( url, method, listener, params )
print( "Network.makeHttpRequest", url, method )
method = method or DEFAULT_METHOD
params = params or {}
-- params.headers = params.headers
-- params.body = params.body
params.bodyType = params.bodyType or DEFAULT_TYPE
-- params.progress = params.progress
-- params.response = params.response
params.timeout = params.timeout or DEFAULT_TIMEOUT
-- params.handleRedirects = params.handleRedirects
assert( url )
assert( method and Utils.propertyIn( { 'GET', 'POST', 'HEAD', 'PUT', 'DELETE' }, method ) )
assert( listener )
assert( params.progress==nil or Utils.propertyIn( { 'upload', 'download' }, params.progress ) )
assert( Utils.propertyIn( { 'text', 'binary' }, params.bodyType ) )
--==--
local url_parts, hrequest
local req_params, resp_body = {}, {}
local event
url_parts = urllib.parse( url )
if url_parts.scheme == 'https' then
hrequest = https.request
else
hrequest = http.request
end
req_params = {
url = url,
method = method,
source = ltn12.source.string( params.body ),
headers = params.headers,
redirect = params.redirect,
sink = ltn12.sink.table( resp_body )
}
local resp_success, resp_code, resp_headers = hrequest( req_params )
--[[
print( 'http:', resp_success, resp_code, resp_headers )
on success:
http: 1 200 <table>
on error:
http: nil closed nil
--]]
event = {
isError=(resp_success==nil),
status=resp_code,
phase='ended',
response=tconcat( resp_body ),
headers=resp_headers
}
if listener then listener( event ) end
end
--====================================================================--
--== Network Facade
--====================================================================--
return {
request = makeHttpRequest
}
|
data:extend({
{
type = "recipe",
name = "wooden-wall",
enabled = true,
normal =
{
ingredients = { {"wood", 4} },
result = "wooden-wall",
result_count = 2,
energy_required = 1,
},
expensive =
{
ingredients = { {"wood", 4} },
result = "wooden-wall",
result_count = 1,
energy_required = 1
}
}
})
|
local fs = require('fs')
local Emitter = require('core').Emitter
local Buffer = require('buffer').Buffer
-- https://www.kernel.org/doc/Documentation/input/joystick-api.txt
local function parse(buffer)
local event = {
time = buffer:readUInt32LE(1),
number = buffer:readUInt8(8),
value = buffer:readUInt16LE(5),
}
local type = buffer:readUInt8(7)
if bit.band(type, 0x80) > 0 then event.init = true end
if bit.band(type, 0x01) > 0 then event.type = "button" end
if bit.band(type, 0x02) > 0 then event.type = "axis" end
return event
end
-- Expose as a nice Lua API
local Joystick = Emitter:extend()
function Joystick:initialize(id)
self:wrap("onOpen")
self:wrap("onRead")
self.id = id
fs.open("/dev/input/js" .. id, "r", "0644", self.onOpen)
end
function Joystick:onOpen(fd)
print("fd", fd)
self.fd = fd
self:startRead()
end
function Joystick:startRead()
fs.read(self.fd, 8, nil, self.onRead)
end
function Joystick:onRead(chunk)
local event = parse(Buffer:new(chunk))
event.id = self.id
self:emit(event.type, event)
if self.fd then self:startRead() end
end
function Joystick:close(callback)
local fd = self.fd
self.fd = nil
fs.close(fd, callback)
end
--------------------------------------------------------------------------------
-- Sample usage
local js = Joystick:new(0)
js:on('button', p);
js:on('axis', p);
js:on('error', function (err)
print("Error", err)
end)
|
-- --------------------------------------------------------
-- non-RainbowMode (normal) background
local file = ...
local anim_data = {
color_add = {0,1,1,0,0,0,1,1,1,1},
diffusealpha = {0.05,0.2,0.1,0.1,0.1,0.1,0.1,0.05,0.1,0.1},
xy = {0,40,80,120,200,280,360,400,480,560},
texcoordvelocity = {{0.03,0.01},{0.03,0.02},{0.03,0.01},{0.02,0.02},{0.03,0.03},{0.02,0.02},{0.03,0.01},{-0.03,0.01},{0.05,0.03},{0.03,0.04}}
}
local t = Def.ActorFrame {
InitCommand=function(self)
self:visible(not ThemePrefs.Get("RainbowMode"))
end,
OnCommand=function(self) self:accelerate(0.8):diffusealpha(1) end,
HideCommand=function(self) self:visible(false) end,
BackgroundImageChangedMessageCommand=function(self)
if not ThemePrefs.Get("RainbowMode") then
self:visible(true):linear(0.6):diffusealpha(1)
local new_file = THEME:GetPathG("", "_VisualStyles/" .. ThemePrefs.Get("VisualTheme") .. "/SharedBackground.png")
self:RunCommandsOnChildren(function(child) child:Load(new_file) end)
else
self:linear(0.6):diffusealpha(0):queuecommand("Hide")
end
end
}
for i=1,10 do
t[#t+1] = Def.Sprite {
Texture=file,
InitCommand=function(self)
self:diffuse(GetHexColor(SL.Global.ActiveColorIndex+anim_data.color_add[i]))
end,
OnCommand=function(self)
self:zoom(1.3):xy(anim_data.xy[i], anim_data.xy[i])
:customtexturerect(0,0,1,1):texcoordvelocity(anim_data.texcoordvelocity[i][1], anim_data.texcoordvelocity[i][2])
:diffusealpha(anim_data.diffusealpha[i])
end,
ColorSelectedMessageCommand=function(self)
self:linear(0.5)
:diffuse(GetHexColor(SL.Global.ActiveColorIndex+anim_data.color_add[i]))
:diffusealpha(anim_data.diffusealpha[i])
end
}
end
return t
|
function init()
message.setHandler("setState", function(_, _, state)
animator.setAnimationState("screen", state)
end)
end
|
--V4 Engines
ACF.RegisterEngineClass("V4", {
Name = "V4 Engine",
})
do -- Diesel Engines
ACF.RegisterEngine("1.9L-V4", "V4", {
Name = "1.9L V4 Diesel",
Description = "Torquey little lunchbox; for those smaller vehicles that don't agree with petrol powerbands",
Model = "models/engines/v4s.mdl",
Sound = "acf_base/engines/i4_diesel2.wav",
Fuel = { Diesel = true },
Type = "GenericDiesel",
Mass = 110,
Torque = 206,
FlywheelMass = 0.3,
RPM = {
Idle = 650,
PeakMin = 950,
PeakMax = 3000,
Limit = 4000,
}
})
ACF.RegisterEngine("3.3L-V4", "V4", {
Name = "3.3L V4 Diesel",
Description = "Compact cube of git; for moderate utility applications",
Model = "models/engines/v4m.mdl",
Sound = "acf_base/engines/i4_dieselmedium.wav",
Fuel = { Diesel = true },
Type = "GenericDiesel",
Mass = 275,
Torque = 600,
FlywheelMass = 1.05,
RPM = {
Idle = 600,
PeakMin = 1050,
PeakMax = 3100,
Limit = 3900,
}
})
end
ACF.SetCustomAttachment("models/engines/v4m.mdl", "driveshaft", Vector(-5.99, 0, 4.85), Angle(0, 90, 90))
ACF.SetCustomAttachment("models/engines/v4s.mdl", "driveshaft", Vector(-4.79, 0, 3.88), Angle(0, 90, 90))
|
local L = (...)
local oop = L:get("lcore.utility.oop")
local sound = L:get("whack.sound")
local game_music
game_music = oop:class()({
state_changing = function(self, to)
if (not to.game_music) then
sound:fade("music-game")
end
end,
state_changed = function(self, from)
if (not from.game_music) then
sound:play("music-game")
end
end
})
return game_music
|
EtcdClientResult = EtcdClientResult or class("EtcdClientResult")
function EtcdClientResult:ctor()
self.fail_event = nil
self.fail_code = 0
self.op_result = nil
end
function EtcdClientResult:prase_op_result(json_str)
self.op_result = rapidjson.decode(json_str)
end
function EtcdClientResult:to_json()
local tb = {
fail_event = self.fail_event,
fail_code = self.fail_code,
op_result = self.op_result,
}
local ret = rapidjson.encode(tb)
return ret
end
|
function map(f, ...)
local t = {}
for k, v in ipairs(...) do
t[#t+1] = f(v)
end
return t
end
function timestwo(n)
return n * 2
end
function squared(n)
return n ^ 2
end
function partial(f, ...)
local args = ...
return function(...)
return f(args, ...)
end
end
timestwo_s = partial(map, timestwo)
squared_s = partial(map, squared)
print(table.concat(timestwo_s{0, 1, 2, 3}, ', '))
print(table.concat(squared_s{0, 1, 2, 3}, ', '))
print(table.concat(timestwo_s{2, 4, 6, 8}, ', '))
print(table.concat(squared_s{2, 4, 6, 8}, ', '))
|
FPP = FPP or {}
FPP.DisconnectedPlayers = FPP.DisconnectedPlayers or {}
local PLAYER = FindMetaTable("Player")
local ENTITY = FindMetaTable("Entity")
/*---------------------------------------------------------------------------
Checks is a model is blocked
---------------------------------------------------------------------------*/
local function isBlocked(model)
if model == "" or not FPP.Settings or not FPP.Settings.FPP_BLOCKMODELSETTINGS1 or
not tobool(FPP.Settings.FPP_BLOCKMODELSETTINGS1.toggle)
or not FPP.BlockedModels or not model then return end
model = string.lower(model or "")
model = string.Replace(model, "\\", "/")
model = string.gsub(model, "[\\/]+", "/")
if string.find(model, "../", 1, true) then
return true, "The model path goes up in the folder tree."
end
local found = FPP.BlockedModels[model]
if tobool(FPP.Settings.FPP_BLOCKMODELSETTINGS1.iswhitelist) and not found then
-- Prop is not in the white list
return true, "The model of this entity is not in the white list!"
elseif not tobool(FPP.Settings.FPP_BLOCKMODELSETTINGS1.iswhitelist) and found then
-- prop is in the black list
return true, "The model of this entity is in the black list!"
end
return false
end
/*---------------------------------------------------------------------------
Prevents spawning a prop or effect when its model is blocked
---------------------------------------------------------------------------*/
local function propSpawn(ply, model)
local blocked, msg = isBlocked(model)
if blocked then
FPP.Notify(ply, msg, false)
return false
end
end
hook.Add("PlayerSpawnObject", "FPP_SpawnEffect", propSpawn) -- prevents precaching
hook.Add("PlayerSpawnProp", "FPP_SpawnProp", propSpawn) -- PlayerSpawnObject isn't always called
hook.Add("PlayerSpawnEffect", "FPP_SpawnEffect", propSpawn)
hook.Add("PlayerSpawnRagdoll", "FPP_SpawnEffect", propSpawn)
/*---------------------------------------------------------------------------
Setting owner when someone spawns something
---------------------------------------------------------------------------*/
if cleanup then
FPP.oldcleanup = FPP.oldcleanup or cleanup.Add
function cleanup.Add(ply, Type, ent)
if not IsValid(ply) or not IsValid(ent) then return FPP.oldcleanup(ply, Type, ent) end
--Set the owner of the entity
ent:CPPISetOwner(ply)
if not tobool(FPP.Settings.FPP_BLOCKMODELSETTINGS1.propsonly) then
local model = ent.GetModel and ent:GetModel()
local blocked, msg = isBlocked(model)
if blocked then
FPP.Notify(ply, msg, false)
ent:Remove()
return
end
end
if FPP.AntiSpam and Type ~= "constraints" and Type ~= "stacks" and Type ~= "AdvDupe2" and (not AdvDupe2 or not AdvDupe2.SpawningEntity) and (not ent.IsVehicle or not ent:IsVehicle()) then
FPP.AntiSpam.CreateEntity(ply, ent, Type == "duplicates")
end
if ent:GetClass() == "gmod_wire_expression2" then
ent:SetCollisionGroup(COLLISION_GROUP_WEAPON)
end
return FPP.oldcleanup(ply, Type, ent)
end
end
if PLAYER.AddCount then
FPP.oldcount = FPP.oldcount or PLAYER.AddCount
function PLAYER:AddCount(Type, ent)
if not IsValid(self) or not IsValid(ent) then return FPP.oldcount(self, Type, ent) end
--Set the owner of the entity
ent:CPPISetOwner(self)
return FPP.oldcount(self, Type, ent)
end
end
local entSetCreator = ENTITY.SetCreator
if entSetCreator then
function ENTITY:SetCreator(ply)
self:CPPISetOwner(ply)
entSetCreator(self, ply)
end
end
if undo then
local AddEntity, SetPlayer, Finish = undo.AddEntity, undo.SetPlayer, undo.Finish
local Undo = {}
local UndoPlayer
function undo.AddEntity(ent, ...)
if not isbool(ent) and IsValid(ent) then table.insert(Undo, ent) end
AddEntity(ent, ...)
end
function undo.SetPlayer(ply, ...)
UndoPlayer = ply
SetPlayer(ply, ...)
end
function undo.Finish(...)
if IsValid(UndoPlayer) then
for _, v in pairs(Undo) do
v:CPPISetOwner(UndoPlayer)
end
end
Undo = {}
UndoPlayer = nil
Finish(...)
end
end
hook.Add("PlayerSpawnedSWEP", "FPP.Spawn.SWEP", function(ply, ent)
ent:CPPISetOwner(ply)
end)
hook.Add("PlayerSpawnedSENT", "FPP.Spawn.SENT", function(ply, ent)
ent:CPPISetOwner(ply)
end)
--------------------------------------------------------------------------------------
--The protecting itself
--------------------------------------------------------------------------------------
FPP.Protect = {}
--Physgun Pickup
function FPP.Protect.PhysgunPickup(ply, ent)
if not tobool(FPP.Settings.FPP_PHYSGUN1.toggle) then if FPP.UnGhost then FPP.UnGhost(ply, ent) end return end
if not ent:IsValid() then return end
local cantouch
local skipReturn = false
if isfunction(ent.PhysgunPickup) then
cantouch = ent:PhysgunPickup(ply, ent)
-- Do not return the value, the gamemode will do this
-- Allows other hooks to run
skipReturn = true
elseif ent.PhysgunPickup ~= nil then
cantouch = ent.PhysgunPickup
else
cantouch = not ent:IsPlayer() and FPP.plyCanTouchEnt(ply, ent, "Physgun")
skipReturn = ent:IsPlayer()
end
if cantouch and FPP.UnGhost then FPP.UnGhost(ply, ent) end
if not cantouch and not skipReturn then return false end
end
hook.Add("PhysgunPickup", "FPP.Protect.PhysgunPickup", FPP.Protect.PhysgunPickup)
--Physgun reload
function FPP.Protect.PhysgunReload(weapon, ply)
if not tobool(FPP.Settings.FPP_PHYSGUN1.reloadprotection) then return end
local ent = ply:GetEyeTrace().Entity
if not IsValid(ent) then return end
local cantouch
local skipReturn = false
if isfunction(ent.OnPhysgunReload) then
cantouch = ent:OnPhysgunReload(ply, ent)
-- Do not return the value, the gamemode will do this
-- Allows other hooks to run
skipReturn = true
elseif ent.OnPhysgunReload ~= nil then
cantouch = ent.OnPhysgunReload
else
cantouch = not ent:IsPlayer() and FPP.plyCanTouchEnt(ply, ent, "Physgun")
end
if cantouch and FPP.UnGhost then FPP.UnGhost(ply, ent) end
if not cantouch and not skipReturn then return false end
-- Double reload breaks when returning true here
end
hook.Add("OnPhysgunReload", "FPP.Protect.PhysgunReload", FPP.Protect.PhysgunReload)
function FPP.PhysgunFreeze(weapon, phys, ent, ply)
if isfunction(ent.OnPhysgunFreeze) then
local val = ent:OnPhysgunFreeze(weapon, phys, ent, ply)
-- Do not return the value, the gamemode will do this
if val ~= nil then return end
elseif ent.OnPhysgunFreeze ~= nil then
return ent.OnPhysgunFreeze
end
end
hook.Add("OnPhysgunFreeze", "FPP.Protect.PhysgunFreeze", FPP.PhysgunFreeze)
--Gravgun pickup
function FPP.Protect.GravGunPickup(ply, ent)
if not tobool(FPP.Settings.FPP_GRAVGUN1.toggle) then return end
if not IsValid(ent) then return end -- You don't want a cross when looking at the floor while holding right mouse
if ent:IsPlayer() then return end
local cantouch
if isfunction(ent.GravGunPickup) then
cantouch = ent:GravGunPickup(ply, ent)
elseif ent.GravGunPickup ~= nil then
cantouch = ent.GravGunPickup
else
cantouch = not ent:IsPlayer() and FPP.plyCanTouchEnt(ply, ent, "Gravgun")
end
if cantouch and FPP.UnGhost then FPP.UnGhost(ply, ent) end
if cantouch == false then DropEntityIfHeld(ent) end
end
hook.Add("GravGunOnPickedUp", "FPP.Protect.GravGunPickup", FPP.Protect.GravGunPickup)
function FPP.Protect.CanGravGunPickup(ply, ent)
if not tobool(FPP.Settings.FPP_GRAVGUN1.toggle) or not IsValid(ent) then return end
if isfunction(ent.GravGunPickup) then
-- Function name different than gamemode's (GravGunPickup vs GravGunPickupAllowed)
-- Override FPP's behavior when implemented
local val = ent:GravGunPickup(ply, ent)
if val ~= nil then
if val == false then return false end
return
end
elseif ent.GravGunPickup ~= nil then
if ent.GravGunPickup == false then return false end
return
end
local cantouch = FPP.plyCanTouchEnt(ply, ent, "Gravgun")
if cantouch == false then return false end
end
hook.Add("GravGunPickupAllowed", "FPP.Protect.CanGravGunPickup", FPP.Protect.CanGravGunPickup)
--Gravgun punting
function FPP.Protect.GravGunPunt(ply, ent)
if tobool(FPP.Settings.FPP_GRAVGUN1.noshooting) then DropEntityIfHeld(ent) return false end
if not IsValid(ent) then DropEntityIfHeld(ent) return end
local cantouch
local skipReturn = false
if isfunction(ent.GravGunPunt) then
cantouch = ent:GravGunPunt(ply, ent)
-- Do not return the value, the gamemode will do this
-- Allows other hooks to run
skipReturn = true
elseif ent.GravGunPunt ~= nil then
cantouch = ent.GravGunPunt
else
cantouch = not ent:IsPlayer() and FPP.plyCanTouchEnt(ply, ent, "Gravgun")
end
if cantouch and FPP.UnGhost then FPP.UnGhost(ply, ent) end
if not cantouch then DropEntityIfHeld(ent) end
if not cantouch and not skipReturn then return false end
end
hook.Add("GravGunPunt", "FPP.Protect.GravGunPunt", FPP.Protect.GravGunPunt)
--PlayerUse
function FPP.Protect.PlayerUse(ply, ent)
if not tobool(FPP.Settings.FPP_PLAYERUSE1.toggle) then return end
if not IsValid(ent) then return end
local cantouch
local skipReturn = false
if isfunction(ent.PlayerUse) then
cantouch = ent:PlayerUse(ply, ent)
-- Do not return the value, the gamemode will do this
-- Allows other hooks to run
skipReturn = true
elseif ent.PlayerUse ~= nil then
cantouch = ent.PlayerUse
else
cantouch = not ent:IsPlayer() and FPP.plyCanTouchEnt(ply, ent, "PlayerUse")
end
if cantouch and FPP.UnGhost then FPP.UnGhost(ply, ent) end
if not cantouch and not skipReturn then return false end
end
hook.Add("PlayerUse", "FPP.Protect.PlayerUse", FPP.Protect.PlayerUse)
--EntityDamage
function FPP.Protect.EntityDamage(ent, dmginfo)
if not IsValid(ent) then return end
local inflictor = dmginfo:GetInflictor()
local attacker = dmginfo:GetAttacker()
local amount = dmginfo:GetDamage()
if isfunction(ent.EntityDamage) then
local val = ent:EntityDamage(ent, inflictor, attacker, amount, dmginfo)
-- Do not return the value, the gamemode will do this
if val ~= nil then return end
elseif ent.EntityDamage ~= nil then
return ent.EntityDamage
end
if not tobool(FPP.Settings.FPP_ENTITYDAMAGE1.toggle) then return end
-- Don't do anything about players
if ent:IsPlayer() then return end
if not attacker:IsPlayer() then
if not tobool(FPP.Settings.FPP_ENTITYDAMAGE1.protectpropdamage) then return end
local attackerOwner = attacker:CPPIGetOwner()
local entOwner = ent:CPPIGetOwner()
if IsValid(attackerOwner) and IsValid(entOwner) then
local cantouch = FPP.plyCanTouchEnt(attackerOwner, ent, "EntityDamage")
if not cantouch then
dmginfo:SetDamage(0)
ent.FPPAntiDamageWorld = ent.FPPAntiDamageWorld or 0
ent.FPPAntiDamageWorld = ent.FPPAntiDamageWorld + 1
timer.Simple(1, function()
if not ent.FPPAntiDamageWorld then return end
ent.FPPAntiDamageWorld = ent.FPPAntiDamageWorld - 1
if ent.FPPAntiDamageWorld == 0 then
ent.FPPAntiDamageWorld = nil
end
end)
end
return
end
if attacker == game.GetWorld() and ent.FPPAntiDamageWorld then
dmginfo:SetDamage(0)
end
return
end
local cantouch = FPP.plyCanTouchEnt(attacker, ent, "EntityDamage")
if not cantouch then dmginfo:SetDamage(0) end
end
hook.Add("EntityTakeDamage", "FPP.Protect.EntityTakeDamage", FPP.Protect.EntityDamage)
--Toolgun
--for advanced duplicator, you can't use the IsWeapon function
local allweapons = {
["weapon_crowbar"] = true,
["weapon_physgun"] = true,
["weapon_physcannon"] = true,
["weapon_pistol"] = true,
["weapon_stunstick"] = true,
["weapon_357"] = true,
["weapon_smg1"] = true,
["weapon_ar2"] = true,
["weapon_shotgun"] = true,
["weapon_crossbow"] = true,
["weapon_frag"] = true,
["weapon_rpg"] = true,
["gmod_camera"] = true,
["gmod_tool"] = true,
["weapon_bugbait"] = true}
timer.Simple(5, function()
for _, v in ipairs(weapons.GetList()) do
if v.ClassName then allweapons[string.lower(v.ClassName or "")] = true end
end
end)
local invalidToolData = {
["model"] = {
"*",
"\\"
},
["material"] = {
"*",
"\\",
" ",
"effects/highfive_red",
"pp/copy",
".v",
"skybox/"
},
["sound"] = {
"?",
" "
},
["soundname"] = {
" ",
"?"
},
["tracer"] = {
"dof_node"
},
["door_class"] = {
"env_laser"
},
-- Limit wheel torque
["rx"] = 360,
["ry"] = 360,
["rz"] = 360
}
invalidToolData.override = invalidToolData.material
invalidToolData.rope_material = invalidToolData.material
function FPP.Protect.CanTool(ply, trace, tool, ENT)
local ignoreGeneralRestrictTool = false
local SteamID = ply:SteamID()
FPP.RestrictedToolsPlayers = FPP.RestrictedToolsPlayers or {}
if FPP.RestrictedToolsPlayers[tool] and FPP.RestrictedToolsPlayers[tool][SteamID] ~= nil then--Player specific
if FPP.RestrictedToolsPlayers[tool][SteamID] == false then
FPP.Notify(ply, "Toolgun restricted for you!", false)
return false
elseif FPP.RestrictedToolsPlayers[tool][SteamID] == true then
ignoreGeneralRestrictTool = true --If someone is allowed, then he's allowed even though he's not admin, so don't check for further restrictions
end
end
if not ignoreGeneralRestrictTool then
local Group = FPP.Groups[FPP.GroupMembers[SteamID]] or FPP.Groups[ply:GetUserGroup()] or FPP.Groups.default -- What group is the player in. If not in a special group, then he's in default group
local CanGroup = true
if Group and ((Group.allowdefault and table.HasValue(Group.tools, tool)) or -- If the tool is on the BLACKLIST or
(not Group.allowdefault and not table.HasValue(Group.tools, tool))) then -- If the tool is NOT on the WHITELIST
CanGroup = false
end
if FPP.RestrictedTools[tool] then
if tonumber(FPP.RestrictedTools[tool].admin) == 1 and not ply:IsAdmin() then
FPP.Notify(ply, "Toolgun restricted! Admin only!", false)
return false
elseif tonumber(FPP.RestrictedTools[tool].admin) == 2 and not ply:IsSuperAdmin() then
FPP.Notify(ply, "Toolgun restricted! Superadmin only!", false)
return false
elseif (tonumber(FPP.RestrictedTools[tool].admin) == 1 and ply:IsAdmin()) or (tonumber(FPP.RestrictedTools[tool].admin) == 2 and ply:IsSuperAdmin()) then
CanGroup = true -- If the person is not in the BUT has admin access, he should be able to use the tool
end
if FPP.RestrictedTools[tool]["team"] and #FPP.RestrictedTools[tool]["team"] > 0 and not table.HasValue(FPP.RestrictedTools[tool]["team"], ply:Team()) then
FPP.Notify(ply, "Toolgun restricted! incorrect team!", false)
return false
end
end
if not CanGroup then
FPP.Notify(ply, "Toolgun restricted! incorrect group!", false)
return false
end
end
-- Anti server crash
if IsValid(ply:GetActiveWeapon()) and ply:GetActiveWeapon().GetToolObject and ply:GetActiveWeapon():GetToolObject() then
local toolObj = ply:GetActiveWeapon():GetToolObject()
for t, block in pairs(invalidToolData) do
local clientInfo = string.lower(toolObj:GetClientInfo(t) or "")
-- Check for number limits
if isnumber(block) then
local num = tonumber(clientInfo) or 0
if num > block or num < -block then
FPP.Notify(ply, "The client settings of the tool are invalid!", false)
return false
end
continue
end
for _, item in pairs(block) do
if string.find(clientInfo, item, 1, true) then
FPP.Notify(ply, "The client settings of the tool are invalid!", false)
return false
end
end
end
end
local ent = IsEntity(ENT) and ENT or trace and trace.Entity
if IsEntity(ent) and isfunction(ent.CanTool) and ent:GetClass() ~= "gmod_cameraprop" and ent:GetClass() ~= "gmod_rtcameraprop" then
local val = ent:CanTool(ply, trace, tool, ENT)
-- Do not return the value, the gamemode will do this
if val ~= nil then return end
elseif IsEntity(ent) and ent.CanTool ~= nil and ent:GetClass() ~= "gmod_cameraprop" and ent:GetClass() ~= "gmod_rtcameraprop" then
return ent.CanTool
end
if tobool(FPP.Settings.FPP_TOOLGUN1.toggle) and IsValid(ent) then
local cantouch = FPP.plyCanTouchEnt(ply, ent, "Toolgun")
if not cantouch then return false end
end
if tool ~= "adv_duplicator" and tool ~= "duplicator" and tool ~= "advdupe2" then return end
if not ENT and not FPP.AntiSpam.DuplicatorSpam(ply) then return false end
local EntTable =
(tool == "adv_duplicator" and ply:GetActiveWeapon():GetToolObject().Entities) or
(tool == "advdupe2" and ply.AdvDupe2 and ply.AdvDupe2.Entities) or
(tool == "duplicator" and ply.CurrentDupe and ply.CurrentDupe.Entities)
if not EntTable then return end
for k, v in pairs(EntTable) do
local lowerClass = string.lower(v.Class)
if tobool(FPP.Settings.FPP_TOOLGUN1.duplicatenoweapons) and
(not ply:IsAdmin() or (ply:IsAdmin() and not tobool(FPP.Settings.FPP_TOOLGUN1.spawnadmincanweapon))) and
(allweapons[lowerClass] or string.find(lowerClass, "ai_") == 1 or string.find(lowerClass, "item_ammo_") == 1) then
FPP.Notify(ply, "Duplicating blocked entity " .. lowerClass, false)
EntTable[k] = nil
end
if tobool(FPP.Settings.FPP_TOOLGUN1.duplicatorprotect) and (not ply:IsAdmin() or (ply:IsAdmin() and not tobool(FPP.Settings.FPP_TOOLGUN1.spawnadmincanblocked))) then
local setspawning = tobool(FPP.Settings.FPP_TOOLGUN1.spawniswhitelist)
if not tobool(FPP.Settings.FPP_TOOLGUN1.spawniswhitelist) and FPP.Blocked.Spawning1[lowerClass] then
FPP.Notify(ply, "Duplicating blocked entity " .. lowerClass, false)
EntTable[k] = nil
end
-- if the whitelist is on you can't spawn it unless it's found
if tobool(FPP.Settings.FPP_TOOLGUN1.spawniswhitelist) and FPP.Blocked.Spawning1[lowerClass] then
setspawning = false
end
if setspawning then
FPP.Notify(ply, "Duplicating blocked entity " .. lowerClass, false)
EntTable[k] = nil
end
end
end
return
end
hook.Add("CanTool", "FPP.Protect.CanTool", FPP.Protect.CanTool)
function FPP.Protect.CanEditVariable(ent, ply, key, varVal, editTbl)
local val = FPP.Protect.CanProperty(ply, "editentity", ent)
if val ~= nil then return val end
end
hook.Add("CanEditVariable", "FPP.Protect.CanEditVariable", FPP.Protect.CanEditVariable)
function FPP.Protect.CanProperty(ply, property, ent)
-- Use Toolgun because I'm way too lazy to make a new type
local cantouch = FPP.plyCanTouchEnt(ply, ent, "Toolgun")
if not cantouch then return false end
end
hook.Add("CanProperty", "FPP.Protect.CanProperty", FPP.Protect.CanProperty)
function FPP.Protect.CanDrive(ply, ent)
-- Use Toolgun because I'm way too lazy to make a new type
local cantouch = FPP.plyCanTouchEnt(ply, ent, "Toolgun")
if not cantouch then return false end
end
hook.Add("CanDrive", "FPP.Protect.CanDrive", FPP.Protect.CanDrive)
local function freezeDisconnected(ply)
local SteamID = ply:SteamID()
for _, ent in ipairs(ents.GetAll()) do
local physObj = ent:GetPhysicsObject()
if ent.FPPOwnerID ~= SteamID or ent:GetPersistent() or not physObj:IsValid() then continue end
physObj:EnableMotion(false)
end
end
--Player disconnect, not part of the Protect table.
function FPP.PlayerDisconnect(ply)
if not IsValid(ply) then return end
local SteamID = ply:SteamID()
FPP.DisconnectedPlayers[SteamID] = true
if tobool(FPP.Settings.FPP_GLOBALSETTINGS1.freezedisconnected) then
freezeDisconnected(ply)
end
if ply.FPPFallbackOwner then
-- FPP.DisconnectedOriginalOwners = FPP.DisconnectedOriginalOwners or {}
-- FPP.DisconnectedOriginalOwners[SteamID] = {props = {}}
local fallback = player.GetBySteamID(ply.FPPFallbackOwner)
for _, v in ipairs(ents.GetAll()) do
if v.FPPOwnerID ~= SteamID or v:GetPersistent() then continue end
v.FPPFallbackOwner = ply.FPPFallbackOwner
if IsValid(fallback) then
v:CPPISetOwner(fallback)
end
-- table.insert(FPP.DisconnectedOriginalOwners[SteamID].props, v)
-- Only set when not set already
-- this prevents the original owner being set again
-- when the fallback hands their props over to a second
-- (or third, or nth) fallback
if v:GetNW2String("FPP_OriginalOwner", "") == "" then
v:SetNW2String("FPP_OriginalOwner", SteamID)
end
end
-- Create disconnect timer if fallback is not in server
-- ownership is transferred immediately when fallback is in server
if IsValid(fallback) then
return
end
end
if not tobool(FPP.Settings.FPP_GLOBALSETTINGS1.cleanupdisconnected) or
not FPP.Settings.FPP_GLOBALSETTINGS1.cleanupdisconnectedtime then
return
end
if ply:IsAdmin() and not tobool(FPP.Settings.FPP_GLOBALSETTINGS1.cleanupadmin) then return end
timer.Simple(FPP.Settings.FPP_GLOBALSETTINGS1.cleanupdisconnectedtime, function()
if not tobool(FPP.Settings.FPP_GLOBALSETTINGS1.cleanupdisconnected) then return end -- Settings can change in time.
for _, v in ipairs(player.GetAll()) do
if v:SteamID() == SteamID then
return
end
end
for _, v in ipairs(ents.GetAll()) do
if v.FPPOwnerID ~= SteamID or v:GetPersistent() then continue end
v:Remove()
end
FPP.DisconnectedPlayers[SteamID] = nil -- Player out of the Disconnect table
end)
end
hook.Add("PlayerDisconnected", "FPP.PlayerDisconnect", FPP.PlayerDisconnect)
-- PlayerInitialspawn, the props he had left before will now be theirs again
function FPP.PlayerInitialSpawn(ply)
local RP = RecipientFilter()
local SteamID = ply:SteamID()
timer.Simple(5, function()
if not IsValid(ply) then return end
RP:AddAllPlayers()
RP:RemovePlayer(ply)
net.Start("FPP_CheckBuddy") --Message everyone that a new player has joined
net.WriteEntity(ply)
net.Send(RP)
end)
local entities = {}
if FPP.DisconnectedPlayers[SteamID] then -- Check if the player has rejoined within the auto remove time
for _, v in ipairs(ents.GetAll()) do
if (v.FPPOwnerID == SteamID or v.FPPFallbackOwner == SteamID or v:GetNW2String("FPP_OriginalOwner") == SteamID) then
v.FPPFallbackOwner = nil
v:CPPISetOwner(ply)
table.insert(entities, v)
if v:GetNW2String("FPP_OriginalOwner", "") ~= "" then
v:SetNW2String("FPP_OriginalOwner", "")
end
end
end
end
local plys = {}
for _, v in ipairs(player.GetAll()) do if v ~= ply then table.insert(plys, v) end end
timer.Create("FPP_recalculate_cantouch_" .. ply:UserID(), 0, 1, function()
FPP.recalculateCanTouch({ply}, ents.GetAll())
end)
end
hook.Add("PlayerInitialSpawn", "FPP.PlayerInitialSpawn", FPP.PlayerInitialSpawn)
local backup = ENTITY.FireBullets
local blockedEffects = {"particleeffect", "smoke", "vortdispel", "helicoptermegabomb"}
function ENTITY:FireBullets(bullet, ...)
if not bullet.TracerName then return backup(self, bullet, ...) end
if table.HasValue(blockedEffects, string.lower(bullet.TracerName)) then
bullet.TracerName = ""
end
return backup(self, bullet, ...)
end
-- Hydraulic exploit workaround
-- One should not be able to constrain doors to anything
local canConstrain = constraint.CanConstrain
local disallowedConstraints = {
["prop_door_rotating"] = true,
["func_door"] = true,
["func_breakable_surf"] = true
}
function constraint.CanConstrain(ent, bone)
if IsValid(ent) and disallowedConstraints[string.lower(ent:GetClass())] then return false end
return canConstrain(ent, bone)
end
-- Crash exploit workaround
local setAngles = ENTITY.SetAngles
function ENTITY:SetAngles(ang)
if not ang then return setAngles(self, ang) end
ang.p = ang.p % 360
ang.y = ang.y % 360
ang.r = ang.r % 360
return setAngles(self, ang)
end
|
#!/usr/bin/env tarantool
test = require("sqltester")
test:plan(8)
--!./tcltestrunner.lua
-- 2001 September 15
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, never taking more than you give.
--
-------------------------------------------------------------------------
-- This file implements regression tests for SQLite library. The
-- focus of this file is the ability to specify table and column names
-- as quoted strings.
--
-- $Id: quote.test,v 1.7 2007/04/25 11:32:30 drh Exp $
-- ["set","testdir",[["file","dirname",["argv0"]]]]
-- ["source",[["testdir"],"\/tester.tcl"]]
-- MUST_WORK_TEST
--Create a table with a strange name and with strange column names.
test:do_catchsql_test(
"quote-1.0",
[[
--- CREATE TABLE '@abc' ( '#xyz' int PRIMARY KEY, '!pqr' text );
CREATE TABLE "abc5_" (id INT PRIMARY KEY, "#xyz" INT UNIQUE, "!pqr" TEXT );
]], {
-- <quote-1.0>
0
-- </quote-1.0>
})
-- Insert, update and query the table.
--
test:do_catchsql_test(
"quote-1.1",
[[
INSERT INTO "abc5_" VALUES(1, 5,'hello')
]], {
-- <quote-1.1>
0
-- </quote-1.1>
})
test:do_catchsql_test(
"quote-1.2.1",
[[
SELECT * FROM "abc5_"
]], {
-- <quote-1.2.1>
0, {1, 5, "hello"}
-- </quote-1.2.1>
})
test:do_catchsql_test(
"quote-1.3",
[[
SELECT "abc5_"."!pqr", "abc5_"."#xyz"+5 FROM "abc5_"
]], {
-- <quote-1.3>
0, {"hello", 10}
-- </quote-1.3>
})
test:do_catchsql_test(
"quote-1.3.1",
[[
SELECT "!pqr", "#xyz"+5 FROM "abc5_"
]], {
-- <quote-1.3.2>
0, {"hello", 10}
-- </quote-1.3.2>
})
test:do_catchsql_test(
"quote-1.4",
[[
UPDATE "abc5_" SET "#xyz"=11
]], {
-- <quote-1.4>
0
-- </quote-1.4>
})
test:do_catchsql_test(
"quote-1.5",
[[
SELECT "abc5_"."!pqr", "abc5_"."#xyz"+5 FROM "abc5_"
]], {
-- <quote-1.5>
0, {"hello", 16}
-- </quote-1.5>
})
-- Drop the table with the strange name.
--
test:do_catchsql_test(
"quote-1.6",
[[
DROP TABLE "abc5_"
]], {
-- <quote-1.6>
0
-- </quote-1.6>
})
test:finish_test()
|
local createEnum = import("../createEnum")
return createEnum("VerticalAlignment", {
Center = 0,
Top = 1,
Bottom = 2,
})
|
-- LocaleKeysCleanUp.lua
-- Author: Rubgrsch
-- License: MIT
-- This code helps you find unused localeKeys in your WoW addon.
-- What may cause false positive
-- 1. keys in comments
-- 2. keys separated among lines
-- 3. keys doesn't match any patterns, e.g. L[ThisIsVariable]
-- Notes:
-- 1. Filenames in output only suggest one file that contains it. You need to search in files.
-- 2. The code is for Windows OS. You can find OS specific code with searching "io.popen".
-- 3. The code will not find redundant keys among locale files.
-- codePath is the dir (or file) of your addon. localePathT is an array of locale files or dirs.
-- exceptionPathT is an array of files or dirs that should't be processed (e.g. Libraries).
-- localePatternT is an array of regex patterns that match your locale keys.
-- You should use absolute path.
local codePath = [[path\to\elvui-master]]
local localePathT = {[[path\to\elvui-master\ElvUI_Config\locales]],[[path\to\elvui-master\ElvUI\locales]]}
local exceptionPathT = {[[path\to\elvui-master\ElvUI_Config\Libraries]],[[path\to\elvui-master\ElvUI\Libraries]]}
local localePatternT = {'L%[%".-%"%]', "L%[%'.-%'%]"}
-- Start of code --
local strfind, pairs, ipairs, strmatch, print = string.find, pairs, ipairs, string.match, print
localePathT = localePathT or {}
local codefilenameT = {} -- filenames of lua source files, [filename] = true
for filename in io.popen([[dir ]]..codePath..[[ /b /s /a-d]]):lines() do -- Change this if you're not on Windows
if strfind(filename,"%.lua$") then codefilenameT[filename] = true end
end
local localefilenameT = {} -- filenames of locale files, [filename] = true
for _,path in ipairs(localePathT) do
for filename in io.popen([[dir ]]..path..[[ /b /s /a-d]]):lines() do -- Change this if you're not on Windows
if strfind(filename,"%.lua$") then localefilenameT[filename] = true end
end
end
-- Remove exceptions
if exceptionPathT and type(exceptionPathT) == "table" then
for _,exceptionName in ipairs(exceptionPathT) do
for filename in pairs(codefilenameT) do
if strfind(filename,exceptionName,1,true) then codefilenameT[filename] = nil end
end
for filename in pairs(localefilenameT) do
if strfind(filename,exceptionName,1,true) then localefilenameT[filename] = nil end
end
end
end
-- Remove locale files in lua source file
for _,exceptionName in ipairs(localePathT) do
for filename in pairs(codefilenameT) do
if strfind(filename,exceptionName,1,true) then codefilenameT[filename] = nil end
end
end
local function matchKey(fileNameTbl)
local tbl = {}
for filename in pairs(fileNameTbl) do
local file = io.open(filename, "r")
for line in file:lines() do
-- Multi locales can exist in the same line, use a loop instead
local left,right,flag = 1
repeat
flag = 0
for _,pattern in ipairs(localePatternT) do
local l,r = strfind(line,pattern,left)
if l then
left,right = l,r
tbl[strmatch(line,pattern,left)] = filename
left = right + 1
flag = 1
break
end
end
until flag == 0
end
file:close()
end
return tbl
end
-- locale keys found in lua source files, [key] = filename
local codeKey = matchKey(codefilenameT)
-- locale keys found in locale files, [key] = filename
local localeKey = matchKey(localefilenameT)
-- Output
local count = 0
for key,filename in pairs(codeKey) do
if not localeKey[key] then
print("Unlocalized Key \t"..key.."\t in code file: "..filename)
count = count + 1
end
end
for key,filename in pairs(localeKey) do
if not codeKey[key] then
print("Unused Key \t"..key.."\t in locale file: "..filename)
count = count + 1
end
end
if count == 0 then
print("No unused key found!")
else
print("Found "..count.."!")
end
|
return ondemand('aurora.fs')
|
local ParticlesPlus = {}
local Presets = {}
local Internal = {
Smoke = {};
}
local TweenService = game:GetService("TweenService")
local RunService = game:GetService("RunService")
local DebrisService = game:GetService("Debris")
local HTTPS = game:GetService("HttpService")
local function shallowCopy(original)
local copy = {}
for key, value in pairs(original) do
copy[key] = value
end
return copy
end
local CreateWithData = function(self, data)
local particle = shallowCopy(self)
particle.CreateWithData = nil
for k, v in ipairs(data) do
particle[k] = v
end
local returnParticle = newproxy(true)
return setmetatable(getmetatable(returnParticle), {
__metatable = {};
__index = particle;
__newindex = function()
error("Attempted to edit properties of particle object.", 2)
end;
})
end
local folder = Instance.new("Folder")
folder.Name = "Particles"
folder.Parent = workspace
Presets.Explosion = {
Position = Vector3.new();
Color = Color3.new(0.815686, 0.760784, 0.121569);
Transparency = 0.5;
MinRadius = 2;
MaxRadius = 10;
Time = 1;
Ring = false;
Callback = function() end;
Fire = function(self)
local Explosion = Instance.new("Part")
Explosion.Shape = Enum.PartType.Ball
Explosion.Color = self.Color
Explosion.Size = Vector3.new(self.MinRadius, self.MinRadius, self.MinRadius)
Explosion.Position = self.Position
Explosion.Anchored = true
Explosion.CanCollide = false
Explosion.Transparency = self.Transparency
Explosion.Material = Enum.Material.SmoothPlastic
Explosion.Parent = folder
local action = TweenService:Create(Explosion, TweenInfo.new(self.Time), {Size = Vector3.new(self.MaxRadius, self.MaxRadius, self.MaxRadius)})
action:Play()
action.Completed:Connect(function()
local action2 = TweenService:Create(Explosion, TweenInfo.new(0.5), {Transparency = 1})
action2:Play()
action2.Completed:Connect(function()
Explosion:Destroy()
self.Callback()
end)
end)
end;
CreateWithData = CreateWithData;
}
Presets.Smoke = {
Position = Vector3.new();
Color = Color3.new(0.156863, 0.156863, 0.156863);
Transparency = 0;
SmokeSize = 2;
SmokeBaseRadius = 3;
Speed = 5;
Density = 4;
Callback = function() end;
SmokeID = HTTPS:GenerateGUID();
Start = function(self)
if not Internal.Smoke[self.SmokeID] then
Internal.Smoke[self.SmokeID] = {
connection = nil;
isEnabled = false;
}
end
local Smoke = Instance.new("Folder")
Smoke.Parent = folder
local function spawnSmoke()
local function r()
return (math.random()-0.5) * self.SmokeBaseRadius * 2
end
local smoke = Instance.new("Part")
smoke.Shape = Enum.PartType.Ball
smoke.Color = self.Color
smoke.Transparency = self.Transparency
smoke.Position = self.Position + Vector3.new(r(), 0, r())
smoke.Material = Enum.Material.Pebble
smoke.CanCollide = false
smoke.Anchored = true
local distance = (smoke.Position - self.Position).Magnitude
smoke.Size = Vector3.new(self.SmokeSize, self.SmokeSize, self.SmokeSize) * math.min((1 / math.log(3 / distance, 2)), 1)
smoke.Parent = Smoke
DebrisService:AddItem(smoke, math.log(3 / distance, 2) + 0.1)
end
Internal.Smoke[self.SmokeID].isEnabled = true
spawn(function()
while wait() do
if Internal.Smoke[self.SmokeID].isEnabled then
for i = 1, self.Density do
spawnSmoke()
end
else
break
end
end
end)
if Internal.Smoke[self.SmokeID].connection then
Internal.Smoke[self.SmokeID].connection:Disconnect()
end
Internal.Smoke[self.SmokeID].connection = RunService.Heartbeat:Connect(function(dt)
for i, v in ipairs(Smoke:GetChildren()) do
v.Position = v.Position + Vector3.new(0, dt*self.Speed, 0)
end
end)
end;
Stop = function(self)
Internal.Smoke[self.SmokeID].isEnabled = false
self.Callback()
end;
CreateWithData = CreateWithData;
}
ParticlesPlus.NewParticle = function(name, data)
assert(Presets[name], "Invalid particle. Non-existant.")
return Presets[name]:CreateWithData(data)
end
return ParticlesPlus
|
-- Copyright 2014-2015 Greentwip. All Rights Reserved.
local opening = import("app.core.gameplay.control.layout_base").create("opening")
local sprite = import("app.core.graphical.sprite")
function opening:onLoad()
local initiate = cc.CallFunc:create(function()
self:opening_intro_a()
end)
local sequence = cc.Sequence:create(initiate, nil)
self:runAction(sequence)
--audio.playMusic("sounds/bgm_title.mp3", true)
-- self variables
self.triggered_ = false
end
function opening:opening_intro_a()
self.greentwip_logo_ = sprite:create("sprites/gameplay/screens/opening/greentwip/greentwip_logo", cc.p(0, 0))
:setPosition(cc.p(0,0))
:addTo(self)
local actions = {}
actions[#actions + 1] = {name = "greentwip_logo", animation = {name = "greentwip_logo", forever = false, delay = 0.20} }
self.greentwip_logo_:load_actions_set(actions, false)
local pre_callback = cc.CallFunc:create(function()
self.greentwip_logo_:run_action("greentwip_logo")
end)
local duration = cc.DelayTime:create(self.greentwip_logo_:get_action_duration("greentwip_logo"))
local post_callback = cc.CallFunc:create(function()
self.greentwip_logo_:stopAllActions()
self.greentwip_logo_:removeSelf()
self.greentwip_logo_ = nil
self:getApp():enterScene("screens.title", "FADE", 1)
end)
local sequence = cc.Sequence:create(pre_callback, duration, post_callback, nil)
self:runAction(sequence)
end
function opening:step(dt)
-- if not self.triggered_ then
-- if cc.key_pressed(cc.key_code_.start) then
-- self.triggered_ = true
-- audio.playSound("sounds/sfx_selected.mp3")
-- self:getApp():enterScene("gameplay.stage_select", "FADE", 1)
-- end
-- end
self:post_step(dt)
return self
end
return opening
|
-----------------------------------------------------------------------------------------------
local title = "Mole Hills"
local version = "0.0.3"
local mname = "molehills"
-----------------------------------------------------------------------------------------------
-- Idea by Sokomine
-- Code & textures by Mossmanikin
abstract_molehills = {}
dofile(minetest.get_modpath("molehills").."/molehills_settings.txt")
-----------------------------------------------------------------------------------------------
-- NoDe
-----------------------------------------------------------------------------------------------
minetest.register_node("molehills:molehill",{
drawtype = "nodebox",
description = "Mole Hill",
inventory_image = "molehills_side.png",
tiles = {
"molehills_dirt.png",--"molehill_top.png",
"molehills_dirt.png",--"molehill_top.png",
"molehills_dirt.png"--"molehill_side.png"
},
paramtype = "light",
node_box = {
type = "fixed",
fixed = {
-- { left, bottom, front, right, top, back}
{-2/16, -3/16, -1/16, 2/16, -2/16, 1/16},
{-1/16, -3/16, -2/16, 1/16, -2/16, 2/16},
-- { left, bottom, front, right, top, back}
{-4/16, -4/16, -2/16, 4/16, -3/16, 2/16},
{-2/16, -4/16, -4/16, 2/16, -3/16, 4/16},
{-3/16, -4/16, -3/16, 3/16, -3/16, 3/16},
-- { left, bottom, front, right, top, back}
{-5/16, -5/16, -2/16, 5/16, -4/16, 2/16},
{-2/16, -5/16, -5/16, 2/16, -4/16, 5/16},
{-4/16, -5/16, -4/16, 4/16, -4/16, 4/16},
-- { left, bottom, front, right, top, back}
{-6/16, -6/16, -2/16, 6/16, -5/16, 2/16},
{-2/16, -6/16, -6/16, 2/16, -5/16, 6/16},
{-5/16, -6/16, -4/16, 5/16, -5/16, 4/16},
{-4/16, -6/16, -5/16, 4/16, -5/16, 5/16},
-- { left, bottom, front, right, top, back}
{-7/16, -7/16, -3/16, 7/16, -6/16, 3/16},
{-3/16, -7/16, -7/16, 3/16, -6/16, 7/16},
{-6/16, -7/16, -4/16, 6/16, -6/16, 4/16},
{-4/16, -7/16, -6/16, 4/16, -6/16, 6/16},
{-5/16, -7/16, -5/16, 5/16, -6/16, 5/16},
-- { left, bottom, front, right, top, back}
--[[b]] {-1/2 , -1/2 , -3/16, 1/2 , -7/16, 3/16}, -- left to right
--[[o]] {-3/16, -1/2 , -1/2 , 3/16, -7/16, 1/2 }, -- front to back
--[[t]] {-7/16, -1/2 , -5/16, 7/16, -7/16, 5/16},
--[[t]] {-5/16, -1/2 , -7/16, 5/16, -7/16, 7/16},
--[[m]] {-6/16, -1/2 , -6/16, 6/16, -7/16, 6/16}, -- mid
},
},
selection_box = {
type = "fixed",
fixed = {-1/2, -1/2, -1/2, 1/2, 2/16, 1/2},
},
groups = {crumbly=3},
sounds = default.node_sound_dirt_defaults(),
})
-----------------------------------------------------------------------------------------------
-- CRaFTiNG
-----------------------------------------------------------------------------------------------
minetest.register_craft({ -- molehills --> dirt
output = "default:dirt",
recipe = {
{"molehills:molehill","molehills:molehill"},
{"molehills:molehill","molehills:molehill"},
}
})
-----------------------------------------------------------------------------------------------
-- GeNeRaTiNG
-----------------------------------------------------------------------------------------------
abstract_molehills.place_molehill = function(pos)
local right_here = {x=pos.x , y=pos.y+1, z=pos.z }
if minetest.get_node({x=pos.x+1, y=pos.y, z=pos.z }).name ~= "air"
and minetest.get_node({x=pos.x-1, y=pos.y, z=pos.z }).name ~= "air"
and minetest.get_node({x=pos.x , y=pos.y, z=pos.z+1}).name ~= "air"
and minetest.get_node({x=pos.x , y=pos.y, z=pos.z-1}).name ~= "air"
and minetest.get_node({x=pos.x+1, y=pos.y, z=pos.z+1}).name ~= "air"
and minetest.get_node({x=pos.x+1, y=pos.y, z=pos.z-1}).name ~= "air"
and minetest.get_node({x=pos.x-1, y=pos.y, z=pos.z+1}).name ~= "air"
and minetest.get_node({x=pos.x-1, y=pos.y, z=pos.z-1}).name ~= "air" then
minetest.add_node(right_here, {name="molehills:molehill"})
end
end
plantslib:register_generate_plant({
surface = {"default:dirt_with_grass"},
max_count = Molehills_Max_Count,
rarity = Molehills_Rarity,
min_elevation = 1,
max_elevation = 40,
avoid_nodes = {"group:tree","group:liquid","group:stone","group:falling_node"--[[,"air"]]},
avoid_radius = 4,
plantlife_limit = -0.3,
},
"abstract_molehills.place_molehill"
)
-----------------------------------------------------------------------------------------------
print("[Mod] "..title.." ["..version.."] ["..mname.."] Loaded...")
-----------------------------------------------------------------------------------------------
|
-- In KBX, ReverseOn is the default state.
return Def.ActorFrame {
-- Background Gradient
Def.Quad {
InitCommand=function(self) self:x(0):diffuse(0,0,0,0.75):scaletoclipped(64,192) end,
ReverseOnCommand=function(self) self:fadetop(0.25) end,
ReverseOffCommand=function(self) self:fadebottom(0.25) end
},
-- Receptor Body
Def.Quad {
InitCommand=function(self) self:y(0):scaletoclipped(64,24) end,
ReverseOnCommand=function(self) self:diffuse(color("#800000")):diffusebottomedge(color("#FF0000")) end,
ReverseOffCommand=function(self) self:diffuse(color("#FF0000")):diffusebottomedge(color("#800000")) end,
},
-- Top Border Line
Def.Quad {
InitCommand=function(self) self:y(11):scaletoclipped(64,2):diffuse(1,1,1,0.25) end
},
-- Bottom Border Line
Def.Quad {
InitCommand=function(self) self:y(-11):scaletoclipped(64,2):diffuse(1,1,1,0.25) end
},
-- Upper Gradient Flash
Def.Quad {
InitCommand=function(self) self:scaletoclipped(64,24):diffuse(1,1,1,1):effectclock("beat"):queuecommand("Flash") end,
FlashCommand=function(self) self:diffuseramp():effectcolor1(0,0.75,1,0.625):effectcolor2(0,0.75,1,1):effecttiming(0.2,0,0.8,0) end,
ReverseOnCommand=function(self) self:y(-24):fadetop(0.875) end,
ReverseOffCommand=function(self) self:y(24):fadebottom(0.875) end
},
-- Lane Flash
Def.Quad {
InitCommand=function(self) self:diffuse(color("#00C0FF")):scaletoclipped(64,768):diffusealpha(0) end,
PressCommand=function(self) self:diffusealpha(0.375) end,
LiftCommand=function(self) self:stoptweening():linear(0.2):diffusealpha(0) end,
ReverseOnCommand=function(self) self:y(32):valign(1):fadetop(1) end,
ReverseOffCommand=function(self) self:y(-32):valign(0):fadebottom(1) end
}
}
|
local Path = require(script.Parent.Path)
local ScriptManager = {}
ScriptManager.__index = ScriptManager
function ScriptManager.new(root)
local self = setmetatable({}, ScriptManager)
self.Root = root
return self
end
function ScriptManager:GetObject(path)
return Path.GetObjectAt(path, self.Root)
end
function ScriptManager:CreateObject(path, type)
if self:GetObject(path) then return self:GetObject(path) end
local parts = Path.Split(path)
local obj = Instance.new(type)
local parent = Path.CreateTree(path, self.Root, true)
obj.Parent = parent
obj.Name = parts[#parts]
return obj
end
function ScriptManager:RemoveObject(path)
local object = self:GetObject(path)
if object then
while #object.Parent:GetChildren() < 2 and object.Parent ~= self.Root do
object = object.Parent
end
object:Destroy()
end
end
function ScriptManager:SetObjectSource(path, source)
local object = self:GetObject(path)
if object then
object.Source = source
end
end
return ScriptManager
|
if not jit or not jit.status or not jit.status() then return end
for i=1,100 do
if i==50 then jit.flush(2) end
for j=1,100 do end
for j=1,100 do end
end
jit.flush()
local function f() for i=1,100 do end end
for i=1,100 do local x = gcinfo(); f() end
jit.flush()
local function fib(n)
if n < 2 then return 1 end
return fib(n-2) + fib(n-1)
end
fib(11)
jit.flush()
local names = {}
for i=1,100 do names[i] = i end
function f()
for k,v in ipairs(names) do end
end
f()
for i=1,2 do
f()
f()
jit.flush()
end
jit.flush()
jit.flush(1) -- ignored
jit.flush(2) -- ignored
for i=1,1e7 do end -- causes trace #1
jit.flush(2) -- ignored
jit.flush(1) -- ok
jit.flush(1) -- crashes
|
mound_mite = Creature:new {
objectName = "@mob/creature_names:mound_mite",
socialGroup = "self",
faction = "",
level = 9,
chanceHit = 0.27,
damageMin = 80,
damageMax = 90,
baseXp = 292,
baseHAM = 675,
baseHAMmax = 825,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "meat_insect",
meatAmount = 5,
hideType = "hide_scaley",
hideAmount = 4,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/mound_mite.iff"},
hues = { 24, 25, 26, 27, 28, 29, 30, 31 },
controlDeviceTemplate = "object/intangible/pet/rock_mite_hue.iff",
scale = 0.8,
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"",""},
{"stunattack",""}
}
}
CreatureTemplates:addCreatureTemplate(mound_mite, "mound_mite")
|
-- _.iterRight.lua
--
_.iterRight = function(value)
if _.isString(value) then
local i = #value + 1
return function()
if _.gt(i, 1) then
i = i - 1
local c = value:sub(i, i)
return i, c
end
end
elseif _.isTable(value) then
return iterCollection(value, true)
else
return function() end
end
end
|
--[[
LuCI - Lua Configuration Interface
$Id: wifimanager.lua 2/17/2016
$ [email protected]
]]--
local sys = require ("luci.sys")
local m, s, o
m = Map("wifimanager", translate("Wifi Manager"), translate("Here you can configure your WifiManager Settings"))
m.on_after_commit = function()
sys.exec("reload_config &")
end
s = m:section(NamedSection, "conn", "set", translate("General Settings"))
s.anonymous = true
s.addremove = false
--
-- General Settings
--
o = s:option(Value, "ConnCheckTimer", translate("Network Check Interval"))
o.default = 60
o.rmempty = false
for i=10, 60, 10 do
o:value(i, i)
end
o = s:option(Value, "net_tries", translate("Network Check Retries"))
o.default = 3
o.rmempty = false
for i=1, 10 do
o:value(i, i)
end
o = s:option(Value, "boot_tries", translate("Firstboot Ping Retires"))
o.default = 5
o.rmempty = false
for i=1, 10 do
o:value(i, i)
end
o = s:option(ListValue, "log_lev", translate("Logging Level"))
o.default = "OFF"
o:value("0", "OFF")
o:value("1", "BASIC")
o:value("2", "ADVANCED")
o:value("3", "DEBUGGING")
o = s:option(Value, "PingLocation", translate("Ping Adddress"))
o.default = "www.google.com"
o.rmempty = false
o = s:option(Flag, "new_nets", translate("Auto Add Newworks"))
o.default = 0
o.disabled = 0
o.enabled = 1
o.rmempty = false
o = s:option(Flag, "randMac", translate("Randonmize Mac Address"))
o.rmempty = false
o.default = 0
o.disabled = 0
o.enabled = 1
return m
|
local Native = require('lib.stdlib.native')
local converter = require('lib.stdlib.enum.converter')
---@class AbilityIntegerField
local AbilityIntegerField = {
ButtonPositionNormalX = 0x61627078, --ABILITY_IF_BUTTON_POSITION_NORMAL_X
ButtonPositionNormalY = 0x61627079, --ABILITY_IF_BUTTON_POSITION_NORMAL_Y
ButtonPositionActivatedX = 0x61756278, --ABILITY_IF_BUTTON_POSITION_ACTIVATED_X
ButtonPositionActivatedY = 0x61756279, --ABILITY_IF_BUTTON_POSITION_ACTIVATED_Y
ButtonPositionResearchX = 0x61727078, --ABILITY_IF_BUTTON_POSITION_RESEARCH_X
ButtonPositionResearchY = 0x61727079, --ABILITY_IF_BUTTON_POSITION_RESEARCH_Y
MissileSpeed = 0x616D7370, --ABILITY_IF_MISSILE_SPEED
TargetAttachments = 0x61746163, --ABILITY_IF_TARGET_ATTACHMENTS
CasterAttachments = 0x61636163, --ABILITY_IF_CASTER_ATTACHMENTS
Priority = 0x61707269, --ABILITY_IF_PRIORITY
Levels = 0x616C6576, --ABILITY_IF_LEVELS
RequiredLevel = 0x61726C76, --ABILITY_IF_REQUIRED_LEVEL
LevelSkipRequirement = 0x616C736B, --ABILITY_IF_LEVEL_SKIP_REQUIREMENT
}
AbilityIntegerField = converter(Native.ConvertAbilityIntegerField, AbilityIntegerField)
return AbilityIntegerField
|
local set = vim.opt_local
set.tabstop = 2
set.softtabstop = 2
set.shiftwidth = 2
set.wrap = false
|
local EZban = {}
local DS = game:GetService("DataStoreService")
local MS = game:GetService("MessagingService")
local store = game:GetService("DataStoreService"):GetDataStore("TimeBanInfo")
local Timenow = os.time()
local plrs = game:GetService("Players")
local updatetime = coroutine.create(function()
while wait(1) do
Timenow = os.time()
end
end)
coroutine.resume(updatetime)
local function round(n)
return math.floor(n+.5)
end
game.Players.PlayerAdded:Connect(function(player)
local data
local success, errormessage = pcall(function()
data = store:GetAsync(player.UserId.."-Timeban")
end)
if success and data ~= nil then
local Mode = data[2]
local TLIS = os.difftime(data[1],Timenow)
local timeleft = 0
local finaltime = nil
if TLIS > 0 then
if Mode == "minutes" then timeleft = TLIS/60 elseif Mode == "hours" then timeleft = TLIS/3600 elseif Mode == "days" then timeleft = TLIS/86400 elseif Mode == "weeks" then timeleft = TLIS/604800 end
if timeleft > 1 then
finaltime = round(timeleft)
end
if finaltime ~= nil then
player:Kick("You were banned from the game. You will be unbanned in "..tostring(finaltime).." "..data[2])
else
player:Kick("You were banned from the game. You will be unbanned in "..tostring(timeleft).." "..data[2])
end
end
end
end)
function EZban.TimeBan(User,Length,Mode)
--Mode = "minutes"
local UserId = plrs:GetUserIdFromNameAsync(User)
local LIS = 0
Mode = string.lower(Mode)
if Mode == "minutes" then LIS = Length*60 elseif Mode == "hours" then LIS = Length*3600 elseif Mode == "days" then LIS = Length*86400 elseif Mode == "weeks" then LIS = Length*604800 end
local endE = Timenow + LIS
local info = {endE,Mode,UserId}
store:SetAsync(UserId.."-Timeban",info)
if plrs:GetPlayerByUserId(UserId) then
plrs:GetPlayerByUserId(UserId):Kick("You were banned for "..Length.." "..Mode)
end
end
return EZban
|
User = game.Players.LocalPlayer
--lego
Char = User.Character
moving = false
Position = 1
cen = Instance.new("Part", User.Character)
cen.BottomSurface = "Smooth"
cen.TopSurface = "Smooth"
cen.CanCollide = false
cen.formFactor = "Symmetric"
cen.Size = Vector3.new(1,1,1)
cen.BrickColor = BrickColor.new("Really black")
cen.Transparency = 1
--this script was made by benningtonguy and probably stolen by accountmonitor
cen2 = Instance.new("Part", User.Character)
cen2.BottomSurface = "Smooth"
cen2.TopSurface = "Smooth"
cen2.CanCollide = false
cen2.formFactor = "Symmetric"
cen2.Size = Vector3.new(1,1,1)
cen2.BrickColor = BrickColor.new("Really black")
cen2.Transparency = 1
cenw = Instance.new("Weld", cen)
cenw.Part0 = Char["Torso"]
cenw.Part1 = cen
cenw.C1 = CFrame.new(-1.5,-0.5,0)
cenw2 = Instance.new("Weld", cen2)
cenw2.Part0 = Char["Torso"]
cenw2.Part1 = cen2
cenw2.C1 = CFrame.new(1.5,-0.5,0)
haw = Instance.new("Weld", cen)
haw.Part0 = cen
haw.Part1 = Char["Right Arm"]
haw.C1 = CFrame.new(0,0.5,0)
haw2 = Instance.new("Weld", cen2)
haw2.Part0 = cen2
haw2.Part1 = Char["Left Arm"]
haw2.C1 = CFrame.new(0,0.5,0)
haw.C0 = CFrame.Angles(0,math.rad(10),0)
haw.C1 = CFrame.new(0.5,0.5,1)
haw2.C0 = CFrame.Angles(math.rad(45),0,math.rad(45))
haw2.C1 = CFrame.new(0,1.5,0)
--this script was made by benningtonguy and probably stolen by accountmonitor
mainb = Instance.new("Part", Char)
mainb.formFactor = "Symmetric"
mainb.Size = Vector3.new(1,1,1)
mainb.BrickColor = BrickColor.new("Dark stone grey")
mainbm = Instance.new("CylinderMesh", mainb)
mainbm.Scale = Vector3.new(1.3,2,1.3)
mainb:BreakJoints()
mainbw = Instance.new("Weld", mainb)
mainbw.Part0 = Char["Torso"]
mainbw.Part1 = mainb
mainbw.C1 = CFrame.new(0.6,0,-1)
mainb2 = Instance.new("Part", Char)
mainb2.formFactor = "Symmetric"
mainb2.Size = Vector3.new(1,1,1)
mainb2.BrickColor = BrickColor.new("Dark stone grey")
mainbm2 = Instance.new("CylinderMesh", mainb2)
mainbm2.Scale = Vector3.new(1.3,2,1.3)
mainb2:BreakJoints()
mainbw2 = Instance.new("Weld", mainb2)
mainbw2.Part0 = Char["Torso"]
mainbw2.Part1 = mainb2
mainbw2.C1 = CFrame.new(-0.6,0,-1)
top = Instance.new("Part", Char)
top.formFactor = "Symmetric"
top.Size = Vector3.new(1,1,1)
top.BrickColor = BrickColor.new("Dark stone grey")
topm = Instance.new("SpecialMesh", top)
topm.MeshType = "Sphere"
topm.Scale = Vector3.new(1.3,1,1.3)
top:BreakJoints()
topw = Instance.new("Weld", top)
topw.Part0 = mainb
topw.Part1 = top
topw.C1 = CFrame.new(0,-1,0)
top2 = Instance.new("Part", Char)
top2.formFactor = "Symmetric"
top2.Size = Vector3.new(1,1,1)
top2.BrickColor = BrickColor.new("Dark stone grey")
topm2 = Instance.new("SpecialMesh", top2)
topm2.MeshType = "Sphere"
topm2.Scale = Vector3.new(1.3,1,1.3)
top2:BreakJoints()
topw2 = Instance.new("Weld", top2)
topw2.Part0 = mainb2
topw2.Part1 = top2
topw2.C1 = CFrame.new(0,-1,0)
cir = Instance.new("Part", Char)
cir.formFactor = "Symmetric"
cir.Size = Vector3.new(1,1,1)
cir.BrickColor = BrickColor.new("Stone grey")
cirm = Instance.new("CylinderMesh", cir)
cirm.Scale = Vector3.new(1.35,0.3,1.35)
cir:BreakJoints()
cirw = Instance.new("Weld", cir)
cirw.Part0 = mainb
cirw.Part1 = cir
cirw.C1 = CFrame.new(0,-1,0)
cir2 = Instance.new("Part", Char)
cir2.formFactor = "Symmetric"
cir2.Size = Vector3.new(1,1,1)
cir2.BrickColor = BrickColor.new("Stone grey")
cirm2 = Instance.new("CylinderMesh", cir2)
cirm2.Scale = Vector3.new(1.35,0.3,1.35)
cir2:BreakJoints()
cirw2 = Instance.new("Weld", cir2)
cirw2.Part0 = mainb2
cirw2.Part1 = cir2
cirw2.C1 = CFrame.new(0,-1,0)
cir3 = Instance.new("Part", Char)
cir3.formFactor = "Symmetric"
cir3.Size = Vector3.new(1,1,1)
cir3.BrickColor = BrickColor.new("Stone grey")
cirm3 = Instance.new("CylinderMesh", cir3)
cirm3.Scale = Vector3.new(1.35,0.3,1.35)
cir3:BreakJoints()
cirw3 = Instance.new("Weld", cir3)
cirw3.Part0 = mainb
cirw3.Part1 = cir3
cirw3.C1 = CFrame.new(0,0,0)
cir4 = Instance.new("Part", Char)
cir4.formFactor = "Symmetric"
cir4.Size = Vector3.new(1,1,1)
cir4.BrickColor = BrickColor.new("Stone grey")
cirm4 = Instance.new("CylinderMesh", cir4)
cirm4.Scale = Vector3.new(1.35,0.3,1.35)
cir4:BreakJoints()
cirw4 = Instance.new("Weld", cir4)
cirw4.Part0 = mainb2
cirw4.Part1 = cir4
cirw4.C1 = CFrame.new(0,0,0)
--this script was made by benningtonguy and probably stolen by accountmonitor
cir5 = Instance.new("Part", Char)
cir5.formFactor = "Symmetric"
cir5.Size = Vector3.new(1,1,1)
cir5.BrickColor = BrickColor.new("Stone grey")
cirm5 = Instance.new("CylinderMesh", cir5)
cirm5.Scale = Vector3.new(1.35,0.3,1.35)
cir5:BreakJoints()
cirw5 = Instance.new("Weld", cir5)
cirw5.Part0 = mainb
cirw5.Part1 = cir5
cirw5.C1 = CFrame.new(0,1,0)
--this script was made by benningtonguy and probably stolen by accountmonitor
cir6 = Instance.new("Part", Char)
cir6.formFactor = "Symmetric"
cir6.Size = Vector3.new(1,1,1)
cir6.BrickColor = BrickColor.new("Stone grey")
cirm6 = Instance.new("CylinderMesh", cir6)
cirm6.Scale = Vector3.new(1.35,0.3,1.35)
cir6:BreakJoints()
cirw6 = Instance.new("Weld", cir6)
cirw6.Part0 = mainb2
cirw6.Part1 = cir6
cirw6.C1 = CFrame.new(0,1,0)
--this script was made by benningtonguy and probably stolen by accountmonitor
------------------------------------------FLAMETHROWER ITSELF
prt1 = Instance.new("Part", Char)
prt1.Size = Vector3.new(1,1,1)
prt1.CanCollide = false
prt1.BrickColor = BrickColor.new("Really black")
prt1.TopSurface = "Smooth"
prt1.Transparency = 0
prt1.BottomSurface = "Smooth"
prtM = Instance.new("CylinderMesh", prt1)
prtM.Scale = Vector3.new(0.7,1.5,0.7)
prt1:BreakJoints()
prtW = Instance.new("Weld", prt1)
prtW.Part0 = Char["Right Arm"]
prtW.Part1 = prt1
prtW.C1 = CFrame.new(0,0,1)*CFrame.Angles(math.rad(90),0,math.rad(0))
prt2 = Instance.new("Part", Char)
prt2.Size = Vector3.new(1,1,1)
prt2.CanCollide = false
prt2.BrickColor = BrickColor.new("Dark stone grey")
prt2.TopSurface = "Smooth"
prt2.Transparency = 0
prt2.BottomSurface = "Smooth"
prtM2 = Instance.new("CylinderMesh", prt2)
prtM2.Scale = Vector3.new(0.5,3,0.5)
prt2:BreakJoints()
prtW2 = Instance.new("Weld", prt2)
prtW2.Part0 = prt1
prtW2.Part1 = prt2
prtW2.C1 = CFrame.new(0,-2.5,0)*CFrame.Angles(math.rad(0),0,math.rad(0))
prt3 = Instance.new("Part", Char)
prt3.Size = Vector3.new(1,1,1)
prt3.CanCollide = false
prt3.BrickColor = BrickColor.new("Dark stone grey")
prt3.TopSurface = "Smooth"
prt3.Transparency = 0
prt3.BottomSurface = "Smooth"
prtM3 = Instance.new("CylinderMesh", prt3)
prtM3.Scale = Vector3.new(0.2,0.5,0.2)
prt3:BreakJoints()
prtW3 = Instance.new("Weld", prt3)
prtW3.Part0 = prt2
prtW3.Part1 = prt3
prtW3.C1 = CFrame.new(0,0.5,0)*CFrame.Angles(math.rad(-115),math.rad(0),math.rad(0))
prt4 = Instance.new("Part", Char)
prt4.Size = Vector3.new(1,1,1)
prt4.CanCollide = false
prt4.BrickColor = BrickColor.new("Dark stone grey")
prt4.TopSurface = "Smooth"
prt4.Transparency = 0
prt4.BottomSurface = "Smooth"
prtM4 = Instance.new("CylinderMesh", prt4)
prtM4.Scale = Vector3.new(0.5,3,0.5)
prt4:BreakJoints()
prtW4 = Instance.new("Weld", prt2)
prtW4.Part0 = prt2
prtW4.Part1 = prt4
prtW4.C1 = CFrame.new(0,-0.6,0.7)*CFrame.Angles(math.rad(0),0,math.rad(0))
prt5 = Instance.new("Part", Char)
prt5.Size = Vector3.new(1,1,1)
prt5.CanCollide = false
prt5.BrickColor = BrickColor.new("Dark stone grey")
prt5.TopSurface = "Smooth"
prt5.Transparency = 0
prt5.BottomSurface = "Smooth"
prtM5 = Instance.new("CylinderMesh", prt5)
prtM5.Scale = Vector3.new(0.2,0.5,0.2)
prt5:BreakJoints()
prtW5 = Instance.new("Weld", prt5)
prtW5.Part0 = prt4
prtW5.Part1 = prt5
prtW5.C1 = CFrame.new(0,0.5,1.5)*CFrame.Angles(math.rad(-115),math.rad(0),math.rad(0))
prt6 = Instance.new("Part", Char)
prt6.Size = Vector3.new(1,1,1)
prt6.CanCollide = false
prt6.BrickColor = BrickColor.new("Really black")
prt6.TopSurface = "Smooth"
prt6.Transparency = 0
prt6.BottomSurface = "Smooth"
prtM6 = Instance.new("CylinderMesh", prt6)
prtM6.Scale = Vector3.new(0.7,0.5,0.7)
prt6:BreakJoints()
prtW6 = Instance.new("Weld", prt6)
prtW6.Part0 = prt2
prtW6.Part1 = prt6
prtW6.C1 = CFrame.new(0,-1.51,0)*CFrame.Angles(math.rad(0),0,math.rad(0))
prt7 = Instance.new("Part", Char)
prt7.Size = Vector3.new(1,2,1)
prt7.CanCollide = false
prt7.BrickColor = BrickColor.new("Really black")
prt7.TopSurface = "Smooth"
prt7.Transparency = 1
prt7.BottomSurface = "Smooth"
prtM7 = Instance.new("CylinderMesh", prt7)
prtM7.Scale = Vector3.new(1,1,1)
prt7:BreakJoints()
prtW7 = Instance.new("Weld", prt7)
prtW7.Part0 = prt6
prtW7.Part1 = prt7
prtW7.C1 = CFrame.new(0,-2,0)*CFrame.Angles(math.rad(0),0,math.rad(0))
fire = Instance.new("Fire", prt6)
fire.Heat = 25
fire.Size = 2
fire.Enabled = false
if not script.Parent:IsA("HopperBin") then
h = Instance.new("HopperBin", User.Backpack)
h.Name = "Pyro"
script.Parent = h
end
script.Parent.Selected:connect(function(mouse)
delay(0, function()
--[[while wait() do
pcall(function()
User.Character.Torso["Neck"].C0 = CFrame.new(0, 1.5, 0.25)
User.Character.Torso["Neck"].C1 = CFrame.fromEulerAnglesXYZ(math.rad(0), 0, 0) * CFrame.new(0, 0, 0.5) * (CFrame.new((User.Character.Torso.CFrame * CFrame.new(1.5, 0, 0)).p, mouse.Hit.p) - (User.Character.Torso.CFrame * CFrame.new(1.5, 0, 0)).p):inverse() * (User.Character.Torso.CFrame - User.Character.Torso.Position)
end)
end]]
end)
mouse.Button1Down:connect(function()
fire.Enabled = true
end)
mouse.Button1Up:connect(function()
fire.Enabled = false
end)
end)
prt7.Touched:connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") ~= nil and hit.Parent.Name ~= User.Name and fire.Enabled == true and hit:FindFirstChild("Fire") == nil then
local fiar = Instance.new("Fire", hit)
fiar.Size = 2
for i = 1,100 do
hit.Parent.Humanoid.Health = hit.Parent.Humanoid.Health - 10
wait()
end
fiar:Remove()
end
end)
|
ITEM.name = "Exohelm (No Visor)"
ITEM.description = "A high-end helmet."
ITEM.longdesc = "This helmet resembles that of an ordinary exoskeleton, but differs sightly from its standard counterpart and has differing protective characteristics. Good protection from gunfire and high calibre rounds in combination with anomaly protection make this helmet one of the best in its category."
ITEM.model = "models/kek1ch/helm_tactic.mdl"
ITEM.price = 45000
--ITEM.busflag = {"ARMOR4", "SPECIAL6_1"}
ITEM.busflag = {"headgear1_1_1"}
ITEM.br = 0.25
ITEM.fbr = 0
ITEM.ar = 0
ITEM.far = 0
ITEM.radProt = 0
ITEM.isGasmask = false
ITEM.isHelmet = true
ITEM.ballisticlevels = {"lll-a"}
ITEM.repairCost = ITEM.price/100*1
ITEM.img = ix.util.GetMaterial("cotz/ui/icons/headgear_radsuit.png")
ITEM.weight = 6.100
ITEM.pacData = {
[1] = {
["children"] = {
[1] = {
["children"] = {
},
["self"] = {
["Skin"] = 0,
["Invert"] = false,
["LightBlend"] = 1,
["CellShade"] = 0,
["OwnerName"] = "self",
["AimPartName"] = "",
["IgnoreZ"] = false,
["AimPartUID"] = "",
["Passes"] = 1,
["Name"] = "",
["NoTextureFiltering"] = false,
["DoubleFace"] = false,
["PositionOffset"] = Vector(0, 0, 0),
["IsDisturbing"] = false,
["Fullbright"] = false,
["EyeAngles"] = false,
["DrawOrder"] = 0,
["TintColor"] = Vector(0, 0, 0),
["UniqueID"] = "4086462223",
["Translucent"] = false,
["LodOverride"] = -1,
["BlurSpacing"] = 0,
["Alpha"] = 1,
["Material"] = "",
["UseWeaponColor"] = false,
["UsePlayerColor"] = false,
["UseLegacyScale"] = false,
["Bone"] = "head",
["Color"] = Vector(255, 255, 255),
["Brightness"] = 1,
["BoneMerge"] = false,
["BlurLength"] = 0,
["Position"] = Vector(-73.03099822998, -10.041000366211, -1.7330000400543),
["AngleOffset"] = Angle(0, 0, 0),
["AlternativeScaling"] = false,
["Hide"] = false,
["OwnerEntity"] = false,
["Scale"] = Vector(1.0299999713898, 1, 1),
["ClassName"] = "model",
["EditorExpand"] = true,
["Size"] = 1.1499999761581,
["ModelFallback"] = "",
["Angles"] = Angle(1.9980000257492, -82.575248718262, -88.762619018555),
["TextureFilter"] = 3,
["Model"] = "models/projectpt/headwear_radsuit.mdl",
["BlendMode"] = "",
},
},
},
["self"] = {
["DrawOrder"] = 0,
["UniqueID"] = "1121170306",
["AimPartUID"] = "",
["Hide"] = false,
["Duplicate"] = false,
["ClassName"] = "group",
["OwnerName"] = "self",
["IsDisturbing"] = false,
["Name"] = "radsuit",
["EditorExpand"] = false,
},
},
}
ITEM.pacDataExpedition = {
[1] = {
["children"] = {
[1] = {
["children"] = {
[1] = {
["children"] = {
},
["self"] = {
["Jiggle"] = false,
["DrawOrder"] = 0,
["AlternativeBones"] = false,
["FollowPartName"] = "",
["Angles"] = Angle(0, 0, 0),
["OwnerName"] = "self",
["AimPartName"] = "",
["FollowPartUID"] = "",
["Bone"] = "spine 4",
["InvertHideMesh"] = false,
["ScaleChildren"] = false,
["ClassName"] = "bone",
["FollowAnglesOnly"] = false,
["Position"] = Vector(0, 0, 0),
["AimPartUID"] = "",
["UniqueID"] = "2144846675",
["Hide"] = false,
["Name"] = "",
["Scale"] = Vector(1, 1, 1),
["MoveChildrenToOrigin"] = false,
["EditorExpand"] = false,
["Size"] = 1,
["PositionOffset"] = Vector(0, 0, 0),
["IsDisturbing"] = false,
["AngleOffset"] = Angle(0, 0, 0),
["EyeAngles"] = false,
["HideMesh"] = true,
},
},
[2] = {
["children"] = {
},
["self"] = {
["Jiggle"] = false,
["DrawOrder"] = 0,
["AlternativeBones"] = true,
["FollowPartName"] = "",
["Angles"] = Angle(0, 7.4000000953674, 0),
["OwnerName"] = "self",
["AimPartName"] = "",
["FollowPartUID"] = "",
["Bone"] = "head",
["InvertHideMesh"] = false,
["ScaleChildren"] = false,
["ClassName"] = "bone",
["FollowAnglesOnly"] = false,
["Position"] = Vector(-0.60000002384186, -0.80000001192093, 0),
["AimPartUID"] = "",
["UniqueID"] = "3387404245",
["Hide"] = false,
["Name"] = "",
["Scale"] = Vector(1, 1.0599999427795, 0.95999997854233),
["MoveChildrenToOrigin"] = false,
["EditorExpand"] = false,
["Size"] = 1,
["PositionOffset"] = Vector(0, 0, 0),
["IsDisturbing"] = false,
["AngleOffset"] = Angle(0, 0, 0),
["EyeAngles"] = false,
["HideMesh"] = false,
},
},
},
["self"] = {
["Invert"] = false,
["EyeTargetName"] = "",
["NoLighting"] = false,
["OwnerName"] = "self",
["AimPartName"] = "",
["IgnoreZ"] = false,
["AimPartUID"] = "",
["Materials"] = "",
["Name"] = "",
["LevelOfDetail"] = 0,
["NoTextureFiltering"] = false,
["PositionOffset"] = Vector(0, 0, 0),
["NoCulling"] = false,
["Translucent"] = false,
["DrawOrder"] = 0,
["Alpha"] = 1,
["Material"] = "",
["Bone"] = "head",
["UniqueID"] = "2815537229",
["BoneMerge"] = true,
["EyeTargetUID"] = "",
["Position"] = Vector(0, 0, 0),
["BlendMode"] = "",
["Angles"] = Angle(0, 0, 0),
["Hide"] = false,
["EyeAngles"] = false,
["Scale"] = Vector(1, 1, 1),
["AngleOffset"] = Angle(0, 0, 0),
["EditorExpand"] = false,
["Size"] = 0.94999998807907,
["Color"] = Vector(1, 1, 1),
["ClassName"] = "model2",
["IsDisturbing"] = false,
["ModelModifiers"] = "",
["Model"] = "models/stalkerisaac/outfits/radsuit_helm.mdl",
},
},
},
["self"] = {
["DrawOrder"] = 0,
["UniqueID"] = "1121170306",
["AimPartUID"] = "",
["Hide"] = true,
["Duplicate"] = false,
["ClassName"] = "group",
["OwnerName"] = "self",
["IsDisturbing"] = false,
["Name"] = "radsuit",
["EditorExpand"] = false,
},
},
}
ITEM.pacDataBerill1 = {
[18] = {
["children"] = {
[1] = {
["children"] = {
},
["self"] = {
["Skin"] = 0,
["Invert"] = false,
["LightBlend"] = 1,
["CellShade"] = 0,
["OwnerName"] = "self",
["AimPartName"] = "",
["IgnoreZ"] = false,
["AimPartUID"] = "",
["Passes"] = 1,
["Name"] = "",
["NoTextureFiltering"] = false,
["DoubleFace"] = false,
["PositionOffset"] = Vector(0, 0, 0),
["IsDisturbing"] = false,
["Fullbright"] = false,
["EyeAngles"] = false,
["DrawOrder"] = 0,
["TintColor"] = Vector(0, 0, 0),
["UniqueID"] = "4086462223",
["Translucent"] = false,
["LodOverride"] = -1,
["BlurSpacing"] = 0,
["Alpha"] = 1,
["Material"] = "",
["UseWeaponColor"] = false,
["UsePlayerColor"] = false,
["UseLegacyScale"] = false,
["Bone"] = "head",
["Color"] = Vector(255, 255, 255),
["Brightness"] = 1,
["BoneMerge"] = false,
["BlurLength"] = 0,
["Position"] = Vector(-70.430999755859, -10.440999984741, -1.7330000400543),
["AngleOffset"] = Angle(0, 0, 0),
["AlternativeScaling"] = false,
["Hide"] = false,
["OwnerEntity"] = false,
["Scale"] = Vector(1, 1, 1),
["ClassName"] = "model",
["EditorExpand"] = true,
["Size"] = 1.1,
["ModelFallback"] = "",
["Angles"] = Angle(1.9980000257492, -82.575248718262, -88.762619018555),
["TextureFilter"] = 3,
["Model"] = "models/projectpt/headwear_radsuit.mdl",
["BlendMode"] = "",
},
},
},
["self"] = {
["DrawOrder"] = 0,
["UniqueID"] = "1121170306",
["AimPartUID"] = "",
["Hide"] = false,
["Duplicate"] = false,
["ClassName"] = "group",
["OwnerName"] = "self",
["IsDisturbing"] = false,
["Name"] = "radsuit",
["EditorExpand"] = false,
},
},
}
ITEM.pacDataNBC = {
[1] = {
["children"] = {
[1] = {
["children"] = {
},
["self"] = {
["Skin"] = 0,
["Invert"] = false,
["LightBlend"] = 1,
["CellShade"] = 0,
["OwnerName"] = "self",
["AimPartName"] = "",
["IgnoreZ"] = false,
["AimPartUID"] = "",
["Passes"] = 1,
["Name"] = "",
["NoTextureFiltering"] = false,
["DoubleFace"] = false,
["PositionOffset"] = Vector(0, 0, 0),
["IsDisturbing"] = false,
["Fullbright"] = false,
["EyeAngles"] = false,
["DrawOrder"] = 0,
["TintColor"] = Vector(0, 0, 0),
["UniqueID"] = "4086462223",
["Translucent"] = false,
["LodOverride"] = -1,
["BlurSpacing"] = 0,
["Alpha"] = 1,
["Material"] = "",
["UseWeaponColor"] = false,
["UsePlayerColor"] = false,
["UseLegacyScale"] = false,
["Bone"] = "head",
["Color"] = Vector(255, 255, 255),
["Brightness"] = 1,
["BoneMerge"] = false,
["BlurLength"] = 0,
["Position"] = Vector(-73.231002807617, -8.5410003662109, -1.6130000352859),
["AngleOffset"] = Angle(0, 0, 0),
["AlternativeScaling"] = false,
["Hide"] = false,
["OwnerEntity"] = false,
["Scale"] = Vector(1.0299999713898, 1, 1),
["ClassName"] = "model",
["EditorExpand"] = true,
["Size"] = 1.1499999761581,
["ModelFallback"] = "",
["Angles"] = Angle(1.9980000257492, -82.575248718262, -88.762619018555),
["TextureFilter"] = 3,
["Model"] = "models/projectpt/headwear_radsuit.mdl",
["BlendMode"] = "",
},
},
},
["self"] = {
["DrawOrder"] = 0,
["UniqueID"] = "1121170306",
["AimPartUID"] = "",
["Hide"] = false,
["Duplicate"] = false,
["ClassName"] = "group",
["OwnerName"] = "self",
["IsDisturbing"] = false,
["Name"] = "radsuit",
["EditorExpand"] = false,
},
},
}
|
#!/usr/bin/env tarantool
local test = require("sqltester")
test:plan(1)
--!./tcltestrunner.lua
-- 2010 April 15
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, never taking more than you give.
--
-------------------------------------------------------------------------
-- This file implements regression tests for sql library.
--
-- This file implements tests to verify that ticket [02a8e81d44] has been
-- fixed.
--
-- ["set","testdir",[["file","dirname",["argv0"]]]]
-- ["source",[["testdir"],"\/tester.tcl"]]
test:do_execsql_test(
"tkt-02a838-1.1",
[[
CREATE TABLE t1(a INT primary key);
INSERT INTO t1 VALUES(1);
INSERT INTO t1 VALUES(2);
INSERT INTO t1 VALUES(4);
INSERT INTO t1 VALUES(5);
SELECT * FROM (SELECT a FROM t1 LIMIT 1) UNION ALL SELECT 3;
]], {
-- <tkt-02a838-1.1>
1, 3
-- </tkt-02a838-1.1>
})
test:finish_test()
|
local fs = require("filesystem")
local http = require("http")
local args = {...}
local url = args[1]
local outPath
if not url then
print("Usage: wget <url> [file name]")
return true
end
if args[2] then
outPath = fs.joinPath(shell.getWorkingDirectory(), args[2])
else
outPath = fs.joinPath(shell.getWorkingDirectory(), fs.getName(url))
end
local content, err = http.get(url)
if not content then
printError(err)
return false
end
fs.writeFile(outPath, content, true)
print("Saved as " .. outPath)
return true
|
local imgr = {}
imgr.rng = love.math.newRandomGenerator()
imgr.set = nil
imgr.idx = -1
function imgr.setSet(s)
imgr.set = s
imgr._shuffle()
imgr.idx = 0
end
function imgr._shuffle()
for i, v in ipairs(imgr.set) do
local j = imgr.rng:random(i, #imgr.set)
imgr._swap(i, j)
end
end
function imgr._swap(i, j)
local tmp = imgr.set[j]
imgr.set[j] = imgr.set[i]
imgr.set[i] = tmp
end
function imgr.next()
if imgr.set then
imgr.idx = imgr.idx + 1
if imgr.idx > #imgr.set then
imgr._shuffle()
imgr.idx = 1
end
return imgr.set[imgr.idx]
end
end
function imgr.update()
imgr.rng:random()
end
return imgr
|
--- Tools for working with tiles.
-- A tile represents a 1 unit<sup>2</sup> on a surface in Factorio.
-- @module Tile
-- @usage local Tile = require('stdlib/area/tile')
-- @see LuaTile
local Tile = {_module_name = 'Tile'}
setmetatable(Tile, {__index = require('stdlib/core')})
local Is = Tile.Is
local Game = require('stdlib/game')
local Position = require('stdlib/area/position')
--- Get the @{LuaTile.position|tile position} of a tile where the given position resides.
-- @function Tile.from_position
-- @see Position.tile_position
Tile.from_position = Position.tile_position
--- Converts a tile position to the @{Concepts.BoundingBox|area} of the tile it is in.
-- @function Tile.to_area
-- @see Position.expand_to_tile_area
Tile.to_area = Position.expand_to_tile_area
--- Creates an array of tile positions for all adjacent tiles (N, E, S, W) **OR** (N, NE, E, SE, S, SW, W, NW) if diagonal is set to true.
-- @tparam LuaSurface surface the surface to examine for adjacent tiles
-- @tparam LuaTile.position position the tile position of the origin tile
-- @tparam[opt=false] boolean diagonal whether to include diagonal tiles
-- @tparam[opt] string tile_name whether to restrict adjacent tiles to a particular tile name (example: "water-tile")
-- @treturn {LuaTile.position,...} an array of tile positions of the tiles that are adjacent to the origin tile
function Tile.adjacent(surface, position, diagonal, tile_name)
Is.Assert(surface, 'missing surface argument')
Is.Assert(position, 'missing position argument')
local offsets = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
if diagonal then
offsets = {{0, 1}, {1, 1}, {1, 0}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}}
end
local adjacent_tiles = {}
for _, offset in pairs(offsets) do
local adj_pos = Position.add(position, offset)
if tile_name then
local tile = surface.get_tile(adj_pos.x, adj_pos.y)
if tile and tile.name == tile_name then
table.insert(adjacent_tiles, adj_pos)
end
else
table.insert(adjacent_tiles, adj_pos)
end
end
return adjacent_tiles
end
--- Gets the user data that is associated with a tile.
-- The user data is stored in the global object and it persists between loads.
-- @tparam LuaSurface surface the surface on which the user data is looked up
-- @tparam LuaTile.position tile_pos the tile position on which the user data is looked up
-- @tparam[opt] Mixed default_value the user data to set for the tile and returned if it did not have user data
-- @treturn ?|nil|Mixed the user data **OR** *nil* if it does not exist for the tile and no default_value was set
function Tile.get_data(surface, tile_pos, default_value)
surface = Game.get_surface(surface)
Is.Assert(surface, 'invalid surface')
local key = Position(tile_pos):tile_position():to_key()
return Game.get_or_set_data('_tile_data', surface.index, key, false, default_value)
end
Tile.get = Tile.get_data
--- Associates the user data to a tile.
-- The user data will be stored in the global object and it will persist between loads.
-- @tparam LuaSurface surface the surface on which the user data will reside
-- @tparam LuaTile.position tile_pos the tile position of a tile that will be associated with the user data
-- @tparam ?|nil|Mixed value the user data to set **OR** *nil* to erase the existing user data for the tile
-- @treturn ?|nil|Mixed the previous user data associated with the tile **OR** *nil* if the tile had no previous user data
function Tile.set_data(surface, tile_pos, value)
surface = Game.get_surface(surface)
Is.Assert.Valid(surface, 'invalid surface')
local key = Position(tile_pos):tile_position():to_key()
return Game.get_or_set_data('_tile_data', surface.index, key, true, value)
end
Tile.set = Tile.set_data
return Tile
|
function onEvent(name)
if name == 'Note NO' then
if value1 == '1' then
setProperty('opponentStrums.visible', false)
end
if value1 == '2' then
setProperty('opponentStrums.visible', true)
end end end
|
--[[
Title: SessionsData
Author(s): big
CreateDate: 2019.07.24
ModifyDate: 2021.09.24
place: Foshan
Desc:
use the lib:
------------------------------------------------------------
local SessionsData = NPL.load('(gl)Mod/WorldShare/database/SessionsData.lua')
------------------------------------------------------------
]]
-- config
local Config = NPL.load('(gl)Mod/WorldShare/config/Config.lua')
local SessionsData = NPL.export()
-- session struct
--[[
{
selectedUser = "1111",
allUsers = {
{
value = "1111",
text = "1111",
session = {
account = "1111",
loginServer = "ONLINE",
password = "12345678",
autoLogin = true,
rememberMe = true,
token = "jwttoken",
tokenExpire = 12345678,
loginTime = 111111111,
doNotNoticeVerify = false,
isVip = false,
userType = {
orgAdmin = false,
teacher = false,
student = false,
freeStudent = false,
plain = true,
}
},
allPositions = {
{
projectId = 1111,
lastPosition = { x = 19200, y = 6, x = 19200 },
orientation = { CameraLiftupAngle = 0.11111, CameraRotY = 0.22222 }
}
}
},
{
value = "2222",
text = "2222",
session = {
account = "2222",
loginServer = "STAGE",
autoLogin = false,
rememberMe = true,
token = "jwttoken",
tokenExpire = 12345678
}
},
{
value = "3333",
text = "3333",
session = {
account = "3333",
loginServer = "ONLINE",
autoLogin = false,
rememberMe = false,
password = "123456",
token = "jwttoken",
tokenExpire = 12345678
}
},
}
}
]]
function SessionsData:GetSessions()
local playerController = GameLogic.GetPlayerController()
return playerController:LoadLocalData("sessions", {
selectedUser = "",
allUsers = {}
}, true)
end
function SessionsData:RemoveSession(username)
local sessionsData = self:GetSessions()
if sessionsData.selectedUser == username then
sessionsData.selectedUser = ""
end
local newAllUsers = commonlib.Array:new(sessionsData.allUsers);
for key, item in ipairs(newAllUsers) do
if item.value == username then
newAllUsers:remove(key)
break
end
end
sessionsData.allUsers = newAllUsers
GameLogic.GetPlayerController():SaveLocalData("sessions", sessionsData, true)
end
function SessionsData:SaveSession(session)
if not session or not session.account or not session.loginServer then
return false
end
local oldSession = self:GetSessionByUsername(session.account)
if oldSession then
for key, item in pairs(oldSession) do
if session[key] == nil then
session[key] = item
end
end
end
if session.rememberMe == false then
session.password = nil
end
session.account = string.lower(session.account)
session.loginTime = os.time()
local sessionsData = self:GetSessions()
sessionsData.selectedUser = session.account
local beExist = false
for key, item in ipairs(sessionsData.allUsers) do
if item.value == session.account then
item.session = session
beExist = true
end
end
if not beExist then
sessionsData.allUsers[#sessionsData.allUsers + 1] = {
value = session.account,
text = session.account,
session = session
}
end
GameLogic.GetPlayerController():SaveLocalData("sessions", sessionsData, true)
end
function SessionsData:GetAnonymousUser()
local default = {
value = 'ano',
text = 'ano',
session = {
account = 'ano',
loginServer = Config.defaultEnv,
}
}
local sessionsData = self:GetSessions()
if not sessionsData or not sessionsData.allUsers then
return default
end
for key, item in ipairs(sessionsData.allUsers) do
if item.value == 'ano' then
return item
end
end
return default
end
function SessionsData:GetAnonymousInfo()
local anonymousUser = self:GetAnonymousUser()
if anonymousUser and anonymousUser.anonymousInfo and type(anonymousUser.anonymousInfo) == 'table' then
return anonymousUser.anonymousInfo
else
return {}
end
end
function SessionsData:SetAnyonymousInfo(key, value)
if not key or type(key) ~= 'string' or not value then
return false
end
local anonymousInfo = self:GetAnonymousInfo()
anonymousInfo[key] = value
local sessionsData = self:GetSessions()
if not sessionsData or type(sessionsData) ~= 'table' then
return false
end
local beExist = false
for key, item in ipairs(sessionsData.allUsers) do
if item.value == 'ano' then
item.anonymousInfo = anonymousInfo
beExist = true
end
end
if not beExist then
local anoUser = self:GetAnonymousUser()
anoUser.anonymousInfo = anonymousInfo
sessionsData.allUsers[#sessionsData.allUsers + 1] = anoUser
end
GameLogic.GetPlayerController():SaveLocalData("sessions", sessionsData, true)
return true
end
function SessionsData:GetSessionByUsername(username)
local sessionsData = SessionsData:GetSessions()
if not sessionsData or not sessionsData.allUsers then
return false
end
for key, item in ipairs(sessionsData.allUsers) do
if item.value == username then
return item.session
end
end
return false
end
function SessionsData:GetDeviceUUID()
local sessionsData = self:GetSessions()
local currentParacraftDir = ParaIO.GetWritablePath()
if not sessionsData.softwareUUID or
not sessionsData.paracraftDir or
sessionsData.paracraftDir ~= currentParacraftDir then
sessionsData.paracraftDir = ParaIO.GetWritablePath()
sessionsData.softwareUUID = System.Encoding.guid.uuid()
GameLogic.GetPlayerController():SaveLocalData("sessions", sessionsData, true)
end
local machineID = ParaEngine.GetAttributeObject():GetField("MachineID","")
return sessionsData.softwareUUID .. "-" .. machineID
end
function SessionsData:GetUserLastPosition(projectId, username)
if not username then
username = Mod.WorldShare.Store:Get('user/username')
end
if not projectId then
local currentEnterWorld = Mod.WorldShare.Store:Get('world/currentEnterWorld')
if not currentEnterWorld or not currentEnterWorld.kpProjectId or currentEnterWorld.kpProjectId == 0 then
return
end
projectId = currentEnterWorld.kpProjectId
end
local session = self:GetSessionByUsername(username)
if not session or type(session) ~= 'table' then
return
end
if session.allPositions and type(session.allPositions) == 'table' then
for key, item in ipairs(session.allPositions) do
if tonumber(item.projectId) == tonumber(projectId) then
return item
end
end
end
end
function SessionsData:SetUserLocation(where, username)
local session = self:GetSessionByUsername(username)
if not session or type(session) ~= 'table' then
return
end
session.where = where
self:SaveSession(session)
end
function SessionsData:SetUserLastPosition(x, y, z, cameraLiftupAngle, cameraRotY, projectId, username)
if not x or not y or not z or not cameraLiftupAngle or not cameraRotY then
return
end
if not username then
username = Mod.WorldShare.Store:Get('user/username')
end
if not projectId then
local currentEnterWorld = Mod.WorldShare.Store:Get('world/currentEnterWorld')
if not currentEnterWorld or not currentEnterWorld.kpProjectId or currentEnterWorld.kpProjectId == 0 then
return
end
projectId = currentEnterWorld.kpProjectId
end
local session = self:GetSessionByUsername(username)
if not session or type(session) ~= 'table' then
return
end
local beExist = false
local curItem = {}
if session.allPositions and type(session.allPositions) == 'table' then
for key, item in ipairs(session.allPositions) do
if tonumber(item.projectId) == tonumber(projectId) then
beExist = true
curItem = item
break
end
end
end
if beExist then
curItem.position = { x = x, y = y, z = z }
curItem.orientation = { cameraLiftupAngle = cameraLiftupAngle , cameraRotY = cameraRotY }
else
curItem = {
projectId = projectId,
position = { x = x, y = y, z = z },
orientation = { cameraLiftupAngle = cameraLiftupAngle , cameraRotY = cameraRotY }
}
if not session.allPositions or type(session.allPositions) ~= 'table' then
session.allPositions = {}
end
session.allPositions[#session.allPositions + 1] = curItem
end
self:SaveSession(session)
end
|
---@meta
---@class ccs.ArmatureDataManager :cc.Ref
local ArmatureDataManager={ }
ccs.ArmatureDataManager=ArmatureDataManager
---* brief remove animation data<br>
---* param id the id of the animation data
---@param id string
---@return self
function ArmatureDataManager:removeAnimationData (id) end
---* Add armature data<br>
---* param id The id of the armature data<br>
---* param armatureData ArmatureData *
---@param id string
---@param armatureData ccs.ArmatureData
---@param configFilePath string
---@return self
function ArmatureDataManager:addArmatureData (id,armatureData,configFilePath) end
---@overload fun(string:string,string:string,string:string):self
---@overload fun(string:string):self
---@param imagePath string
---@param plistPath string
---@param configFilePath string
---@return self
function ArmatureDataManager:addArmatureFileInfo (imagePath,plistPath,configFilePath) end
---*
---@param configFilePath string
---@return self
function ArmatureDataManager:removeArmatureFileInfo (configFilePath) end
---*
---@return map_table
function ArmatureDataManager:getTextureDatas () end
---* brief get texture data<br>
---* param id the id of the texture data you want to get<br>
---* return TextureData *
---@param id string
---@return ccs.TextureData
function ArmatureDataManager:getTextureData (id) end
---* brief get armature data<br>
---* param id the id of the armature data you want to get<br>
---* return ArmatureData *
---@param id string
---@return ccs.ArmatureData
function ArmatureDataManager:getArmatureData (id) end
---* brief get animation data from _animationDatas(Dictionary)<br>
---* param id the id of the animation data you want to get<br>
---* return AnimationData *
---@param id string
---@return ccs.AnimationData
function ArmatureDataManager:getAnimationData (id) end
---* brief add animation data<br>
---* param id the id of the animation data<br>
---* return AnimationData *
---@param id string
---@param animationData ccs.AnimationData
---@param configFilePath string
---@return self
function ArmatureDataManager:addAnimationData (id,animationData,configFilePath) end
---* Init ArmatureDataManager
---@return boolean
function ArmatureDataManager:init () end
---* brief remove armature data<br>
---* param id the id of the armature data you want to get
---@param id string
---@return self
function ArmatureDataManager:removeArmatureData (id) end
---*
---@return map_table
function ArmatureDataManager:getArmatureDatas () end
---* brief remove texture data<br>
---* param id the id of the texture data you want to get
---@param id string
---@return self
function ArmatureDataManager:removeTextureData (id) end
---* brief add texture data<br>
---* param id the id of the texture data<br>
---* return TextureData *
---@param id string
---@param textureData ccs.TextureData
---@param configFilePath string
---@return self
function ArmatureDataManager:addTextureData (id,textureData,configFilePath) end
---*
---@return map_table
function ArmatureDataManager:getAnimationDatas () end
---* brief Judge whether or not need auto load sprite file
---@return boolean
function ArmatureDataManager:isAutoLoadSpriteFile () end
---* brief Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name
---@param plistPath string
---@param imagePath string
---@param configFilePath string
---@return self
function ArmatureDataManager:addSpriteFrameFromFile (plistPath,imagePath,configFilePath) end
---*
---@return self
function ArmatureDataManager:destroyInstance () end
---*
---@return self
function ArmatureDataManager:getInstance () end
|
module(..., package.seeall)
local constants = require("apps.lwaftr.constants")
local fragmentv6 = require("apps.lwaftr.fragmentv6")
local fragv6_h = require("apps.lwaftr.fragmentv6_hardened")
local ndp = require("apps.lwaftr.ndp")
local lwutil = require("apps.lwaftr.lwutil")
local icmp = require("apps.lwaftr.icmp")
local lwcounter = require("apps.lwaftr.lwcounter")
local ethernet = require("lib.protocol.ethernet")
local ipv6 = require("lib.protocol.ipv6")
local checksum = require("lib.checksum")
local packet = require("core.packet")
local counter = require("core.counter")
local lib = require("core.lib")
local link = require("core.link")
local engine = require("core.app")
local bit = require("bit")
local ffi = require("ffi")
local receive, transmit = link.receive, link.transmit
local wr16 = lwutil.wr16
local is_ipv6, is_ipv6_fragment = lwutil.is_ipv6, lwutil.is_ipv6_fragment
local htons = lib.htons
local ipv6_fixed_header_size = constants.ipv6_fixed_header_size
local proto_icmpv6 = constants.proto_icmpv6
local ethernet_header_size = constants.ethernet_header_size
local o_icmpv6_header = ethernet_header_size + ipv6_fixed_header_size
local o_icmpv6_msg_type = o_icmpv6_header + constants.o_icmpv6_msg_type
local o_icmpv6_checksum = o_icmpv6_header + constants.o_icmpv6_checksum
local icmpv6_echo_request = constants.icmpv6_echo_request
local icmpv6_echo_reply = constants.icmpv6_echo_reply
local ehs = constants.ethernet_header_size
ReassembleV6 = {}
Fragmenter = {}
NDP = {}
ICMPEcho = {}
function ReassembleV6:new(conf)
local max_ipv6_reassembly_packets = conf.max_ipv6_reassembly_packets
local max_fragments_per_reassembly_packet = conf.max_fragments_per_reassembly_packet
local o = {
counters = lwcounter.init_counters(),
ctab = fragv6_h.initialize_frag_table(max_ipv6_reassembly_packets,
max_fragments_per_reassembly_packet),
}
counter.set(o.counters["memuse-ipv6-frag-reassembly-buffer"],
o.ctab:get_backing_size())
return setmetatable(o, {__index = ReassembleV6})
end
function ReassembleV6:cache_fragment(fragment)
return fragv6_h.cache_fragment(self.ctab, fragment)
end
function ReassembleV6:push ()
local input, output = self.input.input, self.output.output
local errors = self.output.errors
for _ = 1, link.nreadable(input) do
local pkt = receive(input)
if is_ipv6_fragment(pkt) then
counter.add(self.counters["in-ipv6-frag-needs-reassembly"])
local status, maybe_pkt, ejected = self:cache_fragment(pkt)
if ejected then
counter.add(self.counters["drop-ipv6-frag-random-evicted"])
end
if status == fragv6_h.REASSEMBLY_OK then
counter.add(self.counters["in-ipv6-frag-reassembled"])
transmit(output, maybe_pkt)
elseif status == fragv6_h.FRAGMENT_MISSING then
-- Nothing useful to be done yet, continue
elseif status == fragv6_h.REASSEMBLY_INVALID then
counter.add(self.counters["drop-ipv6-frag-invalid-reassembly"])
if maybe_pkt then -- This is an ICMP packet
transmit(errors, maybe_pkt)
end
else -- unreachable
packet.free(pkt)
end
else
-- Forward all packets that aren't IPv6 fragments.
counter.add(self.counters["in-ipv6-frag-reassembly-unneeded"])
transmit(output, pkt)
end
end
end
function Fragmenter:new(conf)
local o = {
counters = lwcounter.init_counters(),
mtu = assert(conf.mtu),
}
return setmetatable(o, {__index=Fragmenter})
end
function Fragmenter:push ()
local input, output = self.input.input, self.output.output
local mtu = self.mtu
for _ = 1, link.nreadable(input) do
local pkt = receive(input)
if pkt.length > mtu + ehs and is_ipv6(pkt) then
-- It's possible that the IPv6 packet has an IPv4 packet as
-- payload, and that payload has the Don't Fragment flag set.
-- However ignore this; the fragmentation policy of the L3
-- protocol (in this case, IP) doesn't affect the L2 protocol.
-- We always fragment.
local unfragmentable_header_size = ehs + ipv6_fixed_header_size
local pkts = fragmentv6.fragment(pkt, unfragmentable_header_size, mtu)
for i=1,#pkts do
counter.add(self.counters["out-ipv6-frag"])
transmit(output, pkts[i])
end
else
counter.add(self.counters["out-ipv6-frag-not"])
transmit(output, pkt)
end
end
end
function NDP:new(conf)
local o = setmetatable({}, {__index=NDP})
o.conf = conf
-- TODO: verify that the src and dst ipv6 addresses and src mac address
-- have been provided, in pton format.
if not conf.dst_eth then
self.ns_pkt = ndp.form_ns(conf.src_eth, conf.src_ipv6, conf.dst_ipv6)
self.ns_interval = 3 -- Send a new NS every three seconds.
end
o.dst_eth = conf.dst_eth -- Intentionally nil if to request by NS
return o
end
function NDP:maybe_send_ns_request (output)
if self.dst_eth then return end
self.next_ns_time = self.next_ns_time or engine.now()
if self.next_ns_time <= engine.now() then
print(("NDP: Resolving '%s'"):format(ipv6:ntop(self.conf.dst_ipv6)))
self:send_ns(output)
self.next_ns_time = engine.now() + self.ns_interval
end
end
function NDP:send_ns (output)
transmit(output, packet.clone(self.ns_pkt))
end
function NDP:push()
local isouth, osouth = self.input.south, self.output.south
local inorth, onorth = self.input.north, self.output.north
-- TODO: do unsolicited neighbor advertisement on start and on
-- configuration reloads?
-- This would be an optimization, not a correctness issue
self:maybe_send_ns_request(osouth)
for _ = 1, link.nreadable(isouth) do
local p = receive(isouth)
if ndp.is_ndp(p) then
if not self.dst_eth and ndp.is_solicited_neighbor_advertisement(p) then
local dst_ethernet = ndp.get_dst_ethernet(p, {self.conf.dst_ipv6})
if dst_ethernet then
print(("NDP: '%s' resolved (%s)"):format(ipv6:ntop(self.conf.dst_ipv6),
ethernet:ntop(dst_ethernet)))
self.dst_eth = dst_ethernet
end
packet.free(p)
elseif ndp.is_neighbor_solicitation_for_addr(p, self.conf.src_ipv6) then
local snap = ndp.form_nsolicitation_reply(self.conf.src_eth, self.conf.src_ipv6, p)
if snap then
transmit(osouth, snap)
end
packet.free(p)
else -- TODO? incoming NDP that we don't handle; drop it silently
packet.free(p)
end
else
transmit(onorth, p)
end
end
for _ = 1, link.nreadable(inorth) do
local p = receive(inorth)
if not self.dst_eth then
-- drop all southbound packets until the next hop's ethernet address is known
packet.free(p)
else
lwutil.set_dst_ethernet(p, self.dst_eth)
transmit(osouth, p)
end
end
end
function ICMPEcho:new(conf)
local addresses = {}
if conf.address then
addresses[ffi.string(conf.address, 16)] = true
end
if conf.addresses then
for _, v in ipairs(conf.addresses) do
addresses[ffi.string(v, 16)] = true
end
end
return setmetatable({addresses = addresses}, {__index = ICMPEcho})
end
function ICMPEcho:push()
local l_in, l_out, l_reply = self.input.south, self.output.north, self.output.south
for _ = 1, link.nreadable(l_in) do
local out, pkt = l_out, receive(l_in)
if icmp.is_icmpv6_message(pkt, icmpv6_echo_request, 0) then
local pkt_ipv6 = ipv6:new_from_mem(pkt.data + ethernet_header_size,
pkt.length - ethernet_header_size)
local pkt_ipv6_dst = ffi.string(pkt_ipv6:dst(), 16)
if self.addresses[pkt_ipv6_dst] then
ethernet:new_from_mem(pkt.data, ethernet_header_size):swap()
-- Swap IP source/destination
pkt_ipv6:dst(pkt_ipv6:src())
pkt_ipv6:src(pkt_ipv6_dst)
-- Change ICMP message type
pkt.data[o_icmpv6_msg_type] = icmpv6_echo_reply
-- Recalculate checksums
wr16(pkt.data + o_icmpv6_checksum, 0)
local ph_len = pkt.length - o_icmpv6_header
local ph = pkt_ipv6:pseudo_header(ph_len, proto_icmpv6)
local csum = checksum.ipsum(ffi.cast("uint8_t*", ph), ffi.sizeof(ph), 0)
csum = checksum.ipsum(pkt.data + o_icmpv6_header, 4, bit.bnot(csum))
csum = checksum.ipsum(pkt.data + o_icmpv6_header + 4,
pkt.length - o_icmpv6_header - 4,
bit.bnot(csum))
wr16(pkt.data + o_icmpv6_checksum, htons(csum))
out = l_reply
end
end
transmit(out, pkt)
end
l_in, l_out = self.input.north, self.output.south
for _ = 1, link.nreadable(l_in) do
transmit(l_out, receive(l_in))
end
end
|
---
-- String buffer facilities.
--
-- Lua's string operations are very flexible and offer an easy-to-use way to
-- manipulate strings. Concatenation using the <code>..</code> operator is such
-- an operation. The drawback of the built-in API however is the way it handles
-- concatenation of many string values. Since strings in Lua are immutable
-- values, each time you concatenate two strings both get copied into the
-- result string.
--
-- The <code>strbuf</code> module offers a workaround for this problem, while
-- maintaining the nice syntax. This is accomplished by overloading the
-- concatenation operator (<code>..</code>), the equality operator (<code>==</code>) and the <code>tostring</code>
-- operator. A string buffer is created by passing a string to
-- <code>strbuf.new</code>. Afterwards you can append to the string buffer,
-- or compare two string buffers for equality just as you would do with normal
-- strings.
--
-- When looking at the details there are some more restrictions/oddities: The
-- concatenation operator requires its left-hand value to be a string buffer.
-- Therefore, if you want to prepend a string to a given string buffer you have
-- to create a new string buffer out of the string you want to prepend. The
-- string buffer's <code>tostring</code> operator concatenates the strings
-- inside the buffer using newlines by default, since this appears to be the
-- separator used most often.
--
-- Example usage:
-- <code>
-- local buf = strbuf.new()
-- local buf2 = strbuf.new('hello')
-- buf = buf .. 'string'
-- buf = buf .. 'data'
-- print(buf) -- default separator is a newline
-- print(strbuf.dump(buf)) -- no separator
-- print(strbuf.dump(buf, ' ')) -- separated by spaces
-- strbuf.clear(buf)
-- </code>
-- @copyright Same as Nmap--See https://nmap.org/book/man-legal.html
-- DEPENDENCIES --
local stdnse = require "stdnse"
local table = require "table"
local getmetatable = getmetatable;
local setmetatable = setmetatable;
local type = type;
local error = error;
local ipairs = ipairs;
local pairs = pairs;
local concat = table.concat;
_ENV = stdnse.module("strbuf", stdnse.seeall)
-- String buffer functions. Concatenation is not efficient in
-- lua as strings are immutable. If a large amount of '..' sequential
-- operations are needed a string buffer should be used instead
-- e.g. for i = 1, 10 do s = s..i end
--- Dumps the string buffer as a string.
--
-- The second parameter is used as a delimiter between the strings stored inside
-- the string buffer.
-- @name dump
-- @class function
-- @param sbuf String buffer to dump.
-- @param delimiter String to separate the buffer's contents.
-- @return Concatenated string result.
dump = concat;
--- Appends a string to a string buffer.
-- @param sbuf String buffer.
-- @param s String to append.
-- @return <code>sbuf</code>.
function concatbuf(sbuf, s)
if type(s) == "string" then
sbuf[#sbuf+1] = s;
elseif getmetatable(s) == getmetatable(sbuf) then
for _,v in ipairs(s) do
sbuf[#sbuf+1] = v;
end
else
error("bad #2 operand to strbuf concat operation", 2);
end
return sbuf;
end
--- Determines if the two string buffers are equal. Two buffers are equal
-- if they are the same or if they have equivalent contents.
-- @param sbuf1 String buffer one.
-- @param sbuf2 String buffer two.
-- @return True if equal, false otherwise.
function eqbuf(sbuf1, sbuf2)
if getmetatable(sbuf1) ~= getmetatable(sbuf2) then
error("one or more operands is not a string buffer", 2);
elseif #sbuf1 ~= #sbuf2 then
return false;
else
for i = 1, #sbuf1 do
if sbuf1[i] ~= sbuf2[i] then
return false;
end
end
return true;
end
end
--- Clears a string buffer.
-- @param sbuf String buffer.
function clear(sbuf)
for k in pairs(sbuf) do
sbuf[k] = nil;
end
end
--- Returns the string buffer as a string. The delimiter used is a newline.
-- @param sbuf String buffer.
-- @return String made from concatenating the buffer.
function tostring(sbuf)
return concat(sbuf, "\n");
end
local mt = {
__concat = concatbuf,
__tostring = tostring,
__eq = eqbuf,
__index = _M,
};
--- Create a new string buffer.
--
-- The optional arguments are added to the string buffer. The result of adding
-- non-strings is undefined. The <code>equals</code> and <code>tostring</code>
-- operators for string buffers are overloaded to be <code>eqbuf</code> and
-- <code>tostring</code> respectively.
-- @param ... Strings to add to the buffer initially.
-- @return String buffer.
function new(...)
return setmetatable({...}, mt);
end
return _ENV;
|
local K, C, L, _ = select(2, ...):unpack()
local argcheck = oGlow.argcheck
local colorTable = setmetatable(
{},
{__index = function(self, val)
argcheck(val, 2, "number")
local r, g, b = GetItemQualityColor(val)
rawset(self, val, {r, g, b})
return self[val]
end}
)
local createBorder = function(self, point)
local bc = self.oGlowBorder
if not bc then
if IsAddOnLoaded("Aurora") == true then
if not self:IsObjectType("Frame") then
bc = CreateFrame("Frame", nil, self:GetParent())
else
bc = CreateFrame("Frame", nil, self)
end
bc:SetBackdrop({
edgeFile = C.Media.Blank,
edgeSize = 1,
})
if self.backdrop then
bc:SetPoint("TOPLEFT", 0, 0)
bc:SetPoint("BOTTOMRIGHT", 0, 0)
else
bc:SetPoint("TOPLEFT", point or self, 0, 0)
bc:SetPoint("BOTTOMRIGHT", point or self, 0, 0)
end
else
if not self:IsObjectType("Frame") then
bc = self:GetParent():CreateTexture(nil, "OVERLAY")
else
bc = self:CreateTexture(nil, "OVERLAY")
end
bc:SetTexture("Interface\\Buttons\\UI-ActionButton-Border")
bc:SetBlendMode("ADD")
bc:SetAlpha(0.8)
bc:SetWidth(70)
bc:SetHeight(70)
bc:SetPoint("CENTER", point or self)
end
self.oGlowBorder = bc
end
return bc
end
local borderDisplay = function(frame, color)
if color then
local bc = createBorder(frame)
local rgb = colorTable[color]
if rgb then
if IsAddOnLoaded("Aurora") == true then
bc:SetBackdropBorderColor(rgb[1], rgb[2], rgb[3])
if bc.backdrop then
bc.backdrop:SetBackdropBorderColor(rgb[1], rgb[2], rgb[3])
end
else
bc:SetVertexColor(rgb[1], rgb[2], rgb[3])
end
bc:Show()
end
return true
elseif frame.oGlowBorder then
frame.oGlowBorder:Hide()
end
end
function oGlow:RegisterColor(name, r, g, b)
argcheck(name, 2, "string", "number")
argcheck(r, 3, "number")
argcheck(g, 4, "number")
argcheck(b, 5, "number")
if(rawget(colorTable, name)) then
return nil, string.format("Color [%s] is already registered.", name)
else
rawset(colorTable, name, {r, g, b})
end
return true
end
oGlow:RegisterDisplay("Border", borderDisplay)
|
local util = {}
function util.disableFastUpToDateCheck(projectNames)
require "vstudio"
local p = premake;
local vc = p.vstudio.vc2010;
function disableFastUpToDateCheck(prj, cfg)
for _, value in pairs(projectNames) do
if prj.name == value then
vc.element("DisableFastUpToDateCheck", nil, "true")
end
end
end
p.override(vc.elements, "globalsCondition", function(oldfn, prj, cfg)
local elements = oldfn(prj, cfg)
elements = table.join(elements, { disableFastUpToDateCheck })
return elements
end)
end
function util.joinFlags(...)
local t = ""
for _, g in ipairs({...}) do
for _, v in ipairs(g) do
t = t .. v .. " "
end
end
return t
end
return util
|
---
--- time.lua
---
--- Copyright (C) 2018-2020 Xrysnow. All rights reserved.
---
--
local M = {}
local ffi = require('ffi')
local k32 = ffi.load('kernel32')
ffi.cdef [[
BOOL QueryPerformanceFrequency(
LARGE_INTEGER *lpFrequency
);
BOOL QueryPerformanceCounter(
LARGE_INTEGER *lpPerformanceCount
);
void Sleep(
DWORD dwMilliseconds
);
]]
ffi.cdef [[
typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME;
void GetLocalTime(
PSYSTEMTIME lpSystemTime
);
//void GetSystemTime(
// PSYSTEMTIME lpSystemTime
//);
void GetSystemTimeAsFileTime(
PFILETIME lpSystemTimeAsFileTime
);
void GetSystemTimeAsPreciseFileTime(
PFILETIME lpSystemTimeAsFileTime
);
]]
function M.QueryPerformanceFrequency()
local lpFrequency = ffi.new('LARGE_INTEGER[1]')
k32.QueryPerformanceFrequency(lpFrequency)
return lpFrequency[0]
end
function M.QueryPerformanceCounter()
local lpPerformanceCount = ffi.new('LARGE_INTEGER[1]')
k32.QueryPerformanceFrequency(lpPerformanceCount)
return lpPerformanceCount[0]
end
function M.Sleep(ms)
assert(ms >= 0)
k32.Sleep(ms)
end
local cpu_counters, pdh
local function getProcesserTimePath(n)
if n then
return string.format([[\Processor Information(0,%d)\]], n) .. "% Processor Time"
else
return [[\Processor Information(_Total)\% Processor Time]]
end
end
--- QueryCPUTime
--- This function should be called at a interval of at least 1 second.
function M.QueryCPUTime()
pdh = pdh or require('platform.windows.pdh')
if not cpu_counters then
cpu_counters = {}
cpu_counters[-1] = pdh.PdhAddCounter(getProcesserTimePath())
for i = 0, 7 do
cpu_counters[i] = pdh.PdhAddCounter(getProcesserTimePath(i))
end
end
pdh.PdhCollectQueryData()
M.Sleep(1000)
pdh.PdhCollectQueryData()
local ret = {}
for i = -1, 7 do
local val = pdh.PdhGetFormattedCounterValue(cpu_counters[i], { 'double' }).doubleValue
ret[i] = val
end
return ret
end
return M
|
local Table = require("Utils.Table")
local ScenarioUtils = {}
function ScenarioUtils.create_item_chests(surface, position, force, items, chest_type)
local chest
local created_chests = {}
if not chest_type then chest_type = "steel-chest" end
local function create_chest()
local pos = surface.find_non_colliding_position(chest_type, position, 10, 0.5)
chest = surface.create_entity{name=chest_type, force = force, position = pos}
table.insert(created_chests, chest)
end
create_chest()
for item, count in pairs(items) do
-- Insert into current chest, then create new ones and insert until all of this type is inserted.
local all_inserted = false
while not all_inserted do
local inserted = chest.get_inventory(defines.inventory.chest).insert{name=item, count=count}
count = count - inserted
if count > 0 then
create_chest()
else
all_inserted = true
end
end
end
return created_chests
end
function ScenarioUtils.spawn_player(player, surface, position, items)
if player.character then player.character.destroy() end
local pos = surface.find_non_colliding_position("player", position, 30, 1.3)
player.teleport(pos, surface)
player.create_character()
for item_type, item_param in pairs(items or {}) do
if type(item_param) == "number" then
player.insert{name=item_type, count=item_param}
else
-- Armor
if type(item_param) == "table" and item_param.type == "armor" then
local inv = player.get_inventory(defines.inventory.player_armor)
inv.insert{name=item_type}
local grid = inv[1].grid
for _, item in pairs(item_param.equipment) do
if type(item) == "string" then
grid.put{name=item}
else
if item.count == "fill" then
local added = true
while added do
added = grid.put{name=item.name, position=item.position}
end
else
for _=1, item.count or 1 do
grid.put{name=item.name, position=item.position}
end
end
end
end
end
end
end
end
return ScenarioUtils
|
--[[
MIT License
Copyright (c) 2021 Michael Wiesendanger
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 mod = rgpvpw
local me = {}
mod.testCombatEventsSelfAvoidDruidEn = me
me.tag = "TestCombatEventsSelfAvoidDruidEn"
local testGroupName = "CombatEventsSelfAvoidDruidEn"
local testCategory = "druid"
function me.Test()
mod.testReporter.StartTestGroup(testGroupName)
me.CollectTestCases()
mod.testReporter.PlayTestQueueWithDelay(function()
mod.testReporter.StopTestGroup() -- asyncron finish of testgroup
end)
end
function me.CollectTestCases()
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventSelfAvoidEntanglingRootsImmune)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventSelfAvoidEntanglingRootsResisted)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventSelfAvoidFaerieFireImmune)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventSelfAvoidFaerieFireResisted)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventSelfAvoidFaerieFireFeralImmune)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventSelfAvoidFaerieFireFeralResisted)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventSelfAvoidBashDodged)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventSelfAvoidBashParried)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventSelfAvoidBashImmune)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventSelfAvoidBashMissed)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventSelfAvoidBashResisted)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventSelfAvoidFeralChargeEffectImmune)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventSelfAvoidFeralChargeEffectResisted)
end
function me.TestCombatEventSelfAvoidEntanglingRootsImmune()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventSelfAvoidEntanglingRootsImmune",
testCategory,
"Entangling Roots",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF,
RGPVPW_CONSTANTS.MISS_TYPES.IMMUNE
)
end
function me.TestCombatEventSelfAvoidEntanglingRootsResisted()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventSelfAvoidEntanglingRootsResisted",
testCategory,
"Entangling Roots",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF,
RGPVPW_CONSTANTS.MISS_TYPES.RESIST
)
end
function me.TestCombatEventSelfAvoidFaerieFireImmune()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventSelfAvoidFaerieFireImmune",
testCategory,
"Faerie Fire",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF,
RGPVPW_CONSTANTS.MISS_TYPES.IMMUNE
)
end
function me.TestCombatEventSelfAvoidFaerieFireResisted()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventSelfAvoidFaerieFireResisted",
testCategory,
"Faerie Fire",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF,
RGPVPW_CONSTANTS.MISS_TYPES.RESIST
)
end
function me.TestCombatEventSelfAvoidFaerieFireFeralImmune()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventSelfAvoidFaerieFireFeralImmune",
testCategory,
"Faerie Fire (Feral)",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF,
RGPVPW_CONSTANTS.MISS_TYPES.IMMUNE
)
end
function me.TestCombatEventSelfAvoidFaerieFireFeralResisted()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventSelfAvoidFaerieFireFeralResisted",
testCategory,
"Faerie Fire (Feral)",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF,
RGPVPW_CONSTANTS.MISS_TYPES.RESIST
)
end
function me.TestCombatEventSelfAvoidBashDodged()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventSelfAvoidBashDodged",
testCategory,
"Bash",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF,
RGPVPW_CONSTANTS.MISS_TYPES.DODGE
)
end
function me.TestCombatEventSelfAvoidBashParried()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventSelfAvoidBashParried",
testCategory,
"Bash",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF,
RGPVPW_CONSTANTS.MISS_TYPES.PARRY
)
end
function me.TestCombatEventSelfAvoidBashImmune()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventSelfAvoidBashImmune",
testCategory,
"Bash",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF,
RGPVPW_CONSTANTS.MISS_TYPES.IMMUNE
)
end
function me.TestCombatEventSelfAvoidBashMissed()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventSelfAvoidBashMissed",
testCategory,
"Bash",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF,
RGPVPW_CONSTANTS.MISS_TYPES.MISS
)
end
function me.TestCombatEventSelfAvoidBashResisted()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventSelfAvoidBashResisted",
testCategory,
"Bash",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF,
RGPVPW_CONSTANTS.MISS_TYPES.RESIST
)
end
function me.TestCombatEventSelfAvoidFeralChargeEffectImmune()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventSelfAvoidFeralChargeEffectImmune",
testCategory,
"Feral Charge Effect",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF,
RGPVPW_CONSTANTS.MISS_TYPES.IMMUNE
)
end
function me.TestCombatEventSelfAvoidFeralChargeEffectResisted()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventSelfAvoidFeralChargeEffectResisted",
testCategory,
"Feral Charge Effect",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF,
RGPVPW_CONSTANTS.MISS_TYPES.RESIST
)
end
|
--[[
Copyright (C) 2013-2018 Draios Inc dba Sysdig.
This file is part of sysdig.
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.
--]]
-- Chisel description
description = "Print the standard error of any process on screen. Combine this script with a filter to limit the output to a specific process or pid. This chisel is compatible with containers using the sysdig -pc or -pcontainer argument, otherwise no container information will be shown. (Blue represents a process running within a container, and Green represents a host process)";
short_description = "Print stderr of processes";
category = "I/O";
-- Chisel argument list
args =
{
{
name = "disable_color",
description = "Set to 'disable_colors' if you want to disable color output",
argtype = "string",
optional = true
},
}
terminal = require "ansiterminal"
terminal.enable_color(true)
-- Argument notification callback
function on_set_arg(name, val)
if name == "disable_color" and val == "disable_color" then
terminal.enable_color(false)
return true
end
return false
end
-- Initialization callback
function on_init()
-- Request the fields that we need
fbuf = chisel.request_field("evt.rawarg.data")
fcontainername = chisel.request_field("container.name")
fcontainerid = chisel.request_field("container.id")
-- The -pc or -pcontainer options was supplied on the cmd line
print_container = sysdig.is_print_container_data()
-- increase the snaplen so we capture more of the conversation
sysdig.set_snaplen(2000)
-- set the filter
chisel.set_filter("fd.num=2 and evt.is_io=true")
return true
end
-- Event parsing callback
function on_event()
local color = ""
-- If -pc or -pcontainer option change default to green
if print_container then
color = terminal.green
end
local buf = evt.field(fbuf)
local containername = evt.field(fcontainername)
local containerid = evt.field(fcontainerid)
if buf ~= nil then
-- The -pc or -pcontainer options was supplied on the cmd line
if print_container then
-- Container will print out as blue
if containername ~= "host" then
color = terminal.blue
end
print(color .. string.format("%-20.20s %-20.20s %s",
containerid,
containername,
buf ))
else
print(buf)
end
end
return true
end
|
local name_comparable = require("spec.name_comparable")
local make_fake_player = require("spec.fake_playerobject")
---@param name string
---@param owner? string
local function make_fake_planet(name, owner)
local planet_type = name_comparable(name)
function planet_type.Get_Name()
return name
end
local planet = name_comparable(name)
function planet.Get_Type()
return planet_type
end
function planet.Get_Owner()
return make_fake_player(owner or "OWNER")
end
return planet
end
return make_fake_planet
|
-----------------------------------
-- Namas Arrow
-- Skill Level: N/A
-- Description: Additional Effect: Temporarily improves Ranged Accuracy
-- Aligned with the Light Gorget, Snow Gorget & Aqua Gorget.
-- Properties
-- Element: N/A
-- Skillchain Properties: Light/Distortion
-- Modifiers: STR: 40% AGI: 40%
-- Damage Multipliers by TP:
-- 100%TP 200%TP 300%TP
-- 2.75 2.75 2.75
-----------------------------------
require("scripts/globals/aftermath")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 1
params.ftp100 = 2.75 params.ftp200 = 2.75 params.ftp300 = 2.75
params.str_wsc = 0.4 params.dex_wsc = 0.0 params.vit_wsc = 0.0
params.agi_wsc = 0.4 params.int_wsc = 0.0 params.mnd_wsc = 0.0
params.chr_wsc = 0.0
params.crit100 = 0.0 params.crit200 = 0.0 params.crit300 = 0.0
params.canCrit = false
params.acc100 = 0.0 params.acc200 = 0.0 params.acc300 = 0.0
params.atk100 = 1; params.atk200 = 1; params.atk300 = 1
params.overrideCE = 160
params.overrideVE = 480
-- Apply aftermath
tpz.aftermath.addStatusEffect(player, tp, tpz.slot.RANGED, tpz.aftermath.type.RELIC)
local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, action, primary)
return tpHits, extraHits, criticalHit, damage
end
|
local att = {}
att.name = "md_rugersup"
att.displayName = "22LR Suppressor"
att.displayNameShort = "Suppressor"
att.isSuppressor = true
att.statModifiers = {DamageMult = -0.2}
if CLIENT then
att.displayIcon = surface.GetTextureID("atts/saker")
att.description = {[1] = {t = "Suppressor and barrel extension.", c = CustomizableWeaponry.textColors.POSITIVE}}
end
function att:attachFunc()
self.dt.Suppressed = true
end
function att:detachFunc()
self.dt.Suppressed = false
end
CustomizableWeaponry:registerAttachment(att)
|
function love.conf(t)
t.identity = "bitmapfontcreator"
t.window.title = "Bitmapfontcreator - loading..."
-- t.console = true
t.window.resizable = true
t.modules.audio = false
t.modules.data = false
-- t.modules.event = false
-- t.modules.font = false
-- t.modules.graphics = false
-- t.modules.image = false
t.modules.joystick = false
-- t.modules.keyboard = false
-- t.modules.math = false
-- t.modules.mouse = false
t.modules.physics = false
t.modules.sound = false
t.modules.system = false
t.modules.thread = false
-- t.modules.timer = false
t.modules.touch = false
t.modules.video = false
-- t.modules.window = false
end
|
local ffi = require("ffi")
require "lj2intelxed.obj.xed-chip-enum"
#include "xed-error-enum"
#include "xed-iclass-enum"
#include "xed-reg-enum"
#include "xed-operand-element-type-enum"
ffi.cdef[[
typedef struct xed_operand_storage_s {
xed_uint64_t disp;
xed_uint64_t uimm0;
xed_uint16_t mem_width;
xed_uint16_t iclass;
xed_uint16_t base0;
xed_uint16_t base1;
xed_uint16_t element_size;
xed_uint16_t index;
xed_uint16_t outreg;
xed_uint16_t reg0;
xed_uint16_t reg1;
xed_uint16_t reg2;
xed_uint16_t reg3;
xed_uint16_t reg4;
xed_uint16_t reg5;
xed_uint16_t reg6;
xed_uint16_t reg7;
xed_uint16_t reg8;
xed_uint16_t seg0;
xed_uint16_t seg1;
xed_uint8_t brdisp_width;
xed_uint8_t disp_width;
xed_uint8_t ild_seg;
xed_uint8_t imm1_bytes;
xed_uint8_t imm_width;
xed_uint8_t max_bytes;
xed_uint8_t modrm_byte;
xed_uint8_t nominal_opcode;
xed_uint8_t nprefixes;
xed_uint8_t nrexes;
xed_uint8_t nseg_prefixes;
xed_uint8_t pos_disp;
xed_uint8_t pos_imm;
xed_uint8_t pos_imm1;
xed_uint8_t pos_modrm;
xed_uint8_t pos_nominal_opcode;
xed_uint8_t pos_sib;
xed_uint8_t uimm1;
xed_uint8_t chip;
xed_uint8_t need_memdisp;
xed_uint8_t bcast;
xed_uint8_t error;
xed_uint8_t esrc;
xed_uint8_t map;
xed_uint8_t nelem;
xed_uint8_t scale;
xed_uint8_t type;
xed_uint8_t hint;
xed_uint8_t mask;
xed_uint8_t reg;
xed_uint8_t rm;
xed_uint8_t roundc;
xed_uint8_t seg_ovd;
xed_uint8_t sibbase;
xed_uint8_t sibindex;
xed_uint8_t srm;
xed_uint8_t vexdest210;
xed_uint8_t vexvalid;
xed_uint8_t default_seg;
xed_uint8_t easz;
xed_uint8_t eosz;
xed_uint8_t first_f2f3;
xed_uint8_t has_modrm;
xed_uint8_t last_f2f3;
xed_uint8_t llrc;
xed_uint8_t mod;
xed_uint8_t mode;
xed_uint8_t rep;
xed_uint8_t sibscale;
xed_uint8_t smode;
xed_uint8_t vex_prefix;
xed_uint8_t vl;
xed_uint8_t agen;
xed_uint8_t amd3dnow;
xed_uint8_t asz;
xed_uint8_t bcrc;
xed_uint8_t df32;
xed_uint8_t df64;
xed_uint8_t dummy;
xed_uint8_t encoder_preferred;
xed_uint8_t evexrr;
xed_uint8_t has_sib;
xed_uint8_t ild_f2;
xed_uint8_t ild_f3;
xed_uint8_t imm0;
xed_uint8_t imm0signed;
xed_uint8_t imm1;
xed_uint8_t lock;
xed_uint8_t lzcnt;
xed_uint8_t mem0;
xed_uint8_t mem1;
xed_uint8_t modep5;
xed_uint8_t modep55c;
xed_uint8_t mode_first_prefix;
xed_uint8_t modrm;
xed_uint8_t mpxmode;
xed_uint8_t needrex;
xed_uint8_t norex;
xed_uint8_t no_scale_disp8;
xed_uint8_t osz;
xed_uint8_t out_of_bytes;
xed_uint8_t p4;
xed_uint8_t prefix66;
xed_uint8_t ptr;
xed_uint8_t realmode;
xed_uint8_t relbr;
xed_uint8_t rex;
xed_uint8_t rexb;
xed_uint8_t rexr;
xed_uint8_t rexrr;
xed_uint8_t rexw;
xed_uint8_t rexx;
xed_uint8_t sae;
xed_uint8_t sib;
xed_uint8_t skip_osz;
xed_uint8_t tzcnt;
xed_uint8_t ubit;
xed_uint8_t using_default_segment0;
xed_uint8_t using_default_segment1;
xed_uint8_t vexdest3;
xed_uint8_t vexdest4;
xed_uint8_t vex_c4;
xed_uint8_t zeroing;
} xed_operand_storage_t;
]]
|
-- Lua bindings for /Volumes/Brume/Celedev CodeFlow/CodeFlow Sample Applications/TextKitSimpleLayout/TextKitSimpleLayout/PathImageView.h
-- Generated by Celedev® LuaBindingsGenerator on 2015-09-16 12:27:42 +0000
-- Objective C interface: @interface PathImageView
local PathImageView = objc.classInterface ("PathImageView") --[[ @inherits UIView]]
function PathImageView:initWithFrame_shape_image (frame --[[@type struct.CGRect]], shape --[[@type objc.UIBezierPath]], image --[[@type objc.UIImage]]) --[[@return objcid]] end
PathImageView.viewShape --[[@type objc.UIBezierPath]] = nil
PathImageView.viewImage --[[@type objc.UIImage]] = nil
function PathImageView:viewShape () --[[@return objc.UIBezierPath]] end
function PathImageView:setViewShape (viewShape --[[@type objc.UIBezierPath]]) --[[@return nil]] end
function PathImageView:viewImage () --[[@return objc.UIImage]] end
function PathImageView:setViewImage (viewImage --[[@type objc.UIImage]]) --[[@return nil]] end
|
-----------------------------------
-- Area: West Ronfaure
-- NPC: Aaveleon
-- Involved in Quest: A Sentry's Peril
-- !pos -431 -45 343 100
-----------------------------------
require("scripts/globals/npc_util")
require("scripts/globals/quests")
-----------------------------------
function onTrade(player, npc, trade)
if player:getQuestStatus(SANDORIA, tpz.quest.id.sandoria.A_SENTRY_S_PERIL) == QUEST_ACCEPTED then
if npcUtil.tradeHas(trade, 600) then
player:startEvent(100)
else
player:startEvent(118)
end
end
end
function onTrigger(player, npc)
player:startEvent(101)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 100 and npcUtil.giveItem(player, 601) then
player:confirmTrade()
end
end
|
local GAME_LAYER =
{
LAYER_SKYBOX = 1,
LAYER_GAME = 2,
LAYER_UI = 3,
LAYER_ACTOR = 4,
LAYER_ZOOM = 5,
LAYER_OSD = 6,
LAYER_COUNT = 7,
}
local s_CF =
{
cc.CameraFlag.DEFAULT,
cc.CameraFlag.USER1,
cc.CameraFlag.USER2,
cc.CameraFlag.USER3,
cc.CameraFlag.USER4,
cc.CameraFlag.USER5,
}
local s_CM =
{
s_CF[1],
s_CF[2],
s_CF[3],
s_CF[4],
s_CF[5],
s_CF[6],
}
----------------------------------------
----TerrainWalkThru
----------------------------------------
local PLAER_STATE =
{
LEFT = 0,
RIGHT = 1,
IDLE = 2,
FORWARD = 3,
BACKWARD = 4,
}
local PLAYER_HEIGHT = 0
local camera_offset = cc.vec3(0, 45, 60)
local Player = class("Player", function(file, cam, terrain)
local sprite = cc.Sprite3D:create(file)
if nil ~= sprite then
sprite._headingAngle = 0
sprite._playerState = PLAER_STATE.IDLE
sprite._cam = cam
sprite._terrain = terrain
end
return sprite
end)
function Player:ctor()
-- body
self:init()
end
function Player:init()
self._headingAxis = cc.vec3(0.0, 0.0, 0.0)
self:scheduleUpdateWithPriorityLua(function(dt)
local curPos = self:getPosition3D()
if self._playerState == PLAER_STATE.IDLE then
elseif self._playerState == PLAER_STATE.FORWARD then
local newFaceDir = cc.vec3( self._targetPos.x - curPos.x, self._targetPos.y - curPos.y, self._targetPos.z - curPos.z)
newFaceDir.y = 0.0
newFaceDir = cc.vec3normalize(newFaceDir)
local offset = cc.vec3(newFaceDir.x * 25.0 * dt, newFaceDir.y * 25.0 * dt, newFaceDir.z * 25.0 * dt)
curPos = cc.vec3(curPos.x + offset.x, curPos.y + offset.y, curPos.z + offset.z)
self:setPosition3D(curPos)
elseif self._playerState == PLAER_STATE.BACKWARD then
local transform = self:getNodeToWorldTransform()
local forward_vec = cc.vec3(-transform[9], -transform[10], -transform[11])
forward_vec = cc.vec3normalize(forward_vec)
self:setPosition3D(cc.vec3(curPos.x - forward_vec.x * 15 * dt, curPos.y - forward_vec.y * 15 * dt, curPos.z - forward_vec.z * 15 *dt))
elseif self._playerState == PLAER_STATE.LEFT then
player:setRotation3D(cc.vec3(curPos.x, curPos.y + 25 * dt, curPos.z))
elseif self._playerState == PLAER_STATE.RIGHT then
player:setRotation3D(cc.vec3(curPos.x, curPos.y - 25 * dt, curPos.z))
end
local normal = cc.vec3(0.0, 0.0, 0.0)
local player_h, normal = self._terrain:getHeight(self:getPositionX(), self:getPositionZ(), normal)
self:setPositionY(player_h + PLAYER_HEIGHT)
--need to scriptfile
local q2 = cc.quaternion_createFromAxisAngle(cc.vec3(0, 1, 0), -math.pi)
local headingQ = cc.quaternion_createFromAxisAngle(self._headingAxis, self._headingAngle)
local x = headingQ.w * q2.x + headingQ.x * q2.w + headingQ.y * q2.z - headingQ.z * q2.y
local y = headingQ.w * q2.y - headingQ.x * q2.z + headingQ.y * q2.w + headingQ.z * q2.x
local z = headingQ.w * q2.z + headingQ.x * q2.y - headingQ.y * q2.x + headingQ.z * q2.w
local w = headingQ.w * q2.w - headingQ.x * q2.x - headingQ.y * q2.y - headingQ.z * q2.z
headingQ = cc.quaternion(x, y, z, w)
self:setRotationQuat(headingQ)
local vec_offset = cc.vec4(camera_offset.x, camera_offset.y, camera_offset.z, 1)
local transform = self:getNodeToWorldTransform()
local dst = cc.vec4(0.0, 0.0, 0.0, 0.0)
vec_offset = mat4_transformVector(transform, vec_offset, dst)
local playerPos = self:getPosition3D()
self._cam:setPosition3D(cc.vec3(playerPos.x + camera_offset.x, playerPos.y + camera_offset.y, playerPos.z + camera_offset.z))
self:updateState()
end, 0)
self:registerScriptHandler(function (event)
-- body
if "exit" == event then
self:unscheduleUpdate()
end
end)
end
function Player:updateState()
if self._playerState == PLAER_STATE.FORWARD then
local player_pos = cc.p(self:getPositionX(),self:getPositionZ())
local targetPos = cc.p(self._targetPos.x, self._targetPos.z)
local dist = cc.pGetDistance(player_pos, targetPos)
if dist < 1 then
self._playerState = PLAER_STATE.IDLE
end
end
end
local TerrainWalkThru = class("TerrainWalkThru", function ()
local layer = cc.Layer:create()
Helper.initWithLayer(layer)
return layer
end)
function TerrainWalkThru:ctor()
-- body
local function onNodeEvent(event)
if "enter" == event then
self:onEnter()
elseif "exit" == event then
self:onExit()
end
end
self:registerScriptHandler(onNodeEvent)
end
function TerrainWalkThru:onEnter()
self:init()
end
function TerrainWalkThru:onExit()
end
function TerrainWalkThru:init()
Helper.titleLabel:setString(self:title())
Helper.subtitleLabel:setString(self:subtitle())
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(function (touches, event)
end,cc.Handler.EVENT_TOUCHES_BEGAN)
listener:registerScriptHandler(function (touches, event)
local touch = touches[1]
local location = touch:getLocationInView()
if self._camera ~= nil then
if self._player ~= nil then
local nearP = cc.vec3(location.x, location.y, 0.0)
local farP = cc.vec3(location.x, location.y, 1.0)
local size = cc.Director:getInstance():getWinSize()
nearP = self._camera:unproject(size, nearP, nearP)
farP = self._camera:unproject(size, farP, farP)
local dir = cc.vec3(farP.x - nearP.x, farP.y - nearP.y, farP.z - nearP.z)
dir = cc.vec3normalize(dir)
local rayStep = cc.vec3(15 * dir.x, 15 * dir.y, 15 * dir.z)
local rayPos = nearP
local rayStartPosition = nearP
local lastRayPosition = rayPos
rayPos = cc.vec3(rayPos.x + rayStep.x, rayPos.y + rayStep.y, rayPos.z + rayStep.z)
-- Linear search - Loop until find a point inside and outside the terrain Vector3
local height = self._terrain:getHeight(rayPos.x, rayPos.z)
while rayPos.y > height do
lastRayPosition = rayPos
rayPos = cc.vec3(rayPos.x + rayStep.x, rayPos.y + rayStep.y, rayPos.z + rayStep.z)
height = self._terrain:getHeight(rayPos.x,rayPos.z)
end
local startPosition = lastRayPosition
local endPosition = rayPos
for i = 1, 32 do
-- Binary search pass
local middlePoint = cc.vec3(0.5 * (startPosition.x + endPosition.x), 0.5 * (startPosition.y + endPosition.y), 0.5 * (startPosition.z + endPosition.z))
if (middlePoint.y < height) then
endPosition = middlePoint
else
startPosition = middlePoint
end
end
local collisionPoint = cc.vec3(0.5 * (startPosition.x + endPosition.x), 0.5 * (startPosition.y + endPosition.y), 0.5 * (startPosition.z + endPosition.z))
local playerPos = self._player:getPosition3D()
dir = cc.vec3(collisionPoint.x - playerPos.x, collisionPoint.y - playerPos.y, collisionPoint.z - playerPos.z)
dir.y = 0
dir = cc.vec3normalize(dir)
self._player._headingAngle = -1 * math.acos(-dir.z)
self._player._headingAxis = vec3_cross(dir, cc.vec3(0, 0, -1), self._player._headingAxis)
self._player._targetPos = collisionPoint
-- self._player:forward()
self._player._playerState = PLAER_STATE.FORWARD
end
end
end,cc.Handler.EVENT_TOUCHES_ENDED)
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
local visibleSize = cc.Director:getInstance():getVisibleSize()
self._camera = cc.Camera:createPerspective(60, visibleSize.width/visibleSize.height, 0.1, 200)
self._camera:setCameraFlag(cc.CameraFlag.USER1)
self:addChild(self._camera)
local detailMapR = { _detailMapSrc = "TerrainTest/dirt.jpg", _detailMapSize = 35}
local detailMapG = { _detailMapSrc = "TerrainTest/Grass2.jpg", _detailMapSize = 10}
local detailMapB = { _detailMapSrc = "TerrainTest/road.jpg", _detailMapSize = 35}
local detailMapA = { _detailMapSrc = "TerrainTest/GreenSkin.jpg", _detailMapSize = 20}
local terrainData = { _heightMapSrc = "TerrainTest/heightmap16.jpg", _alphaMapSrc = "TerrainTest/alphamap.png" , _detailMaps = {detailMapR, detailMapG, detailMapB, detailMapA}, _detailMapAmount = 4, _mapHeight = 40.0, _mapScale = 2.0 }
self._terrain = cc.Terrain:create(terrainData,cc.Terrain.CrackFixedType.SKIRT)
self._terrain:setMaxDetailMapAmount(4)
self._terrain:setCameraMask(2)
self._terrain:setDrawWire(false)
self._terrain:setSkirtHeightRatio(3)
self._terrain:setLODDistance(64,128,192)
self._player = Player:create("Sprite3DTest/girl.c3b", self._camera, self._terrain)
self._player:setCameraMask(2)
self._player:setScale(0.08)
self._player:setPositionY(self._terrain:getHeight(self._player:getPositionX(), self._player:getPositionZ()) + PLAYER_HEIGHT)
--add Particle3D for test blend
local rootps = cc.PUParticleSystem3D:create("Particle3D/scripts/mp_torch.pu")
rootps:setCameraMask(cc.CameraFlag.USER1)
rootps:setScale(30.0)
rootps:startParticleSystem()
self._player:addChild(rootps)
--add BillBoard for test blend
local billboard = cc.BillBoard:create("Images/btn-play-normal.png")
billboard:setPosition3D(cc.vec3(0,180,0))
billboard:setCameraMask(cc.CameraFlag.USER1)
self._player:addChild(billboard)
local animation = cc.Animation3D:create("Sprite3DTest/girl.c3b","Take 001")
if nil ~= animation then
local animate = cc.Animate3D:create(animation)
self._player:runAction(cc.RepeatForever:create(animate))
end
local playerPos = self._player:getPosition3D()
self._camera:setPosition3D(cc.vec3(playerPos.x + camera_offset.x, playerPos.y + camera_offset.y, playerPos.z + camera_offset.z))
self._camera:setRotation3D(cc.vec3(-45,0,0))
self:addChild(self._player)
self:addChild(self._terrain)
self:extend()
end
function TerrainWalkThru:title()
return "Player walk around in terrain"
end
function TerrainWalkThru:subtitle()
return "touch to move"
end
function TerrainWalkThru:extend()
end
----------------------------------------
----Scene3DTest
----------------------------------------
local Scene3DTest = class("Scene3DTest", TerrainWalkThru)
function Scene3DTest:create3DWorld()
-- terrain and player has been create in TerrainWalkThru:init
-- we only need override there camera mask
self._terrain:setCameraMask(s_CM[GAME_LAYER.LAYER_GAME])
self._player:setCameraMask(s_CM[GAME_LAYER.LAYER_GAME])
self._player:setScale(self._player:getScale() * 1.5)
--add two Sprite3D monster, one is transparent
local playerPos = self._player:getPosition3D()
local monster = cc.Sprite3D:create("Sprite3DTest/orc.c3b")
monster:setRotation3D(cc.vec3(0,180,0))
monster:setPosition3D(cc.vec3(playerPos.x + 50, playerPos.y - 10, playerPos.z))
monster:setCameraMask(s_CM[GAME_LAYER.LAYER_GAME])
monster:setOpacity(128)
self:addChild(monster)
monster = cc.Sprite3D:create("Sprite3DTest/orc.c3b")
monster:setRotation3D(cc.vec3(0,180,0))
monster:setPosition3D(cc.vec3(playerPos.x - 50, playerPos.y - 5, playerPos.z))
monster:setCameraMask(s_CM[GAME_LAYER.LAYER_GAME])
self:addChild(monster)
--add a particle 3d above player
local rootps = cc.PUParticleSystem3D:create("Particle3D/scripts/blackHole.pu", "Particle3D/materials/pu_mediapack_01.material")
rootps:setScale(2)
rootps:setPosition3D(cc.vec3(0, 150, 0))
rootps:setCameraMask(s_CM[GAME_LAYER.LAYER_GAME])
local moveby = cc.MoveBy:create(2.0, cc.p(50.0, 0.0))
local moveby1 = cc.MoveBy:create(2.0, cc.p(-50.0, 0.0))
rootps:runAction(cc.RepeatForever:create(cc.Sequence:create(moveby, moveby1)))
rootps:startParticleSystem()
self._player:addChild(rootps, 0)
--then, create skybox
--create and set our custom shader
local shader = cc.GLProgram:createWithFilenames("Sprite3DTest/cube_map.vert", "Sprite3DTest/cube_map.frag")
local state = cc.GLProgramState:create(shader)
--create the second texture for cylinder
self._textureCube = cc.TextureCube:create("Sprite3DTest/skybox/left.jpg", "Sprite3DTest/skybox/right.jpg",
"Sprite3DTest/skybox/top.jpg", "Sprite3DTest/skybox/bottom.jpg",
"Sprite3DTest/skybox/front.jpg", "Sprite3DTest/skybox/back.jpg")
--set texture parameters
local tRepeatParams = { magFilter = gl.LINEAR , minFilter = gl.LINEAR , wrapS = gl.MIRRORED_REPEAT , wrapT = gl.MIRRORED_REPEAT }
self._textureCube:setTexParameters(tRepeatParams)
--pass the texture sampler to our custom shader
state:setUniformTexture("u_cubeTex", self._textureCube)
--add skybox
self._skyBox = cc.Skybox:create()
self._skyBox:setCameraMask(s_CM[GAME_LAYER.LAYER_SKYBOX])
self._skyBox:setTexture(self._textureCube)
self._skyBox:setScale(700.0)
self:addChild(self._skyBox)
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
if targetPlatform == cc.PLATFORM_OS_ANDROID or targetPlatform == cc.PLATFORM_OS_WINRT or targetPlatform == cc.PLATFORM_OS_WP8 then
self._backToForegroundListener = cc.EventListenerCustom:create("event_renderer_recreated", function (eventCustom)
local state = self._skyBox:getGLProgramState()
local glProgram = state:getGLProgram()
glProgram:reset()
glProgram:initWithFilenames("Sprite3DTest/cube_map.vert", "Sprite3DTest/cube_map.frag")
glProgram:link()
glProgram:updateUniforms()
self._textureCube:reloadTexture()
local tRepeatParams = { magFilter = gl.NEAREST , minFilter = gl.NEAREST , wrapS = gl.MIRRORED_REPEAT , wrapT = gl.MIRRORED_REPEAT }
self._textureCube:setTexParameters(tRepeatParams)
state:setUniformTexture("u_cubeTex", self._textureCube)
self._skyBox:reload()
self._skyBox:setTexture(self._textureCube)
end)
cc.Director:getInstance():getEventDispatcher():addEventListenerWithFixedPriority(self._backToForegroundListener, 1)
end
end
function Scene3DTest:createUI()
--add player button
local showLeftDlgItem = cc.MenuItemImage:create("Images/Pea.png", "Images/Pea.png")
showLeftDlgItem:registerScriptTapHandler(function (tag, sender)
if nil ~= self._playerDlg then
self._playerDlg:setVisible(not self._playerDlg:isVisible())
end
end)
showLeftDlgItem:setPosition(VisibleRect:left().x + 30, VisibleRect:top().y - 30)
local ttfConfig = { fontFilePath = "fonts/arial.ttf", fontSize = 20}
local descItem = cc.MenuItemLabel:create(cc.Label:createWithTTF(ttfConfig, "Description"))
descItem:registerScriptTapHandler(function(tag, sender)
if nil ~= self._descDlg then
self._descDlg:setVisible(not self._descDlg:isVisible())
end
end)
descItem:setPosition(cc.p(VisibleRect:right().x - 50, VisibleRect:top().y - 25))
local backItem = cc.MenuItemLabel:create(cc.Label:createWithTTF(ttfConfig, "Back"))
backItem:setPosition(cc.p(VisibleRect:right().x - 50, VisibleRect:bottom().y + 25))
local menu = cc.Menu:create(showLeftDlgItem, descItem, backItem)
menu:setPosition(cc.p(0.0, 0.0))
menu:setCameraMask(s_CM[GAME_LAYER.LAYER_UI], true)
self:addChild(menu)
end
function Scene3DTest:createPlayerDlg()
cc.SpriteFrameCache:getInstance():addSpriteFrames(s_s9s_ui_plist)
local dlgSize = cc.size(190, 240)
local pos = VisibleRect:center()
local margin = 10
--first, create dialog ui part, include background, title and buttons
self._playerDlg = ccui.Scale9Sprite:createWithSpriteFrameName("button_actived.png")
self._playerDlg:setContentSize(dlgSize)
self._playerDlg:setAnchorPoint(cc.p(1, 0.5))
pos.y = pos.y - margin
pos.x = pos.x - margin
self._playerDlg:setPosition(pos)
--title
local title = cc.Label:createWithTTF("Player Dialog","fonts/arial.ttf",16)
title:setPosition(dlgSize.width / 2, dlgSize.height - margin * 2)
self._playerDlg:addChild(title)
--player background
local bgSize = cc.size(110, 180)
local bgPos = cc.p(margin, dlgSize.height / 2 - margin)
local playerBg = ccui.Scale9Sprite:createWithSpriteFrameName("item_bg.png")
playerBg:setContentSize(bgSize)
playerBg:setAnchorPoint(cc.p(0, 0.5))
playerBg:setPosition(bgPos)
self._playerDlg:addChild(playerBg)
--item background and item
local itemSize = cc.size(48, 48)
local itemAnchor = cc.p(0, 1)
local itemPos = cc.p(bgPos.x + bgSize.width + margin, bgPos.y + bgSize.height / 2)
local itemBg = ccui.Scale9Sprite:createWithSpriteFrameName("item_bg.png")
itemBg:setContentSize(itemSize)
itemBg:setAnchorPoint(itemAnchor)
itemBg:setPosition(itemPos)
self._playerDlg:addChild(itemBg)
local item = ccui.Button:create("crystal.png", "", "", ccui.TextureResType.plistType)
item:setScale(1.5)
item:setAnchorPoint(itemAnchor)
item:setPosition(itemPos)
item:addClickEventListener(function(sender)
if self._detailDlg ~= nil then
self._detailDlg:setVisible(not self._detailDlg:isVisible())
end
end)
self._playerDlg:addChild(item)
--after add ui element, add player dialog to scene
self._playerDlg:setCameraMask(s_CM[GAME_LAYER.LAYER_UI])
self:addChild(self._playerDlg)
--second, add 3d actor, which on dialog layer
local girl = cc.Sprite3D:create("Sprite3DTest/girl.c3b")
girl:setScale(0.5)
girl:setPosition(bgSize.width / 2, margin * 2)
girl:setCameraMask(s_CM[GAME_LAYER.LAYER_ACTOR])
playerBg:addChild(girl)
--third, add zoom in/out button, which is 2d ui element and over 3d actor
local zoomIn = ccui.Button:create("cocosui/animationbuttonnormal.png","cocosui/animationbuttonpressed.png")
zoomIn:setScale(0.5)
zoomIn:setAnchorPoint(cc.p(1, 1))
zoomIn:setPosition(cc.p(bgSize.width / 2 - margin / 2, bgSize.height - margin))
zoomIn:addClickEventListener(function(sender)
girl:setScale(girl:getScale() * 2)
end)
zoomIn:setTitleText("Zoom In")
zoomIn:setCameraMask(s_CM[GAME_LAYER.LAYER_ZOOM])
playerBg:addChild(zoomIn)
local zoomOut = ccui.Button:create("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png")
zoomOut:setScale(0.5)
zoomOut:setAnchorPoint(cc.p(0, 1))
zoomOut:setPosition(cc.p(bgSize.width / 2 + margin / 2, bgSize.height - margin))
zoomOut:addClickEventListener(function(sender)
girl:setScale(girl:getScale() / 2)
end)
zoomOut:setTitleText("Zoom Out")
zoomOut:setCameraMask(s_CM[GAME_LAYER.LAYER_ZOOM])
playerBg:addChild(zoomOut)
end
function Scene3DTest:createDetailDlg()
cc.SpriteFrameCache:getInstance():addSpriteFrames(s_s9s_ui_plist)
local dlgSize = cc.size(190, 240)
local pos = VisibleRect:center()
local margin = 10
--create dialog
self._detailDlg = ccui.Scale9Sprite:createWithSpriteFrameName("button_actived.png")
self._detailDlg:setContentSize(dlgSize)
self._detailDlg:setAnchorPoint(cc.p(0, 0.5))
self._detailDlg:setOpacity(224)
pos.y = pos.y - margin
pos.x = pos.x + margin
self._detailDlg:setPosition(pos)
-- title
local title = cc.Label:createWithTTF("Detail Dialog","fonts/arial.ttf",16)
title:setPosition(dlgSize.width / 2, dlgSize.height - margin * 2)
self._detailDlg:addChild(title)
-- add a spine ffd animation on it
local skeletonNode = sp.SkeletonAnimation:create("spine/goblins-ffd.json", "spine/goblins-ffd.atlas", 1.5)
skeletonNode:setAnimation(0, "walk", true)
skeletonNode:setSkin("goblin")
skeletonNode:setScale(0.25)
local windowSize = cc.Director:getInstance():getWinSize()
skeletonNode:setPosition(cc.p(dlgSize.width / 2, 20))
self._detailDlg:addChild(skeletonNode)
local listener = cc.EventListenerTouchOneByOne:create()
listener:registerScriptHandler(function (touch, event)
if (not skeletonNode:getDebugBonesEnabled()) then
skeletonNode:setDebugBonesEnabled(true)
elseif skeletonNode:getTimeScale() == 1 then
skeletonNode:setTimeScale(0.3)
else
skeletonNode:setTimeScale(1)
skeletonNode:setDebugBonesEnabled(false)
end
return true
end,cc.Handler.EVENT_TOUCH_BEGAN )
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
--after add ui element, add dialog to scene
self._detailDlg:setCameraMask(s_CM[GAME_LAYER.LAYER_UI])
self:addChild(self._detailDlg)
end
function Scene3DTest:createDescDlg()
cc.SpriteFrameCache:getInstance():addSpriteFrames(s_s9s_ui_plist)
local dlgSize = cc.size(440, 240)
local pos = VisibleRect:center()
local margin = 10
--create dialog
self._descDlg = ccui.Scale9Sprite:createWithSpriteFrameName("button_actived.png")
self._descDlg:setContentSize(dlgSize)
self._descDlg:setOpacity(224)
self._descDlg:setPosition(pos)
--title
local title = cc.Label:createWithTTF("Description Dialog","fonts/arial.ttf",16)
title:setPosition(dlgSize.width / 2, dlgSize.height - margin * 2)
self._descDlg:addChild(title)
--add a label to retain description text
local textSize = cc.size(400, 220)
local desc = "Scene 3D test for 2D and 3D mix rendering.\n" ..
"\n" ..
"- Game world composite with terrain, skybox and 3D objects.\n" ..
"- UI composite with 2D nodes.\n" ..
"- Click the icon at the topleft conner, will show a player dialog which" ..
"there is a 3D sprite on it.\n" ..
"- There are two button to zoom the player model, which should keep above" ..
"on 3D model.\n" ..
"- This description dialog should above all other elements.\n" ..
"\n" ..
"Click \"Description\" button to hide this dialog.\n"
local text = cc.Label:createWithSystemFont(desc, "Helvetica", 12, textSize)
text:setAnchorPoint(cc.p(0, 1))
text:setPosition(margin, dlgSize.height - (20 + margin))
self._descDlg:addChild(text)
--after add ui element, add dialog to scene
self._descDlg:setCameraMask(s_CM[GAME_LAYER.LAYER_OSD])
self:addChild(self._descDlg)
end
function Scene3DTest:extend()
self._playerDlg = nil
self._detailDlg = nil
self._descDlg = nil
self._gameCameras = {nil, nil, nil, nil, nil, nil}
cc.Director:getInstance():setDisplayStats(false)
local ca = nil
local visibleSize = cc.Director:getInstance():getVisibleSize()
--first, create a camera to look the skybox
ca = cc.Camera:createPerspective(60, visibleSize.width / visibleSize.height, 10, 1000)
ca:setPosition3D(cc.vec3(0.0, 0.0, 50.0))
ca:setCameraFlag(s_CF[GAME_LAYER.LAYER_SKYBOX])
ca:setDepth(GAME_LAYER.LAYER_SKYBOX)
self._gameCameras[GAME_LAYER.LAYER_SKYBOX] = ca
self:addChild(ca)
-- second, create a camera to look the 3D game scene
-- it has been create in TerrainWalkThru:init
ca = self._camera
ca:setCameraFlag(s_CF[GAME_LAYER.LAYER_GAME])
ca:setDepth(GAME_LAYER.LAYER_GAME)
self._gameCameras[GAME_LAYER.LAYER_GAME] = ca
--third, use the default camera to look 2D base UI layer
local scene = cc.Director:getInstance():getRunningScene()
ca = scene:getDefaultCamera()
ca:setCameraFlag(s_CF[GAME_LAYER.LAYER_UI])
ca:setDepth(GAME_LAYER.LAYER_UI)
self._gameCameras[GAME_LAYER.LAYER_UI] = ca
--forth, create a camera to look the 3D model in dialogs
ca = cc.Camera:create()
ca:setCameraFlag(s_CF[GAME_LAYER.LAYER_ACTOR])
ca:setDepth(GAME_LAYER.LAYER_ACTOR)
self._gameCameras[GAME_LAYER.LAYER_ACTOR] = ca
self:addChild(ca)
-- fifth, create a camera to look the UI element over on the 3D models
ca = cc.Camera:create()
ca:setCameraFlag(s_CF[GAME_LAYER.LAYER_ZOOM])
ca:setDepth(GAME_LAYER.LAYER_ZOOM)
self._gameCameras[GAME_LAYER.LAYER_ZOOM] = ca
self:addChild(ca)
--sixth, create a camera to look the OSD UI
ca = cc.Camera:create()
ca:setCameraFlag(s_CF[GAME_LAYER.LAYER_OSD])
ca:setDepth(GAME_LAYER.LAYER_OSD)
self._gameCameras[GAME_LAYER.LAYER_OSD] = ca
self:addChild(ca)
self:create3DWorld()
self:createUI()
self:createPlayerDlg()
self:createDetailDlg()
self:createDescDlg()
self._playerDlg:setVisible(false)
self._detailDlg:setVisible(false)
end
function Scene3DTest:title()
return ""
end
function Scene3DTest:subtitle()
return ""
end
function Scene3DTest:onExit()
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
if targetPlatform == cc.PLATFORM_OS_ANDROID or targetPlatform == cc.PLATFORM_OS_WINRT or targetPlatform == cc.PLATFORM_OS_WP8 then
cc.Director:getInstance():getEventDispatcher():removeEventListener(self._backToForegroundListener)
end
end
function Scene3DTestMain()
local scene = cc.Scene:create()
Helper.createFunctionTable =
{
Scene3DTest.create,
}
scene:addChild(Scene3DTest.create())
scene:addChild(CreateBackMenuItem())
return scene
end
|
local applicationHotkeys =
{
{'c', 'iTerm'},
{'d', 'Google Chrome Canary'},
{'f', {'ForkLift', 'Finder'}},
{'g', 'Firefox'},
{'h', 'Dash'},
{'i', {'VLC', 'Spotify'}},
{'n', 'Numi'},
{'o', 'Skype', 'focus'},
{'r', 'ReadKit'},
{'s', 'Mailbox (Beta)'},
{'t', 'Trello'},
{'u', 'Google Chrome'},
{'v', 'Atom'},
{'w', 'nvALT'},
{'y', 'PivotalTracker'},
{']', 'Slack', 'focus'},
{'\\', '1Password 5'},
}
-- hs.hotkey.bind({"cmd", "alt", "ctrl"}, "i", function()
-- if launchedNotFrontmost("VLC") then
-- hs.application.launchOrFocus("VLC")
-- return
-- end
-- hs.application.launchOrFocus("Spotify")
-- end)
-- hs.hotkey.bind({"cmd", "alt", "ctrl"}, "i", function()
-- if launchedNotFrontmost("VLC") then
-- hs.application.launchOrFocus("VLC")
-- return
-- end
-- hs.application.launchOrFocus("Spotify")
-- end)
local function bindApplication(hotkey, appName, options)
if type(appName) == 'table' then
hs.hotkey.bind({"cmd", "alt", "ctrl"}, hotkey, function()
for _, app in ipairs(appName) do
if launchedNotFrontmost(app) then
hs.application.launchOrFocus(app)
return
end
end
end)
else
hs.hotkey.bind({"cmd", "alt", "ctrl"}, hotkey, function()
if options and options == 'focus' then
focusLaunchedApp(appName)
else
hs.application.launchOrFocus(appName)
end
end)
end
end
function launchedNotFrontmost(name)
app = hs.application.find(name)
if app and not app:isFrontmost() then
return true
else
return false
end
end
function focusLaunchedApp(name)
app = hs.application.find(name)
if app then
app:activate()
end
end
for _, applicationHotkey in ipairs(applicationHotkeys) do
hotkey, application, options =
applicationHotkey[1], applicationHotkey[2], applicationHotkey[3]
bindApplication(hotkey, application, options)
end
|
PoliticalParty = class("PoliticalParty")
function PoliticalParty:init(data)
local politicalTable = loadjson(".\\tables\\political_party.JSON")
self.leadership = choice(politicalTable["leadership"])
self.economic_policy = choice(politicalTable["economic_policy"])
self.important_issues = choice(politicalTable["important_issues"])
self.name = choice(politicalTable["descriptor"]).." "..choice(politicalTable["name"])
if(debug)then
logger("Political Party:")
logger("Name: "..self.name)
logger("Leadership: "..self.leadership)
logger("Economic Policy: "..self.economic_policy)
logger("Important Issues: "..self.important_issues)
end
end
function PoliticalParty:Serialize()
local results = {}
table.insert(results,self.name)
table.insert(results,self.leadership)
table.insert(results,self.economic_policy)
table.insert(results,self.important_issues)
return results
end
--= Return Factory
return PoliticalParty
|
require 'torch'
require 'nn'
require 'cunn'
require 'cudnn'
require 'lfs'
require 'paths'
local ffi = require 'ffi'
image = require 'image'
local models = require 'models/init_test'
local opts = require 'opts'
local DataLoader = require 'dataloader'
local checkpoints = require 'checkpoints'
opt = opts.parse(arg)
show = false -- Set show to true if you want to visualize. In addition, you need to use qlua instead of th.
checkpoint, optimState = checkpoints.latest(opt)
model = models.setup(opt, checkpoint)
offset = 0
if opt.smooth then
offset = 1
end
print(model)
local valLoader = DataLoader.create(opt)
print('data loaded')
input = torch.CudaTensor()
function copyInputs(sample)
input = input or (opt.nGPU == 1
and torch.CudaTensor()
or cutorch.createCudaHostTensor())
input:resize(sample.input:size()):copy(sample.input)
return input
end
function sleep(n)
os.execute("sleep " .. tonumber(n))
end
function process( scoremap )
local avg = nn.Sequential()
avg:add(nn.SpatialSoftMax())
avg:add(nn.SplitTable(1, 3))
avg:add(nn.NarrowTable(2, 4))
local paral = nn.ParallelTable()
local seq = nn.Sequential()
seq:add(nn.Contiguous())
seq:add(nn.View(1, 288, 960):setNumInputDims(2))
local conv = nn.SpatialConvolution(1, 1, 9, 9, 1, 1, 4, 4)
conv.weight:fill(1/81)
conv.bias:fill(0)
seq:add(conv)
paral:add(seq)
for i=1, 3 do
paral:add(seq:clone('weight', 'bias','gradWeight','gradBias'))
end
avg:add(paral)
avg:add(nn.JoinTable(1, 3))
avg:cuda()
return avg:forward(scoremap)
end
model:evaluate()
T = 0
N = 0
for n, sample in valLoader:run() do
print(n)
input = copyInputs(sample)
local imgpath = sample.imgpath
local timer = torch.Timer()
output = model:forward(input)
local t = timer:time().real
print('time: ' .. t)
local scoremap = output[1] --:double()
if opt.smooth then
scoremap = process(scoremap):float()
else
local softmax = nn.SpatialSoftMax():cuda()
scoremap = softmax(scoremap):float()
end
if n > 1 then
T = T + t
N = N + 1
print('avgtime: ' .. T/N)
end
timer:reset()
local exist = output[2]:float()
local outputn
for b = 1, input:size(1) do
print('img: ' .. ffi.string(imgpath[b]:data()))
local img = image.load(opt.data .. ffi.string(imgpath[b]:data()), 3, 'float')
outputn = scoremap[{b,{},{},{}}]
--print(outputn:size())
local _, maxMap = torch.max(outputn, 1)
local save_path = string.sub(ffi.string(imgpath[b]:data()), 15, -16) .. '.json_'
for cnt = 1, 5 do
out_img = maxMap:eq(cnt) -- outputn[{cnt, {}, {}}]--maxMap:eq(cnt) * 1
out_img = image.scale(out_img, 1276, 384, 'simple')
if cnt == 1 then
out_img = torch.cat(torch.ones(1, 333, 1276):byte(), out_img, 2)
else
out_img = torch.cat(torch.zeros(1, 333, 1276):byte(), out_img, 2)
end
image.save(opt.save .. save_path .. (cnt -1) .. '.png', out_img:cuda())
end
end
end
|
CustomizableWeaponry:addFireSound("DELISLE_FIRE", {"weapons/cwdelisle/fire-1.wav","weapons/cwdelisle/fire-2.wav","weapons/cwdelisle/fire-3.wav"}, 1, 60, CHAN_STATIC)
CustomizableWeaponry:addReloadSound("DELISLE_BOLT", "weapons/cwdelisle/dlbolt.wav")
CustomizableWeaponry:addReloadSound("DELISLE_MAGOUT", "weapons/cwdelisle/dlmagout.wav")
CustomizableWeaponry:addReloadSound("DELISLE_MAGIN1", "weapons/cwdelisle/dlmagin1.wav")
CustomizableWeaponry:addReloadSound("DELISLE_MAGIN2", "weapons/cwdelisle/dlmagin2.wav")
|
package.path = '../src/?.lua;src/?.lua;' .. package.path
pcall(require, 'luarocks.require')
local nats = require 'nats'
local params = {
host = '127.0.0.1',
port = 4222,
}
local client = nats.connect(params)
local function subscribe_callback(payload)
print('Received data: ' .. payload)
end
-- client:enable_trace()
client:connect()
local subscribe_id = client:subscribe('foo', subscribe_callback)
client:wait(2)
client:unsubscribe(subscribe_id)
|
--------------------------------------------------
--HEARTH
------------------------------------------------
--Functions
----------
-- On construct
-- set form
local hearth_on_construct = function(pos)
local inv = minetest.get_meta(pos):get_inventory()
inv:set_size("fuel", 1)
local meta = minetest.get_meta(pos)
meta:set_string("formspec",
"size[8,5.3]" ..
default.gui_bg ..
default.gui_bg_img ..
default.gui_slots ..
"list[current_name;fuel;3.5,0;1,1;]" ..
"list[current_player;main;0,1.15;8,1;]" ..
"list[current_player;main;0,2.38;8,3;8]" ..
"listring[current_name;main]" ..
"listring[current_player;main]" ..
default.get_hotbar_bg(0,1.15)
)
end
----------
--Digging only if no fuel
local hearth_can_dig = function(pos, player)
local inv = minetest.get_meta(pos):get_inventory()
return inv:is_empty("fuel")
end
-------------
-- Only fuel items allowed
local hearth_allow_metadata_inventory_put = function(pos, listname, index, stack, player)
if listname == "fuel" then
if minetest.get_craft_result({method="fuel", width=1, items={stack}}).time ~= 0 then
return stack:get_count()
else
return 0
end
end
return 0
end
--------------
--Particle Effects
local function hearth_fire_on(pos, time)
local meta = minetest.get_meta(pos)
--flames
minetest.add_particlespawner({
amount = 4,
time = time,
minpos = {x = pos.x - 0.1, y = pos.y + 0.6, z = pos.z - 0.1},
maxpos = {x = pos.x + 0.1, y = pos.y + 1, z = pos.z + 0.1},
minvel = {x= 0, y= 0, z= 0},
maxvel = {x= 0.001, y= 0.001, z= 0.001},
minacc = {x= 0, y= 0, z= 0},
maxacc = {x= 0.001, y= 0.001, z= 0.001},
minexptime = 3,
maxexptime = 5,
minsize = 4,
maxsize = 8,
collisiondetection = false,
vertical = true,
texture = "fire_basic_flame_animated.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1
},
glow = 13,
})
--Smoke
minetest.add_particlespawner({
amount = 4,
time = time,
minpos = {x = pos.x - 0.1, y = pos.y + 0.8, z = pos.z - 0.1},
maxpos = {x = pos.x + 0.1, y = pos.y + 1, z = pos.z + 0.1},
minvel = {x= 0, y= 0, z= 0},
maxvel = {x= 0.01, y= 0.07, z= 0.01},
minacc = {x= 0, y= 0, z= 0},
maxacc = {x= 0.01, y= 0.2, z= 0.01},
minexptime = 5,
maxexptime = 20,
minsize = 1,
maxsize = 8,
collisiondetection = true,
vertical = true,
texture = "default_item_smoke.png",
--animation = {type="vertical_frames", aspect_w=16, aspect_h=16, length = 0.7,},
})
end
----------
--Burn
--add flames and burn fuel
local hearth_burn = function(pos, elapsed)
local pos_above = {x=pos.x, y=pos.y+1, z=pos.z}
local node_above = minetest.get_node(pos_above)
local timer = minetest.get_node_timer(pos)
local inv = minetest.get_inventory({type="node", pos=pos})
local item = inv:get_stack("fuel", 1)
local fuel_burned = minetest.get_craft_result({method="fuel", width=1, items={item:peek_item(1)}}).time
--remove light...
-- so it doesn't stay on permanently
if inv:is_empty("fuel") and node_above.name == "earthbuild:hearth_air" then
minetest.set_node(pos_above, {name = "air"})
end
--burn item and add smoke and flames
if fuel_burned > 0 and (node_above.name == "air" or node_above.name == "earthbuild:hearth_air") then
--randomly remove an item of fuel based on it's burn time.
--this is so it can get through the fuel slowly, but..
-- still do frequent flames
--i.e. every X sec it will have a 1/X chance of burning
local burn_time = fuel_burned * 30
local burn_it = math.random(1, burn_time)
--it's luck was up, it got burnt away.
if burn_it == 1 then
item:set_count(item:get_count() - 1)
inv:set_stack("fuel", 1, item)
end
--if has no light
if node_above.name == "air" then
minetest.set_node(pos_above, {name = "earthbuild:hearth_air"})
end
--do fire effects and restart timer
timer:start(5)
hearth_fire_on(pos, 5)
minetest.sound_play("fire_small",{pos=pos, max_hear_distance = 15, loop=false, gain=0.2})
end
end
--Removed node..make sure to remove light
local no_hearth = function(pos, oldnode)
local pos_above = {x=pos.x, y=pos.y+1, z=pos.z}
local node_above = minetest.get_node(pos_above)
if node_above.name == "earthbuild:hearth_air" then
minetest.set_node(pos_above, {name = "air"})
end
end
-------------------------------------------------
--Node
-- adds hearth
minetest.register_node('earthbuild:hearth', {
description = 'Hearth',
drawtype = "normal",
tiles = {
"earthbuild_hearth_top.png",
"earthbuild_cob.png",
"earthbuild_hearth_side.png",
"earthbuild_hearth_side.png",
"earthbuild_hearth_side.png",
"earthbuild_hearth_side.png"
},
paramtype = "light",
drop = "earthbuild:hearth",
groups = {crumbly = 1, cracky = 1, oddly_breakable_by_hand = 2},
damage_per_second = 1,
sounds = default.node_sound_dirt_defaults(),
on_construct = hearth_on_construct,
can_dig = hearth_can_dig,
allow_metadata_inventory_put = hearth_allow_metadata_inventory_put,
on_metadata_inventory_put = hearth_burn,
on_timer = hearth_burn,
after_destruct = no_hearth,
})
-----------------------------------------
--Hearth Air
--this is to add a light source
-- an invisible glowing block added above the fire when burning
--this is needed because particles give no light
minetest.register_node("earthbuild:hearth_air", {
description = "Hearth Air",
tiles = {"earthbuild_hearth_top.png"},
drawtype = "airlike",
paramtype = "light",
sunlight_propagates = true,
walkable = false,
pointable = false,
diggable = false,
buildable_to = true,
protected = true,
groups = {not_in_creative_inventory = 1, igniter = 2},
light_source= 9,
on_blast = function(pos)
end,
})
----------------------------------------------
--Crafts
-- adds hearth recipes
minetest.register_craft({
output = 'earthbuild:hearth',
recipe = {
{'', 'group:tree', ''},
{'group:stick', 'group:stick', 'group:stick'},
{'', 'earthbuild:rammed_earth', ''},
}
})
minetest.register_craft({
output = 'earthbuild:hearth',
recipe = {
{'', 'group:tree', ''},
{'group:stick', 'group:stick', 'group:stick'},
{'', 'earthbuild:cob', ''},
}
})
minetest.register_craft({
output = 'earthbuild:hearth',
recipe = {
{'', 'group:tree', ''},
{'group:stick', 'group:stick', 'group:stick'},
{'default:dirt', 'default:dirt', 'default:dirt'},
}
})
|
purge_mage = {
cast = function(player, target)
local magic = 30
if not player:canCast(1, 1, 0) then
return
end
if (player.magic < magic) then
player:sendMinitext("You do not have enough mana.")
return
end
target:removeDuras(venoms)
player:sendMinitext("You cast Purge.")
player:sendAction(6, 35)
player.magic = player.magic - magic
target:playSound(10)
target:sendAnimation(10)
target:sendStatus()
player:sendStatus()
end,
requirements = function(player)
local level = 30
local items = {
Item("gold_acorn").id,
Item("antler").id,
Item("mountain_ginseng").id,
0
}
local itemAmounts = {1, 10, 1, 150}
local description = "Removes poison from target"
return level, items, itemAmounts, description
end
}
cure_illness_mage = {
cast = function(player, target)
local magic = 30
if not player:canCast(1, 1, 0) then
return
end
if (player.magic < magic) then
player:sendMinitext("You do not have enough mana.")
return
end
target:removeDuras(venoms)
player:sendMinitext("You cast Cure illness.")
player:sendAction(6, 35)
player.magic = player.magic - magic
target:playSound(10)
target:sendAnimation(70)
target:sendStatus()
player:sendStatus()
end,
requirements = function(player)
local level = 30
local items = {
Item("gold_acorn").id,
Item("antler").id,
Item("mountain_ginseng").id,
0
}
local itemAmounts = {1, 10, 1, 150}
local description = "Removes poison from target"
return level, items, itemAmounts, description
end
}
restore_health_mage = {
cast = function(player, target)
local magic = 30
if not player:canCast(1, 1, 0) then
return
end
if (player.magic < magic) then
player:sendMinitext("You do not have enough mana.")
return
end
target:removeDuras(venoms)
player:sendMinitext("You cast Restore health.")
player:sendAction(6, 35)
player.magic = player.magic - magic
target:playSound(10)
target:sendAnimation(57)
target:sendStatus()
player:sendStatus()
end,
requirements = function(player)
local level = 30
local items = {
Item("gold_acorn").id,
Item("antler").id,
Item("mountain_ginseng").id,
0
}
local itemAmounts = {1, 10, 1, 150}
local description = "Removes poison from target"
return level, items, itemAmounts, description
end
}
remove_poison_mage = {
cast = function(player, target)
local magic = 30
if not player:canCast(1, 1, 0) then
return
end
if (player.magic < magic) then
player:sendMinitext("You do not have enough mana.")
return
end
target:removeDuras(venoms)
player:sendMinitext("You cast Remove poison.")
player:sendAction(6, 35)
player.magic = player.magic - magic
target:playSound(10)
target:sendAnimation(108)
target:sendStatus()
player:sendStatus()
end,
requirements = function(player)
local level = 30
local items = {
Item("gold_acorn").id,
Item("antler").id,
Item("mountain_ginseng").id,
0
}
local itemAmounts = {1, 10, 1, 150}
local description = "Removes poison from target"
return level, items, itemAmounts, description
end
}
|
--- This is a simple module which contains a function
-- @module fancy.module
--- @tparam string a A string
return function(a) end
|
showconsole()
mydir="./"
open(mydir .. "dyneboard10.fem")
mi_saveas(mydir .. "temp.fem")
mi_seteditmode("group")
for n=0,10 do
mi_analyze()
mi_loadsolution()
mo_groupselectblock(1)
fz=mo_blockintegral(19)
print((10-n)/10,fz)
if (n<10) then
mi_selectgroup(1)
mi_movetranslate(0,0.49)
end
end
mo_close()
mi_close()
|
local map = vim.api.nvim_buf_set_keymap
local noremap = { noremap = true }
-- Hot Reload
map(0, "n", "<leader>r", "<cmd>FlutterReload<cr>", noremap)
-- Hot Restart
map(0, "n", "<leader>R", "<cmd>FlutterRestart<cr>", noremap)
-- Open log vertically.
map(0, "n", "<leader>v", "<cmd>FlutterVSplit<cr>", noremap)
|
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
ESX.RegisterUsableItem(Config.Useitem, function(source)
local _source = source
local identifier = ESX.GetPlayerFromId(_source).identifier
local image = Config.SteamIdentifiers[identifier]
local xPlayer = ESX.GetPlayerFromId(source)
if xPlayer.job.name == 'police' then
TriggerClientEvent('fire-badge:badgeanim', _source)
TriggerClientEvent('fire-badge:open', -1, _source, image)
else
TriggerClientEvent('notification', _source, "This is not yours :)")
end
end)
|
--- **AceTimer-3.0** provides a central facility for registering timers.
-- AceTimer supports one-shot timers and repeating timers. All timers are stored in an efficient
-- data structure that allows easy dispatching and fast rescheduling. Timers can be registered
-- or canceled at any time, even from within a running timer, without conflict or large overhead.\\
-- AceTimer is currently limited to firing timers at a frequency of 0.01s. This constant may change
-- in the future, but for now it's required as animations with lower frequencies are buggy.
--
-- All `:Schedule` functions will return a handle to the current timer, which you will need to store if you
-- need to cancel the timer you just registered.
--
-- **AceTimer-3.0** can be embeded into your addon, either explicitly by calling AceTimer:Embed(MyAddon) or by
-- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object
-- and can be accessed directly, without having to explicitly call AceTimer itself.\\
-- It is recommended to embed AceTimer, otherwise you'll have to specify a custom `self` on all calls you
-- make into AceTimer.
-- @class file
-- @name AceTimer-3.0
-- @release $Id$
local MAJOR, MINOR = "AceTimer-3.0", 16 -- Bump minor on changes
local AceTimer, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceTimer then return end -- No upgrade needed
AceTimer.frame = AceTimer.frame or CreateFrame("Frame", "AceTimer30Frame") -- Animation parent
AceTimer.inactiveTimers = AceTimer.inactiveTimers or {} -- Timer recycling storage
AceTimer.activeTimers = AceTimer.activeTimers or {} -- Active timer list
-- Lua APIs
local type, unpack, next, error, pairs, tostring, select = type, unpack, next, error, pairs, tostring, select
-- Upvalue our private data
local inactiveTimers = AceTimer.inactiveTimers
local activeTimers = AceTimer.activeTimers
local function OnFinished(self)
local id = self.id
if type(self.func) == "string" then
-- We manually set the unpack count to prevent issues with an arg set that contains nil and ends with nil
-- e.g. local t = {1, 2, nil, 3, nil} print(#t) will result in 2, instead of 5. This fixes said issue.
self.object[self.func](self.object, unpack(self.args, 1, self.argsCount))
else
self.func(unpack(self.args, 1, self.argsCount))
end
-- If the id is different it means that the timer was already cancelled
-- and has been used to create a new timer during the OnFinished callback.
if not self.looping and id == self.id then
activeTimers[self.id] = nil
self.args = nil
inactiveTimers[self] = true
end
end
local function new(self, loop, func, delay, ...)
local timer = next(inactiveTimers)
if timer then
inactiveTimers[timer] = nil
else
local anim = AceTimer.frame:CreateAnimationGroup()
timer = anim:CreateAnimation()
timer:SetScript("OnFinished", OnFinished)
end
-- Very low delays cause the animations to fail randomly.
-- A limited resolution of 0.01 seems reasonable.
if delay < 0.01 then
delay = 0.01
end
timer.object = self
timer.func = func
timer.looping = loop
timer.args = {...}
timer.argsCount = select("#", ...)
local anim = timer:GetParent()
if loop then
anim:SetLooping("REPEAT")
else
anim:SetLooping("NONE")
end
timer:SetDuration(delay)
local id = tostring(timer.args)
timer.id = id
activeTimers[id] = timer
anim:Play()
return id
end
--- Schedule a new one-shot timer.
-- The timer will fire once in `delay` seconds, unless canceled before.
-- @param callback Callback function for the timer pulse (funcref or method name).
-- @param delay Delay for the timer, in seconds.
-- @param ... An optional, unlimited amount of arguments to pass to the callback function.
-- @usage
-- MyAddOn = LibStub("AceAddon-3.0"):NewAddon("MyAddOn", "AceTimer-3.0")
--
-- function MyAddOn:OnEnable()
-- self:ScheduleTimer("TimerFeedback", 5)
-- end
--
-- function MyAddOn:TimerFeedback()
-- print("5 seconds passed")
-- end
function AceTimer:ScheduleTimer(func, delay, ...)
if not func or not delay then
error(MAJOR..": ScheduleTimer(callback, delay, args...): 'callback' and 'delay' must have set values.", 2)
end
if type(func) == "string" then
if type(self) ~= "table" then
error(MAJOR..": ScheduleTimer(callback, delay, args...): 'self' - must be a table.", 2)
elseif not self[func] then
error(MAJOR..": ScheduleTimer(callback, delay, args...): Tried to register '"..func.."' as the callback, but it doesn't exist in the module.", 2)
end
end
return new(self, nil, func, delay, ...)
end
--- Schedule a repeating timer.
-- The timer will fire every `delay` seconds, until canceled.
-- @param callback Callback function for the timer pulse (funcref or method name).
-- @param delay Delay for the timer, in seconds.
-- @param ... An optional, unlimited amount of arguments to pass to the callback function.
-- @usage
-- MyAddOn = LibStub("AceAddon-3.0"):NewAddon("MyAddOn", "AceTimer-3.0")
--
-- function MyAddOn:OnEnable()
-- self.timerCount = 0
-- self.testTimer = self:ScheduleRepeatingTimer("TimerFeedback", 5)
-- end
--
-- function MyAddOn:TimerFeedback()
-- self.timerCount = self.timerCount + 1
-- print(("%d seconds passed"):format(5 * self.timerCount))
-- -- run 30 seconds in total
-- if self.timerCount == 6 then
-- self:CancelTimer(self.testTimer)
-- end
-- end
function AceTimer:ScheduleRepeatingTimer(func, delay, ...)
if not func or not delay then
error(MAJOR..": ScheduleRepeatingTimer(callback, delay, args...): 'callback' and 'delay' must have set values.", 2)
end
if type(func) == "string" then
if type(self) ~= "table" then
error(MAJOR..": ScheduleRepeatingTimer(callback, delay, args...): 'self' - must be a table.", 2)
elseif not self[func] then
error(MAJOR..": ScheduleRepeatingTimer(callback, delay, args...): Tried to register '"..func.."' as the callback, but it doesn't exist in the module.", 2)
end
end
return new(self, true, func, delay, ...)
end
--- Cancels a timer with the given id, registered by the same addon object as used for `:ScheduleTimer`
-- Both one-shot and repeating timers can be canceled with this function, as long as the `id` is valid
-- and the timer has not fired yet or was canceled before.
-- @param id The id of the timer, as returned by `:ScheduleTimer` or `:ScheduleRepeatingTimer`
function AceTimer:CancelTimer(id)
local timer = activeTimers[id]
if not timer then return false end
local anim = timer:GetParent()
anim:Stop()
activeTimers[id] = nil
timer.args = nil
inactiveTimers[timer] = true
return true
end
--- Cancels all timers registered to the current addon object ('self')
function AceTimer:CancelAllTimers()
for k,v in pairs(activeTimers) do
if v.object == self then
AceTimer.CancelTimer(self, k)
end
end
end
--- Returns the time left for a timer with the given id, registered by the current addon object ('self').
-- This function will return 0 when the id is invalid.
-- @param id The id of the timer, as returned by `:ScheduleTimer` or `:ScheduleRepeatingTimer`
-- @return The time left on the timer.
function AceTimer:TimeLeft(id)
local timer = activeTimers[id]
if not timer then return 0 end
return timer:GetDuration() - timer:GetElapsed()
end
-- ---------------------------------------------------------------------
-- Upgrading
-- Upgrade from old hash-bucket based timers to animation timers
if oldminor and oldminor < 10 then
-- disable old timer logic
AceTimer.frame:SetScript("OnUpdate", nil)
AceTimer.frame:SetScript("OnEvent", nil)
AceTimer.frame:UnregisterAllEvents()
-- convert timers
for object,timers in pairs(AceTimer.selfs) do
for handle,timer in pairs(timers) do
if type(timer) == "table" and timer.callback then
local id
if timer.delay then
id = AceTimer.ScheduleRepeatingTimer(timer.object, timer.callback, timer.delay, timer.arg)
else
id = AceTimer.ScheduleTimer(timer.object, timer.callback, timer.when - GetTime(), timer.arg)
end
-- change id to the old handle
local t = activeTimers[id]
activeTimers[id] = nil
activeTimers[handle] = t
t.id = handle
end
end
end
AceTimer.selfs = nil
AceTimer.hash = nil
AceTimer.debug = nil
elseif oldminor and oldminor < 13 then
for handle, id in pairs(AceTimer.hashCompatTable) do
local t = activeTimers[id]
if t then
activeTimers[id] = nil
activeTimers[handle] = t
t.id = handle
end
end
AceTimer.hashCompatTable = nil
end
-- upgrade existing timers to the latest OnFinished
for timer in pairs(inactiveTimers) do
timer:SetScript("OnFinished", OnFinished)
end
for _,timer in pairs(activeTimers) do
timer:SetScript("OnFinished", OnFinished)
end
-- ---------------------------------------------------------------------
-- Embed handling
AceTimer.embeds = AceTimer.embeds or {}
local mixins = {
"ScheduleTimer", "ScheduleRepeatingTimer",
"CancelTimer", "CancelAllTimers",
"TimeLeft"
}
function AceTimer:Embed(target)
AceTimer.embeds[target] = true
for _,v in pairs(mixins) do
target[v] = AceTimer[v]
end
return target
end
-- AceTimer:OnEmbedDisable(target)
-- target (object) - target object that AceTimer is embedded in.
--
-- cancel all timers registered for the object
function AceTimer:OnEmbedDisable(target)
target:CancelAllTimers()
end
for addon in pairs(AceTimer.embeds) do
AceTimer:Embed(addon)
end
|
luaj = require(cc.PACKAGE_NAME .. ".luaj")
function io.exists(path)
return CCFileUtils:sharedFileUtils():isFileExist(path)
end
function io.readfile(path)
return CCFileUtils:sharedFileUtils():getFileData(path)
end
|
local RunService = game:GetService("RunService")
local function useCameraDistance(hooks, origin)
local distance, set = hooks.useState(math.huge)
hooks.useEffect(function()
local conn = RunService.Heartbeat:Connect(function()
local camera = workspace.CurrentCamera
if camera then
set((origin - camera.CFrame.p).Magnitude)
end
end)
return function()
conn:Disconnect()
end
end, {
origin,
})
return distance
end
return useCameraDistance
|
FACTION.name = "Metro Dweller"
FACTION.description = "A dweller of the post-apocalyptic Metro tunnels."
FACTION.color = Color(150, 125, 100, 255)
FACTION.isDefault = true
FACTION.models = {
"models/half-dead/metrollfix/a1b1.mdl",
"models/half-dead/metrollfix/a3b1.mdl",
"models/half-dead/metrollfix/a2b1.mdl",
"models/half-dead/metrollfix/a4b1.mdl",
"models/half-dead/metrollfix/a5b1.mdl",
"models/half-dead/metrollfix/m2b1.mdl",
"models/half-dead/metrollfix/m4b1.mdl",
"models/half-dead/metrollfix/m5b1.mdl",
"models/half-dead/metrollfix/m6b1.mdl",
"models/half-dead/metrollfix/m7b1.mdl",
"models/half-dead/metrollfix/m8b1.mdl",
"models/half-dead/metrollfix/m9b1.mdl",
"models/half-dead/metrollfix/a6b1.mdl",
"models/half-dead/metrollfix/m3b1.mdl",
"models/half-dead/metrollfix/m1b1.mdl",
"models/half-dead/metrollfix/f7b1.mdl",
"models/half-dead/metrollfix/f6b1.mdl",
"models/half-dead/metrollfix/f4b1.mdl",
"models/half-dead/metrollfix/f3b1.mdl",
"models/half-dead/metrollfix/f2b1.mdl",
"models/half-dead/metrollfix/f1b1.mdl"
}
function FACTION:OnCharacterCreated(client, character)
local inventory = character:GetInventory()
inventory:Add("flashlight", 1)
end
FACTION_METRO = FACTION.index
|
---@class ClimateHistory : zombie.iso.weather.ClimateHistory
ClimateHistory = {}
---@public
---@param arg0 ClimateManager
---@return void
function ClimateHistory:init(arg0) end
---@public
---@param arg0 ClimateManager
---@return void
function ClimateHistory:updateDayChange(arg0) end
|
-- -----------------------------------------------------------
--
-- AUTO-KEEP-GUI-OPEN.LUA
-- Version: 1.0.1
-- Author: VideoPlayerCode
-- URL: https://github.com/VideoPlayerCode/mpv-tools
--
-- Description:
--
-- Intelligently switches mpv's "keep-open" behavior based on
-- whether you are running in video-mode or audio-only mode.
--
-- -----------------------------------------------------------
--
-- Recommended configuration:
-- AKGO_WINDOW_KEEP_OPEN_VALUE="yes" (or "always")
-- AKGO_NOWINDOW_KEEP_OPEN_VALUE="no" (or "original")
-- AKGO_USE_WINDOW_FOR_AUDIO_AFTER_VIDEO=true
--
-- Result:
-- * If you manually queue up a bunch of audio-only files via your
-- command line, then you'll never see a GUI, so you'll always be in
-- the "NOWINDOW" state, which means that the player automatically
-- advances to the next audio file and quits when it reaches the end.
-- * It's only when you play a *video* file that the "WINDOW" state
-- happens, and thanks to the "USE_WINDOW" option mpv will then
-- automatically *stay* in the video/window state and use the
-- "AKGO_WINDOW_KEEP_OPEN_VALUE" for the rest of the playlist.
-- * This script therefore automatically gives you the best of both
-- worlds. Audio-only playlists started from the command line will
-- stay in CLI mode if started from CLI, but Video / Audio+Video
-- playlists (regardless of whether they were started from the
-- desktop via double-clicking or via the command line) will *stay*
-- in GUI mode and use the WINDOW keep-open value, which makes mpv
-- behave even better as a GUI application, without hurting CLI mode.
--
-- -----------------------------------------------------------
--
-- ### START OF USER CONFIGURATION:
--
-------
--
-- AKGO_WINDOW_KEEP_OPEN_VALUE:
-- Possible values are: "no", "yes", "always", "original".
-- Reference: https://mpv.io/manual/master/#options-keep-open
--
-- The "keep-open" option will be set to this value every time the video
-- output is created. Most video output modules create a GUI, so in
-- other words, this is the "keep-open" value that mpv will use when in
-- GUI mode with a video window on screen.
--
-- Note: The special value "original" means whatever was in your user
-- config before this script was loaded.
--
--
-- I recommend setting this option to "yes", so that mpv's GUI stays
-- open after you've reached the end of your playlist or scrubbed the
-- playback position to the end of the last file. This means that you
-- can safely scrub the playback without worrying that you'll hover near
-- the end and make mpv "insta-terminate" when you were just trying to
-- scrub the video position. It makes mpv behave much better as a GUI
-- application.
--
-- You may even want to set it to "always", to always pause after the
-- end of every playlist item (instead of just the last one), to give
-- you manual control over advancing your playlists. But to most people,
-- that isn't as important as simply ensuring that the player stays alive
-- after the end of the final file.
--
-- The benefit of using this script instead of setting the option
-- globally, is that it makes it easy to have one "keep-open" setting
-- for music and another for videos, without having to fiddle with
-- manual per-extension settings. This script is smarter than extension
-- filters, since we detect when video output is used, as opposed to
-- blindly guessing based on file extension. The dynamic switching of
-- this script means that you preserve the ability to use mpv from the
-- command line to play your music files without worrying about having
-- to manually advance every music playlist step by step if you had used
-- a global "keep-open" setting. And your mpv GUI will be much more
-- reliable for video playback as well, since you will prevent mpv from
-- accidentally quitting its GUI at the slightest accidental touch. ;-)
--
AKGO_WINDOW_KEEP_OPEN_VALUE="yes"
--
-------
--
-- AKGO_NOWINDOW_KEEP_OPEN_VALUE:
-- Possible values are: "no", "yes", "always", "original".
-- Reference: https://mpv.io/manual/master/#options-keep-open
--
-- The "keep-open" option will be set to this value every time the video
-- output is destroyed. If you want non-video files in your playlist
-- to be treated differently, then this is for you.
--
-- Note: The special value "original" means whatever was in your user
-- config before this script was loaded.
--
--
-- However, if you set AKGO_USE_WINDOW_FOR_AUDIO_AFTER_VIDEO to true,
-- then all audio files in the playlist (*after* a *video* has played)
-- will continue using the GUI, and this "NOWINDOW" state won't happen.
--
-- I recommend keeping this at "no" or "original" (which means "no" if
-- you haven't set any custom config value for "keep-open").
--
AKGO_NOWINDOW_KEEP_OPEN_VALUE="original"
--
-------
--
-- AKGO_USE_WINDOW_FOR_AUDIO_AFTER_VIDEO:
-- Possible values are: true, false.
-- Reference: https://mpv.io/manual/master/#options-force-window
--
-- If true, we will automatically enable "force-window" after mpv has
-- used video output at least once during the current playlist session.
--
--
-- For most people (who only play a single file) this won't do anything.
-- Nor for people who start mpv with "--player-operation-mode pseudo-gui"
-- since that already enables the video output for audio files too.
--
-- Instead, this option is for when you're *manually* queuing up
-- multiple files from the command line and some of them are video files
-- and some are audio files. Without this option, mpv would switch back
-- and forth between terminal output (CLI) for the playlist's audio
-- files, and video output (GUI) for its video files.
--
-- Automatically switching to force-window means we will use the GUI
-- even for the audio files.
--
-- I recommend leaving this option enabled.
--
AKGO_USE_WINDOW_FOR_AUDIO_AFTER_VIDEO=true
--
-------
--
-- ### END OF USER CONFIGURATION.
-- -----------------------------------------------------------
-- Only proceed if user's personal/system mpv config was loaded.
-- NOTE: This is just a safeguard to protect programs that use
-- mpv as their backend via "--no-config" mode. For now, that
-- actually prevents all user scripts from loading, but there's
-- no guarantee it will always be that way. Better safe than sorry.
if (mp.get_property("config") ~= "no") then
local originalKeepOpenValue = mp.get_property("keep-open")
-- This runs with "false" at mpv initialization (before the playback
-- of the first file), regardless of whether that file will use
-- video output or not. After that, it runs whenever the video
-- output (usually a GUI window) is created or destroyed. So if the
-- first file is a video, it runs twice at startup (false -> true).
--
-- Implementation details:
-- vo-configured == video output created && its configuration went ok.
-- What that means depends on the platform-specific video output module,
-- but usually it means there is a GUI on screen to display video.
mp.observe_property(
"vo-configured",
"bool",
function (name, value)
if (value and mp.get_property("vo") ~= "image") then
-- Video output (usually a GUI) has been created.
-- NOTE: We ignore the "image" vo driver, which isn't a "real"
-- window since it has no GUI and just writes images to disk.
if (AKGO_WINDOW_KEEP_OPEN_VALUE == "original") then
mp.set_property("keep-open", originalKeepOpenValue)
else
mp.set_property("keep-open", AKGO_WINDOW_KEEP_OPEN_VALUE)
end
if (AKGO_USE_WINDOW_FOR_AUDIO_AFTER_VIDEO) then
mp.set_property("force-window", "yes")
end
else
-- Video output (usually a GUI) has been destroyed.
if (AKGO_NOWINDOW_KEEP_OPEN_VALUE == "original") then
mp.set_property("keep-open", originalKeepOpenValue)
else
mp.set_property("keep-open", AKGO_NOWINDOW_KEEP_OPEN_VALUE)
end
end
end)
end
|
local plr = game.Players.LocalPlayer
local chr = plr.Character
local maus = plr:GetMouse()
local PGui=plr.PlayerGui
local lleg = chr["Left Leg"]
local rleg = chr["Right Leg"]
local larm = chr["Left Arm"]
local rarm = chr["Right Arm"]
local hed = chr.Head
local rutprt = chr.HumanoidRootPart
local torso = chr.Torso
local otheranims=false
local armmovement=false
chr.Animate.Disabled=true
local RunSpeed=36
local WlkSpeed=18
local runnin=false
local tik=0
local rollvalue=0
local swimming=false
local fldb={['w']=false,['a']=false,['s']=false,['d']=false}
local jumpval=0
local idlerollv=0
local BallColor=torso.BrickColor
local BallTransparency=0
local BallReflectance=0
local BallMaterial="Neon"
coroutine.wrap(function()
for i,x in pairs(hed:GetChildren()) do if x:IsA('Sound') then x:Destroy() end end end)()
function Lerp(a, b, i)
local com1 = {a.X, a.Y, a.Z, a:toEulerAnglesXYZ()}
local com2 = {b.X, b.Y, b.Z, b:toEulerAnglesXYZ()}
local calx = com1[1] + (com2[1] - com1[1]) * i
local caly = com1[2] + (com2[2] - com1[2]) * i
local calz = com1[3] + (com2[3] - com1[3]) * i
local cala = com1[4] + (com2[4] - com1[4]) * i
local calb = com1[5] + (com2[5] - com1[5]) * i
local calc = com1[6] + (com2[6] - com1[6]) * i
return CFrame.new(calx, caly, calz) * CFrame.Angles(cala, calb, calc)
end
function TwnSingleNumber(s,f,m)
local wot=s+(f-s)*m
return wot
end
function TwnVector3(q,w,e)
local begin={q.x,q.y,q.z}
local ending={w.x,w.y,w.z}
local bgx=begin[1]+(ending[1]-begin[1])*e
local bgy=begin[2]+(ending[2]-begin[2])*e
local bgz=begin[3]+(ending[3]-begin[3])*e
return Vector3.new(bgx,bgy,bgz)
end
newWeld = function(wld, wp0, wp1, wc0x, wc0y, wc0z)
wld = Instance.new("Weld", wp1)
wld.Part0 = wp0
wld.Part1 = wp1
wld.C0 = CFrame.new(wc0x, wc0y, wc0z)
end
function Avg(a, b)
return CFrame.new((a.X+b.X)/2,(a.Y+b.Y)/2,(a.Z+b.Z)/2)
end
local jump=Instance.new('Sound',rutprt)
jump.Volume=.2
jump.Pitch=1
jump.SoundId='http://www.roblox.com/asset?id=170588191'
newWeld(law, torso, larm, -1.5, 0.5, 0)
newWeld(raw, torso, rarm, 1.5, 0.5, 0)
newWeld(llw, torso, lleg, -.5, -2, 0)
newWeld(rlw, torso, rleg, .5, -2, 0)
newWeld(hw, torso, hed, 0, 1.5, 0)
local rutwald=Instance.new('Weld',rutprt)
rutwald.Part0=rutprt
rutwald.Part1=torso
larm.Weld.C1 = CFrame.new(0, 0.5, 0)
rarm.Weld.C1 = CFrame.new(0, 0.5, 0)
rleg.Weld.C1=CFrame.new(0,0,0)*CFrame.Angles(math.rad(0),0,0)
lleg.Weld.C1=CFrame.new(0,0,0)*CFrame.Angles(math.rad(0),0,0)
local anim = "Idling"
local lastanim = "Idling"
local val = 0
local syne = 0
local num = 0
local runtime = 0
maus.KeyDown:connect(function(kei)
if string.byte(kei)==48 and not otheranims and not sitting and not disabled then
runnin=true
end
if kei=='w' then fldb.w=true end
if kei=='a' then fldb.a=true end
if kei=='s' then fldb.s=true end
if kei=='d' then fldb.d=true end
end)
maus.KeyUp:connect(function(kei)
if string.byte(kei)==48 and not otheranims and not sitting and not disabled then
runnin=false
end
if kei=='w' then fldb.w=false end
if kei=='a' then fldb.a=false end
if kei=='s' then fldb.s=false end
if kei=='d' then fldb.d=false end
end)
local bawl=Instance.new("Part",torso)
bawl.formFactor="Custom"
bawl.Shape="Ball"
bawl.BrickColor=(BallColor or torso.BrickColor)
bawl.Material=BallMaterial
bawl.Transparency=(BallTransparency or 0)
bawl.Reflectance=(BallReflectance or 0)
bawl.Size=Vector3.new(5.35,5.35,5.35)
bawl.TopSurface=10
bawl.BottomSurface=10
bawl.LeftSurface=10
bawl.RightSurface=10
bawl.FrontSurface=10
bawl.BackSurface=10
bawl.Anchored=false
bawl:breakJoints''
bawl.Locked=true
bawl.CanCollide=true
--[[local bawlmesh=Instance.new("SpecialMesh",bawl)
bawlmesh.MeshId="http://www.roblox.com/asset/?id=1527559"
--bawlmesh.TextureId="http://www.roblox.com/asset?id=25701026"
bawlmesh.Scale=Vector3.new(2.35,2.35,2.35)]]
local bawllight=Instance.new("PointLight",bawl)
bawllight.Brightness=1
bawllight.Range=15
bawllight.Color=bawl.BrickColor.Color
bawllight.Shadows=true
local bawlweld=Instance.new("Weld",bawl)
bawlweld.Part0=rutprt
bawlweld.Part1=bawl
bawlweld.C1=CFrame.new(0,0,0)
rutprt.Weld.C1=CFrame.new(0,-bawl.Size.y,0)*CFrame.Angles(math.rad(0),math.rad(0),0)
chr.Humanoid.Swimming:connect(function(speedpls)
if speedpls>=5 and not otheranims and not disabled and not sitting then
swimming=true
anim="Swimming"
elseif speedpls<5 and not otheranims and not disabled and not sitting then
swimming=false
end
end)
coroutine.resume(coroutine.create(function()
while true do
if trailing then
local Ray=Ray.new(rutprt.CFrame.p,(rutprt.CFrame.p-(rutprt.CFrame*CFrame.new(0,-2,0)).p).unit*-5)
local hitbrick,hitposition=Workspace:FindPartOnRay(Ray,chr)
if hitbrick and hitposition then
local splash=Instance.new("Part",bawl)
splash.Anchored=true
splash.CanCollide=false
splash.Transparency=0
splash.formFactor="Custom"
splash.BrickColor=hitbrick.BrickColor
splash.Size=Vector3.new(2,2,2)
game:service'Debris':AddItem(splash,2)
splash.CFrame=CFrame.new(hitposition)*CFrame.Angles(math.random(1,3),math.random(1,3),math.random(1,3))
local splm=Instance.new("BlockMesh",splash)
coroutine.wrap(function()
for a=0,1,.05 do
splm.Scale=Vector3.new(a,a,a) splash.Transparency=splash.Transparency+.05 splash.CFrame=splash.CFrame+Vector3.new(0,.05,0) wait'' end
end)()
end
wait''
else
wait''
end
end
end))
game:service'RunService'.RenderStepped:connect(function()
syne=syne+1
if not otheranims and not swimming then
if (torso.Velocity*Vector3.new(1, 0, 1)).magnitude < 1 and not dnc and not chr.Humanoid.Jump then-- and torso.Velocity.y<5 and torso.Velocity.y>-5
anim="Idling"
elseif (rutprt.Velocity*Vector3.new(1, 0, 1)).magnitude > 1 and (rutprt.Velocity*Vector3.new(1, 0, 1)).magnitude < RunSpeed-5 and not chr.Humanoid.Jump then-- and torso.Velocity.y<5 and torso.Velocity.y>-5
anim="Walking"
dnc=false
elseif (torso.Velocity*Vector3.new(1, 0, 1)).magnitude > RunSpeed-10 and not chr.Humanoid.Jump then-- and torso.Velocity.y<5 and torso.Velocity.y>-5
anim="Sprinting"
dnc=false
elseif torso.Velocity.y>5 and chr.Humanoid.Jump then
anim='Jumping'
dnc=false
elseif (torso.Velocity.y < -5) and chr.Humanoid.Jump then
anim='Falling'
dnc=false
end
end
if anim~=lastanim then runtime=0 end
lastanim=anim
if anim=="Idling" then
trailing=false
if not armmovement then
rarm.Weld.C0=Lerp(rarm.Weld.C0,CFrame.new(1.5,.525+math.cos(syne/32.5)/25,0)*CFrame.Angles(0,0,math.rad(3)),.1)
larm.Weld.C0=Lerp(larm.Weld.C0,CFrame.new(-1.5,.525+math.cos(syne/32.5)/25,0)*CFrame.Angles(0,0,math.rad(-3)),.1)
end
lleg.Weld.C0=Lerp(lleg.Weld.C0,CFrame.new(-.55,-1.9-math.cos(syne/32.5)/20,(math.cos(syne/32.5)/35))*CFrame.Angles(-(math.cos(syne/32.5)/35),0,math.rad(-2.5)),.1)
rleg.Weld.C0=Lerp(rleg.Weld.C0,CFrame.new(.55,-1.9-math.cos(syne/32.5)/20,(math.cos(syne/32.5)/35))*CFrame.Angles(-(math.cos(syne/32.5)/35),0,math.rad(2.5)),.1)
hed.Weld.C0=Lerp(hed.Weld.C0,CFrame.new(0,1.5+math.cos(syne/32.5)/50,0)*CFrame.Angles(math.cos(syne/32.5)/40,0,0),.1)
rutprt.Weld.C0=Lerp(rutprt.Weld.C0,CFrame.new(0,-.4,-math.cos(syne/25)*3)*CFrame.Angles(math.cos(syne/25)/4,math.rad(0),math.rad(0)),.1)
bawlweld.C0=Lerp(bawlweld.C0,CFrame.new(0,-.5,-math.cos(syne/25)*3)*CFrame.Angles(math.rad(rollvalue),0,0),.25)
end
if anim=="Walking" then
trailing=true
rollvalue=rollvalue+3
if rollvalue>=359 then rollvalue=0 bawlweld.C0=CFrame.new(0,-.5,0)*CFrame.Angles(-math.rad(rollvalue),0,-(math.cos(syne/4)/5))
elseif rollvalue>=177 and rollvalue<=183 then rollvalue=184 bawlweld.C0=CFrame.new(0,-.5,0)*CFrame.Angles(-math.rad(rollvalue),0,-(math.cos(syne/4)/5))
else
bawlweld.C0=Lerp(bawlweld.C0,CFrame.new(0,-.5,0)*CFrame.Angles(-math.rad(rollvalue),0,-(math.cos(syne/4)/5)),.2) end
if not armmovement then
rarm.Weld.C0=Lerp(rarm.Weld.C0,CFrame.new(1.5,.525-math.cos(syne/8)/6,math.cos(syne/8)/6)*CFrame.Angles(-math.cos(syne/8)/3+math.rad(25),0,math.rad(12.5)),.1)
larm.Weld.C0=Lerp(larm.Weld.C0,CFrame.new(-1.5,.525+math.cos(syne/8)/6,-math.cos(syne/8)/6)*CFrame.Angles(math.cos(syne/8)/3+math.rad(25),0,math.rad(-12.5)),.1)
end
lleg.Weld.C0=Lerp(lleg.Weld.C0,CFrame.new(-(math.cos(syne/8)/11)-.5,-1.7+math.sin(syne/4)/3.5-math.cos(syne/8)/4,math.rad(-5)-(math.cos(syne/8)))*CFrame.Angles(math.rad(5)+(math.cos(syne/8)),0,-(math.cos(syne/8)/11)+math.rad(1)),.1)
rleg.Weld.C0=Lerp(rleg.Weld.C0,CFrame.new(-(math.cos(syne/8)/11)+.5,-1.7-math.sin(syne/4)/3.5+math.cos(syne/8)/4,math.rad(-5)+(math.cos(syne/8)))*CFrame.Angles(math.rad(5)-(math.cos(syne/8)),0,-(math.cos(syne/8)/11)+math.rad(-1)),.1)
rutprt.Weld.C0=Lerp(rutprt.Weld.C0,CFrame.new(0,-.5-math.cos(syne/4)/2,-math.cos(syne/4)*1.5)*CFrame.Angles(math.cos(syne/4)/10+math.rad(-5),math.cos(syne/4)/10,math.cos(syne/8)/10+math.sin(rutprt.RotVelocity.y/2)/10),.1)
end
if anim=="Sprinting" then
trailing=true
rollvalue=rollvalue+5
if rollvalue>=359 then rollvalue=0 bawlweld.C0=CFrame.new(0,-.5,0)*CFrame.Angles(-math.rad(rollvalue),0,-(math.cos(syne/3)/5))
elseif rollvalue>=177 and rollvalue<=183 then rollvalue=184 bawlweld.C0=CFrame.new(0,-.5,0)*CFrame.Angles(-math.rad(rollvalue),0,-(math.cos(syne/3)/5))
else
bawlweld.C0=Lerp(bawlweld.C0,CFrame.new(0,-.5,0)*CFrame.Angles(-math.rad(rollvalue),0,-(math.cos(syne/3)/5)),.2) end
if not armmovement then
rarm.Weld.C0=Lerp(rarm.Weld.C0,CFrame.new(1.5,.525-math.cos(syne/6)/6,math.sin(syne/6)/5)*CFrame.Angles(-math.cos(syne/6)/3+math.rad(25),0,math.rad(12.5)),.1)
larm.Weld.C0=Lerp(larm.Weld.C0,CFrame.new(-1.5,.525+math.cos(syne/6)/6,-math.sin(syne/6)/5)*CFrame.Angles(math.cos(syne/6)/3+math.rad(25),0,math.rad(-12.5)),.1)
end
lleg.Weld.C0=Lerp(lleg.Weld.C0,CFrame.new(-(math.cos(syne/6)/11)-.575,-1.7+math.cos(syne/3)/4-math.cos(syne/6)/4,math.rad(-5)-(math.cos(syne/6)))*CFrame.Angles(math.rad(5)+(math.cos(syne/6)),0,-(math.cos(syne/6)/11)+math.rad(-5)),.1)
rleg.Weld.C0=Lerp(rleg.Weld.C0,CFrame.new(-(math.cos(syne/6)/11)+.575,-1.7-math.cos(syne/3)/4+math.cos(syne/6)/4,math.rad(-5)+(math.cos(syne/6)))*CFrame.Angles(math.rad(5)-(math.cos(syne/6)),0,-(math.cos(syne/6)/11)+math.rad(5)),.1)
rutprt.Weld.C0=Lerp(rutprt.Weld.C0,CFrame.new(0,-.5-math.cos(syne/3)/2,-math.cos(syne/3)*1.5)*CFrame.Angles(math.cos(syne/3)/10+math.rad(-5),math.cos(syne/3)/10,math.cos(syne/6)/10+math.sin(rutprt.RotVelocity.y/2)/10),.1)
end
if anim=="Falling" then
trailing=false
if not armmovement then
rarm.Weld.C0=Lerp(rarm.Weld.C0,CFrame.new(1.5,.525,0)*CFrame.Angles(math.rad(25),0,math.rad(25)),.1)
larm.Weld.C0=Lerp(larm.Weld.C0,CFrame.new(-1.5,.525,0)*CFrame.Angles(math.rad(25),0,math.rad(-25)),.1)
end
lleg.Weld.C0=Lerp(lleg.Weld.C0,CFrame.new(-.55,-1.9,math.rad(-20))*CFrame.Angles(math.rad(20),0,math.rad(-2.5)),.1)
rleg.Weld.C0=Lerp(rleg.Weld.C0,CFrame.new(.55,-1.9,math.rad(-20))*CFrame.Angles(math.rad(20),0,math.rad(2.5)),.1)
hed.Weld.C0=Lerp(hed.Weld.C0,CFrame.new(0,1.5,-.3)*CFrame.Angles(math.rad(-15),0,0),.1)
rutprt.Weld.C0=Lerp(rutprt.Weld.C0,CFrame.new(0,rutprt.Weld.C0.y+.2,1.75)*CFrame.Angles(math.rad(-15),math.rad(0),math.rad(0)),.1)
bawlweld.C0=Lerp(bawlweld.C0,CFrame.new(0,-.5,0)*CFrame.Angles(math.rad(rollvalue),0,0),.325)
end
if anim=="Jumping" then
trailing=false
if not armmovement then
rarm.Weld.C0=Lerp(rarm.Weld.C0,CFrame.new(1.5,.525,0)*CFrame.Angles(math.rad(-25),0,math.rad(25)),.1)
larm.Weld.C0=Lerp(larm.Weld.C0,CFrame.new(-1.5,.525,0)*CFrame.Angles(math.rad(-25),0,math.rad(-25)),.1)
end
lleg.Weld.C0=Lerp(lleg.Weld.C0,CFrame.new(-.55,-1.9,math.rad(5))*CFrame.Angles(math.rad(-5),0,math.rad(-2.5)),.1)
rleg.Weld.C0=Lerp(rleg.Weld.C0,CFrame.new(.55,-1.9,math.rad(5))*CFrame.Angles(math.rad(-5),0,math.rad(2.5)),.1)
hed.Weld.C0=Lerp(hed.Weld.C0,CFrame.new(0,1.5,.05)*CFrame.Angles(math.rad(15),0,0),.1)
rutprt.Weld.C0=Lerp(rutprt.Weld.C0,CFrame.new(0,rutprt.Weld.C0.y+.1,0)*CFrame.Angles(math.rad(5),math.rad(0),math.rad(0)),.1)
bawlweld.C0=Lerp(bawlweld.C0,CFrame.new(0,-.5,0)*CFrame.Angles(math.rad(rollvalue),0,0),.325)
end
if anim=="WallRun" then
chr.Humanoid.Jump=true
trailing=false
rollvalue=rollvalue+7
if rollvalue>=359 then rollvalue=0 bawlweld.C0=CFrame.new(0,-.5,0)*CFrame.Angles(-math.rad(rollvalue),0,-(math.cos(syne/3)/5))
elseif rollvalue>=177 and rollvalue<=183 then rollvalue=184 bawlweld.C0=CFrame.new(0,-.5,0)*CFrame.Angles(-math.rad(rollvalue),0,-(math.cos(syne/3)/5))
else
bawlweld.C0=Lerp(bawlweld.C0,CFrame.new(0,-.5,0)*CFrame.Angles(-math.rad(rollvalue),0,-(math.cos(syne/3)/5)),.2) end
if not armmovement then
rarm.Weld.C0=Lerp(rarm.Weld.C0,CFrame.new(1.325,.525,.2)*CFrame.Angles(math.rad(-45),0,math.rad(3)),.1)
larm.Weld.C0=Lerp(larm.Weld.C0,CFrame.new(-1.325,.525,.2)*CFrame.Angles(math.rad(-45),0,math.rad(-3)),.1)
end
lleg.Weld.C0=Lerp(lleg.Weld.C0,CFrame.new(-(math.cos(syne/5)/11)-.575,-1.8-math.cos(syne/2.5)/2+math.cos(syne/5)/6,math.rad(-30)-(math.cos(syne/5)))*CFrame.Angles(math.rad(30)+(math.cos(syne/5)),0,-(math.cos(syne/5)/11)+math.rad(-5)),.1)
rleg.Weld.C0=Lerp(rleg.Weld.C0,CFrame.new(-(math.cos(syne/5)/11)+.575,-1.8+math.cos(syne/2.5)/2-math.cos(syne/5)/6,math.rad(-30)+(math.cos(syne/5)))*CFrame.Angles(math.rad(30)-(math.cos(syne/5)),0,-(math.cos(syne/5)/11)+math.rad(5)),.1)
hed.Weld.C0=Lerp(hed.Weld.C0,CFrame.new(0,1.45,.25)*CFrame.Angles(math.rad(30),0,0),.1)
rutprt.Weld.C0=Lerp(rutprt.Weld.C0,CFrame.new(0,-1-math.cos(syne/2.5)/2,2-math.cos(syne/3)*1.5)*CFrame.Angles(math.cos(syne/2.5)/10+math.rad(-3),math.cos(syne/2.5)/10,math.cos(syne/5)/10+math.sin(rutprt.RotVelocity.y/2)/10),.1)
end
if anim=="Swimming" then
rollvalue=rollvalue+4
if rollvalue>=360 then rollvalue=0 end
if not armmovement then
rarm.Weld.C0=Lerp(rarm.Weld.C0,CFrame.new(1.5,.525-math.cos(syne/8)/6,math.cos(syne/8)/6)*CFrame.Angles(-math.cos(syne/8)/3+math.rad(25),0,math.rad(12.5)),.1)
larm.Weld.C0=Lerp(larm.Weld.C0,CFrame.new(-1.5,.525+math.cos(syne/8)/6,-math.cos(syne/8)/6)*CFrame.Angles(math.cos(syne/8)/3+math.rad(25),0,math.rad(-12.5)),.1)
end
lleg.Weld.C0=Lerp(lleg.Weld.C0,CFrame.new(-.55,-1.7+math.cos(syne/4)/4,math.rad(-5)-(math.cos(syne/8)))*CFrame.Angles(math.rad(5)+(math.cos(syne/8)),0,math.rad(-5)),.1)
rleg.Weld.C0=Lerp(rleg.Weld.C0,CFrame.new(.55,-1.7-math.cos(syne/4)/4,math.rad(-5)+(math.cos(syne/8)))*CFrame.Angles(math.rad(5)-(math.cos(syne/8)),0,math.rad(5)),.1)
bawlweld.C0=Lerp(bawlweld.C0,CFrame.new(0,-.5,0)*CFrame.Angles(-math.rad(rollvalue),0,0),.25)
rutprt.Weld.C0=Lerp(rutprt.Weld.C0,CFrame.new(0,-.4-math.cos(syne/4)/4,-math.cos(syne/4)*1.25)*CFrame.Angles(math.cos(syne/4)/10+math.rad(95),math.cos(syne/4)/10,math.cos(syne/8)/10+math.sin(rutprt.RotVelocity.y/2)/10),.1)
end
chr.Humanoid.CameraOffset=(rutprt.CFrame:toObjectSpace(hed.CFrame)).p+Vector3.new(0,-1.25,0)
if runnin and not disabled and not otheranims and not sitting then
chr.Humanoid.WalkSpeed=RunSpeed
elseif not runnin and not disabled and not otheranims and not sitting then
chr.Humanoid.WalkSpeed=WlkSpeed
end
if rutprt:findFirstChild("WallRunningVelocitypls") and otheranims then
local rei=Ray.new((rutprt.CFrame).p,(((rutprt.CFrame*CFrame.new(0,0,-1)).p)-rutprt.CFrame.p).unit*((bawl.Size.y/2)))
local hitpart,hitpos=Workspace:FindPartOnRay(rei,chr)
if not hitpart then
otheranims=false
rutprt:findFirstChild("WallRunningVelocitypls"):Destroy''
else
return
end
end
if runnin and (fldb.w or fldb.a or fldb.s or fldb.d) then
local rei=Ray.new((rutprt.CFrame).p,(((rutprt.CFrame*CFrame.new(0,0,-1)).p)-rutprt.CFrame.p).unit*((bawl.Size.y/2)))
local hitpart,hitpos=Workspace:FindPartOnRay(rei,chr)
if hitpart and hitpart.CanCollide then
otheranims=true
anim="WallRun"
if not rutprt:findFirstChild("WallRunningVelocitypls") then
local wlvelo=Instance.new("BodyVelocity",rutprt)
wlvelo.Name="WallRunningVelocitypls"
wlvelo.maxForce=Vector3.new(0,math.huge,0)
wlvelo.velocity=Vector3.new(0,RunSpeed*1.2,0)
end
end
else
if rutprt:findFirstChild("WallRunningVelocitypls") and otheranims then
otheranims=false
rutprt:findFirstChild("WallRunningVelocitypls"):destroy''
end
end
end)
|
--luacheck: no self
local curdir = std.getinfo(1).source:gsub("^(.+[\\/])[^\\/]+$", "%1"):gsub("^@", "");
local mrd = {
lang = false;
words = {};
dirs = {''};
dict_file = 'dict.mrd';
}
local msg = dprint or print
local function debug(...)
if DEBUG then
dprint(...)
end
end
local function cache_add(cache, key, val)
table.insert(cache.list, 1, key)
local len = #cache.list
if len > (cache.len or 128) then
local okey = cache.list[len]
table.remove(cache.list, len)
cache.hash[okey] = nil
end
cache.hash[key] = val
end
local function split(str, sep)
local words = {}
if not str then
return words
end
for w in str:gmatch(sep or "[^ \t]+") do
table.insert(words, w)
end
return words
end
local function empty(l)
l = l:gsub("[ \t]+", "")
return l == ""
end
function mrd:gramtab(path)
local f, e = io.open(path or 'rgramtab.tab', 'rb')
if not f then
return false, e
end
self.gram = {
an = {}; -- by ancodes
t = {}; -- by types
}
for l in f:lines() do
if not l:find("^[ \t]*//") and not empty(l) then -- not comments
local w = split(l)
if #w < 3 then
msg("Skipping gram: "..l)
else
local a = split(w[4], '[^,]+')
local an = {}
for _, v in ipairs(a) do
an[v] = true
end
an.t = w[3] -- type
self.gram.an[w[1]] = an;
self.gram.t[w[3]] = an;
end
end
end
f:close()
end
local function section(f, fn, ...)
local n = f:read("*line")
n = n and tonumber(n)
if not n then
return false
end
if n == 0 then
return true
end
for l in f:lines() do -- skip accents
if fn then fn(l, ...) end
n = n - 1
if n == 0 then
break
end
end
return true
end
local flex_filter
local function flex_fn(l, flex, an)
l = l:gsub("//.*$", "")
local fl = {}
for w in l:gmatch("[^%%]+") do
local ww = split(w, "[^%*]+")
if #ww > 3 or #ww < 1 then
msg("Skip lex: ", w, l);
else
local f = { }
if #ww == 1 then
f.an = ww[1]
f.post = ''
else
f.post = ww[1]
f.an = ww[2]
end
f.pre = ww[3] or ''
local a = an[f.an]
if not a then
msg("Gram not found. Skip lex: "..f.an)
else
f.an_name = f.an
f.an = a
if flex_filter(f) then
f.filter = true
end
table.insert(fl, f)
end
end
end
table.insert(flex, fl)
end
local function pref_fn(l, pref)
local p = split(l, "[^,]+")
table.insert(pref, p)
end
--[[
local function dump(vv)
local s = ''
if type(vv) ~= 'table' then
return string.format("%s", tostring(vv))
end
for k, v in pairs(vv) do
s = s .. string.format("%s = %s ", k, v)
end
return s
end
local function gram_dump(v)
for _, f in ipairs(v.flex) do
local tt = v.pref .. f.pre .. v.t .. f.post
print("=== ", tt)
for _, v in pairs(f.an) do
print(_, v)
end
end
end
]]--
local busy_cnt = 0
local function word_fn(l, self, dict)
local norm = mrd.lang.norm
local words = self.words
local words_list = self.words_list
local w = split(l)
if #w ~= 6 then
msg("Skipping word: "..l)
return
end
if w[1] == '#' then w[1] = '' end
local nflex = tonumber(w[2]) or false
local an = w[5]
if an == '-' then an = false end
local an_name = an
local npref = tonumber(w[6]) or false
if not nflex then
msg("Skipping word:"..l)
return
end
nflex = self.flex[nflex + 1]
if not nflex then
msg("Wrong paradigm number for word: "..l)
return
end
if an then
an = self.gram.an[an]
if not an then
msg("Wrong ancode for word: "..l)
return
end
end
if npref then
npref = self.pref[npref + 1]
if not npref then
msg("Wrong prefix for word: "..l)
return
end
end
local t = w[1]
local num = 0
local used = false
for _, v in ipairs(nflex) do
if v.filter then
for _, pref in ipairs(npref or { '' }) do
local tt = norm(pref .. v.pre .. t .. v.post)
-- if tt == 'ЗАКРЕПЛЕН' then
-- gram_dump { t = t, pref = pref, flex = nflex, an = v.an }
-- end
if not dict or dict[tt] then
local a = {}
for kk, _ in pairs(an or {}) do
a[kk] = an[kk]
end
for kk, _ in pairs(v.an) do
a[kk] = v.an[kk]
end
local wds = words[tt] or {}
table.insert(wds,
{ t = t, pref = pref, flex = nflex, an = a })
nflex.used = true
used = true
if npref then
npref.used = true
end
num = num + 1
if #wds == 1 then
words[tt] = wds
end
end
end
end
end
if used then
table.insert(words_list, { t = w[1], flex = nflex, pref = npref, an = an_name })
end
self.words_nr = self.words_nr + num
busy_cnt = busy_cnt + 1
if busy_cnt > 1000 then
if std then std.busy(true) end
busy_cnt = 0
end
return
end
function mrd:load(path, dict)
local f, e = io.open(path or 'morphs.mrd', 'rb')
if not f then
return false, e
end
local flex = {}
flex_filter = mrd.lang.flex_filter
if not section(f, flex_fn, flex, self.gram.an) then
return false, "Error in section 1"
end
self.flex = flex
if not section(f) then
return false, "Error in section 2"
end
if not section(f) then
return false, "Error in section 3"
end
local pref = {}
if not section(f, pref_fn, pref) then
return false, "Error in section 4"
end
self.pref = pref
self.words_nr = 0
self.words = {}
self.words_list = {}
collectgarbage("stop")
if not section(f, word_fn, self, dict) then
collectgarbage("restart")
return false, "Error in section 4"
end
collectgarbage("restart")
msg("Generated: "..tostring(self.words_nr).." word(s)");
local crc = f:read("*line")
if crc then crc = tonumber(crc) end
f:close()
if std then std.busy(false) end
return true, crc
end
function mrd:dump(path, crc)
local f, e = io.open(path or 'dict.mrd', 'wb')
if not f then
return false, e
end
local n = 0
for _, v in ipairs(self.flex) do
if v.used then
v.norm_no = n
n = n + 1
end
end
f:write(string.format("%d\n", n))
for _, v in ipairs(self.flex) do
if v.used then
local s = ''
for _, vv in ipairs(v) do
s = s .. '%'
if vv.post == '' then
s = s..vv.an_name
else
s = s..vv.post..'*'..vv.an_name
end
if vv.pre ~= '' then
s = s .. '*'..vv.pre
end
end
f:write(s.."\n")
end
end
f:write("0\n")
f:write("0\n")
n = 0
for _, v in ipairs(self.pref) do
if v.used then
v.norm_no = n
n = n + 1
end
end
f:write(string.format("%d\n", n))
for _, v in ipairs(self.pref) do
if v.used then
local s = ''
for _, vv in ipairs(v) do
if s ~= '' then s = s .. ',' end
s = s .. vv
end
f:write(s.."\n")
end
end
f:write(string.format("%d\n", #self.words_list))
for _, v in ipairs(self.words_list) do
local s
if v.t == '' then
s = '#'
else
s = v.t
end
s = s ..' '..tostring(v.flex.norm_no)
s = s..' - -'
if v.an then
s = s .. ' '..v.an
else
s = s .. ' -'
end
if v.pref then
s = s ..' '..tostring(v.pref.norm_no)
else
s = s .. ' -'
end
f:write(s..'\n')
end
if crc then
f:write(string.format("%d\n", crc))
end
f:close()
end
local function gram2an(g)
local a = {}
for _, v in ipairs(g) do
if v:sub(1, 1) == '~' then
a[v:sub(2)] = false
else
a[v] = true
end
end
a.t = nil
return a
end
local lookup_cache = {
hash = {};
list = {};
len = 512;
}
local function hint_append(hint, h)
if h == "" or not h then return hint end
if hint == "" or not hint then return h end
return hint .. ',' .. h
end
function mrd:lookup(w, g)
local key = ""
for _, v in ipairs(g or {}) do
key = hint_append(key, v)
end
key = w .. '/'..key
local cc = lookup_cache.hash[key]
if cc then
return cc.w, cc.g
end
w, g = self:__lookup(w, g)
cache_add(lookup_cache, key, { w = w, g = g })
return w, g
end
function mrd:__lookup(w, g)
local ow = w
local cap, upper = self.lang.is_cap(w)
local tt = self.lang.upper(self.lang.norm(w))
w = self.words[tt]
if not w then
return false, "No word in dictionary"
end
local res = {}
local gram_compat = self.lang.gram_compat
local gram_score = self.lang.gram_score
for _, v in ipairs(w) do
local flex = v.flex
local score = gram_score(v.an, g)
local t = v.an.t
for _, f in ipairs(flex) do
if gram_compat(v.an, f.an, gram2an(g)) then
local sc = gram_score(f.an, g)
if sc >= 0 then
if t ~= f.an.t then sc = sc - 1 end -- todo
--[[
local tt = v.pref .. f.pre .. v.t .. f.post
if tt == 'ЛЕВЫЙ' or tt == 'ЛЕВОГО' or tt == 'ШЛЕМОМ' then
print ("======looking for:", g.noun)
for _, v in pairs(g) do
print(_, v)
end
print ("======looking got:", score + sc, sc)
print(tt, v.t, score + sc)
for _, v in pairs(f.an) do
print(_, v)
end
end
]]--
table.insert(res, { score = score + sc, pos = #res, word = v, flex = f })
end
end
end
end
if #res == 0 then
return ow, gram2an(g) -- false, "No gram"
end
table.sort(res, function(a, b)
if a.score == b.score then
return a.pos < b.pos
end
return a.score > b.score
end)
--[[
for i = 1, #res do
local w = res[i]
local tt = self.lang.lower(w.word.pref .. w.flex.pre .. w.word.t .. w.flex.post)
print(i, "res: ", tt, w.score)
if tt == 'красный' or tt == 'красного' then
for _, v in pairs(w.flex.an) do
print(_, v)
end
end
-- print(tt, w.score)
end
]]--
w = res[1]
local gram = {}
for k, v in pairs(w.flex.an) do
gram[k] = v
end
for k, v in pairs(w.word.an) do
gram[k] = v
end
w = self.lang.lower(w.word.pref .. w.flex.pre .. w.word.t .. w.flex.post)
if upper then
w = self.lang.upper(w)
elseif cap then
w = self.lang.cap(w)
end
return w, gram
end
local word_match = "[^ \t,%-!/:%+&]+"
local missed_words = {}
local word_cache = { list = {}, hash = {} }
function mrd:word(w, ob)
local cache = word_cache
if ob then
if not ob.__word_cache then
std.rawset(ob, '__word_cache', {
list = {},
hash = {},
len = 32,
})
end
cache = ob.__word_cache
end
local key = w
local c = cache.hash[key]
if c then
return std.clone(c[1]), std.clone(c[2])
end
local ow = w
local s, _ = w:find("/[^/]*$")
local g = {}
local grams = {}
local hints = ''
if s then
hints = w:sub(s + 1)
w = w:sub(1, s - 1)
g = split(hints, "[^, ]+")
end
local found = true
local noun = false
local lang = self.lang
w = w:gsub(word_match,
function(t)
if noun then return t end
local ww, gg
if ob then
ww, gg = self:dict(ob.__dict, t..'/'..hints)
end
if not ww then
ww, gg = self:dict(game.__dict, t..'/'..hints)
end
if not ww then
ww, gg = self:dict(self.__dict, t..'/'..hints)
end
noun = gg and gg[lang.gram_t.noun]
if not ww then
ww, gg = self:lookup(t, g)
noun = gg and gg.t == lang.gram_t.noun
end
if gg and (gg[lang.gram_t.proper] or gg[lang.gram_t.surname]) then
noun = false
end
if not ww then
found = false
else
table.insert(grams, gg)
end
return ww or t
end)
if not found then
if DEBUG and not tonumber(w) and not missed_words[w] then
missed_words[w] = true
debug("Can not find word: '"..ow.."'")
end
end
cache_add(cache, key, { w, grams })
return w, grams
end
function mrd:file(f, dict)
dict = dict or {}
local ff, e = io.open(f, "rb")
if not ff then
return false, e
end
debug("Added file: ", f)
for l in ff:lines() do
for w in l:gmatch('%-"[^"]+"') do
w = w:gsub('^%-"', ""):gsub('"$', "")
local words = split(w, '[^|]+')
for _, word in ipairs(words) do
word = word:gsub("/[^/]*$", "")
for ww in word:gmatch(word_match) do
local t = self.lang.upper(self.lang.norm(ww))
if not dict[t] and not t:find("%*$") then
dict[t] = true;
debug("mrd: Added word: ", ww)
end
end
end
end
end
ff:close()
return dict
end
local function str_hint(str)
-- str = str:gsub("^%+", "")
local s, _ = str:find("/[^/]*$")
if not s then
return str, ""
end
if s == 1 then
return "", str:sub(2)
end
return str:sub(1, s - 1), str:sub(s + 1)
end
local function str_strip(str)
return std.strip(str)
end
local function str_split(str, delim)
local a = std.split(str, delim)
for k, _ in ipairs(a) do
a[k] = str_strip(a[k])
end
return a
end
function mrd:dict(dict, word)
if not dict then return end
local tab = {}
local w, hints = str_hint(word)
hints = str_split(hints, ",")
local tt = dict[w]
if not tt then
return
end
for _, v in ipairs(tt) do
local whints = {}
local w, h = str_hint(v)
local hh = str_split(h, ",")
for _, vv in ipairs(hh) do
whints[vv] = true
end
local t = { w, score = 0, pos = #tab, w = w }
for _, hv in ipairs(hints) do
if hv:sub(1, 1) ~= '~' then
if whints[hv] then
t.score = t.score + 1
end
else
if whints[str_strip(hv:sub(2))] then
t.score = t.score - 1
end
end
end
t.hints = str_split(hint_append(tt.hints, h), ",")
if mrd.lang.gram_t.nom and whints[mrd.lang.gram_t.nom] then
t.score = t.score + 0.5
end
table.insert(tab, t)
end
if #tab == 0 then
return
end
table.sort(tab,
function(a, b)
if a.score == b.score then
return a.pos < b.pos
end
return a.score > b.score
end)
if tab[1].score > 0 then
return tab[1].w, gram2an(tab[1].hints)
end
end
function mrd.dispof(w)
if w.raw_word ~= nil then
local d = std.call(w, 'raw_word')
return d, true
end
if w.word ~= nil then
local d = std.call(w, 'word')
return d
end
return std.titleof(w) or std.nameof(w)
end
local obj_cache = { hash = {}, list = {}, len = 128 }
function mrd:obj(w, n, nn)
local hint = ''
local hint2, disp, ob, raw
if type(w) == 'string' then
w, hint = str_hint(w)
elseif type(n) == 'string' then
hint = n
n = nn
end
if type(w) ~= 'string' then
-- w = std.object(w)
ob = w
disp, raw = self.dispof(w)
else
disp = w
end
local d = obj_cache.hash[disp]
if not d then
d = str_split(disp, '|')
if #d == 0 then
std.err("Wrong object display: ".. (disp or 'nil'), 2)
end
-- normalize
local nd = {}
for k, v in ipairs(d) do
w, hint2 = str_hint(v)
local dd = raw and { w } or str_split(w, ',')
for _, vv in ipairs(dd) do
table.insert(nd, { word = vv, hint = hint2 or '', alias = k, idx = _ })
-- for w in vv:gmatch("[^ ]+") do
-- table.insert(nd, { word = w, hint = hint2 or '', alias = k, idx = _ })
-- end
end
end
d = nd
cache_add(obj_cache, disp, d)
end
if type(n) == 'table' then
local ret = n
for _, v in ipairs(d) do
table.insert(ret, { word = v.word, hint = hint_append(hint, v.hint), alias = v.alias, idx = v.idx });
end
return ob, ret
end
n = n or (ob and ob.__word_alias) or 1
for k, v in ipairs(d) do
if v.alias == n then
n = k
break
end
end
if not d[n] then n = 1 end
w = d[n].word
hint2 = d[n].hint
return ob, w, hint_append(hint, hint2)
end
local function noun_append(rc, tab, w)
-- w = mrd.lang.norm(w)
if tab then
table.insert(tab, w)
else
if rc ~= '' then rc = rc .. '|' end
rc = rc .. w
end
return rc
end
function mrd:noun_hint(ob, n)
if not ob then
return ''
end
if not ob.__hint_cache then
std.rawset(ob, '__hint_cache', {
list = {},
hash = {},
len = 16,
})
end
local key = n or ob.__word_alias or 1
local c
if type(ob.word) == 'string' then -- do not use caching if function
c = ob.__hint_cache.hash[key]
end
if c then
return c
end
local g = ob and ob:gram('noun', n) or {}
local hint = ''
local lang = self.lang
for _, v in ipairs { lang.gram_t.male, lang.gram_t.female,
lang.gram_t.neuter, lang.gram_t.plural,
lang.gram_t.live } do
if g[v] then
hint = hint_append(hint, v)
end
end
if not g[self.lang.gram_t.live] then
hint = hint_append(hint, lang.gram_t.nonlive)
end
if ob then
hint = hint_append(hint, "noun")
end
cache_add(ob.__hint_cache, key, hint)
return hint
end
function mrd:noun(w, n, nn)
local hint, ob
local rc = ''
local tab = false
ob, w, hint = self:obj(w, n, nn)
if type(w) ~= 'table' then
local alias = nn
if type(alias) ~= 'number' then alias = n end
if type(alias) ~= 'number' then alias = nil end
w = {{ word = w, hint = hint, alias = alias }}
else
tab = {}
end
for _, v in ipairs(w) do
local hint2 = self:noun_hint(ob, v.alias)
local m = self:word(v.word .. '/'.. hint_append(v.hint, hint2), ob)
rc = noun_append(rc, tab, m)
end
return tab and tab or rc
end
local function str_hash(str)
local sum = 0
for i = 1, str:len() do
sum = sum + string.byte(str, i)
end
return sum
end
function mrd:init(l)
self.lang = l
if type(l.dict) == 'table' then
std.obj.dict(self, l.dict)
end
if self:gramtab(curdir .. "rgramtab.tab") == false then
msg("Error while opening gramtab.")
return
end
local _, crc = self:load(mrd.dict_file)
self:create(mrd.dict_file, crc) -- create or update
end
function mrd:create(fname, crc)
local dict = {}
if not std.readdir then
return
end
for _, d in ipairs(self.dirs) do
if d == '' then d = instead.gamepath() end
local list = {}
for f in std.readdir(d) do
if f:find("%.lua$") or f:find("%.LUA$") then
table.insert(list, f)
end
end
table.sort(list)
for _, f in ipairs(list) do
local path = d .. "/" .. f
mrd:file(path, dict)
end
end
local sum = 0
for w, _ in pairs(dict) do
sum = sum + str_hash(w)
sum = sum % 4294967291;
end
if crc ~= sum then
msg("Generating dict.mrd with sum: ", sum)
if mrd:load(curdir .. "morphs.mrd", dict) then
mrd:dump(fname or 'dict.mrd', sum)
else
msg("Can not find morph/morphs.mrd")
end
else
msg("Using dict.mrd")
end
end
if std then
std.obj.noun = function(self, ...)
return mrd:noun(self, ...)
end
std.obj.Noun = function(self, ...)
return mrd.lang.cap(mrd:noun(self, ...))
end
std.obj.gram = function(self, ...)
local hint, w, gram, _
_, w, hint = mrd:obj(self, ...)
_, gram = mrd:word(w .. '/'..hint)
local thint = ''
local t = mrd.lang.gram_t.noun
hint = str_split(hint, ",")
local g = gram and gram[1] or {}
for _, v in ipairs(gram or {}) do
if v.t == t or v[t] then
g = v
break
end
end
local gg = std.clone(g)
for _, v in ipairs(hint) do
gg[v] = true
end
for k, v in pairs(gg) do
if v then
thint = hint_append(thint, k)
end
end
gg.hint = thint
return gg
end
std.obj.dict = function(self, t)
local idx = std.rawget(self, '__dict') or {}
for word, v in pairs(t) do
local w, hints = str_hint(word)
if type(v) == 'table' then
idx[w] = v
v.hints = hints or ""
else
if not idx[w] then
idx[w] = { hints = "", }
end
table.insert(idx[w], v .. '/' .. hints)
end
end
std.rawset(self, '__dict', idx)
return self
end
local onew = std.obj.new
std.obj.new = function(self, v)
if type(v[1]) == 'string' or type(v[1]) == 'function' then
v.word = v[1]
table.remove(v, 1)
end
return onew(self, v)
end
end
local mt = getmetatable("")
function mt.__unm(v)
return v
end
return mrd
--mrd:gramtab()
--mrd.lang = require "lang-ru"
--mrd:load(false, { [mrd.lang.upper "подосиновики"] = true, [mrd.lang.upper "красные"] = true })
--local w = mrd:word(-"красные подосиновики/рд")
--print(w)
--mrd:file("mrd.lua")
|
local myutils = require 'myutils'
local utils = require 'utils'
local image = require 'image'
local BatchProviderVID = torch.class('fbcoco.BatchProviderVID')
-- DEBUG flag
local DEBUG = false
function BatchProviderVID:__init(anno, transformer, opt)
assert(transformer,'must provide transformer!')
self.anno = anno
self.prop_dir = opt.prop_dir
self.fg_threshold = opt.fg_threshold
self.bg_threshold = opt.bg_threshold
self.fg_fraction = opt.fg_fraction
self.batch_size = opt.batch_size
self.test_batch_size = opt.test_batch_size
self.sample_n_per_box = opt.sample_n_per_box
self.sample_sigma = opt.sample_sigma
self.batch_N = opt.seq_per_batch or 2
self.batch_T = opt.timestep_per_batch or 16
self.frame_stride = opt.frame_stride
self.spec_im_size = opt.spec_im_size
self.scale = opt.scale or 600
self.max_size = opt.max_size or 1000
self.image_transformer = transformer
self.img_dir = opt.img_dir
-- how many threads for Parallel feeding
self.parallel_roi_batch = opt.parallel_roi_batch or 1
-- whether to focus on the center or not
self.seq_center = opt.seq_center or false
-- uniformly jitter the scale by this frac
self.scale_jitter = opt.scale_jitter or 0 -- default to 0
-- uniformly jitter the scale by this frac
self.aspect_jitter = opt.aspect_jitter or 0 -- default to 0
-- likelihood of doing a random crop (in each dimension, independently)
self.crop_likelihood = crop_likelihood or 0
-- number of attempts to try to find a valid crop
self.crop_attempts = 10
-- a crop must preserve at least this fraction of the iamge
self.crop_min_frac = 0.7
-- get a deterministic list of video names
self.video_names = myutils.keys(anno)
self.non_redundant_sampling = opt.sampling_mode == 'NONE_REDUNDANT' -- 'RANDOM' or 'NONE_REDUNDANT'
-- init the video reading list
self:shuffle()
if self.non_redundant_sampling then
self:init_sampling_hist()
end
-- augment the category name list
local category_list
if opt.dataset == 'ImageNetVID' then
category_list = {'airplane', 'antelope', 'bear', 'bicycle', 'bird', 'bus', 'car', 'cattle',
'dog', 'domestic_cat', 'elephant', 'fox', 'giant_panda', 'hamster', 'horse', 'lion',
'lizard', 'monkey', 'motorcycle', 'rabbit', 'red_panda', 'sheep', 'snake', 'squirrel',
'tiger', 'train', 'turtle', 'watercraft', 'whale', 'zebra'
}
else
assert(false, 'Unknown dataset.')
end
self.cat_name_to_id = {}
self.cat_id_to_name = {}
self.class_num = #category_list
for cat_id, cat_name in ipairs(category_list) do
self.cat_name_to_id[cat_name] = cat_id + 1 -- +1 because we leave 1 to background class
self.cat_id_to_name[cat_id + 1] = cat_name
end
-- initialize a transformer
if opt.brightness_var and opt.contrast_var and opt.saturation_var and opt.lighting_var then
self.color_jitter = fbcoco.ColorTransformer(opt.brightness_var,
opt.contrast_var, opt.saturation_var, opt.lighting_var)
else
self.color_jitter = nil
end
-- init a counter array recording the encounter of objects of different categories
self.cat_counter = torch.FloatTensor(self.class_num + 1):zero()
end
function BatchProviderVID:load_prop(video_name)
local filename = paths.concat(self.prop_dir, string.format('%s.t7', video_name))
local res = torch.load(filename)
return res
end
function BatchProviderVID:init_sampling_hist()
self.sampling_hist = {}
for vid_name, vid in pairs(self.anno) do
self.sampling_hist[vid_name] = torch.IntTensor(#vid.im_list):zero()
end
end
function BatchProviderVID:get_next_video_idx()
self.video_ptr = self.video_ptr + 1
if self.video_ptr > self.video_index_list:nElement() then
self:shuffle()
end
local video_idx = self.video_index_list[self.video_ptr]
return video_idx
end
function BatchProviderVID:shuffle()
self.video_index_list = torch.randperm(#self.video_names):long()
self.video_ptr = 1
end
function BatchProviderVID:getFlows(video_name, frame_seq, flip, transform, spec_im_size)
-- sample some jittering parameters
flip = flip == 1
-- transform flag
if transform == nil then
transform = true
else
transform = transform == 1
end
local num_images = frame_seq:nElement()
local im_s, im_scale
-- load images from disk
local flows
for ii, frame_idx in ipairs(frame_seq:totable()) do
local concise_video_name = paths.basename(video_name)
local ptr = frame_idx
local u_filename = paths.concat(self.img_dir, 'u', concise_video_name, string.format('frame%.6d.jpg', ptr))
while not myutils.file_exists(u_filename) do
--assert(frame_idx - ptr <= 3, 'Fallback too much.')
if frame_idx - ptr > 3 then
print(string.format('WARNING: file -- %s, |target_idx - actual_idx| = %d', u_filename, frame_idx - ptr))
end
ptr = ptr - 1
u_filename = paths.concat(self.img_dir, 'u', concise_video_name, string.format('frame%.6d.jpg', ptr))
end
local u = image.load(u_filename, 1, 'float')
local ptr = frame_idx
local v_filename = paths.concat(self.img_dir, 'v', concise_video_name, string.format('frame%.6d.jpg', ptr))
while not myutils.file_exists(v_filename) do
--assert(frame_idx - ptr <= 3, 'Fallback too much.')
if frame_idx - ptr > 3 then
print(string.format('WARNING: file -- %s, |target_idx - actual_idx| = %d', v_filename, frame_idx - ptr))
end
ptr = ptr - 1
v_filename = paths.concat(self.img_dir, 'v', concise_video_name, string.format('frame%.6d.jpg', ptr))
end
local v = image.load(v_filename, 1, 'float')
if ii == 1 then
if spec_im_size ~= nil then
im_s = spec_im_size
else
local im_size = u[1]:size()
local im_size_min = math.min(im_size[1],im_size[2])
local im_size_max = math.max(im_size[1],im_size[2])
im_scale = self.scale/im_size_min
im_scale = {im_scale, im_scale}
im_s = {math.ceil(im_size[1]*im_scale[1]), math.ceil(im_size[2]*im_scale[1])}
for dim = 1,2 do
if im_s[dim] > self.max_size then
local rat = im_s[dim] / self.max_size
im_s = {math.ceil(im_s[1] / rat), math.ceil(im_s[2] / rat)}
im_scale = {im_scale[1] / rat, im_scale[2] / rat}
end
end
end
im_s = {math.floor(im_s[1]), math.floor(im_s[2])}
flows = torch.FloatTensor(num_images, 2, im_s[1], im_s[2]):zero()
end
if flip then
u = image.hflip(u)
u = 1 - u
v = image.hflip(v)
end
local flow = torch.cat({u, v}, 1)
flow = self:scale_flow(flow, im_s[1], im_s[2])
if transform then
flow = self.image_transformer:forward(flow)
end
flows[ii]:copy(flow)
end
im_s = torch.FloatTensor(im_s)
return flows, im_s
end
function BatchProviderVID:scale_flow(flow, hgt, wid)
-- flow: [2, H, W], first x (horizontal) then y
local H, W = flow:size(2), flow:size(3)
local u = image.scale(flow[1], wid, hgt)
local v = image.scale(flow[2], wid, hgt)
--u:mul(wid/W)
--v:mul(hgt/H)
local scaled_flow = torch.cat({u:view(1, hgt, wid), v:view(1, hgt, wid)}, 1)
return scaled_flow
end
function BatchProviderVID:getImages(video_name, frame_seq, flip, transform, spec_im_size)
-- Load one video chunk
local imgs = {}
-- transform flag
if transform == nil then
transform = true
else
transform = transform == 1
end
-- sample some jittering parameters
local num_images = frame_seq:nElement()
local aspect_jitter = 1 + (torch.uniform(-1.0,1.0))*self.aspect_jitter
local scale_jitter = 1 + (torch.uniform(-1.0,0.0))*self.scale_jitter
--local aspect_jitter = 1 + (torch.uniform(-1.5,0.5))*self.aspect_jitter
--local scale_jitter = 1 + (torch.uniform(-1.5,0.5))*self.scale_jitter
flip = flip == 1
local im_s, im_scale, expand_shape
if self.color_jitter then
self.color_jitter:SampleColorParams()
end
-- load images from disk
local im_set = {}
for ii, frame_idx in ipairs(frame_seq:totable()) do
local img_filename = self.anno[video_name].im_list[frame_idx]
img_filename = paths.concat(self.img_dir, video_name, img_filename)
local im = image.load(img_filename, 3, 'double')
im_set[ii] = im
end
for ii, frame_idx in ipairs(frame_seq:totable()) do
local im = im_set[ii]
-- perform photometric transformation
if self.color_jitter then
im = self.color_jitter:forward(im)
end
if transform then
im = self.image_transformer:forward(im)
end
if flip then im = image.hflip(im) end
if ii == 1 then
if spec_im_size ~= nil then
im_s = spec_im_size
else
local im_size = im[1]:size()
local im_size_min = math.min(im_size[1],im_size[2])
local im_size_max = math.max(im_size[1],im_size[2])
im_scale = self.scale/im_size_min
im_scale = im_scale * scale_jitter
im_scale = {im_scale * math.sqrt(aspect_jitter), im_scale / math.sqrt(aspect_jitter)}
im_s = {math.ceil(im_size[1]*im_scale[1]), math.ceil(im_size[2]*im_scale[2])}
for dim = 1,2 do
if im_s[dim] > self.max_size then
local rat = im_s[dim] / self.max_size
im_s = {math.ceil(im_s[1] / rat), math.ceil(im_s[2] / rat)}
im_scale = {im_scale[1] / rat, im_scale[2] / rat}
end
end
end
im_s = {math.floor(im_s[1]), math.floor(im_s[2])}
expand_shape = torch.LongStorage({1, 3, im_s[1], im_s[2]})
end
table.insert(imgs, image.scale(im,im_s[2],im_s[1]):view(expand_shape))
end
imgs = torch.cat(imgs, 1)
im_s = torch.FloatTensor(im_s)
return imgs, im_s
end
function BatchProviderVID:sampleAroundGTBoxes(boxes, n_per_box, sigma)
local samples = torch.repeatTensor(boxes, n_per_box, 1)
return samples:add(torch.FloatTensor(#samples):normal(0,sigma))
end
function BatchProviderVID:organize_boxes(gtboxes, rois, gtlabels, obj_n)
if self.sample_n_per_box > 0 and gtboxes:numel() > 0 then
local sampled = self:sampleAroundGTBoxes(gtboxes:narrow(2, 1, 4), self.sample_n_per_box, self.sample_sigma)
rois = rois:cat(sampled, 1)
end
-- compute IOU
local overlap = torch.FloatTensor(gtboxes:size(1), rois:size(1))
for ii = 1, gtboxes:size(1) do
local gtbox = gtboxes[ii]
local o = utils.boxoverlap_01(rois, gtbox)
overlap[ii] = o
end
local max_overlap, max_idx = torch.max(overlap, 1)
max_overlap = max_overlap:view(-1)
max_idx = max_idx:view(-1)
local labels = gtlabels:index(1, max_idx)
-- pick the foreground and background boxes
local fg = max_overlap:ge(self.fg_threshold):nonzero()
local fg_boxes, fg_labels, fg_max_idx = nil, nil, nil
if fg:nElement() > 0 then
fg = fg:view(-1)
local fg_num = fg:nElement()
fg = fg:index(1, torch.randperm(fg_num)[{{1, math.min(fg_num, self.fg_num_each)}}]:long())
fg_boxes = rois:index(1, fg)
fg_labels = labels:index(1, fg)
fg_max_idx = max_idx:index(1, fg)
end
local bg = max_overlap:ge(self.bg_threshold[1]):cmul(max_overlap:lt(
self.bg_threshold[2])):nonzero()
local bg_boxes, bg_labels, bg_max_idx = nil, nil, nil
if bg:nElement() > 0 then
bg = bg:view(-1)
local bg_num = bg:nElement()
bg = bg:index(1, torch.randperm(bg_num)[{{1, math.min(bg_num, self.bg_num_each)}}]:long())
bg_boxes = rois:index(1, bg)
bg_labels = torch.IntTensor(bg:nElement()):fill(1)
bg_max_idx = max_idx.new(bg:nElement()):zero()
end
local boxes, labels, correspondance = nil, nil, nil
local obj_id = gtboxes[{{}, 5}]:clone()
local obj_box = torch.FloatTensor(obj_n, 4):fill(-1)
for idx = 1, gtboxes:size(1) do
local cur_obj_id = obj_id[idx]
obj_box[{cur_obj_id, {}}]:copy(gtboxes[{idx, {1, 4}}])
end
gtboxes = gtboxes[{{}, {1, 4}}]
if bg:nElement() > 0 and fg:nElement() > 0 then
boxes = torch.cat({fg_boxes, bg_boxes}, 1)
labels = torch.cat({fg_labels, bg_labels}, 1)
correspondance = torch.cat({fg_max_idx, bg_max_idx}, 1)
else
if bg:nElement() > 0 then
boxes = bg_boxes
labels = bg_labels
correspondance = bg_max_idx
elseif fg:nElement() > 0 then
boxes = fg_boxes
labels = fg_labels
correspondance = fg_max_idx
else
boxes = torch.FloatTensor(0, 4)
labels = torch.IntTensor(0)
correspondance = torch.LongTensor(0)
end
end
-- add the ground truth box
if boxes:nElement() > 0 then
boxes = torch.cat({gtboxes, boxes}, 1)
labels = torch.cat({gtlabels, labels}, 1)
correspondance = torch.cat({torch.range(1, gtlabels:nElement()):type(
correspondance:type()), correspondance}, 1)
else
boxes = gtboxes
labels = gtlabels
correspondance = torch.range(1, gtlabels:nElement()):type(correspondance:type())
end
boxes = boxes:contiguous()
return {boxes = boxes, labels = labels, correspondance = correspondance,
obj_id = obj_id, obj_box = obj_box}
end
function BatchProviderVID:gen_rois(box_coll, im_size_coll)
local img_counter = 1
local rois, labels, gtboxes = {}, {}, {}
for vid_idx, vid in ipairs(box_coll) do
local im_size = im_size_coll[vid_idx]
for fr_idx, fr in ipairs(vid) do
local fr_labels = fr.labels
local fr_correspondance = fr.correspondance
local fr_boxes = fr.boxes
local fr_obj_id = fr.obj_id
fr_boxes[{{}, 1}]:mul(im_size[2])
fr_boxes[{{}, 3}]:mul(im_size[2])
fr_boxes[{{}, 2}]:mul(im_size[1])
fr_boxes[{{}, 4}]:mul(im_size[1])
fr_boxes = utils.calibrate_box(torch.round(fr_boxes), im_size[1], im_size[2])
local fr_gtboxes = fr_boxes:clone():zero()
local fg_idx = fr_labels:ge(2):nonzero():view(-1) -- all labels > 1 (>= 2)
local fg_correspondance = fr_correspondance:index(1, fg_idx)
--fr_gtboxes:index(1, fg_idx):copy(fr_boxes:index(1, fg_correspondance))
fr_gtboxes:indexCopy(1, fg_idx, fr_boxes:index(1, fg_correspondance))
fr_boxes = torch.cat({fr_boxes.new(fr_boxes:size(1), 1):fill(img_counter), fr_boxes}, 2)
-- this is not the last frame
if fr_idx ~= #vid then
-- Below are two ways of computing the motion prediction target:
-- 1) Making use of all data, from any box --> gtbox at next frame
-- 2) Only do prediction from gtbox at current frame --> gtbox at next frame
--local obj_idx = fr_obj_id:index(1, fg_correspondance):long()
--local tmp_idx = fg_idx
local obj_idx = fr_obj_id:long()
local tmp_idx = torch.range(1, obj_idx:nElement()):long()
local nxt_fr = vid[fr_idx+1]
local nxt_fr_obj_box = nxt_fr.obj_box
local cand_nxt_fr_gtboxes = nxt_fr_obj_box:index(1, obj_idx)
local valid = cand_nxt_fr_gtboxes[{{}, 1}]:ge(0):nonzero():view(-1)
cand_nxt_fr_gtboxes = cand_nxt_fr_gtboxes:index(1, valid)
tmp_idx = tmp_idx:index(1, valid)
end
table.insert(rois, fr_boxes)
table.insert(gtboxes, fr_gtboxes)
table.insert(labels, fr_labels)
img_counter = img_counter + 1
end
end
-- flatten
rois = torch.cat(rois, 1)
gtboxes = torch.cat(gtboxes, 1)
labels = torch.cat(labels, 1)
-- compute regression target
local bboxregr_vals = torch.FloatTensor(rois:size(1), 4*(self.class_num + 1)):zero()
for i,label in ipairs(labels:totable()) do
if label > 1 then
local out = bboxregr_vals[i]:narrow(1,(label-1)*4 + 1,4)
utils.convertTo(out, rois[i]:narrow(1,2,4), gtboxes[i])
out:add(-1,self.bbox_regr.mean):cdiv(self.bbox_regr.std)
end
end
return rois, labels, bboxregr_vals
end
function BatchProviderVID:squeeze_im_to_tensor(images, im_size)
-- create single tensor with all images, padding with zero for different sizes
im_size = torch.cat(im_size, 2)
local channel = images[1]:size(2)
local max_shape = im_size:max(2):view(-1)
local im_tensor = torch.FloatTensor(self.batch_N,self.batch_T,channel,max_shape[1],max_shape[2]):zero()
for i,v in ipairs(images) do
im_tensor[{i, {}, {}, {1,v:size(3)}, {1,v:size(4)}}]:copy(v)
end
im_tensor = im_tensor:view(self.batch_N*self.batch_T,channel,max_shape[1],max_shape[2])
return im_tensor
end
function BatchProviderVID:crop_squeeze_im_to_tensor(images, boxes, im_size)
-- compute aspect ratios
local ar = {}
for idx, siz in ipairs(im_size) do
ar[idx] = siz[1] / siz[2]
end
-- create single tensor with all images, padding with zero for different sizes
im_size = torch.cat(im_size, 2)
local max_shape = im_size:max(2):view(-1)
local im_tensor = torch.FloatTensor(self.batch_N,self.batch_T,3,max_shape[1],max_shape[2]):zero()
for i,v in ipairs(images) do
im_tensor[{i, {}, {}, {1,v:size(3)}, {1,v:size(4)}}]:copy(v)
end
im_tensor = im_tensor:view(self.batch_N*self.batch_T,3,max_shape[1],max_shape[2])
return im_tensor
end
--------------------------------------------
function BatchProviderVID:light_sample_target(video_name, frame_idx_seq, flat_flag)
-- perform light sample with certain target, without touching ground-truth
collectgarbage()
-- loop over videos
local prop = self:load_prop(video_name)
local box_coll = {}
for _, frame_idx in ipairs(frame_idx_seq:totable()) do
-- get proposals
local rois, roi_scores = self:slice_prop(prop, frame_idx)
table.insert(box_coll, {rois=rois, roi_scores=roi_scores})
end
-- get image
local images, im_sizes = self:getImages(video_name, frame_idx_seq, 0, 0)
-- scale the boxes into absolute coordinate system
local rois = {}
local hgt = im_sizes[1]
local wid = im_sizes[2]
local scaler = torch.FloatTensor({wid, hgt, wid, hgt}):view(1, 4)
for frm_idx, frm in ipairs(box_coll) do
local roi_scores = frm.roi_scores
rois[frm_idx] = utils.calibrate_box(torch.cmul(
frm.rois, scaler:expandAs(frm.rois)):round(), hgt, wid)
if self.test_batch_size then
local sortval, sortidx = torch.sort(roi_scores, 1, true)
sortidx = sortidx[{{1, math.min(self.test_batch_size, roi_scores:nElement())}}]
rois[frm_idx] = rois[frm_idx]:index(1, sortidx)
end
end
return images, rois
end
--------------------------------------------
function BatchProviderVID:light_sample(flat_flag, spec_video_name, spec_start_frm)
collectgarbage()
local collected_N = 0
local box_coll, image_coll, im_size_coll = {}, {}, {}
local record = {vid={}, frm={}}
-- loop over videos
while collected_N < self.batch_N do
local video_name
if not spec_video_name then
local video_idx = self:get_next_video_idx()
video_name = self.video_names[video_idx]
else
video_name = spec_video_name
end
local obj = self.anno[video_name].obj
local prop = self:load_prop(video_name)
local T = #self.anno[video_name].im_list
local indicator = torch.ByteTensor(T, #obj):zero()
local frlen, start_idx, end_idx = {}, {}, {}
local vid_box_coll = {}
local gtlabels = {}
-- figure out how many frames are there for each object
for oi, cur_obj in ipairs(obj) do
indicator[{{cur_obj.start_frame, cur_obj.end_frame}, oi}]:fill(1)
frlen[oi] = cur_obj.end_frame - cur_obj.start_frame + 1
start_idx[oi] = cur_obj.start_frame
end_idx[oi] = cur_obj.end_frame
gtlabels[oi] = self.cat_name_to_id[cur_obj.category]
assert(gtlabels[oi] ~= nil)
end
frlen = torch.IntTensor(frlen)
gtlabels = torch.IntTensor(gtlabels)
local min_len = (self.batch_T - 1) * self.frame_stride + 1
local valid_oi = torch.nonzero(frlen:ge(min_len))
if valid_oi:nElement() > 0 then
valid_oi = valid_oi:view(-1)
collected_N = collected_N + 1
record.vid[collected_N] = video_name
record.frm[video_name] = {}
local oi = valid_oi[{torch.random(valid_oi:nElement())}]
local oi_start_idx = start_idx[oi]
local oi_end_idx = end_idx[oi]
local fi_start
if not self.non_redundant_sampling then
fi_start = torch.random(oi_start_idx, oi_end_idx - min_len + 1)
else
local hit = self.sampling_hist[video_name][{{oi_start_idx, oi_end_idx - min_len + 1}}]
local randperb = torch.randperm(hit:nElement()):type('torch.LongTensor')
local randperb_hit = hit:index(1, randperb)
local _, min_idx = torch.min(randperb_hit, 1)
min_idx = randperb[min_idx[1]]
hit[min_idx] = hit[min_idx] + 1
fi_start = oi_start_idx + min_idx - 1
end
if spec_start_frm then
fi_start = spec_start_frm
end
local fi_end = fi_start + min_len - 1
for _, frame_idx in ipairs(torch.range(fi_start, fi_end, self.frame_stride):totable()) do
table.insert(record.frm[video_name], frame_idx)
local frame_valid_oi = torch.nonzero(indicator[frame_idx]):view(-1)
-- get ground truth boxes
local gtboxes = torch.FloatTensor(frame_valid_oi:nElement(), 4):zero()
for ii, oii in ipairs(frame_valid_oi:totable()) do
--local tmp_idx = torch.nonzero(obj[oii].boxes[{{}, 2}]:eq(frame_idx)):view(-1)
local tmp_idx = frame_idx - obj[oii].start_frame + 1
gtboxes[ii] = obj[oii].boxes[{tmp_idx, {3, 6}}]
end
-- get proposals
local rois, roi_scores = self:slice_prop(prop, frame_idx)
-- select top K
if self.test_batch_size then
local sortval, sortidx = torch.sort(roi_scores, 1, true)
sortidx = sortidx[{{1, math.min(self.test_batch_size, sortidx:nElement())}}]
rois = rois:index(1, sortidx)
end
-- match rois and gtboxes
table.insert(vid_box_coll, {rois=rois, roi_scores=roi_scores, gtboxes=gtboxes})
end
table.insert(box_coll, vid_box_coll)
-- get image
local frame_seq = torch.range(fi_start, fi_end, self.frame_stride)
local images, im_sizes
images, im_sizes = self:getImages(video_name, frame_seq, 0, 0)
table.insert(image_coll, images)
table.insert(im_size_coll, im_sizes)
record.frm[video_name] = torch.IntTensor(record.frm[video_name])
end
end
-- scale the boxes into absolute coordinate system
local rois = {}
for vid_idx, vid in ipairs(box_coll) do
local hgt = im_size_coll[vid_idx][1]
local wid = im_size_coll[vid_idx][2]
local scaler = torch.FloatTensor({wid, hgt, wid, hgt}):view(1, 4)
local vid_rois = {}
for frm_idx, frm in ipairs(vid) do
table.insert(vid_rois, utils.calibrate_box(torch.cmul(
frm.rois, scaler:expandAs(frm.rois)):round(), hgt, wid))
end
table.insert(rois, vid_rois)
end
if flat_flag then
image_coll = self:squeeze_im_to_tensor(image_coll, im_size_coll)
local new_rois = {}
for vid_idx, vid in ipairs(rois) do
for frm_idx, frm in ipairs(vid) do
table.insert(new_rois, frm)
end
end
rois = new_rois
end
-- pack im_size_coll into record
record.im_size = im_size_coll
return image_coll, rois, record
end
function BatchProviderVID:slice_prop(prop, frame_idx)
local rois, roi_scores
if torch.isTensor(prop.boxes) then
rois = prop.boxes[{frame_idx, {}, {}}]
roi_scores = prop.scores[{{}, frame_idx}]
elseif torch.type(prop.boxes) == 'table' then
rois = prop.boxes[frame_idx]
roi_scores = prop.scores[frame_idx]
else
assert(false, 'Unknown proposal format.')
end
return rois, roi_scores
end
function BatchProviderVID:sample()
collectgarbage()
self.fg_num_each = self.fg_fraction * self.batch_size
self.bg_num_each = self.batch_size - self.fg_num_each
local collected_N = 0
local box_coll, image_coll, im_size_coll = {}, {}, {}
local do_flip = torch.FloatTensor(self.batch_N):random(0,1)
local batch_large_hw_ratio
-- loop over videos
while collected_N < self.batch_N do
local video_idx = self:get_next_video_idx()
local video_name = self.video_names[video_idx]
local obj = self.anno[video_name].obj
local prop = self:load_prop(video_name)
local T = #self.anno[video_name].im_list
local indicator = torch.ByteTensor(T, #obj):zero()
local frlen, start_idx, end_idx = {}, {}, {}
local vid_box_coll = {}
local gtlabels = {}
-- figure out how many frames are there for each object
for oi, cur_obj in ipairs(obj) do
indicator[{{cur_obj.start_frame, cur_obj.end_frame}, oi}]:fill(1)
frlen[oi] = cur_obj.end_frame - cur_obj.start_frame + 1
start_idx[oi] = cur_obj.start_frame
end_idx[oi] = cur_obj.end_frame
gtlabels[oi] = self.cat_name_to_id[cur_obj.category]
assert(gtlabels[oi] ~= nil)
end
frlen = torch.IntTensor(frlen)
gtlabels = torch.IntTensor(gtlabels)
local min_len = (self.batch_T - 1) * self.frame_stride + 1
local valid_oi = torch.nonzero(frlen:ge(min_len))
-- figure out the aspect ratio
local large_hw_ratio
if self.anno[video_name].im_size and self.anno[video_name].im_size:nElement() > 0 then
local hgt = self.anno[video_name].im_size[1][1]
local wid = self.anno[video_name].im_size[1][2]
large_hw_ratio = (hgt/wid) > 1
else
local img_filename = self.anno[video_name].im_list[1]
img_filename = paths.concat(self.img_dir, video_name, img_filename)
local im = image.load(img_filename, 3, 'double')
large_hw_ratio = (im:size(2) / im:size(3)) > 1
end
if collected_N == 0 then
batch_large_hw_ratio = large_hw_ratio
end
if valid_oi:nElement() > 0 and batch_large_hw_ratio == large_hw_ratio then
valid_oi = valid_oi:view(-1)
collected_N = collected_N + 1
local flip = do_flip[collected_N] == 1
--local oi = valid_oi[{torch.random(valid_oi:nElement())}]
local _, oi = torch.min(self.cat_counter:index(1, gtlabels:index(1, valid_oi):long()), 1)
oi = valid_oi[oi[1]]
local oi_start_idx = start_idx[oi]
local oi_end_idx = end_idx[oi]
local fi_start
if not self.non_redundant_sampling then
fi_start = torch.random(oi_start_idx, oi_end_idx - min_len + 1)
else
local hit = self.sampling_hist[video_name][{{oi_start_idx, oi_end_idx - min_len + 1}}]
local randperb = torch.randperm(hit:nElement()):type('torch.LongTensor')
local randperb_hit = hit:index(1, randperb)
local _, min_idx = torch.min(randperb_hit, 1)
min_idx = randperb[min_idx[1]]
hit[min_idx] = hit[min_idx] + 1
fi_start = oi_start_idx + min_idx - 1
end
local fi_end = fi_start + min_len - 1
for _, frame_idx in ipairs(torch.range(fi_start, fi_end, self.frame_stride):totable()) do
local frame_valid_oi = torch.nonzero(indicator[frame_idx]):view(-1)
-- get ground truth boxes
local gtboxes = torch.FloatTensor(frame_valid_oi:nElement(), 5):zero()
for ii, oii in ipairs(frame_valid_oi:totable()) do
--local tmp_idx = torch.nonzero(obj[oii].boxes[{{}, 2}]:eq(frame_idx)):view(-1)
local tmp_idx = frame_idx - obj[oii].start_frame + 1
gtboxes[{ii, {1, 4}}]:copy(obj[oii].boxes[{tmp_idx, {3, 6}}])
gtboxes[{ii, 5}] = oii
end
-- get proposals
local rois, roi_scores = self:slice_prop(prop, frame_idx)
if flip then
rois = utils.flipBoxes_01(rois)
gtboxes = utils.flipBoxes_01(gtboxes)
end
-- match rois and gtboxes
table.insert(vid_box_coll, self:organize_boxes(gtboxes, rois,
gtlabels:index(1, frame_valid_oi), #obj))
end
table.insert(box_coll, vid_box_coll)
-- get image
local frame_seq = torch.range(fi_start, fi_end, self.frame_stride)
local images, im_sizes
images, im_sizes = self:getImages(video_name, frame_seq, do_flip[collected_N], 1, self.spec_im_size)
table.insert(image_coll, images)
table.insert(im_size_coll, im_sizes)
end
end
-- put all images into a giant tensor
local images = self:squeeze_im_to_tensor(image_coll, im_size_coll)
-- get rois and regression target
local rois, labels, bboxregr_vals = self:gen_rois(box_coll, im_size_coll)
---- DIAGONOZE DISPLAY
if DEBUG then
local qtwidget = require 'qtwidget'
local win = qtwidget.newwindow(images:size(4), images:size(3))
for debug_idx = 1, rois:size(1) do
local debug_label = labels[debug_idx]
if debug_label > 1 then
local debug_img_idx = rois[debug_idx][1]
local out = bboxregr_vals[debug_idx]:narrow(1,(debug_label-1)*4 + 1,4)
out:cmul(self.bbox_regr.std):add(1,self.bbox_regr.mean)
local raw_box = rois[{debug_idx, {2, 5}}]
utils.convertFrom(out, raw_box, out)
local x1 = out[1]
local y1 = out[2]
local x2 = out[3]
local y2 = out[4]
image.display({image = images[{debug_img_idx, {}, {}, {}}], win = win})
win:fill()
win:rectangle(x1, y1, x2-x1+1, y2-y1+1)
win:stroke()
print(string.format('cat:%s', self.cat_id_to_name[debug_label]))
print('-----')
end
end
end
if self.seq_center then
assert(self.batch_T % 2 == 1, 'You need to have odd number of frames to do seq_center mode.')
local center_frm_idx = (self.batch_T - 1) / 2 + 1
local center_idx = rois[{{}, 1}]:eq(center_frm_idx):nonzero():view(-1)
rois = rois:index(1, center_idx)
labels = labels:index(1, center_idx)
bboxregr_vals = bboxregr_vals:index(1, center_idx)
end
if self.parallel_roi_batch > 1 then
local roi_n = rois:size(1)
local img_n = images:size(1)
rois = torch.cat({rois, torch.range(1, roi_n):float():view(roi_n, 1)}, 2)
local batch_n = img_n / self.parallel_roi_batch
local roi_img_idx = rois[{{}, 1}]
local roi_by_img = {}
local roi_count_by_img = {}
for idx = 1, img_n do
local val_roi_idx = roi_img_idx:eq(idx):nonzero()
assert(val_roi_idx:nElement() > 0, 'It cant be true that there is no roi at all for an image.')
val_roi_idx = val_roi_idx:view(-1)
roi_by_img[idx] = rois:index(1, val_roi_idx)
roi_count_by_img[idx] = roi_by_img[idx]:size(1)
end
roi_count_by_img = torch.FloatTensor(roi_count_by_img)
local max_rois = torch.max(roi_count_by_img)
for idx = 1, img_n do
local mod_idx = (idx - 1) % batch_n + 1
roi_by_img[idx][{{}, 1}]:fill(mod_idx)
if roi_count_by_img[idx] < max_rois then
local fill_n = max_rois - roi_count_by_img[idx]
local candTensor
if fill_n > roi_by_img[idx]:size(1) then
local K = math.ceil(fill_n / roi_by_img[idx]:size(1))
candTensor = torch.repeatTensor(roi_by_img[idx], K, 1)
else
candTensor = roi_by_img[idx]
end
roi_by_img[idx] = torch.cat({candTensor[{{1, fill_n}, {}}], roi_by_img[idx]}, 1)
end
end
rois = torch.cat(roi_by_img, 1)
local sel_idx = rois[{{}, 6}]:long()
rois = rois[{{}, {1,5}}]
labels = labels:index(1, sel_idx)
bboxregr_vals = bboxregr_vals:index(1, sel_idx)
end
local batches = {images, rois}
local targets = {labels, {labels, bboxregr_vals}, g_donkey_idx}
-- stats
local counts = torch.histc(labels:float(), self.class_num+1, 1, self.class_num+1)
self.cat_counter = self.cat_counter + counts
return batches, targets
end
function BatchProviderVID:mine_hard_neg(scan_score, gt_class, opt)
self.logsoftmax = self.logsoftmax or nn.LogSoftMax():cuda()
local backprop_fg_num = math.floor(opt.backprop_batch_size * opt.fg_fraction)
local backprop_bg_num = opt.backprop_batch_size - backprop_fg_num
local prob = self.logsoftmax:forward(scan_score)
local flat_idx = gt_class + torch.range(0, opt.num_classes * (prob:size(1) - 1), opt.num_classes):cuda()
local gt_prob = prob:view(-1):index(1, flat_idx:long())
local pos_idx = gt_class:gt(1):nonzero()
if pos_idx:nElement() > 0 then
pos_idx = pos_idx:view(-1)
local pos_n = pos_idx:nElement()
local sel_idx = torch.randperm(pos_n):narrow(1, 1, math.min(backprop_fg_num, pos_n))
pos_idx = pos_idx:index(1, sel_idx:long())
end
local neg_idx = gt_class:eq(1):nonzero()
if neg_idx:nElement() > 0 then
neg_idx = neg_idx:view(-1)
local y, i = torch.sort(gt_prob:index(1, neg_idx), 1)
i = i:narrow(1, 1, math.min(backprop_bg_num, neg_idx:nElement()))
neg_idx = neg_idx:index(1, i)
end
local final_idx
if pos_idx:nElement() > 0 and neg_idx:nElement() > 0 then
final_idx = torch.cat({pos_idx, neg_idx}, 1):long()
elseif pos_idx:nElement() > 0 then
final_idx = pos_idx:long()
elseif neg_idx:nElement() > 0 then
final_idx = neg_idx:long()
else
assert(false, 'Unexpected.')
end
return final_idx
end
function BatchProviderVID:mine_hard_neg_v2(scan_box, scan_score, gt_class, opt)
self.logsoftmax = self.logsoftmax or nn.LogSoftMax():cuda()
local N = scan_score:size(1)
local prob = self.logsoftmax:forward(scan_score)
local flat_idx = gt_class + torch.range(0, opt.num_classes * (N - 1), opt.num_classes):cuda()
local gt_prob = prob:view(-1):index(1, flat_idx:long())
local sortval, sortidx = torch.sort(gt_prob, 1)
local box = torch.FloatTensor(N, 5)
box:narrow(2, 1, 4):copy(scan_box:index(1, sortidx))
box:select(2, 5):copy(-sortval)
local final_idx = utils.nms_dense(box, opt.ohem_nms_thresh)
final_idx = sortidx:index(1, final_idx)
final_idx = final_idx:narrow(1, 1, math.min(opt.backprop_batch_size, final_idx:nElement()))
return final_idx
end
|
object_intangible_vehicle_mustafar_panning_droid_pcd = object_intangible_vehicle_shared_mustafar_panning_droid_pcd:new {
}
ObjectTemplates:addTemplate(object_intangible_vehicle_mustafar_panning_droid_pcd, "object/intangible/vehicle/mustafar_panning_droid_pcd_.iff")
|
return {
canonShootingFrequency = 2, -- shoots per second
canonBulletsVelocity = 20, -- meters per second
spaceShipForwardVelocity = 10, -- meters per second
asteroidsAngularVelocityRange = {-math.pi, math.pi}, -- radians per second
explosionDuration = 0.1, -- seconds
manoeuveringEnginesThrust = 100000, -- newtons
spaceShipMass = 5000, -- kilograms
initialAsteroidAppearanceFrequency = 1, -- number per seconds
asteroidAppearanceFrequencyIncrease = 0.01 -- number per seconds
}
|
function curry(func, ...)
local args = {...}
local cArgs = #args
return function(...)
local m = select('#', ...)
for i = 1, m do
args[cArgs + i] = select(i, ...)
end
return func(unpack(args, 1, cArgs + m))
end
end
|
require "scripts.core.ability"
require "gamemode.Spark.modifiers.modifier_piercing_light"
PiercingLight = class(Ability)
function PiercingLight:OnCreated ()
self:SetCastingBehavior(CastingBehavior(CastingBehavior.PASSIVE));
end
function PiercingLight:GetModifiers ()
return {
"modifier_piercing_light"
}
end
return PiercingLight
|
-- rocket_flare
return {
["rocket_flare"] = {
usedefaultexplosions = false,
largeflash = {
air = true,
class = [[CBitmapMuzzleFlame]],
count = 1,
ground = true,
underwater = 1,
water = true,
properties = {
colormap = [[1.0 0.5 0.2 0.01 0.7 0.2 0.1 0.1 0.5 0.2 0.1 0.01]],
dir = [[dir]],
frontoffset = 0,
fronttexture = [[muzzlefront]],
length = -25,
sidetexture = [[muzzleside]],
size = -5,
sizegrowth = 0.75,
ttl = 13,
},
},
waterball2 = {
air = false,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
underwater = 1,
water = true,
properties = {
airdrag = 1,
colormap = [[0.1 0.1 0.1 1 0.1 0.1 0.1 0.8 0.1 0.1 0.1 0.8 0 0 0 0.01]],
directional = true,
emitdir = [[0, 0.5, 0]],
emitrot = 90,
emitrotspread = 0,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 260,
particlelife = 4,
particlelifespread = 70,
particlesize = [[8 r12]],
particlesizespread = 0,
particlespeed = [[12.7 r1]],
particlespeedspread = 0,
pos = [[0 r-10 r10, 5 r20, 0 r-10 r10]],
sizegrowth = [[0.50 r-1.6]],
sizemod = 1.0,
texture = [[clouds2]],
useairlos = true,
},
},
smoke2 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.8,
colormap = [[1 1 1 1.0 0 0 0 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 10,
emitvector = [[dir]],
gravity = [[0, 0.09,0]],
numparticles = 20,
particlelife = 30,
particlelifespread = 10,
particlesize = 2,
particlesizespread = 3,
particlespeed = 1,
particlespeedspread = 12,
pos = [[0, 0, 0]],
sizegrowth = 0.2,
sizemod = 1.0,
texture = [[smoke]],
},
},
},
["cannon_flare"] = {
usedefaultexplosions = false,
largeflash = {
air = true,
class = [[CBitmapMuzzleFlame]],
count = 1,
ground = true,
underwater = 1,
water = true,
properties = {
colormap = [[1.0 0.5 0.2 0.01 0.7 0.2 0.1 0.1 0.5 0.2 0.1 0.01]],
dir = [[dir]],
frontoffset = 0,
fronttexture = [[muzzlefront]],
length = -25,
sidetexture = [[muzzleside]],
size = -5,
sizegrowth = 0.75,
ttl = 13,
},
},
smoke2 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.8,
colormap = [[1 1 1 1.0 0 0 0 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 10,
emitvector = [[dir]],
gravity = [[0, 0.19,0]],
numparticles = 20,
particlelife = 30,
particlelifespread = 0,
particlesize = 2,
particlesizespread = 3,
particlespeed = -1,
particlespeedspread = -12,
pos = [[0, 0, 0]],
sizegrowth = 0.5,
sizemod = 1.0,
texture = [[smoke]],
},
},
},
}
|
--[[ Netherstorm -- Nuramoc.lua
This script was written and is protected
by the GPL v2. This script was released
by BlackHer0 of the BLUA Scripting
Project. Please give proper accredidations
when re-releasing or sharing this script
with others in the emulation community.
~~End of License Agreement
-- BlackHer0, September, 29th, 2008. ]]
function Nuramoc_OnEnterCombat(Unit,Event)
Unit:RegisterEvent("Nuramoc_Lightning",2000,0)
Unit:RegisterEvent("Nuramoc_Bolt",4000,0)
Unit:RegisterEvent("Nuramoc_Shield",5000,0)
end
function Nuramoc_Lightning(Unit,Event)
Unit:FullCastSpellOnTarget(15797,Unit:GetClosestPlayer())
end
function Nuramoc_Bolt(Unit,Event)
Unit:FullCastSpellOnTarget(21971,Unit:GetClosestPlayer())
end
function Nuramoc_Shield(Unit,Event)
Unit:CastSpell(38905)
end
function Nuramoc_OnLeaveCombat(Unit,Event)
Unit:RemoveEvents()
end
function Nuramoc_OnDied(Unit,Event)
Unit:RemoveEvents()
end
RegisterUnitEvent (20932, 1, "Nuramoc_OnEnterCombat")
RegisterUnitEvent (20932, 2, "Nuramoc_OnLeaveCombat")
RegisterUnitEvent (20932, 4, "Nuramoc_OnDied")
|
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
--
-- This file is compatible with Lua 5.3
local class = require("class")
require("kaitaistruct")
local stringstream = require("string_stream")
SwitchRepeatExprInvalid = class.class(KaitaiStruct)
function SwitchRepeatExprInvalid:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function SwitchRepeatExprInvalid:_read()
self.code = self._io:read_u1()
self.size = self._io:read_u4le()
self._raw_body = {}
self.body = {}
for i = 0, 1 - 1 do
local _on = self.code
if _on == 255 then
self._raw_body[i + 1] = self._io:read_bytes(self.size)
local _io = KaitaiStream(stringstream(self._raw_body[i + 1]))
self.body[i + 1] = SwitchRepeatExprInvalid.One(_io, self, self._root)
elseif _on == 34 then
self._raw_body[i + 1] = self._io:read_bytes(self.size)
local _io = KaitaiStream(stringstream(self._raw_body[i + 1]))
self.body[i + 1] = SwitchRepeatExprInvalid.Two(_io, self, self._root)
else
self.body[i + 1] = self._io:read_bytes(self.size)
end
end
end
SwitchRepeatExprInvalid.One = class.class(KaitaiStruct)
function SwitchRepeatExprInvalid.One:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function SwitchRepeatExprInvalid.One:_read()
self.first = self._io:read_bytes_full()
end
SwitchRepeatExprInvalid.Two = class.class(KaitaiStruct)
function SwitchRepeatExprInvalid.Two:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function SwitchRepeatExprInvalid.Two:_read()
self.second = self._io:read_bytes_full()
end
|
local Action = require "action"
local Unequip = Action:extend()
Unequip.name = "unequip"
Unequip.targets = {targets.Unequip}
function Unequip:perform(level)
local equipment = self:getTarget(1)
self.owner.slots[equipment.slot] = false
end
return Unequip
|
-----------------------------------
-- Area: Riverne-Site_B01
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[tpz.zone.RIVERNE_SITE_B01] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here.
CONQUEST_BASE = 7049, -- Tallying conquest results...
SD_VERY_SMALL = 7585, -- The spatial displacement is very small. If you only had some item that could make it bigger...
SD_HAS_GROWN = 7586, -- The spatial displacement has grown.
SPACE_SEEMS_DISTORTED = 7587, -- The space around you seems oddly distorted and disrupted.
MONUMENT = 7593, -- Something has been engraved on this stone, but the message is too difficult to make out.
GROUND_GIVING_HEAT = 7595, -- The ground here is giving off heat.
BAHAMUT_TAUNT = 7663, -- Children of Vana'diel, what do you think to accomplish by fighting for your lives? You know your efforts are futile, yet still you resist...
HOMEPOINT_SET = 7699, -- Home point set!
},
mob =
{
IMDUGUD_PH =
{
[16896101] = 16896107, -- 650.770 20.052 676.513
[16896102] = 16896107, -- 643.308 20.049 652.354
[16896103] = 16896107, -- 669.574 19.215 623.129
[16896104] = 16896107, -- 691.504 21.296 583.884
[16896105] = 16896107, -- 687.199 21.161 582.560
[16896106] = 16896107, -- 666.737 20.012 652.352
},
UNSTABLE_CLUSTER = 16896155,
},
npc =
{
DISPLACEMENT_OFFSET = 16896183,
},
}
return zones[tpz.zone.RIVERNE_SITE_B01]
|
ITEM.name = "Revolver"
ITEM.desc = "A slow yet powerful firearm that fires .44 Magnum Rounds"
ITEM.model = "models/arxweapon/revolver.mdl"
ITEM.class = "m9k_mrp_revolver"
ITEM.weaponCategory = "sidearm"
ITEM.width = 2
ITEM.height = 1
ITEM.price = 300
|
local S = contraptions_mod.S
minetest.register_node("useful_contraptions:vacuum_putter_on", {
description = S("Vacuuming Putter"),
_doc_items_longdesc = S("A vacuuming putter that collects items in its range and puts them into a chest below."),
_doc_items_usagehelp = S("Right-click the vacuuming putter or send a mesecon signal to it, to switch it on or off."),
tiles = {"factory_belt_bottom.png^factory_ring_green.png", "factory_belt_bottom.png", "factory_belt_bottom_clean.png",
"factory_belt_bottom_clean.png", "factory_belt_bottom_clean.png", "factory_belt_bottom_clean.png"},
groups = {cracky=3, not_in_creative_inventory=1, mesecon_effector_off = 1},
drawtype = "nodebox",
paramtype = "light",
is_ground_content = true,
drop="useful_contraptions:vacuum_putter_off",
mesecons = {effector = {
action_off = function(pos, node)
minetest.swap_node(pos, {name = "useful_contraptions:vacuum_putter_off", param2 = node.param2})
end
}},
on_rightclick = function (pos, node)
minetest.swap_node(pos, {name = "useful_contraptions:vacuum_putter_off", param2 = node.param2})
end
})
minetest.register_node("useful_contraptions:vacuum_putter_off", {
description = S("Vacuuming Putter"),
_doc_items_longdesc = S("A vacuuming putter that collects items in its range and puts them into a chest below."),
_doc_items_usagehelp = S("Right-click the vacuuming putter or send a mesecon signal to it, to switch it on or off."),
tiles = {"factory_belt_bottom.png^factory_ring_red.png", "factory_belt_bottom.png", "factory_belt_bottom_clean.png",
"factory_belt_bottom_clean.png", "factory_belt_bottom_clean.png", "factory_belt_bottom_clean.png"},
groups = {cracky=3, mesecon_effector_on = 1},
drawtype = "nodebox",
paramtype = "light",
is_ground_content = true,
mesecons = {effector = {
action_on = function(pos, node)
minetest.swap_node(pos, {name = "useful_contraptions:vacuum_putter_on", param2 = node.param2})
end
}},
on_rightclick = function (pos, node)
minetest.swap_node(pos, {name = "useful_contraptions:vacuum_putter_on", param2 = node.param2})
end
})
minetest.register_abm({
nodenames = {"useful_contraptions:vacuum_putter_on"},
neighbors = nil,
interval = 1,
chance = 1,
action = function(pos)
local all_objects = minetest.get_objects_inside_radius(pos, 0.8)
for _,obj in ipairs(all_objects) do
if not obj:is_player() and obj:get_luaentity() and (obj:get_luaentity().name == "__builtin:item") then
local b = {x = pos.x, y = pos.y - 1, z = pos.z,}
local target = minetest.get_node(b)
local stack = ItemStack(obj:get_luaentity().itemstring)
if table.indexof(contraptions_mod.putter_targets, target.name) ~= -1 then
local meta = minetest.env:get_meta(b)
local inv = meta:get_inventory()
if inv:room_for_item("main", stack) then
inv:add_item("main", stack)
obj:remove()
end
end
end
end
all_objects = contraptions_mod.get_objects_with_square_radius({x = pos.x, y = pos.y + 3, z = pos.z}, 2)
for _,obj in ipairs(all_objects) do
if not obj:is_player() and obj:get_luaentity() and
(obj:get_luaentity().name == "__builtin:item" or obj:get_luaentity().name == "useful_contraptions:moving_item") then
obj:moveto({x = pos.x, y = pos.y + 0.5, z = pos.z})
end
end
end,
})
|
local Suite=CreateTestSuite("wow.api.Buffs");
function Suite:TestBuff()
Assert.Succeed(UnitBuff, "Unit buff must succeed");
end;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.