repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
AdamGagorik/darkstar | scripts/zones/Metalworks/npcs/Lexun-Marixun_WW.lua | 13 | 5592 | -----------------------------------
-- Area: Metalworks
-- NPC: Lexun-Maxirun, W.W.
-- @pos 28 -16 28 237
-- X Grant Signet
-- X Recharge Emperor Band, Empress Band, or Chariot Band
-- X Accepts traded Crystals to fill up the Rank bar to open new Missions.
-- X Sells items in exchange for Conquest Points
-- X Start Supply Run Missions and offers a list of already-delivered supplies.
-- Start an Expeditionary Force by giving an E.F. region insignia to you.
-------------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/globals/common");
require("scripts/zones/Metalworks/TextIDs");
local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, JEUNO
local guardtype = 2; -- 1: city, 2: foreign, 3: outpost, 4: border
local size = table.getn(WindInv);
local inventory = WindInv;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then
player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies."
local region = player:getVar("supplyQuest_region");
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region));
player:setVar("supplyQuest_started",0);
player:setVar("supplyQuest_region",0);
player:setVar("supplyQuest_fresh",0);
else
local Menu1 = getArg1(guardnation,player);
local Menu2 = getExForceAvailable(guardnation,player);
local Menu3 = conquestRanking();
local Menu4 = getSupplyAvailable(guardnation,player);
local Menu5 = player:getNationTeleport(guardnation);
local Menu6 = getArg6(player);
local Menu7 = player:getCP();
local Menu8 = getRewardExForce(guardnation,player);
player:startEvent(0x7ff7,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdateCSID: %u",csid);
-- printf("onUpdateOPTION: %u",option);
if (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
CPVerify = 1;
if (player:getCP() >= inventory[Item + 1]) then
CPVerify = 0;
end
player:updateEvent(2,CPVerify,inventory[Item + 2]);
break
end
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
if (player:getFreeSlotsCount() >= 1) then
-- Logic to impose limits on exp bands
if (option >= 32933 and option <= 32935) then
if (checkConquestRing(player) > 0) then
player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]);
break
else
player:setVar("CONQUEST_RING_TIMER",getConquestTally());
end
end
if (player:getNation() == guardnation) then
itemCP = inventory[Item + 1];
else
if (inventory[Item + 1] <= 8000) then
itemCP = inventory[Item + 1] * 2;
else
itemCP = inventory[Item + 1] + 8000;
end
end
if (player:hasItem(inventory[Item + 2]) == false) then
player:delCP(itemCP);
player:addItem(inventory[Item + 2],1);
player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end
break
end
end
elseif (option >= 65541 and option <= 65565) then -- player chose supply quest.
local region = option - 65541;
player:addKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region));
player:setVar("supplyQuest_started",vanaDay());
player:setVar("supplyQuest_region",region);
player:setVar("supplyQuest_fresh",getConquestTally());
end
end; | gpl-3.0 |
martin-ueding/vicious | widgets/volume.lua | 6 | 1380 | ---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2010, Adrian C. <anrxc@sysphere.org>
---------------------------------------------------
-- {{{ Grab environment
local tonumber = tonumber
local io = { popen = io.popen }
local setmetatable = setmetatable
local string = { match = string.match }
-- }}}
-- Volume: provides volume levels and state of requested ALSA mixers
-- vicious.widgets.volume
local volume = {}
-- {{{ Volume widget type
local function worker(format, warg)
if not warg then return end
local mixer_state = {
["on"] = "♫", -- "",
["off"] = "♩" -- "M"
}
-- Get mixer control contents
local f = io.popen("amixer get " .. warg)
local mixer = f:read("*all")
f:close()
-- Capture mixer control state: [5%] ... ... [on]
local volu, mute = string.match(mixer, "([%d]+)%%.*%[([%l]*)")
-- Handle mixers without data
if volu == nil then
return {0, mixer_state["off"]}
end
-- Handle mixers without mute
if mute == "" and volu == "0"
-- Handle mixers that are muted
or mute == "off" then
mute = mixer_state["off"]
else
mute = mixer_state["on"]
end
return {tonumber(volu), mute}
end
-- }}}
return setmetatable(volume, { __call = function(_, ...) return worker(...) end })
| gpl-2.0 |
sbuettner/kong | spec/integration/dao/cassandra/base_dao_spec.lua | 1 | 24318 | local spec_helper = require "spec.spec_helpers"
local cassandra = require "cassandra"
local constants = require "kong.constants"
local DaoError = require "kong.dao.error"
local utils = require "kong.tools.utils"
local cjson = require "cjson"
local uuid = require "uuid"
-- Raw session for double-check purposes
local session
-- Load everything we need from the spec_helper
local env = spec_helper.get_env() -- test environment
local faker = env.faker
local dao_factory = env.dao_factory
local configuration = env.configuration
configuration.cassandra = configuration.databases_available[configuration.database].properties
-- An utility function to apply tests on core collections.
local function describe_core_collections(tests_cb)
for type, dao in pairs({ api = dao_factory.apis,
consumer = dao_factory.consumers }) do
local collection = type == "plugin_configuration" and "plugins_configurations" or type.."s"
describe(collection, function()
tests_cb(type, collection)
end)
end
end
-- An utility function to test if an object is a DaoError.
-- Naming is due to luassert extensibility's restrictions
local function daoError(state, arguments)
local stub_err = DaoError("", "")
return getmetatable(stub_err) == getmetatable(arguments[1])
end
local say = require("say")
say:set("assertion.daoError.positive", "Expected %s\nto be a DaoError")
say:set("assertion.daoError.negative", "Expected %s\nto not be a DaoError")
assert:register("assertion", "daoError", daoError, "assertion.daoError.positive", "assertion.daoError.negative")
-- Let's go
describe("Cassandra", function()
setup(function()
spec_helper.prepare_db()
-- Create a parallel session to verify the dao's behaviour
session = cassandra:new()
session:set_timeout(configuration.cassandra.timeout)
local _, err = session:connect(configuration.cassandra.hosts, configuration.cassandra.port)
assert.falsy(err)
local _, err = session:set_keyspace("kong_tests")
assert.falsy(err)
end)
teardown(function()
if session then
local _, err = session:close()
assert.falsy(err)
end
end)
describe("Base DAO", function()
describe(":insert()", function()
it("should error if called with invalid parameters", function()
assert.has_error(function()
dao_factory.apis:insert()
end, "Cannot insert a nil element")
assert.has_error(function()
dao_factory.apis:insert("")
end, "Entity to insert must be a table")
end)
it("should insert in DB and let the schema validation add generated values", function()
-- API
local api_t = faker:fake_entity("api")
local api, err = dao_factory.apis:insert(api_t)
assert.falsy(err)
assert.truthy(api.id)
assert.truthy(api.created_at)
local apis, err = session:execute("SELECT * FROM apis")
assert.falsy(err)
assert.True(#apis > 0)
assert.equal(api.id, apis[1].id)
-- API
api, err = dao_factory.apis:insert {
public_dns = "test.com",
target_url = "http://mockbin.com"
}
assert.falsy(err)
assert.truthy(api.name)
assert.equal("test.com", api.name)
-- Consumer
local consumer_t = faker:fake_entity("consumer")
local consumer, err = dao_factory.consumers:insert(consumer_t)
assert.falsy(err)
assert.truthy(consumer.id)
assert.truthy(consumer.created_at)
local consumers, err = session:execute("SELECT * FROM consumers")
assert.falsy(err)
assert.True(#consumers > 0)
assert.equal(consumer.id, consumers[1].id)
-- Plugin configuration
local plugin_t = {name = "keyauth", api_id = api.id}
local plugin, err = dao_factory.plugins_configurations:insert(plugin_t)
assert.falsy(err)
assert.truthy(plugin)
local plugins, err = session:execute("SELECT * FROM plugins_configurations")
assert.falsy(err)
assert.True(#plugins > 0)
assert.equal(plugin.id, plugins[1].id)
end)
it("should let the schema validation return errors and not insert", function()
-- Without an api_id, it's a schema error
local plugin_t = faker:fake_entity("plugin_configuration")
local plugin, err = dao_factory.plugins_configurations:insert(plugin_t)
assert.falsy(plugin)
assert.truthy(err)
assert.is_daoError(err)
assert.True(err.schema)
assert.are.same("api_id is required", err.message.api_id)
end)
it("should ensure fields with `unique` are unique", function()
local api_t = faker:fake_entity("api")
-- Success
local _, err = dao_factory.apis:insert(api_t)
assert.falsy(err)
-- Failure
local api, err = dao_factory.apis:insert(api_t)
assert.truthy(err)
assert.is_daoError(err)
assert.True(err.unique)
assert.are.same("name already exists with value '"..api_t.name.."'", err.message.name)
assert.falsy(api)
end)
it("should ensure fields with `foreign` are existing", function()
-- Plugin configuration
local plugin_t = faker:fake_entity("plugin_configuration")
plugin_t.api_id = uuid()
local plugin, err = dao_factory.plugins_configurations:insert(plugin_t)
assert.falsy(plugin)
assert.truthy(err)
assert.is_daoError(err)
assert.True(err.foreign)
assert.are.same("api_id "..plugin_t.api_id.." does not exist", err.message.api_id)
end)
it("should do insert checks for entities with `self_check`", function()
local api, err = dao_factory.apis:insert(faker:fake_entity("api"))
assert.falsy(err)
assert.truthy(api.id)
local plugin_t = faker:fake_entity("plugin_configuration")
plugin_t.api_id = api.id
-- Success: plugin doesn't exist yet
local plugin, err = dao_factory.plugins_configurations:insert(plugin_t)
assert.falsy(err)
assert.truthy(plugin)
-- Failure: the same plugin is already inserted
local plugin, err = dao_factory.plugins_configurations:insert(plugin_t)
assert.falsy(plugin)
assert.truthy(err)
assert.is_daoError(err)
assert.True(err.unique)
assert.are.same("Plugin configuration already exists", err.message)
end)
end) -- describe :insert()
describe(":update()", function()
it("should error if called with invalid parameters", function()
assert.has_error(function()
dao_factory.apis:update()
end, "Cannot update a nil element")
assert.has_error(function()
dao_factory.apis:update("")
end, "Entity to update must be a table")
end)
it("should return nil and no error if no entity was found to update in DB", function()
local api_t = faker:fake_entity("api")
api_t.id = uuid()
-- No entity to update
local entity, err = dao_factory.apis:update(api_t)
assert.falsy(entity)
assert.falsy(err)
end)
it("should consider no entity to be found if an empty table is given to it", function()
local api, err = dao_factory.apis:update({})
assert.falsy(err)
assert.falsy(api)
end)
it("should update specified, non-primary fields in DB", function()
-- API
local apis, err = session:execute("SELECT * FROM apis")
assert.falsy(err)
assert.True(#apis > 0)
local api_t = apis[1]
api_t.name = api_t.name.." updated"
local api, err = dao_factory.apis:update(api_t)
assert.falsy(err)
assert.truthy(api)
apis, err = session:execute("SELECT * FROM apis WHERE name = ?", {api_t.name})
assert.falsy(err)
assert.equal(1, #apis)
assert.equal(api_t.id, apis[1].id)
assert.equal(api_t.name, apis[1].name)
assert.equal(api_t.public_dns, apis[1].public_dns)
assert.equal(api_t.target_url, apis[1].target_url)
-- Consumer
local consumers, err = session:execute("SELECT * FROM consumers")
assert.falsy(err)
assert.True(#consumers > 0)
local consumer_t = consumers[1]
consumer_t.custom_id = consumer_t.custom_id.."updated"
local consumer, err = dao_factory.consumers:update(consumer_t)
assert.falsy(err)
assert.truthy(consumer)
consumers, err = session:execute("SELECT * FROM consumers WHERE custom_id = ?", {consumer_t.custom_id})
assert.falsy(err)
assert.equal(1, #consumers)
assert.equal(consumer_t.name, consumers[1].name)
-- Plugin Configuration
local plugins, err = session:execute("SELECT * FROM plugins_configurations")
assert.falsy(err)
assert.True(#plugins > 0)
local plugin_t = plugins[1]
plugin_t.value = cjson.decode(plugin_t.value)
plugin_t.enabled = false
local plugin, err = dao_factory.plugins_configurations:update(plugin_t)
assert.falsy(err)
assert.truthy(plugin)
plugins, err = session:execute("SELECT * FROM plugins_configurations WHERE id = ?", {cassandra.uuid(plugin_t.id)})
assert.falsy(err)
assert.equal(1, #plugins)
end)
it("should ensure fields with `unique` are unique", function()
local apis, err = session:execute("SELECT * FROM apis")
assert.falsy(err)
assert.True(#apis > 0)
local api_t = apis[1]
-- Should not work because we're reusing a public_dns
api_t.public_dns = apis[2].public_dns
local api, err = dao_factory.apis:update(api_t)
assert.truthy(err)
assert.falsy(api)
assert.is_daoError(err)
assert.True(err.unique)
assert.equal("public_dns already exists with value '"..api_t.public_dns.."'", err.message.public_dns)
end)
describe("full", function()
it("should set to NULL if a field is not specified", function()
local api_t = faker:fake_entity("api")
api_t.path = "/path"
local api, err = dao_factory.apis:insert(api_t)
assert.falsy(err)
assert.truthy(api_t.path)
-- Update
api.path = nil
api, err = dao_factory.apis:update(api, true)
assert.falsy(err)
assert.truthy(api)
assert.falsy(api.path)
-- Check update
api, err = session:execute("SELECT * FROM apis WHERE id = ?", {cassandra.uuid(api.id)})
assert.falsy(err)
assert.falsy(api.path)
end)
it("should still check the validity of the schema", function()
local api_t = faker:fake_entity("api")
local api, err = dao_factory.apis:insert(api_t)
assert.falsy(err)
assert.truthy(api_t)
-- Update
api.public_dns = nil
local nil_api, err = dao_factory.apis:update(api, true)
assert.truthy(err)
assert.falsy(nil_api)
-- Check update failed
api, err = session:execute("SELECT * FROM apis WHERE id = ?", {cassandra.uuid(api.id)})
assert.falsy(err)
assert.truthy(api[1].name)
assert.truthy(api[1].public_dns)
end)
end)
end) -- describe :update()
describe(":find_by_keys()", function()
describe_core_collections(function(type, collection)
it("should error if called with invalid parameters", function()
assert.has_error(function()
dao_factory[collection]:find_by_keys("")
end, "where_t must be a table")
end)
it("should handle empty search fields", function()
local results, err = dao_factory[collection]:find_by_keys({})
assert.falsy(err)
assert.truthy(results)
assert.True(#results > 0)
end)
it("should handle nil search fields", function()
local results, err = dao_factory[collection]:find_by_keys(nil)
assert.falsy(err)
assert.truthy(results)
assert.True(#results > 0)
end)
end)
it("should query an entity from the given fields and return if filtering was needed", function()
-- Filtering needed
local apis, err = session:execute("SELECT * FROM apis")
assert.falsy(err)
assert.True(#apis > 0)
local api_t = apis[1]
local apis, err, needs_filtering = dao_factory.apis:find_by_keys(api_t)
assert.falsy(err)
assert.same(api_t, apis[1])
assert.True(needs_filtering)
-- No Filtering needed
apis, err, needs_filtering = dao_factory.apis:find_by_keys {public_dns = api_t.public_dns}
assert.falsy(err)
assert.same(api_t, apis[1])
assert.False(needs_filtering)
end)
end) -- describe :find_by_keys()
describe(":find()", function()
setup(function()
spec_helper.drop_db()
spec_helper.seed_db(10)
end)
describe_core_collections(function(type, collection)
it("should find entities", function()
local entities, err = session:execute("SELECT * FROM "..collection)
assert.falsy(err)
assert.truthy(entities)
assert.True(#entities > 0)
local results, err = dao_factory[collection]:find()
assert.falsy(err)
assert.truthy(results)
assert.same(#entities, #results)
end)
it("should allow pagination", function()
-- 1st page
local rows_1, err = dao_factory[collection]:find(2)
assert.falsy(err)
assert.truthy(rows_1)
assert.same(2, #rows_1)
assert.truthy(rows_1.next_page)
-- 2nd page
local rows_2, err = dao_factory[collection]:find(2, rows_1.next_page)
assert.falsy(err)
assert.truthy(rows_2)
assert.same(2, #rows_2)
end)
end)
end) -- describe :find()
describe(":find_by_primary_key()", function()
describe_core_collections(function(type, collection)
it("should error if called with invalid parameters", function()
assert.has_error(function()
dao_factory[collection]:find_by_primary_key("")
end, "where_t must be a table")
end)
it("should return nil (not found) if where_t is empty", function()
local res, err = dao_factory[collection]:find_by_primary_key({})
assert.falsy(err)
assert.falsy(res)
end)
end)
it("should find one entity by its primary key", function()
local apis, err = session:execute("SELECT * FROM apis")
assert.falsy(err)
assert.True(#apis > 0)
local api, err = dao_factory.apis:find_by_primary_key { id = apis[1].id }
assert.falsy(err)
assert.truthy(apis)
assert.same(apis[1], api)
end)
it("should handle an invalid uuid value", function()
local apis, err = dao_factory.apis:find_by_primary_key { id = "abcd" }
assert.falsy(apis)
assert.True(err.invalid_type)
assert.equal("abcd is an invalid uuid", err.message.id)
end)
describe("plugin_configurations", function()
setup(function()
local fixtures = spec_helper.seed_db(1)
faker:insert_from_table {
plugin_configuration = {
{ name = "keyauth", value = {key_names = {"apikey"}}, api_id = fixtures.api[1].id }
}
}
end)
it("should unmarshall the `value` field", function()
local plugins, err = session:execute("SELECT * FROM plugins_configurations")
assert.falsy(err)
assert.truthy(plugins)
assert.True(#plugins> 0)
local plugin_t = plugins[1]
local plugin, err = dao_factory.plugins_configurations:find_by_primary_key {
id = plugin_t.id,
name = plugin_t.name
}
assert.falsy(err)
assert.truthy(plugin)
assert.equal("table", type(plugin.value))
end)
end)
end) -- describe :find_by_primary_key()
describe(":delete()", function()
describe_core_collections(function(type, collection)
it("should error if called with invalid parameters", function()
assert.has_error(function()
dao_factory[collection]:delete("")
end, "where_t must be a table")
end)
it("should return false if entity to delete wasn't found", function()
local ok, err = dao_factory[collection]:delete({id = uuid()})
assert.falsy(err)
assert.False(ok)
end)
it("should delete an entity based on its primary key", function()
local entities, err = session:execute("SELECT * FROM "..collection)
assert.falsy(err)
assert.truthy(entities)
assert.True(#entities > 0)
local ok, err = dao_factory[collection]:delete(entities[1])
assert.falsy(err)
assert.True(ok)
local entities, err = session:execute("SELECT * FROM "..collection.." WHERE id = ?", {cassandra.uuid(entities[1].id)})
assert.falsy(err)
assert.truthy(entities)
assert.are.same(0, #entities)
end)
end)
describe("APIs", function()
local api, untouched_api
setup(function()
spec_helper.drop_db()
local fixtures = spec_helper.insert_fixtures {
api = {
{ name = "cascade delete",
public_dns = "mockbin.com",
target_url = "http://mockbin.com" },
{ name = "untouched cascade delete",
public_dns = "untouched.com",
target_url = "http://mockbin.com" }
},
plugin_configuration = {
{name = "keyauth", __api = 1},
{name = "ratelimiting", value = { minute = 6}, __api = 1},
{name = "filelog", value = {path = "/tmp/spec.log" }, __api = 1},
{name = "keyauth", __api = 2}
}
}
api = fixtures.api[1]
untouched_api = fixtures.api[2]
end)
teardown(function()
spec_helper.drop_db()
end)
it("should delete all related plugins_configurations when deleting an API", function()
local ok, err = dao_factory.apis:delete(api)
assert.falsy(err)
assert.True(ok)
-- Make sure we have 0 matches
local results, err = dao_factory.plugins_configurations:find_by_keys {
api_id = api.id
}
assert.falsy(err)
assert.equal(0, #results)
-- Make sure the untouched API still has its plugins
results, err = dao_factory.plugins_configurations:find_by_keys {
api_id = untouched_api.id
}
assert.falsy(err)
assert.equal(1, #results)
end)
end)
describe("Consumers", function()
local consumer, untouched_consumer
setup(function()
spec_helper.drop_db()
local fixtures = spec_helper.insert_fixtures {
api = {
{ name = "cascade delete",
public_dns = "mockbin.com",
target_url = "http://mockbin.com" }
},
consumer = {
{username = "king kong"},
{username = "untouched consumer"}
},
plugin_configuration = {
{name = "ratelimiting", value = { minute = 6}, __api = 1, __consumer = 1},
{name = "response_transformer", __api = 1, __consumer = 1},
{name = "filelog", value = {path = "/tmp/spec.log" }, __api = 1, __consumer = 1},
{name = "request_transformer", __api = 1, __consumer = 2}
}
}
consumer = fixtures.consumer[1]
untouched_consumer = fixtures.consumer[2]
end)
teardown(function()
spec_helper.drop_db()
end)
it("should delete all related plugins_configurations when deleting a Consumer", function()
local ok, err = dao_factory.consumers:delete(consumer)
assert.True(ok)
assert.falsy(err)
local results, err = dao_factory.plugins_configurations:find_by_keys {
consumer_id = consumer.id
}
assert.falsy(err)
assert.are.same(0, #results)
-- Make sure the untouched Consumer still has its plugin
results, err = dao_factory.plugins_configurations:find_by_keys {
consumer_id = untouched_consumer.id
}
assert.falsy(err)
assert.are.same(1, #results)
end)
end)
end) -- describe :delete()
--
-- APIs additional behaviour
--
describe("APIs", function()
setup(function()
spec_helper.seed_db(100)
end)
describe(":find_all()", function()
local apis, err = dao_factory.apis:find_all()
assert.falsy(err)
assert.truthy(apis)
assert.equal(100, #apis)
end)
end)
--
-- Plugins configuration additional behaviour
--
describe("plugin_configurations", function()
describe(":find_distinct()", function()
it("should find distinct plugins configurations", function()
faker:insert_from_table {
api = {
{ name = "tests distinct 1", public_dns = "foo.com", target_url = "http://mockbin.com" },
{ name = "tests distinct 2", public_dns = "bar.com", target_url = "http://mockbin.com" }
},
plugin_configuration = {
{ name = "keyauth", value = {key_names = {"apikey"}, hide_credentials = true}, __api = 1 },
{ name = "ratelimiting", value = { minute = 6}, __api = 1 },
{ name = "ratelimiting", value = { minute = 6}, __api = 2 },
{ name = "filelog", value = { path = "/tmp/spec.log" }, __api = 1 }
}
}
local res, err = dao_factory.plugins_configurations:find_distinct()
assert.falsy(err)
assert.truthy(res)
assert.are.same(3, #res)
assert.truthy(utils.table_contains(res, "keyauth"))
assert.truthy(utils.table_contains(res, "ratelimiting"))
assert.truthy(utils.table_contains(res, "filelog"))
end)
end)
describe(":insert()", function()
local api_id
local inserted_plugin
it("should insert a plugin and set the consumer_id to a 'null' uuid if none is specified", function()
-- Since we want to specifically select plugins configurations which have _no_ consumer_id sometimes, we cannot rely on using
-- NULL (and thus, not inserting the consumer_id column for the row). To fix this, we use a predefined, nullified uuid...
-- Create an API
local api_t = faker:fake_entity("api")
local api, err = dao_factory.apis:insert(api_t)
assert.falsy(err)
local plugin_t = faker:fake_entity("plugin_configuration")
plugin_t.api_id = api.id
local plugin, err = dao_factory.plugins_configurations:insert(plugin_t)
assert.falsy(err)
assert.truthy(plugin)
assert.falsy(plugin.consumer_id)
-- for next test
api_id = api.id
inserted_plugin = plugin
inserted_plugin.consumer_id = nil
end)
it("should select a plugin configuration by 'null' uuid consumer_id and remove the column", function()
-- Now we should be able to select this plugin
local rows, err = dao_factory.plugins_configurations:find_by_keys {
api_id = api_id,
consumer_id = constants.DATABASE_NULL_ID
}
assert.falsy(err)
assert.truthy(rows[1])
assert.are.same(inserted_plugin, rows[1])
assert.falsy(rows[1].consumer_id)
end)
end)
end) -- describe plugins configurations
end) -- describe Base DAO
end) -- describe Cassandra | mit |
AdamGagorik/darkstar | scripts/globals/items/plate_of_ic_pilav_+1.lua | 18 | 1948 | -----------------------------------------
-- ID: 5585
-- Item: plate_of_ic_pilav_+1
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Health % 14
-- Health Cap 65
-- Strength 4
-- Vitality -1
-- Intelligence -1
-- Health Regen While Healing 1
-- Attack % 22
-- Attack Cap 65
-- Ranged ATT % 22
-- Ranged ATT Cap 65
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5585);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 14);
target:addMod(MOD_FOOD_HP_CAP, 65);
target:addMod(MOD_STR, 4);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_INT, -1);
target:addMod(MOD_HPHEAL, 1);
target:addMod(MOD_FOOD_ATTP, 22);
target:addMod(MOD_FOOD_ATT_CAP, 65);
target:addMod(MOD_FOOD_RATTP, 22);
target:addMod(MOD_FOOD_RATT_CAP, 65);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 14);
target:delMod(MOD_FOOD_HP_CAP, 65);
target:delMod(MOD_STR, 4);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_INT, -1);
target:delMod(MOD_HPHEAL, 1);
target:delMod(MOD_FOOD_ATTP, 22);
target:delMod(MOD_FOOD_ATT_CAP, 65);
target:delMod(MOD_FOOD_RATTP, 22);
target:delMod(MOD_FOOD_RATT_CAP, 65);
end;
| gpl-3.0 |
neechbear/colloquy | src/users.lua | 1 | 7009 | -- stuff to handle users
users = {
god = {
password = crypt("godgod"), -- god's default password is "god"
privs = "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
site = "",
talktime = 0,
}
}
-- the users table is keyed by lower-case username. The values are
-- a table describing that user, in the following form:
-- .password = [string] an md5 hash of their password
-- .password2 = [string] new style password - md5 of their username concatenated with their password
-- .privs = [string] a list of the user's priviledges.
-- .site = [string] site the user last connected from
-- .talktime = [number] how many minutes the user has been connected
-- .name = [string] real name of the user
-- .birthday = [string] date of birth in ISO format
-- .location = [string] where the user is based
-- .homepage = [string] url to user's homepage
-- .email = [string] user's email address
-- .sex = [stirng] male/female/etc
-- .around = [string] when the user is next around
-- .restrict = [string] list of restrictions (eg, G)
-- .timeon = [number] seconds of online time.
-- .connected = [number] time of their connection, if they're connected now, otherwise nil.
-- .idlePrompt= [string] If they want something as their prompt when idle
function escapeUserData(data)
-- does stuff to a string so it can be safely saved...
-- strings are assumed to only be sensitive to the double quote chartacter.
local p, l = 1;
local r = '" .. strchar(34) .. "';
local rl = strlen(r);
local dl = 0;
repeat
l = strfind(data, '"', p, 1);
if (l) then
data = strsub(data, 1, l - 1) .. r .. strsub(data, l + 1, - 1);
p = l + rl;
dl = strlen(data);
end;
until l == nil or p > dl
return data;
end;
function saveUsers(dirname)
-- dumps the users table to file in an executable form
for i, v in users do
if (type(v) == "table" and strlower(i) == i) then
local f = openfile(dirname .. "/" .. strlower(i), "w");
write(f, "return ")
dumpUser(v, f, 0)
closefile(f)
end
end
end;
function saveOneUser(user)
local f = openfile(colloquy.users .. "/" .. strlower(user), "w");
write(f, "return ")
dumpUser(users[strlower(user)], f, 0)
closefile(f)
end
function loadUsers(dirname)
local dir = pfiles(dirname .. "/")
if dir then
local e = dir();
while (e) do
if (not strfind(e, "^%.") and strlower(e) == e) then
users[e] = dofile(dirname .. "/" .. e);
end
e = dir();
end
else
if pstat(colloquy.base .. "/data/users.lua") then
write(" (importing old user data)"); flush();
dofile(colloquy.base .. "/data/users.lua");
rename(colloquy.base .. "/data/users.lua", colloquy.base .. "/data/users-old.lua");
pmkdir(dirname)
saveUsers(dirname)
else
users = {
god = {
password = crypt("godgod"), -- god's default password is "god"
privs = "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
site = "",
talktime = 0,
}
}
pmkdir(dirname);
saveOneUser("god");
end
end
end
function dumpUser(table, f, indent)
write(f, "{\n"); indent = indent + 2;
if not table.password then
table.password = table.password2;
table.password2 = nil;
end
for j, k in table do
if (j ~= "n" and j ~= "connected") then
write(f, strrep(" ", indent) .. j .. " = ");
t = type(k);
if (t == "string") then
k = format("%q", k);
write(f, k, ",", "\n");
elseif (t == "number") then write(f, k .. ",\n");
elseif (t == "table") then saveTable(k, f, indent);
end;
end;
end;
indent = indent - 2; write(f, strrep(" ", indent) .. "}\n");
end
function saveTable(table, f, indent)
local i, v;
write(f, "{\n"); indent = indent + 2;
for i, v in table do
if (i ~= "n") then
write(f, strrep(" ", indent) .. i .. " = {\n"); indent = indent + 2;
local j, k, t;
for j, k in v do
if (j ~= "n" and j ~= "connected") then
write(f, strrep(" ", indent) .. j .. " = ");
t = type(k);
if (t == "string") then
k = format("%q", k);
write(f, k, ",", "\n");
elseif (t == "number") then write(f, k .. ",\n");
elseif (t == "table") then saveTable(k, f, indent);
end;
end;
end;
indent = indent - 2; write(f, strrep(" ", indent) .. "},\n");
end;
end;
write(f, "}\n");
end;
--function loadUsers(filename)
-- dofile(filename);
--end;
function checkPasswordWithAuthenticator(authenticator, user, password)
local null, null, rUser, host, port = strfind(authenticator, "^([^%@]-)%@([^%:]-):(.-)$");
if (not null) then
return nil, "Invalid authenticator field.";
end;
local s = connect(host, port);
if (not s) then
return nil, "Unable to connect to authenticator.";
end;
s:send(format("auth %s %s\n", rUser, password));
local r = s:receive("*l");
s:close();
if (not r) then
return nil, "Unable to get response from authenticator.";
end;
local null, null, code, message = strfind(r, "^auth (.-) (.-)$");
if (not null) then
return nil, "Invalid response from authenticator.";
end;
if (code == "1") then
return 1, message;
else
return nil, message;
end;
end;
function checkPassword(user, password)
user = strlower(user);
if (users[user].authenticator) then
-- they have an authenticator!
return checkPasswordWithAuthenticator(users[user].authenticator, user, password);
else
if (users[user].password == crypt(user .. password)) then
return 1, "";
else
return nil, "Incorrect password.";
end;
end;
end;
function changePassword(user, old, new)
user = strlower(user);
if (users[user].authenticator) then
local null, null, rUser, host, port = strfind(users[user].authenticator, "^([^%@]-)%@([^%:]-):(.-)$");
if (not null) then
return nil, "Invalid authenticator field.";
end;
local s = connect(host, port);
if (not s) then
return nil, "Unable to connect to authenticator.";
end;
s:send(format("pass %s %s %s\n", rUser, old, new));
local r = s:receive("*l");
s:close();
if (not r) then
return nil, "Unable to get response from authenticator.";
end;
local null, null, code, message = strfind(r, "^pass (.-) (.-)$");
if (not null) then
return nil, "Invalid response from authenticator.";
end;
if (code == "1") then
return 1, message;
else
return nil, message;
end;
else
local pr, message = checkPassword(user, old);
if (not pr) then
return nil, (message or "Incorrect old password");
end;
users[user].password2 = crypt(user .. new);
users[user].password = nil;
saveUsers(colloquy.users);
return 1, "Password changed.";
end;
end;
| mit |
AdamGagorik/darkstar | scripts/zones/Gusgen_Mines/npcs/_5gc.lua | 13 | 1340 | -----------------------------------
-- Area: Gusgen Mines
-- NPC: _5gc (Lever A)
-- @pos -4 -40.561 -54.199 196
-----------------------------------
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Gusgen_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--local nID = npc:getID();
--printf("id: %u", nID);
local Lever = npc:getID();
npc:openDoor(2); -- Lever animation
if (GetNPCByID(Lever-6):getAnimation() == 9) then
GetNPCByID(Lever-8):setAnimation(9);--close door C
GetNPCByID(Lever-7):setAnimation(9);--close door B
GetNPCByID(Lever-6):setAnimation(8);--open door A
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
Hostle/luci | applications/luci-app-olsr/luasrc/controller/olsr.lua | 9 | 9924 | module("luci.controller.olsr", package.seeall)
local neigh_table = nil
local ifaddr_table = nil
function index()
local ipv4,ipv6
if nixio.fs.access("/etc/config/olsrd") then
ipv4 = 1
end
if nixio.fs.access("/etc/config/olsrd6") then
ipv6 = 1
end
if not ipv4 and not ipv6 then
return
end
require("luci.model.uci")
local uci = luci.model.uci.cursor_state()
uci:foreach("olsrd", "olsrd", function(s)
if s.SmartGateway and s.SmartGateway == "yes" then has_smartgw = true end
end)
local page = node("admin", "status", "olsr")
page.target = template("status-olsr/overview")
page.title = _("OLSR")
page.subindex = true
local page = node("admin", "status", "olsr", "json")
page.target = call("action_json")
page.title = nil
page.leaf = true
local page = node("admin", "status", "olsr", "neighbors")
page.target = call("action_neigh")
page.title = _("Neighbours")
page.subindex = true
page.order = 5
local page = node("admin", "status", "olsr", "routes")
page.target = call("action_routes")
page.title = _("Routes")
page.order = 10
local page = node("admin", "status", "olsr", "topology")
page.target = call("action_topology")
page.title = _("Topology")
page.order = 20
local page = node("admin", "status", "olsr", "hna")
page.target = call("action_hna")
page.title = _("HNA")
page.order = 30
local page = node("admin", "status", "olsr", "mid")
page.target = call("action_mid")
page.title = _("MID")
page.order = 50
if has_smartgw then
local page = node("admin", "status", "olsr", "smartgw")
page.target = call("action_smartgw")
page.title = _("SmartGW")
page.order = 60
end
local page = node("admin", "status", "olsr", "interfaces")
page.target = call("action_interfaces")
page.title = _("Interfaces")
page.order = 70
odsp = entry(
{"admin", "services", "olsrd", "display"},
cbi("olsr/olsrddisplay"), _("Display")
)
end
function action_json()
local http = require "luci.http"
local utl = require "luci.util"
local uci = require "luci.model.uci".cursor()
local jsonreq4
local jsonreq6
local v4_port = uci:get("olsrd", "olsrd_jsoninfo", "port") or 9090
local v6_port = uci:get("olsrd6", "olsrd_jsoninfo", "port") or 9090
jsonreq4 = utl.exec("(echo /status | nc 127.0.0.1 " .. v4_port .. ") 2>/dev/null" )
jsonreq6 = utl.exec("(echo /status | nc ::1 " .. v6_port .. ") 2>/dev/null")
http.prepare_content("application/json")
if not jsonreq4 or jsonreq4 == "" then
jsonreq4 = "{}"
end
if not jsonreq6 or jsonreq6 == "" then
jsonreq6 = "{}"
end
http.write('{"v4":' .. jsonreq4 .. ', "v6":' .. jsonreq6 .. '}')
end
local function local_mac_lookup(ipaddr)
local _, ifa, dev
ipaddr = tostring(ipaddr)
if not ifaddr_table then
ifaddr_table = nixio.getifaddrs()
end
-- ipaddr -> ifname
for _, ifa in ipairs(ifaddr_table) do
if ifa.addr == ipaddr then
dev = ifa.name
break
end
end
-- ifname -> macaddr
for _, ifa in ipairs(ifaddr_table) do
if ifa.name == dev and ifa.family == "packet" then
return ifa.addr
end
end
end
local function remote_mac_lookup(ipaddr)
local _, n
if not neigh_table then
neigh_table = luci.ip.neighbors()
end
for _, n in ipairs(neigh_table) do
if n.mac and n.dest and n.dest:equal(ipaddr) then
return n.mac
end
end
end
function action_neigh(json)
local data, has_v4, has_v6, error = fetch_jsoninfo('links')
if error then
return
end
local uci = require "luci.model.uci".cursor_state()
local resolve = uci:get("luci_olsr", "general", "resolve")
local ntm = require "luci.model.network".init()
local devices = ntm:get_wifidevs()
local sys = require "luci.sys"
local assoclist = {}
--local neightbl = require "neightbl"
local ntm = require "luci.model.network"
local ipc = require "luci.ip"
local nxo = require "nixio"
local defaultgw
ipc.routes({ family = 4, type = 1, dest_exact = "0.0.0.0/0" },
function(rt) defaultgw = rt.gw end)
local function compare(a,b)
if a.proto == b.proto then
return a.linkCost < b.linkCost
else
return a.proto < b.proto
end
end
for _, dev in ipairs(devices) do
for _, net in ipairs(dev:get_wifinets()) do
local radio = net:get_device()
assoclist[#assoclist+1] = {}
assoclist[#assoclist]['ifname'] = net:ifname()
assoclist[#assoclist]['network'] = net:network()[1]
assoclist[#assoclist]['device'] = radio and radio:name() or nil
assoclist[#assoclist]['list'] = net:assoclist()
end
end
for k, v in ipairs(data) do
local snr = 0
local signal = 0
local noise = 0
local mac = ""
local ip
local neihgt = {}
if resolve == "1" then
hostname = nixio.getnameinfo(v.remoteIP, nil, 100)
if hostname then
v.hostname = hostname
end
end
local interface = ntm:get_status_by_address(v.localIP)
local lmac = local_mac_lookup(v.localIP)
local rmac = remote_mac_lookup(v.remoteIP)
for _, val in ipairs(assoclist) do
if val.network == interface and val.list then
for assocmac, assot in pairs(val.list) do
assocmac = string.lower(assocmac or "")
if rmac == assocmac then
signal = tonumber(assot.signal)
noise = tonumber(assot.noise)
snr = (noise*-1) - (signal*-1)
end
end
end
end
if interface then
v.interface = interface
end
v.snr = snr
v.signal = signal
v.noise = noise
if rmac then
v.remoteMAC = rmac
end
if lmac then
v.localMAC = lmac
end
if defaultgw == v.remoteIP then
v.defaultgw = 1
end
end
table.sort(data, compare)
luci.template.render("status-olsr/neighbors", {links=data, has_v4=has_v4, has_v6=has_v6})
end
function action_routes()
local data, has_v4, has_v6, error = fetch_jsoninfo('routes')
if error then
return
end
local uci = require "luci.model.uci".cursor_state()
local resolve = uci:get("luci_olsr", "general", "resolve")
for k, v in ipairs(data) do
if resolve == "1" then
local hostname = nixio.getnameinfo(v.gateway, nil, 100)
if hostname then
v.hostname = hostname
end
end
end
local function compare(a,b)
if a.proto == b.proto then
return a.rtpMetricCost < b.rtpMetricCost
else
return a.proto < b.proto
end
end
table.sort(data, compare)
luci.template.render("status-olsr/routes", {routes=data, has_v4=has_v4, has_v6=has_v6})
end
function action_topology()
local data, has_v4, has_v6, error = fetch_jsoninfo('topology')
if error then
return
end
local function compare(a,b)
if a.proto == b.proto then
return a.tcEdgeCost < b.tcEdgeCost
else
return a.proto < b.proto
end
end
table.sort(data, compare)
luci.template.render("status-olsr/topology", {routes=data, has_v4=has_v4, has_v6=has_v6})
end
function action_hna()
local data, has_v4, has_v6, error = fetch_jsoninfo('hna')
if error then
return
end
local uci = require "luci.model.uci".cursor_state()
local resolve = uci:get("luci_olsr", "general", "resolve")
local function compare(a,b)
if a.proto == b.proto then
return a.genmask < b.genmask
else
return a.proto < b.proto
end
end
for k, v in ipairs(data) do
if resolve == "1" then
hostname = nixio.getnameinfo(v.gateway, nil, 100)
if hostname then
v.hostname = hostname
end
end
if v.validityTime then
v.validityTime = tonumber(string.format("%.0f", v.validityTime / 1000))
end
end
table.sort(data, compare)
luci.template.render("status-olsr/hna", {hna=data, has_v4=has_v4, has_v6=has_v6})
end
function action_mid()
local data, has_v4, has_v6, error = fetch_jsoninfo('mid')
if error then
return
end
local function compare(a,b)
if a.proto == b.proto then
return a.ipAddress < b.ipAddress
else
return a.proto < b.proto
end
end
table.sort(data, compare)
luci.template.render("status-olsr/mid", {mids=data, has_v4=has_v4, has_v6=has_v6})
end
function action_smartgw()
local data, has_v4, has_v6, error = fetch_jsoninfo('gateways')
if error then
return
end
local function compare(a,b)
if a.proto == b.proto then
return a.tcPathCost < b.tcPathCost
else
return a.proto < b.proto
end
end
table.sort(data, compare)
luci.template.render("status-olsr/smartgw", {gws=data, has_v4=has_v4, has_v6=has_v6})
end
function action_interfaces()
local data, has_v4, has_v6, error = fetch_jsoninfo('interfaces')
if error then
return
end
local function compare(a,b)
return a.proto < b.proto
end
table.sort(data, compare)
luci.template.render("status-olsr/interfaces", {iface=data, has_v4=has_v4, has_v6=has_v6})
end
-- Internal
function fetch_jsoninfo(otable)
local uci = require "luci.model.uci".cursor_state()
local utl = require "luci.util"
local json = require "luci.json"
local IpVersion = uci:get_first("olsrd", "olsrd","IpVersion")
local jsonreq4 = ""
local jsonreq6 = ""
local v4_port = uci:get("olsrd", "olsrd_jsoninfo", "port") or 9090
local v6_port = uci:get("olsrd6", "olsrd_jsoninfo", "port") or 9090
jsonreq4 = utl.exec("(echo /" .. otable .. " | nc 127.0.0.1 " .. v4_port .. ") 2>/dev/null")
jsonreq6 = utl.exec("(echo /" .. otable .. " | nc ::1 " .. v6_port .. ") 2>/dev/null")
local jsondata4 = {}
local jsondata6 = {}
local data4 = {}
local data6 = {}
local has_v4 = False
local has_v6 = False
if jsonreq4 == '' and jsonreq6 == '' then
luci.template.render("status-olsr/error_olsr")
return nil, 0, 0, true
end
if jsonreq4 ~= "" then
has_v4 = 1
jsondata4 = json.decode(jsonreq4)
if otable == 'status' then
data4 = jsondata4 or {}
else
data4 = jsondata4[otable] or {}
end
for k, v in ipairs(data4) do
data4[k]['proto'] = '4'
end
end
if jsonreq6 ~= "" then
has_v6 = 1
jsondata6 = json.decode(jsonreq6)
if otable == 'status' then
data6 = jsondata6 or {}
else
data6 = jsondata6[otable] or {}
end
for k, v in ipairs(data6) do
data6[k]['proto'] = '6'
end
end
for k, v in ipairs(data6) do
table.insert(data4, v)
end
return data4, has_v4, has_v6, false
end
| apache-2.0 |
AdamGagorik/darkstar | scripts/zones/Upper_Jeuno/npcs/Migliorozz.lua | 13 | 1048 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Migliorozz
-- Type: Standard NPC
-- @zone: 244
-- @pos -37.760 -2.499 12.924
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x272a);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
AdamGagorik/darkstar | scripts/globals/items/bowl_of_pebble_soup.lua | 18 | 1130 | -----------------------------------------
-- ID: 4455
-- Item: Bowl of Pebble Soup
-- Food Effect: 3 Hr, All Races
-----------------------------------------
-- MP Recovered while healing 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4455);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MPHEAL, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MPHEAL, 2);
end;
| gpl-3.0 |
TrurlMcByte/docker-prosody | etc/prosody-modules/mod_server_status/mod_server_status.lua | 32 | 4748 | -- (C) 2011, Marco Cirillo (LW.Org)
-- Display server stats in readable XML or JSON format
module:depends("http")
local base_path = module:get_option_string("server_status_basepath", "/server-status/")
local show_hosts = module:get_option_array("server_status_show_hosts", nil)
local show_comps = module:get_option_array("server_status_show_comps", nil)
local json_output = module:get_option_boolean("server_status_json", false)
local json_encode = require "util.json".encode
-- code begin
if not prosody.stanza_counter and not show_hosts and not show_comps then
module:log ("error", "mod_server_status requires at least one of the following things:")
module:log ("error", "mod_stanza_counter loaded, or either server_status_show_hosts or server_status_show_comps configuration values set.")
module:log ("error", "check the module wiki at: http://code.google.com/p/prosody-modules/wiki/mod_server_status")
return false
end
local response_table = {}
response_table.header = '<?xml version="1.0" encoding="UTF-8" ?>'
response_table.doc_header = '<document>'
response_table.doc_closure = '</document>'
response_table.stanzas = {
elem_header = ' <stanzas>', elem_closure = ' </stanzas>',
incoming = ' <incoming iq="%d" message="%d" presence="%d" />',
outgoing = ' <outgoing iq="%d" message="%d" presence="%d" />'
}
response_table.hosts = {
elem_header = ' <hosts>', elem_closure = ' </hosts>',
status = ' <status name="%s" current="%s" />'
}
response_table.comps = {
elem_header = ' <components>', elem_closure = ' </components>',
status = ' <status name="%s" current="%s" />'
}
local function forge_response_xml()
local hosts_s = {}; local components = {}; local stats = {}; local hosts_stats = {}; local comps_stats = {}
local function t_builder(t,r) for _, bstring in ipairs(t) do r[#r+1] = bstring end end
if show_hosts then t_builder(show_hosts, hosts_s) end
if show_comps then t_builder(show_comps, components) end
-- build stanza stats if there
if prosody.stanza_counter then
stats[1] = response_table.stanzas.elem_header
stats[2] = response_table.stanzas.incoming:format(prosody.stanza_counter.iq["incoming"],
prosody.stanza_counter.message["incoming"],
prosody.stanza_counter.presence["incoming"])
stats[3] = response_table.stanzas.outgoing:format(prosody.stanza_counter.iq["outgoing"],
prosody.stanza_counter.message["outgoing"],
prosody.stanza_counter.presence["outgoing"])
stats[4] = response_table.stanzas.elem_closure
end
-- build hosts stats if there
if hosts_s[1] then
hosts_stats[1] = response_table.hosts.elem_header
for _, name in ipairs(hosts_s) do
hosts_stats[#hosts_stats+1] = response_table.hosts.status:format(
name, hosts[name] and "online" or "offline")
end
hosts_stats[#hosts_stats+1] = response_table.hosts.elem_closure
end
-- build components stats if there
if components[1] then
comps_stats[1] = response_table.comps.elem_header
for _, name in ipairs(components) do
comps_stats[#comps_stats+1] = response_table.comps.status:format(
name, hosts[name] and hosts[name].modules.component and hosts[name].modules.component.connected and "online" or
hosts[name] and hosts[name].modules.component == nil and "online" or "offline")
end
comps_stats[#comps_stats+1] = response_table.comps.elem_closure
end
-- build xml document
local result = {}
result[#result+1] = response_table.header; result[#result+1] = response_table.doc_header -- start
t_builder(stats, result); t_builder(hosts_stats, result); t_builder(comps_stats, result)
result[#result+1] = response_table.doc_closure -- end
return table.concat(result, "\n")
end
local function forge_response_json()
local result = {}
if prosody.stanza_counter then result.stanzas = {} ; result.stanzas = prosody.stanza_counter end
if show_hosts then
result.hosts = {}
for _,n in ipairs(show_hosts) do result.hosts[n] = hosts[n] and "online" or "offline" end
end
if show_comps then
result.components = {}
for _,n in ipairs(show_comps) do
result.components[n] = hosts[n] and hosts[n].modules.component and hosts[n].modules.component.connected and "online" or
hosts[n] and hosts[n].modules.component == nil and "online" or "offline"
end
end
return json_encode(result)
end
-- http handlers
local function request(event)
local response = event.response
if not json_output then
response.headers.content_type = "text/xml"
response:send(forge_response_xml())
else
response.headers.content_type = "application/json"
response:send(forge_response_json())
end
end
-- initialization.
module:provides("http", {
default_path = base_path,
route = {
["GET /"] = request
}
})
| mit |
AdamGagorik/darkstar | scripts/zones/Selbina/npcs/Humilitie.lua | 39 | 1459 | -----------------------------------
-- Area: Selbina
-- NPC: Humilitie
-- Reports the time remaining before boat arrival.
-- @pos 17.979 -2.39 -58.800 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Based on scripts/zones/Mhaura/Dieh_Yamilsiah.lua
local timer = 1152 - ((os.time() - 1009810800)%1152);
local direction = 0; -- Arrive, 1 for depart
local waiting = 216; -- Offset for Mhaura
if (timer <= waiting) then
direction = 1; -- Ship arrived, switch dialog from "arrive" to "depart"
else
timer = timer - waiting; -- Ship hasn't arrived, subtract waiting time to get time to arrival
end
player:startEvent(231,timer,direction);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
paritoshmmmec/kong | spec/unit/dao/cassandra/query_builder_spec.lua | 13 | 6551 | local builder = require "kong.dao.cassandra.query_builder"
describe("Query Builder", function()
local apis_details = {
primary_key = {"id"},
clustering_key = {"cluster_key"},
indexes = {public_dns = true, name = true}
}
describe("SELECT", function()
it("should build a SELECT query", function()
local q = builder.select("apis")
assert.equal("SELECT * FROM apis", q)
end)
it("should restrict columns to SELECT", function()
local q = builder.select("apis", nil, nil, {"name", "id"})
assert.equal("SELECT name, id FROM apis", q)
end)
it("should return the columns of the arguments to bind", function()
local _, columns = builder.select("apis", {name="mockbin", public_dns="mockbin.com"})
assert.same({"name", "public_dns"}, columns)
end)
describe("WHERE", function()
it("should not allow filtering if all the queried fields are indexed", function()
local q, _, needs_filtering = builder.select("apis", {name="mockbin"}, apis_details)
assert.equal("SELECT * FROM apis WHERE name = ?", q)
assert.False(needs_filtering)
end)
it("should not allow filtering if all the queried fields are primary keys", function()
local q, _, needs_filtering = builder.select("apis", {id="1"}, apis_details)
assert.equal("SELECT * FROM apis WHERE id = ?", q)
assert.False(needs_filtering)
end)
it("should not allow filtering if all the queried fields are primary keys or indexed", function()
local q, _, needs_filtering = builder.select("apis", {id="1", name="mockbin"}, apis_details)
assert.equal("SELECT * FROM apis WHERE name = ? AND id = ?", q)
assert.False(needs_filtering)
end)
it("should not allow filtering if all the queried fields are primary keys or indexed", function()
local q = builder.select("apis", {id="1", name="mockbin", cluster_key="foo"}, apis_details)
assert.equal("SELECT * FROM apis WHERE cluster_key = ? AND name = ? AND id = ?", q)
end)
it("should enable filtering when more than one indexed field is being queried", function()
local q, _, needs_filtering = builder.select("apis", {name="mockbin", public_dns="mockbin.com"}, apis_details)
assert.equal("SELECT * FROM apis WHERE name = ? AND public_dns = ? ALLOW FILTERING", q)
assert.True(needs_filtering)
end)
end)
it("should throw an error if no column_family", function()
assert.has_error(function()
builder.select()
end, "column_family must be a string")
end)
it("should throw an error if select_columns is not a table", function()
assert.has_error(function()
builder.select("apis", {name="mockbin"}, nil, "")
end, "select_columns must be a table")
end)
it("should throw an error if primary_key is not a table", function()
assert.has_error(function()
builder.select("apis", {name="mockbin"}, {primary_key = ""})
end, "primary_key must be a table")
end)
it("should throw an error if indexes is not a table", function()
assert.has_error(function()
builder.select("apis", {name="mockbin"}, {indexes = ""})
end, "indexes must be a table")
end)
it("should throw an error if where_key is not a table", function()
assert.has_error(function()
builder.select("apis", "")
end, "where_t must be a table")
end)
end)
describe("INSERT", function()
it("should build an INSERT query", function()
local q = builder.insert("apis", {id="123", name="mockbin"})
assert.equal("INSERT INTO apis(name, id) VALUES(?, ?)", q)
end)
it("should return the columns of the arguments to bind", function()
local _, columns = builder.insert("apis", {id="123", name="mockbin"})
assert.same({"name", "id"}, columns)
end)
it("should throw an error if no column_family", function()
assert.has_error(function()
builder.insert(nil, {"id", "name"})
end, "column_family must be a string")
end)
it("should throw an error if no insert_values", function()
assert.has_error(function()
builder.insert("apis")
end, "insert_values must be a table")
end)
end)
describe("UPDATE", function()
it("should build an UPDATE query", function()
local q = builder.update("apis", {name="mockbin"}, {id="1"}, apis_details)
assert.equal("UPDATE apis SET name = ? WHERE id = ?", q)
end)
it("should return the columns of the arguments to bind", function()
local _, columns = builder.update("apis", {public_dns="1234", name="mockbin"}, {id="1"}, apis_details)
assert.same({"public_dns", "name", "id"}, columns)
end)
it("should throw an error if no column_family", function()
assert.has_error(function()
builder.update()
end, "column_family must be a string")
end)
it("should throw an error if no update_values", function()
assert.has_error(function()
builder.update("apis")
end, "update_values must be a table")
assert.has_error(function()
builder.update("apis", {})
end, "update_values cannot be empty")
end)
it("should throw an error if no where_t", function()
assert.has_error(function()
builder.update("apis", {name="foo"}, {})
end, "where_t must contain keys")
end)
end)
describe("DELETE", function()
it("should build a DELETE query", function()
local q = builder.delete("apis", {id="1234"})
assert.equal("DELETE FROM apis WHERE id = ?", q)
end)
it("should return the columns of the arguments to bind", function()
local _, columns = builder.delete("apis", {id="1234"})
assert.same({"id"}, columns)
end)
it("should throw an error if no column_family", function()
assert.has_error(function()
builder.delete()
end, "column_family must be a string")
end)
it("should throw an error if no where_t", function()
assert.has_error(function()
builder.delete("apis", {})
end, "where_t must contain keys")
end)
end)
describe("TRUNCATE", function()
it("should build a TRUNCATE query", function()
local q = builder.truncate("apis")
assert.equal("TRUNCATE apis", q)
end)
it("should throw an error if no column_family", function()
assert.has_error(function()
builder.truncate()
end, "column_family must be a string")
end)
end)
end)
| mit |
paritoshmmmec/kong | spec/plugins/ratelimiting/api_spec.lua | 13 | 1370 | local json = require "cjson"
local http_client = require "kong.tools.http_client"
local spec_helper = require "spec.spec_helpers"
local BASE_URL = spec_helper.API_URL.."/apis/%s/plugins/"
describe("Rate Limiting API", function()
setup(function()
spec_helper.prepare_db()
spec_helper.insert_fixtures {
api = {
{ name = "tests ratelimiting 1", public_dns = "test1.com", target_url = "http://mockbin.com" }
}
}
spec_helper.start_kong()
local response = http_client.get(spec_helper.API_URL.."/apis/")
BASE_URL = string.format(BASE_URL, json.decode(response).data[1].id)
end)
teardown(function()
spec_helper.stop_kong()
end)
describe("POST", function()
it("should not save with empty value", function()
local response, status = http_client.post(BASE_URL, { name = "ratelimiting" })
local body = json.decode(response)
assert.are.equal(400, status)
assert.are.equal("You need to set at least one limit: second, minute, hour, day, month, year", body.message)
end)
it("should save with proper value", function()
local response, status = http_client.post(BASE_URL, { name = "ratelimiting", ["value.second"] = 10 })
local body = json.decode(response)
assert.are.equal(201, status)
assert.are.equal(10, body.value.second)
end)
end)
end)
| mit |
AdamGagorik/darkstar | scripts/zones/Windurst_Woods/npcs/Kopua-Mobua_AMAN.lua | 62 | 1375 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Kopua-Mobua A.M.A.N.
-- Type: Mentor Recruiter
-- @pos -23.134 1.749 -67.284 241
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local var = 0;
if (player:getMentor() == 0) then
if (player:getMainLvl() >= 30 and player:getPlaytime() >= 648000) then
var = 1;
end
elseif (player:getMentor() >= 1) then
var = 2;
end
player:startEvent(0X272A, var);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0X272A and option == 0) then
player:setMentor(1);
end
end; | gpl-3.0 |
AdamGagorik/darkstar | scripts/globals/items/plate_of_flapanos_paella.lua | 18 | 1480 | -----------------------------------------
-- ID: 5975
-- Item: Plate of Flapano's Paella
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- HP 45
-- Vitality 6
-- Defense % 26 Cap 155
-- Undead Killer 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5975);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 45);
target:addMod(MOD_VIT, 6);
target:addMod(MOD_FOOD_DEFP, 26);
target:addMod(MOD_FOOD_DEF_CAP, 155);
target:addMod(MOD_UNDEAD_KILLER, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 45);
target:delMod(MOD_VIT, 6);
target:delMod(MOD_FOOD_DEFP, 26);
target:delMod(MOD_FOOD_DEF_CAP, 155);
target:delMod(MOD_UNDEAD_KILLER, 6);
end;
| gpl-3.0 |
AdamGagorik/darkstar | scripts/globals/items/excalibur.lua | 27 | 1097 | -----------------------------------------
-- ID: 18276
-- Item: Excalibur
-- Additional Effect: Damage proportionate to current HP (25% Current HP)
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/weaponskills");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local finalDMG = math.floor(player.getHP(player)/4);
if (finalDMG > 0) then
local physicalResist = target:getMod(MOD_SLASHRES)/1000;
finalDMG = finalDMG*physicalResist;
finalDMG = target:physicalDmgTaken(finalDMG);
finalDMG = finalDMG - target:getMod(MOD_PHALANX);
finalDMG = utils.clamp(finalDMG, 0, 99999);
finalDMG = utils.stoneskin(target, finalDMG);
target:delHP(finalDMG);
return SUBEFFECT_LIGHT_DAMAGE, MSGBASIC_ADD_EFFECT_DMG, finalDMG;
end
end
end;
| gpl-3.0 |
nerdclub-tfg/telegram-bot | plugins/isup.lua | 741 | 3095 | do
local socket = require("socket")
local cronned = load_from_file('data/isup.lua')
local function save_cron(msg, url, delete)
local origin = get_receiver(msg)
if not cronned[origin] then
cronned[origin] = {}
end
if not delete then
table.insert(cronned[origin], url)
else
for k,v in pairs(cronned[origin]) do
if v == url then
table.remove(cronned[origin], k)
end
end
end
serialize_to_file(cronned, 'data/isup.lua')
return 'Saved!'
end
local function is_up_socket(ip, port)
print('Connect to', ip, port)
local c = socket.try(socket.tcp())
c:settimeout(3)
local conn = c:connect(ip, port)
if not conn then
return false
else
c:close()
return true
end
end
local function is_up_http(url)
-- Parse URL from input, default to http
local parsed_url = URL.parse(url, { scheme = 'http', authority = '' })
-- Fix URLs without subdomain not parsed properly
if not parsed_url.host and parsed_url.path then
parsed_url.host = parsed_url.path
parsed_url.path = ""
end
-- Re-build URL
local url = URL.build(parsed_url)
local protocols = {
["https"] = https,
["http"] = http
}
local options = {
url = url,
redirect = false,
method = "GET"
}
local response = { protocols[parsed_url.scheme].request(options) }
local code = tonumber(response[2])
if code == nil or code >= 400 then
return false
end
return true
end
local function isup(url)
local pattern = '^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):?(%d?%d?%d?%d?%d?)$'
local ip,port = string.match(url, pattern)
local result = nil
-- !isup 8.8.8.8:53
if ip then
port = port or '80'
result = is_up_socket(ip, port)
else
result = is_up_http(url)
end
return result
end
local function cron()
for chan, urls in pairs(cronned) do
for k,url in pairs(urls) do
print('Checking', url)
if not isup(url) then
local text = url..' looks DOWN from here. 😱'
send_msg(chan, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
if matches[1] == 'cron delete' then
if not is_sudo(msg) then
return 'This command requires privileged user'
end
return save_cron(msg, matches[2], true)
elseif matches[1] == 'cron' then
if not is_sudo(msg) then
return 'This command requires privileged user'
end
return save_cron(msg, matches[2])
elseif isup(matches[1]) then
return matches[1]..' looks UP from here. 😃'
else
return matches[1]..' looks DOWN from here. 😱'
end
end
return {
description = "Check if a website or server is up.",
usage = {
"!isup [host]: Performs a HTTP request or Socket (ip:port) connection",
"!isup cron [host]: Every 5mins check if host is up. (Requires privileged user)",
"!isup cron delete [host]: Disable checking that host."
},
patterns = {
"^!isup (cron delete) (.*)$",
"^!isup (cron) (.*)$",
"^!isup (.*)$",
"^!ping (.*)$",
"^!ping (cron delete) (.*)$",
"^!ping (cron) (.*)$"
},
run = run,
cron = cron
}
end
| gpl-2.0 |
mohammad25253/seed238 | plugins/isup.lua | 741 | 3095 | do
local socket = require("socket")
local cronned = load_from_file('data/isup.lua')
local function save_cron(msg, url, delete)
local origin = get_receiver(msg)
if not cronned[origin] then
cronned[origin] = {}
end
if not delete then
table.insert(cronned[origin], url)
else
for k,v in pairs(cronned[origin]) do
if v == url then
table.remove(cronned[origin], k)
end
end
end
serialize_to_file(cronned, 'data/isup.lua')
return 'Saved!'
end
local function is_up_socket(ip, port)
print('Connect to', ip, port)
local c = socket.try(socket.tcp())
c:settimeout(3)
local conn = c:connect(ip, port)
if not conn then
return false
else
c:close()
return true
end
end
local function is_up_http(url)
-- Parse URL from input, default to http
local parsed_url = URL.parse(url, { scheme = 'http', authority = '' })
-- Fix URLs without subdomain not parsed properly
if not parsed_url.host and parsed_url.path then
parsed_url.host = parsed_url.path
parsed_url.path = ""
end
-- Re-build URL
local url = URL.build(parsed_url)
local protocols = {
["https"] = https,
["http"] = http
}
local options = {
url = url,
redirect = false,
method = "GET"
}
local response = { protocols[parsed_url.scheme].request(options) }
local code = tonumber(response[2])
if code == nil or code >= 400 then
return false
end
return true
end
local function isup(url)
local pattern = '^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):?(%d?%d?%d?%d?%d?)$'
local ip,port = string.match(url, pattern)
local result = nil
-- !isup 8.8.8.8:53
if ip then
port = port or '80'
result = is_up_socket(ip, port)
else
result = is_up_http(url)
end
return result
end
local function cron()
for chan, urls in pairs(cronned) do
for k,url in pairs(urls) do
print('Checking', url)
if not isup(url) then
local text = url..' looks DOWN from here. 😱'
send_msg(chan, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
if matches[1] == 'cron delete' then
if not is_sudo(msg) then
return 'This command requires privileged user'
end
return save_cron(msg, matches[2], true)
elseif matches[1] == 'cron' then
if not is_sudo(msg) then
return 'This command requires privileged user'
end
return save_cron(msg, matches[2])
elseif isup(matches[1]) then
return matches[1]..' looks UP from here. 😃'
else
return matches[1]..' looks DOWN from here. 😱'
end
end
return {
description = "Check if a website or server is up.",
usage = {
"!isup [host]: Performs a HTTP request or Socket (ip:port) connection",
"!isup cron [host]: Every 5mins check if host is up. (Requires privileged user)",
"!isup cron delete [host]: Disable checking that host."
},
patterns = {
"^!isup (cron delete) (.*)$",
"^!isup (cron) (.*)$",
"^!isup (.*)$",
"^!ping (.*)$",
"^!ping (cron delete) (.*)$",
"^!ping (cron) (.*)$"
},
run = run,
cron = cron
}
end
| gpl-2.0 |
AdamGagorik/darkstar | scripts/zones/Lower_Jeuno/npcs/Panta-Putta.lua | 25 | 4244 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Panta-Putta
-- Starts and Finishes Quest: The Wonder Magic Set, The kind cardian
-- Involved in Quests: The Lost Cardian
-- @zone 245
-- @pos -61 0 -140
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TheWonderMagicSet = player:getQuestStatus(JEUNO,THE_WONDER_MAGIC_SET);
WonderMagicSetKI = player:hasKeyItem(WONDER_MAGIC_SET);
TheLostCardianCS = player:getVar("theLostCardianVar");
TheKindCardian = player:getQuestStatus(JEUNO,THE_KIND_CARDIAN);
if (player:getFameLevel(JEUNO) >= 4 and TheWonderMagicSet == QUEST_AVAILABLE) then
player:startEvent(0x004D); -- Start quest "The wonder magic set"
elseif (TheWonderMagicSet == QUEST_ACCEPTED and WonderMagicSetKI == false) then
player:startEvent(0x0037); -- During quest "The wonder magic set"
elseif (WonderMagicSetKI == true) then
player:startEvent(0x0021); -- Finish quest "The wonder magic set"
elseif (TheWonderMagicSet == QUEST_COMPLETED and player:getQuestStatus(JEUNO,COOK_S_PRIDE) ~= QUEST_COMPLETED) then
player:startEvent(0x0028); -- Standard dialog
elseif (TheWonderMagicSet == QUEST_COMPLETED and player:getQuestStatus(JEUNO,THE_LOST_CARDIAN) == QUEST_AVAILABLE) then
if (TheLostCardianCS >= 1) then
player:startEvent(0x001E); -- Second dialog for "The lost cardien" quest
else
player:startEvent(0x0028); -- Standard dialog
end
elseif (TheKindCardian == QUEST_ACCEPTED and player:getVar("theKindCardianVar") == 2) then
player:startEvent(0x0023); -- Finish quest "The kind cardien"
elseif (TheKindCardian == QUEST_COMPLETED) then
player:startEvent(0x004C); -- New standard dialog after "The kind cardien"
else
player:startEvent(0x004E); -- Base standard dialog
end
end;
-- 0x004E oh zut j'ai besoin de cette marmite
-- 0x001E j'ai été trop dur avec two... et percé la marmite
-- 0x0028 du moment que j'ai cette boite et la marmite je vais enfin battre ce gars
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x004D and option == 1) then
player:addQuest(JEUNO,THE_WONDER_MAGIC_SET);
elseif (csid == 0x0021) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13328);
else
player:addTitle(FOOLS_ERRAND_RUNNER);
player:delKeyItem(WONDER_MAGIC_SET);
player:addItem(13328);
player:messageSpecial(ITEM_OBTAINED,13328);
player:addFame(JEUNO, 30);
player:needToZone(true);
player:completeQuest(JEUNO,THE_WONDER_MAGIC_SET);
end
elseif (csid == 0x001E) then
player:setVar("theLostCardianVar",2);
elseif (csid == 0x0023) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13596);
else
player:addTitle(BRINGER_OF_BLISS);
player:delKeyItem(TWO_OF_SWORDS);
player:setVar("theKindCardianVar",0);
player:addItem(13596);
player:messageSpecial(ITEM_OBTAINED,13596); -- Green Cape
player:addFame(JEUNO, 30);
player:completeQuest(JEUNO,THE_KIND_CARDIAN);
end
end
end;
| gpl-3.0 |
AdamGagorik/darkstar | scripts/zones/Gusgen_Mines/npcs/_5gb.lua | 13 | 1344 | -----------------------------------
-- Area: Gusgen Mines
-- NPC: _5gb (Lever B)
-- @pos 19.999 -40.561 -54.198 196
-----------------------------------
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Gusgen_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--local nID = npc:getID();
--printf("id: %u", nID);
local Lever = npc:getID();
npc:openDoor(2); -- Lever animation
if (GetNPCByID(Lever-6):getAnimation() == 9) then
GetNPCByID(Lever-7):setAnimation(9);--close door C
GetNPCByID(Lever-6):setAnimation(8);--open door B
GetNPCByID(Lever-5):setAnimation(9);--close door A
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
AdamGagorik/darkstar | scripts/zones/Northern_San_dOria/npcs/Sochiene.lua | 13 | 1038 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Sochiene
-- Type: Standard Dialogue NPC
-- @zone: 231
-- @pos 4.000 0.000 -28.000
--
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,SOCHIENE_DIALOG);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
D-m-L/evonara | modules/libs/Peep/LoveFrames/libraries/util.lua | 1 | 10357 | --[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2012-2014 Kenny Shields --
--]]------------------------------------------------
-- util library
loveframes.util = {}
--[[---------------------------------------------------------
- func: SetActiveSkin(name)
- desc: sets the active skin
--]]---------------------------------------------------------
function loveframes.util.SetActiveSkin(name)
loveframes.config["ACTIVESKIN"] = name
end
--[[---------------------------------------------------------
- func: GetActiveSkin()
- desc: gets the active skin
--]]---------------------------------------------------------
function loveframes.util.GetActiveSkin()
local index = loveframes.config["ACTIVESKIN"]
local skin = loveframes.skins.available[index]
return skin
end
--[[---------------------------------------------------------
- func: BoundingBox(x1, x2, y1, y2, w1, w2, h1, h2)
- desc: checks for a collision between two boxes
- note: I take no credit for this function
--]]---------------------------------------------------------
function loveframes.util.BoundingBox(x1, x2, y1, y2, w1, w2, h1, h2)
if x1 > x2 + w2 - 1 or y1 > y2 + h2 - 1 or x2 > x1 + w1 - 1 or y2 > y1 + h1 - 1 then
return false
else
return true
end
end
--[[---------------------------------------------------------
- func: loveframes.util.GetCollisions(object, table)
- desc: gets all objects colliding with the mouse
--]]---------------------------------------------------------
function loveframes.util.GetCollisions(object, t)
local x, y = love.mouse.getPosition()
local curstate = loveframes.state
local object = object or loveframes.base
local visible = object.visible
local children = object.children
local internals = object.internals
local objectstate = object.state
local t = t or {}
if objectstate == curstate and visible then
local objectx = object.x
local objecty = object.y
local objectwidth = object.width
local objectheight = object.height
local col = loveframes.util.BoundingBox(x, objectx, y, objecty, 1, objectwidth, 1, objectheight)
local collide = object.collide
if col and collide then
local clickbounds = object.clickbounds
if clickbounds then
local cx = clickbounds.x
local cy = clickbounds.y
local cwidth = clickbounds.width
local cheight = clickbounds.height
local clickcol = loveframes.util.BoundingBox(x, cx, y, cy, 1, cwidth, 1, cheight)
if clickcol then
table.insert(t, object)
end
else
table.insert(t, object)
end
end
if children then
for k, v in ipairs(children) do
loveframes.util.GetCollisions(v, t)
end
end
if internals then
for k, v in ipairs(internals) do
local type = v.type
if type ~= "tooltip" then
loveframes.util.GetCollisions(v, t)
end
end
end
end
return t
end
--[[---------------------------------------------------------
- func: loveframes.util.GetAllObjects(object, table)
- desc: gets all active objects
--]]---------------------------------------------------------
function loveframes.util.GetAllObjects(object, t)
local object = object or loveframes.base
local internals = object.internals
local children = object.children
local t = t or {}
table.insert(t, object)
if internals then
for k, v in ipairs(internals) do
loveframes.util.GetAllObjects(v, t)
end
end
if children then
for k, v in ipairs(children) do
loveframes.util.GetAllObjects(v, t)
end
end
return t
end
--[[---------------------------------------------------------
- func: GetDirectoryContents(directory, table)
- desc: gets the contents of a directory and all of
its subdirectories
--]]---------------------------------------------------------
function loveframes.util.GetDirectoryContents(dir, t)
local version = love._version
local dir = dir
local t = t or {}
local dirs = {}
local files
files = love.filesystem.getDirectoryItems(dir)
for k, v in ipairs(files) do
local isdir = love.filesystem.isDirectory(dir.. "/" ..v)
if isdir == true then
table.insert(dirs, dir.. "/" ..v)
else
local parts = loveframes.util.SplitString(v, "([.])")
local extension = parts[#parts]
parts[#parts] = nil
local name = table.concat(parts)
table.insert(t, {path = dir, fullpath = dir.. "/" ..v, requirepath = dir .. "." ..name, name = name, extension = extension})
end
end
if #dirs > 0 then
for k, v in ipairs(dirs) do
t = loveframes.util.GetDirectoryContents(v, t)
end
end
return t
end
--[[---------------------------------------------------------
- func: Round(num, idp)
- desc: rounds a number based on the decimal limit
- note: I take no credit for this function
--]]---------------------------------------------------------
function loveframes.util.Round(num, idp)
local mult = 10^(idp or 0)
if num >= 0 then
return math.floor(num * mult + 0.5) / mult
else
return math.ceil(num * mult - 0.5) / mult
end
end
--[[---------------------------------------------------------
- func: SplitString(string, pattern)
- desc: splits a string into a table based on a given pattern
- note: I take no credit for this function
--]]---------------------------------------------------------
function loveframes.util.SplitString(str, pat)
local t = {} -- NOTE: use {n = 0} in Lua-5.0
if pat == " " then
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= #str then
cap = cap .. " "
end
if s ~= 1 or cap ~= "" then
table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
else
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
end
return t
end
--[[---------------------------------------------------------
- func: RemoveAll()
- desc: removes all gui elements
--]]---------------------------------------------------------
function loveframes.util.RemoveAll()
loveframes.base.children = {}
loveframes.base.internals = {}
loveframes.hoverobject = false
loveframes.downobject = false
loveframes.modalobject = false
loveframes.inputobject = false
loveframes.hover = false
end
--[[---------------------------------------------------------
- func: loveframes.util.TableHasValue(table, value)
- desc: checks to see if a table has a specific value
--]]---------------------------------------------------------
function loveframes.util.TableHasValue(table, value)
for k, v in pairs(table) do
if v == value then
return true
end
end
return false
end
--[[---------------------------------------------------------
- func: loveframes.util.TableHasKey(table, key)
- desc: checks to see if a table has a specific key
--]]---------------------------------------------------------
function loveframes.util.TableHasKey(table, key)
for k, v in pairs(table) do
if k == key then
return true
end
end
return false
end
--[[---------------------------------------------------------
- func: loveframes.util.Error(message)
- desc: displays a formatted error message
--]]---------------------------------------------------------
function loveframes.util.Error(message)
error("[Love Frames] " ..message)
end
--[[---------------------------------------------------------
- func: loveframes.util.GetCollisionCount()
- desc: gets the total number of objects colliding with
the mouse
--]]---------------------------------------------------------
function loveframes.util.GetCollisionCount()
local collisioncount = loveframes.collisioncount
return collisioncount
end
--[[---------------------------------------------------------
- func: loveframes.util.GetHover()
- desc: returns loveframes.hover, can be used to check
if the mouse is colliding with a visible
Love Frames object
--]]---------------------------------------------------------
function loveframes.util.GetHover()
return loveframes.hover
end
--[[---------------------------------------------------------
- func: RectangleCollisionCheck(rect1, rect2)
- desc: checks for a collision between two rectangles
based on two tables containing rectangle sizes
and positions
--]]---------------------------------------------------------
function loveframes.util.RectangleCollisionCheck(rect1, rect2)
return loveframes.util.BoundingBox(rect1.x, rect2.x, rect1.y, rect2.y, rect1.width, rect2.width, rect1.height, rect2.height)
end
--[[---------------------------------------------------------
- func: loveframes.util.DeepCopy(orig)
- desc: copies a table
- note: I take not credit for this function
--]]---------------------------------------------------------
function loveframes.util.DeepCopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[loveframes.util.DeepCopy(orig_key)] = loveframes.util.DeepCopy(orig_value)
end
setmetatable(copy, loveframes.util.DeepCopy(getmetatable(orig)))
else -- number, string, boolean, etc
copy = orig
end
return copy
end
--[[---------------------------------------------------------
- func: loveframes.util.GetHoverObject()
- desc: returns loveframes.hoverobject
--]]---------------------------------------------------------
function loveframes.util.GetHoverObject()
return loveframes.hoverobject
end
--[[---------------------------------------------------------
- func: loveframes.util.IsCtrlDown()
- desc: checks for ctrl, for use with multiselect, copy,
paste, and such. On OS X it actually looks for cmd.
--]]---------------------------------------------------------
function loveframes.util.IsCtrlDown()
if love._os == "OS X" then
return love.keyboard.isDown("lmeta") or love.keyboard.isDown("rmeta") or
love.keyboard.isDown("lgui") or love.keyboard.isDown("rgui")
end
return love.keyboard.isDown("lctrl") or love.keyboard.isDown("rctrl")
end | mit |
AdamGagorik/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Cacaroon.lua | 19 | 2405 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Cacaroon
-- Standard Info NPC
-- @pos -72.026 0.000 -82.337 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/missions");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(AHT_URHGAN,RAT_RACE) == QUEST_ACCEPTED and player:getVar("ratraceCS") == 2) then
if (trade:hasItemQty(2184,1) and trade:getItemCount() == 1) then
player:startEvent(850);
end
elseif (player:getVar("AhtUrganStatus") == 1) then
if ((trade:getGil() == 1000 and trade:getItemCount() == 1) or(trade:hasItemQty(2184,1) and trade:getItemCount() == 1)) then
player:startEvent(3022,0,0,0,0,0,0,0,0,0);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- printf("Prog = %u",player:getVar("ratraceCS"));
if (player:getVar("ratraceCS") == 2) then
player:startEvent(853);
elseif (player:getVar("ratraceCS") >= 3) then
player:startEvent(854);
elseif (player:getCurrentMission(TOAU) == KNIGHT_OF_GOLD and player:getVar("AhtUrganStatus") == 0) then
player:startEvent(3035,0,0,0,0,0,0,0,0,0);
elseif (player:getVar("AhtUrganStatus") == 1) then
player:startEvent(3036,0,0,0,0,0,0,0,0,0);
else
player:startEvent(248);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0bdb and option == 1) then
player:setVar("AhtUrganStatus",1);
elseif (csid == 3022) then
player:tradeComplete();
player:setVar("AhtUrganStatus",2);
elseif (csid == 850) then
player:tradeComplete();
player:setVar("ratraceCS",3);
end
end;
| gpl-3.0 |
Nathan22Miles/sile | languages/bn.lua | 4 | 1141 | SILE.hyphenator.languages["bn"] = {};
SILE.hyphenator.languages["bn"].patterns =
{
-- GENERAL RULE
-- Do not break either side of ZERO-WIDTH JOINER (U+200D)
"22",
-- Break on both sides of ZERO-WIDTH NON JOINER (U+200C)
"11",
-- Break before or after any independent vowel.
"অ1",
"আ1",
"ই1",
"ঈ1",
"উ1",
"ঊ1",
"ঋ1",
"ৠ1",
"ঌ1",
"ৡ1",
"এ1",
"ঐ1",
"ও1",
"ঔ1",
-- Break after any dependent vowel, but not before.
"া1",
"ি1",
"ী1",
"ু1",
"ূ1",
"ৃ1",
"ৄ1",
"ৢ1",
"ৣ1",
"ে1",
"ৈ1",
"ো1",
"ৌ1",
"2়2",
"ৗ1",
-- Break before or after any consonant.
"1ক",
"1খ",
"1গ",
"1ঘ",
"1ঙ",
"1চ",
"1ছ",
"1জ",
"1ঝ",
"1ঞ",
"1ট",
"1ঠ",
"1ড",
"1ড়",
"1ঢ",
"1ঢ়",
"1ণ",
"1ত",
"1থ",
"1দ",
"1ধ",
"1ন",
"1প",
"1ফ",
"1ব",
"1ভ",
"1ম",
"1য",
"1য়",
"1র",
"1ল",
"1শ",
"1ষ",
"1স",
"1হ",
-- Do not break after khanda ta.
"ৎ1",
-- Do not break before chandrabindu, anusvara, visarga, avagraha,
-- nukta and au length mark.
"2ঃ1",
"2ং1",
"2ঁ1",
"2ঽ1",
-- Do not break either side of virama (may be within conjunct).
"2্2",
};
| mit |
AdamGagorik/darkstar | scripts/globals/spells/bluemagic/sound_blast.lua | 26 | 1358 | -----------------------------------------
-- Spell: Sound Blast
-- Lowers Intelligence of enemies within range.
-- Spell cost: 25 MP
-- Monster Type: Birds
-- Spell Type: Magical (Fire)
-- Blue Magic Points: 1
-- Stat Bonus: None
-- Level: 32
-- Casting Time: 4 seconds
-- Recast Time: 30 seconds
-- Magic Bursts on: Liquefaction, Fusion, and Light
-- Combos: Magic Attack Bonus
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local typeEffect = EFFECT_INT_DOWN;
local dINT = caster:getStat(MOD_MND) - target:getStat(MOD_MND);
local resist = applyResistance(caster,spell,target,dINT,BLUE_SKILL);
local duration = 30 * resist;
local power = 6;
if (resist > 0.5) then -- Do it!
if (target:addStatusEffect(typeEffect,power,0,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(85);
end;
return typeEffect;
end;
| gpl-3.0 |
AdamGagorik/darkstar | scripts/globals/spells/bluemagic/cursed_sphere.lua | 35 | 1489 | -----------------------------------------
-- Spell: Cursed Sphere
-- Deals water damage to enemies within area of effect
-- Spell cost: 36 MP
-- Monster Type: Vermin
-- Spell Type: Magical (Water)
-- Blue Magic Points: 2
-- Stat Bonus: MND+1
-- Level: 18
-- Casting Time: 3 seconds
-- Recast Time: 19.5 seconds
-- Magic Bursts on: Reverberation, Distortion, and Darkness
-- Combos: Magic Attack Bonus
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.multiplier = 1.50;
params.tMultiplier = 1.0;
params.duppercap = 30;
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.0;
params.agi_wsc = 0.0;
params.int_wsc = 0.3;
params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
damage = BlueMagicalSpell(caster, target, spell, params, INT_BASED);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
return damage;
end; | gpl-3.0 |
AdamGagorik/darkstar | scripts/globals/abilities/konzen-ittai.lua | 27 | 1660 | -----------------------------------
-- Ability: Konzen-Ittai
-- Readies target for a skillchain.
-- Obtained: Samurai Level 65
-- Recast Time: 0:03:00
-- Duration: 1:00 or until next Weapon Skill
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/weaponskills");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getAnimation() ~= 1) then
return MSGBASIC_REQUIRES_COMBAT,0;
else
return 0,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability,action)
if (not target:hasStatusEffect(EFFECT_CHAINBOUND, 0) and not target:hasStatusEffect(EFFECT_SKILLCHAIN, 0)) then
target:addStatusEffectEx(EFFECT_CHAINBOUND, 0, 2, 0, 5, 0, 1);
else
ability:setMsg(156);
end
local skill = player:getWeaponSkillType(SLOT_MAIN);
local anim = 36;
if skill <= 1 then
anim = 37;
elseif skill <= 3 then
anim = 36;
elseif skill == 4 then
anim = 41;
elseif skill == 5 then
anim = 28;
elseif skill <= 7 then
anim = 40;
elseif skill == 8 then
anim = 42;
elseif skill == 9 then
anim = 43;
elseif skill == 10 then
anim = 44;
elseif skill == 11 then
anim = 39;
elseif skill == 12 then
anim = 45;
else
anim = 36;
end
action:animation(target:getID(), anim)
action:speceffect(target:getID(), 1)
return 0
end;
| gpl-3.0 |
aliomega/aliomega | plugins/stats.lua | 866 | 4001 | do
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false)
return --text
end
local function chat_stats2(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nGroups: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == 'teleseed' then -- Put everything you like :)
local about = _config.about_text
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ")
return about
end
if matches[1]:lower() == "statslist" then
if not is_momod(msg) then
return "For mods only !"
end
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats2(chat_id)
end
if matches[1]:lower() == "stats" then
if not matches[2] then
if not is_momod(msg) then
return "For mods only !"
end
if msg.to.type == 'chat' then
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats(chat_id)
else
return
end
end
if matches[2] == "teleseed" then -- Put everything you like :)
if not is_admin(msg) then
return "For admins only !"
else
return bot_stats()
end
end
if matches[2] == "group" then
if not is_admin(msg) then
return "For admins only !"
else
return chat_stats(matches[3])
end
end
end
end
return {
patterns = {
"^[!/]([Ss]tats)$",
"^[!/]([Ss]tatslist)$",
"^[!/]([Ss]tats) (group) (%d+)",
"^[!/]([Ss]tats) (teleseed)",-- Put everything you like :)
"^[!/]([Tt]eleseed)"-- Put everything you like :)
},
run = run
}
end
| gpl-2.0 |
PraveerSINGH/nn | TemporalConvolution.lua | 14 | 2040 | local TemporalConvolution, parent = torch.class('nn.TemporalConvolution', 'nn.Module')
function TemporalConvolution:__init(inputFrameSize, outputFrameSize, kW, dW)
parent.__init(self)
dW = dW or 1
self.inputFrameSize = inputFrameSize
self.outputFrameSize = outputFrameSize
self.kW = kW
self.dW = dW
self.weight = torch.Tensor(outputFrameSize, inputFrameSize*kW)
self.bias = torch.Tensor(outputFrameSize)
self.gradWeight = torch.Tensor(outputFrameSize, inputFrameSize*kW)
self.gradBias = torch.Tensor(outputFrameSize)
self:reset()
end
function TemporalConvolution:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1/math.sqrt(self.kW*self.inputFrameSize)
end
if nn.oldSeed then
self.weight:apply(function()
return torch.uniform(-stdv, stdv)
end)
self.bias:apply(function()
return torch.uniform(-stdv, stdv)
end)
else
self.weight:uniform(-stdv, stdv)
self.bias:uniform(-stdv, stdv)
end
end
function TemporalConvolution:updateOutput(input)
input.THNN.TemporalConvolution_updateOutput(
input:cdata(), self.output:cdata(),
self.weight:cdata(), self.bias:cdata(),
self.kW, self.dW,
self.inputFrameSize, self.outputFrameSize
)
return self.output
end
function TemporalConvolution:updateGradInput(input, gradOutput)
if self.gradInput then
input.THNN.TemporalConvolution_updateGradInput(
input:cdata(), gradOutput:cdata(),
self.gradInput:cdata(), self.weight:cdata(),
self.kW, self.dW
)
return self.gradInput
end
end
function TemporalConvolution:accGradParameters(input, gradOutput, scale)
scale = scale or 1
input.THNN.TemporalConvolution_accGradParameters(
input:cdata(), gradOutput:cdata(),
self.gradWeight:cdata(), self.gradBias:cdata(),
self.kW, self.dW, scale
)
end
-- we do not need to accumulate parameters when sharing
TemporalConvolution.sharedAccUpdateGradParameters = TemporalConvolution.accUpdateGradParameters
| bsd-3-clause |
bmscoordinators/FFXI-Server | scripts/zones/South_Gustaberg/npcs/qm2.lua | 27 | 2839 | -----------------------------------
-- Area: South Gustaberg
-- NPC: ???
-- Involved in Quest: Smoke on the Mountain
-- @pos 461 -21 -580 107
-----------------------------------
package.loaded["scripts/zones/South_Gustaberg/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/South_Gustaberg/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:needToZone() == false) then
player:setVar("SGusta_Sausage_Timer", 0);
end
local SmokeOnTheMountain = player:getQuestStatus(BASTOK,SMOKE_ON_THE_MOUNTAIN);
if (SmokeOnTheMountain == QUEST_ACCEPTED) then
if (trade:hasItemQty(4372,1) and trade:getItemCount() == 1) then
if (player:getVar("SGusta_Sausage_Timer") == 0) then
-- player puts sheep meat on the fire
player:messageSpecial(FIRE_PUT, 4372);
player:tradeComplete();
player:setVar("SGusta_Sausage_Timer", os.time() + 3456); -- 57 minutes 36 seconds, 1 Vana'diel Day
player:needToZone(true);
else
-- message given if sheep meat is already on the fire
player:messageSpecial(MEAT_ALREADY_PUT, 4372)
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:needToZone() == false) then
player:setVar("SGusta_Sausage_Timer", 0);
end
local SmokeOnTheMountain = player:getQuestStatus(BASTOK,SMOKE_ON_THE_MOUNTAIN);
local sausageTimer = player:getVar("SGusta_Sausage_Timer");
if (SmokeOnTheMountain ~= QUEST_AVAILABLE and sausageTimer ~= 0) then
if (sausageTimer >= os.time()) then
player:messageSpecial(FIRE_LONGER, 4372);
elseif (player:getFreeSlotsCount() < 1) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 4395);
elseif (sausageTimer < os.time()) then
player:setVar("SGusta_Sausage_Timer", 0);
player:messageSpecial(FIRE_TAKE, 4395);
player:addItem(4395);
end
elseif (SmokeOnTheMountain ~= QUEST_AVAILABLE and sausageTimer == 0) then
player:messageSpecial(FIRE_GOOD);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
zantze/tuomio-topdown | videogame/vector.lua | 28 | 5323 | --[[
Copyright (c) 2010-2013 Matthias Richter
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.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
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 assert = assert
local sqrt, cos, sin, atan2 = math.sqrt, math.cos, math.sin, math.atan2
local vector = {}
vector.__index = vector
local function new(x,y)
return setmetatable({x = x or 0, y = y or 0}, vector)
end
local zero = new(0,0)
local function isvector(v)
return type(v) == 'table' and type(v.x) == 'number' and type(v.y) == 'number'
end
function vector:clone()
return new(self.x, self.y)
end
function vector:unpack()
return self.x, self.y
end
function vector:__tostring()
return "("..tonumber(self.x)..","..tonumber(self.y)..")"
end
function vector.__unm(a)
return new(-a.x, -a.y)
end
function vector.__add(a,b)
assert(isvector(a) and isvector(b), "Add: wrong argument types (<vector> expected)")
return new(a.x+b.x, a.y+b.y)
end
function vector.__sub(a,b)
assert(isvector(a) and isvector(b), "Sub: wrong argument types (<vector> expected)")
return new(a.x-b.x, a.y-b.y)
end
function vector.__mul(a,b)
if type(a) == "number" then
return new(a*b.x, a*b.y)
elseif type(b) == "number" then
return new(b*a.x, b*a.y)
else
assert(isvector(a) and isvector(b), "Mul: wrong argument types (<vector> or <number> expected)")
return a.x*b.x + a.y*b.y
end
end
function vector.__div(a,b)
assert(isvector(a) and type(b) == "number", "wrong argument types (expected <vector> / <number>)")
return new(a.x / b, a.y / b)
end
function vector.__eq(a,b)
return a.x == b.x and a.y == b.y
end
function vector.__lt(a,b)
return a.x < b.x or (a.x == b.x and a.y < b.y)
end
function vector.__le(a,b)
return a.x <= b.x and a.y <= b.y
end
function vector.permul(a,b)
assert(isvector(a) and isvector(b), "permul: wrong argument types (<vector> expected)")
return new(a.x*b.x, a.y*b.y)
end
function vector:len2()
return self.x * self.x + self.y * self.y
end
function vector:len()
return sqrt(self.x * self.x + self.y * self.y)
end
function vector.dist(a, b)
assert(isvector(a) and isvector(b), "dist: wrong argument types (<vector> expected)")
local dx = a.x - b.x
local dy = a.y - b.y
return sqrt(dx * dx + dy * dy)
end
function vector.dist2(a, b)
assert(isvector(a) and isvector(b), "dist: wrong argument types (<vector> expected)")
local dx = a.x - b.x
local dy = a.y - b.y
return (dx * dx + dy * dy)
end
function vector:normalize_inplace()
local l = self:len()
if l > 0 then
self.x, self.y = self.x / l, self.y / l
end
return self
end
function vector:normalized()
return self:clone():normalize_inplace()
end
function vector:rotate_inplace(phi)
local c, s = cos(phi), sin(phi)
self.x, self.y = c * self.x - s * self.y, s * self.x + c * self.y
return self
end
function vector:rotated(phi)
local c, s = cos(phi), sin(phi)
return new(c * self.x - s * self.y, s * self.x + c * self.y)
end
function vector:perpendicular()
return new(-self.y, self.x)
end
function vector:projectOn(v)
assert(isvector(v), "invalid argument: cannot project vector on " .. type(v))
-- (self * v) * v / v:len2()
local s = (self.x * v.x + self.y * v.y) / (v.x * v.x + v.y * v.y)
return new(s * v.x, s * v.y)
end
function vector:mirrorOn(v)
assert(isvector(v), "invalid argument: cannot mirror vector on " .. type(v))
-- 2 * self:projectOn(v) - self
local s = 2 * (self.x * v.x + self.y * v.y) / (v.x * v.x + v.y * v.y)
return new(s * v.x - self.x, s * v.y - self.y)
end
function vector:cross(v)
assert(isvector(v), "cross: wrong argument types (<vector> expected)")
return self.x * v.y - self.y * v.x
end
-- ref.: http://blog.signalsondisplay.com/?p=336
function vector:trim_inplace(maxLen)
local s = maxLen * maxLen / self:len2()
s = (s > 1 and 1) or math.sqrt(s)
self.x, self.y = self.x * s, self.y * s
return self
end
function vector:angleTo(other)
if other then
return atan2(self.y, self.x) - atan2(other.y, other.x)
end
return atan2(self.y, self.x)
end
function vector:trimmed(maxLen)
return self:clone():trim_inplace(maxLen)
end
-- the module
return setmetatable({new = new, isvector = isvector, zero = zero},
{__call = function(_, ...) return new(...) end})
| mit |
diamondo25/Vana | scripts/instances/hakToMuLung.lua | 2 | 1037 | --[[
Copyright (C) 2008-2016 Vana Development Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2
of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--]]
function beginInstance()
addInstanceMap(200090300);
end
function playerDisconnect(playerId, isPartyLeader)
markForDelete();
end
function timerEnd(name, fromTimer)
if fromTimer then
if name == instance_timer then
if getInstancePlayerCount() > 0 then
moveAllPlayers(250000100);
removeAllInstancePlayers();
end
end
end
end | gpl-2.0 |
mohammad8/0192 | plugins/Location.lua | 185 | 1565 | -- Implement a command !loc [area] which uses
-- the static map API to get a location image
-- Not sure if this is the proper way
-- Intent: get_latlong is in time.lua, we need it here
-- loadfile "time.lua"
-- Globals
-- If you have a google api key for the geocoding/timezone api
do
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
function get_staticmap(area)
local api = base_api .. "/staticmap?"
-- Get a sense of scale
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale=="locality" then zoom=8
elseif scale=="country" then zoom=4
else zoom = 13 end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~=nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
function run(msg, matches)
local receiver = get_receiver(msg)
local lat,lng,url = get_staticmap(matches[1])
-- Send the actual location, is a google maps link
send_location(receiver, lat, lng, ok_cb, false)
-- Send a picture of the map, which takes scale into account
send_photo_from_url(receiver, url)
-- Return a link to the google maps stuff is now not needed anymore
return nil
end
return {
description = "Gets information about a location, maplink and overview",
usage = "!loc (location): Gets information about a location, maplink and overview",
patterns = {"^!loc (.*)$"},
run = run
}
end
| gpl-2.0 |
5620g/38196040 | plugins/location.lua | 185 | 1565 | -- Implement a command !loc [area] which uses
-- the static map API to get a location image
-- Not sure if this is the proper way
-- Intent: get_latlong is in time.lua, we need it here
-- loadfile "time.lua"
-- Globals
-- If you have a google api key for the geocoding/timezone api
do
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
function get_staticmap(area)
local api = base_api .. "/staticmap?"
-- Get a sense of scale
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale=="locality" then zoom=8
elseif scale=="country" then zoom=4
else zoom = 13 end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~=nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
function run(msg, matches)
local receiver = get_receiver(msg)
local lat,lng,url = get_staticmap(matches[1])
-- Send the actual location, is a google maps link
send_location(receiver, lat, lng, ok_cb, false)
-- Send a picture of the map, which takes scale into account
send_photo_from_url(receiver, url)
-- Return a link to the google maps stuff is now not needed anymore
return nil
end
return {
description = "Gets information about a location, maplink and overview",
usage = "!loc (location): Gets information about a location, maplink and overview",
patterns = {"^!loc (.*)$"},
run = run
}
end
| gpl-2.0 |
rizaumami/tdcliBot | plugins/base64.lua | 1 | 1432 | do
local function run(msg, matches)
if matches[1] then
local str = matches[1]
local bit = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
local b64 = ((str:gsub(
'.',
function(x)
local r, bit = '', x:byte()
for integer = 8, 1, -1 do
r = r .. (bit % 2^integer - bit % 2^(integer - 1) > 0 and '1' or '0')
end
return r
end
) .. '0000'):gsub(
'%d%d%d?%d?%d?%d?',
function(x)
if (#x < 6) then
return
end
local c = 0
for integer = 1, 6 do
c = c + (x:sub(integer, integer) == '1' and 2^(6 - integer) or 0)
end
return bit:sub(c + 1, c + 1)
end
) .. ({ '', '==', '=' })[#str % 3 + 1])
sendText(msg.chat_id_, msg.id_, '<code>' .. util.escapeHtml(b64) .. '</code>')
end
end
--------------------------------------------------------------------------------
return {
description = _msg('Converts the given string to base64.'),
usage = {
user = {
'https://telegra.ph/Base-64-02-08',
--'<code>!base64 [string]</code>',
--'<code>!b64 [string]</code>',
--_msg('Converts the given <code>string</code> to base64.')
},
},
patterns = {
_config.cmd .. 'base64 (.*)$',
_config.cmd .. 'b64 (.*)$'
},
run = run
}
end
| gpl-3.0 |
Mogli12/GearboxAddon | Documents/Motorized.lua | 1 | 73056 | --======================================================================================================
-- preLoad
--======================================================================================================
-- Description
-- Called before loading
-- Definition
-- preLoad(table savegame)
-- Arguments
-- table savegame savegame
--======================================================================================================
-- Code
function Motorized:preLoad(savegame)
self.addToPhysics = Utils.overwrittenFunction(self.addToPhysics, Motorized.addToPhysics);
end
--======================================================================================================
-- load
--======================================================================================================
-- Description
-- Called on loading
-- Definition
-- load(table savegame)
-- Arguments
-- table savegame savegame
--======================================================================================================
-- Code
function Motorized:load(savegame)
self.getIsMotorStarted = Utils.overwrittenFunction(self.getIsMotorStarted, Motorized.getIsMotorStarted);
self.getDeactivateOnLeave = Utils.overwrittenFunction(self.getDeactivateOnLeave, Motorized.getDeactivateOnLeave);
self.getDeactivateLights = Utils.overwrittenFunction(self.getDeactivateLights, Motorized.getDeactivateLights);
self.updateFuelUsage = Utils.overwrittenFunction(self.updateFuelUsage, Motorized.updateFuelUsage);
self.startMotor = SpecializationUtil.callSpecializationsFunction("startMotor");
self.stopMotor = SpecializationUtil.callSpecializationsFunction("stopMotor");
self.setIsFuelFilling = SpecializationUtil.callSpecializationsFunction("setIsFuelFilling");
self.setFuelFillLevel = SpecializationUtil.callSpecializationsFunction("setFuelFillLevel");
self.addFuelFillTrigger = Motorized.addFuelFillTrigger;
self.removeFuelFillTrigger = Motorized.removeFuelFillTrigger;
self.motorizedNode = nil;
for _, component in pairs(self.components) do
if component.motorized then
self.motorizedNode = component.node;
break;
end
end
Motorized.loadDifferentials(self, self.xmlFile, self.differentialIndex);
Motorized.loadMotor(self, self.xmlFile, self.configurations["motor"]);
Motorized.loadSounds(self, self.xmlFile, self.configurations["motor"]);
self.motorizedFillActivatable = MotorizedRefuelActivatable:new(self);
self.fuelFillTriggers = {};
self.isFuelFilling = false;
self.fuelFillLitersPerSecond = 10;
self.fuelFillLevel = 0;
self.lastFuelFillLevel = 0;
self:setFuelFillLevel(self.fuelCapacity);
self.sentFuelFillLevel = self.fuelFillLevel;
self.stopMotorOnLeave = true;
if self.isClient then
self.exhaustParticleSystems = {};
local exhaustParticleSystemCount = Utils.getNoNil(getXMLInt(self.xmlFile, "vehicle.exhaustParticleSystems#count"), 0);
for i=1, exhaustParticleSystemCount do
local namei = string.format("vehicle.exhaustParticleSystems.exhaustParticleSystem%d", i);
local ps = {}
ParticleUtil.loadParticleSystem(self.xmlFile, ps, namei, self.components, false, nil, self.baseDirectory)
ps.minScale = Utils.getNoNil(getXMLFloat(self.xmlFile, "vehicle.exhaustParticleSystems#minScale"), 0.5);
ps.maxScale = Utils.getNoNil(getXMLFloat(self.xmlFile, "vehicle.exhaustParticleSystems#maxScale"), 1);
table.insert(self.exhaustParticleSystems, ps)
end
if #self.exhaustParticleSystems == 0 then
self.exhaustParticleSystems = nil
end
local exhaustFlapIndex = getXMLString(self.xmlFile, "vehicle.exhaustFlap#index");
if exhaustFlapIndex ~= nil then
self.exhaustFlap = {};
self.exhaustFlap.node = Utils.indexToObject(self.components, exhaustFlapIndex);
self.exhaustFlap.maxRot = Utils.degToRad(Utils.getNoNil(getXMLFloat(self.xmlFile, "vehicle.exhaustFlap#maxRot"),0));
end
self.exhaustEffects = {};
Motorized.loadExhaustEffects(self, self.xmlFile, self.exhaustEffects);
if table.getn(self.exhaustEffects) == 0 then
self.exhaustEffects = nil;
end
end
self.motorStartDuration = 0;
if self.sampleMotorStart ~= nil then
self.motorStartDuration = self.sampleMotorStart.duration;
end
self.motorStartDuration = Utils.getNoNil( Utils.getNoNil(getXMLFloat(self.xmlFile, "vehicle.motorStartDuration"), self.motorStartDuration), 0);
self.motorStartTime = 0;
self.lastRoundPerMinute = 0;
self.actualLoadPercentage = 0;
self.maxDecelerationDuringBrake = 0;
self.motorizedDirtyFlag = self:getNextDirtyFlag();
self.isMotorStarted = false;
self.motorStopTimer = g_motorStopTimerDuration
self.fuelFillLevelHud = VehicleHudUtils.loadHud(self, self.xmlFile, "fuel");
self.rpmHud = VehicleHudUtils.loadHud(self, self.xmlFile, "rpm");
self.timeHud = VehicleHudUtils.loadHud(self, self.xmlFile, "time");
if self.timeHud ~= nil then
self.minuteChanged = Utils.appendedFunction(self.minuteChanged, Motorized.minuteChanged);
g_currentMission.environment:addMinuteChangeListener(self);
self:minuteChanged();
end
self.speedHud = VehicleHudUtils.loadHud(self, self.xmlFile, "speed");
self.fuelUsageHud = VehicleHudUtils.loadHud(self, self.xmlFile, "fuelUsage");
if savegame ~= nil then
local fuelFillLevel = getXMLFloat(savegame.xmlFile, savegame.key.."#fuelFillLevel");
if fuelFillLevel ~= nil then
if self.fuelCapacity ~= 0 then
local minFuelFillLevel = 0.1*self.fuelCapacity
local numToRefill = math.max(minFuelFillLevel - fuelFillLevel, 0);
if numToRefill > 0 then
fuelFillLevel = minFuelFillLevel;
local delta = numToRefill * g_currentMission.economyManager:getPricePerLiter(FillUtil.FILLTYPE_FUEL)
g_currentMission.missionStats:updateStats("expenses", delta);
g_currentMission:addSharedMoney(-delta, "purchaseFuel");
end
end
self:setFuelFillLevel(fuelFillLevel);
end
end
self.motorTurnedOnRotationNodes = Utils.loadRotationNodes(self.xmlFile, {}, "vehicle.turnedOnRotationNodes.turnedOnRotationNode", "motor", self.components);
end
--======================================================================================================
-- loadExhaustEffects
--======================================================================================================
-- Description
-- Loading of exhaust effects from xml file
-- Definition
-- loadExhaustEffects(integer xmlFile, table exhaustEffects)
-- Arguments
-- integer xmlFile id of xml object
-- table exhaustEffects table to ass exhaustEffects
--======================================================================================================
-- Code
function Motorized:loadExhaustEffects(xmlFile, exhaustEffects)
local i = 0;
while true do
local key = string.format("vehicle.exhaustEffects.exhaustEffect(%d)", i);
if not hasXMLProperty(xmlFile, key) then
break;
end
local linkNode = Utils.indexToObject(self.components, getXMLString(xmlFile, key.."#index"));
local filename = getXMLString(xmlFile, key .. "#filename");
if filename ~= nil and linkNode ~= nil then
local i3dNode = Utils.loadSharedI3DFile(filename, self.baseDirectory, false, false, false);
if i3dNode ~= 0 then
local node = getChildAt(i3dNode, 0);
if getHasShaderParameter(node, "param") then
local effect = {};
effect.effectNode = node
effect.node = linkNode
effect.filename = filename;
link(effect.node, effect.effectNode);
setVisibility(effect.effectNode, false);
delete(i3dNode);
effect.minRpmColor = Utils.getVectorNFromString(Utils.getNoNil(getXMLString(xmlFile, key.."#minRpmColor"), "0 0 0 1"), 4);
effect.maxRpmColor = Utils.getVectorNFromString(Utils.getNoNil(getXMLString(xmlFile, key.."#maxRpmColor"), "0.0384 0.0359 0.0627 2.0"), 4);
effect.minRpmScale = Utils.getNoNil(getXMLFloat(xmlFile, key.."#minRpmScale"), 0.25);
effect.maxRpmScale = Utils.getNoNil(getXMLFloat(xmlFile, key.."#maxRpmScale"), 0.95);
effect.maxForwardSpeed = Utils.getNoNil(getXMLFloat(xmlFile, key.."#maxForwardSpeed"), math.ceil(self.motor:getMaximumForwardSpeed()*3.6));
effect.maxBackwardSpeed = Utils.getNoNil(getXMLFloat(xmlFile, key.."#maxBackwardSpeed"), math.ceil(self.motor:getMaximumBackwardSpeed()*3.6));
effect.xzRotationsOffset = Utils.getRadiansFromString(Utils.getNoNil(getXMLString(xmlFile, key.."#xzRotationsOffset"), "0 0"), 2);
effect.xzRotationsForward = Utils.getRadiansFromString(Utils.getNoNil(getXMLString(xmlFile, key.."#xzRotationsForward"), "0 0"), 2);
effect.xzRotationsBackward = Utils.getRadiansFromString(Utils.getNoNil(getXMLString(xmlFile, key.."#xzRotationsBackward"), "0 0"), 2);
effect.xzRotationsLeft = Utils.getRadiansFromString(Utils.getNoNil(getXMLString(xmlFile, key.."#xzRotationsLeft"), "0 0"), 2);
effect.xzRotationsRight = Utils.getRadiansFromString(Utils.getNoNil(getXMLString(xmlFile, key.."#xzRotationsRight"), "0 0"), 2);
effect.xRot = 0;
effect.zRot = 0;
table.insert(exhaustEffects, effect);
end
end
end
i = i + 1;
end
self.exhaustEffectMaxSteeringSpeed = 0.001;
end
--======================================================================================================
-- loadDifferentials
--======================================================================================================
-- Description
-- Load differentials from xml
-- Definition
-- loadDifferentials(integer xmlFile, integer configDifferentialIndex)
-- Arguments
-- integer xmlFile id of xml object
-- integer configDifferentialIndex index of differential config
--======================================================================================================
-- Code
function Motorized:loadDifferentials(xmlFile, configDifferentialIndex)
local key,_ = Vehicle.getXMLConfigurationKey(xmlFile, configDifferentialIndex, "vehicle.differentialConfigurations.differentials", "vehicle.differentials", "differential");
self.differentials = {};
if self.isServer and self.motorizedNode ~= nil then
local i = 0;
while true do
local key = string.format(key..".differential(%d)", i);
if not hasXMLProperty(xmlFile, key) then
break;
end
local torqueRatio = Utils.getNoNil(getXMLFloat(xmlFile, key.."#torqueRatio"), 0.5);
local maxSpeedRatio = Utils.getNoNil(getXMLFloat(xmlFile, key.."#maxSpeedRatio"), 1.3);
local diffIndex1, diffIndex1IsWheel;
local diffIndex2, diffIndex2IsWheel;
local wheelIndex1 = getXMLInt(xmlFile, key.."#wheelIndex1");
if wheelIndex1 ~= nil then
local wheel = self.wheels[wheelIndex1+1];
if wheel ~= nil then
diffIndex1IsWheel = true;
diffIndex1 = wheelIndex1+1;
end
else
diffIndex1IsWheel = false;
diffIndex1 = getXMLInt(xmlFile, key.."#differentialIndex1");
end
local wheelIndex2 = getXMLInt(xmlFile, key.."#wheelIndex2");
if wheelIndex2 ~= nil then
local wheel = self.wheels[wheelIndex2+1];
if wheel ~= nil then
diffIndex2IsWheel = true;
diffIndex2 = wheelIndex2+1;
end
else
diffIndex2IsWheel = false;
diffIndex2 = getXMLInt(xmlFile, key.."#differentialIndex2");
end
if diffIndex1 ~= nil and diffIndex2 ~= nil then
table.insert(self.differentials, {torqueRatio=torqueRatio, maxSpeedRatio=maxSpeedRatio, diffIndex1=diffIndex1, diffIndex1IsWheel=diffIndex1IsWheel, diffIndex2=diffIndex2, diffIndex2IsWheel=diffIndex2IsWheel});
addDifferential(self.motorizedNode, diffIndex1IsWheel and self.wheels[diffIndex1].wheelShape or diffIndex1, diffIndex1IsWheel, diffIndex2IsWheel and self.wheels[diffIndex2].wheelShape or diffIndex2, diffIndex2IsWheel, torqueRatio, maxSpeedRatio);
else
print("Error: Invalid differential indices in '"..self.configFileName.."'");
end
i = i + 1;
end
end
end
--======================================================================================================
-- addToPhysics
--======================================================================================================
-- Description
-- Add to physics
-- Definition
-- addToPhysics()
-- Return Values
-- boolean success success
--======================================================================================================
-- Code
function Motorized:addToPhysics(superFunc)
if superFunc ~= nil then
if not superFunc(self) then
return false;
end
end
if self.isServer then
if self.motorizedNode ~= nil then
for _, differential in pairs(self.differentials) do
local diffIndex1IsWheel, diffIndex1, diffIndex2IsWheel, diffIndex2 = differential.diffIndex1IsWheel, differential.diffIndex1, differential.diffIndex2IsWheel, differential.diffIndex2;
if diffIndex1IsWheel then
diffIndex1 = self.wheels[diffIndex1].wheelShape;
end
if diffIndex2IsWheel then
diffIndex2 = self.wheels[diffIndex2].wheelShape;
end
addDifferential(self.motorizedNode, diffIndex1, diffIndex1IsWheel, diffIndex2, diffIndex2IsWheel, differential.torqueRatio, differential.maxSpeedRatio);
end
end
end
return true
end
--======================================================================================================
-- loadMotor
--======================================================================================================
-- Description
-- Load motor from xml file
-- Definition
-- loadMotor(integer xmlFile, integer motorId)
-- Arguments
-- integer xmlFile id of xml object
-- integer motorId index of motor configuration
--======================================================================================================
-- Code
function Motorized:loadMotor(xmlFile, motorId)
local key, motorId = Vehicle.getXMLConfigurationKey(xmlFile, motorId, "vehicle.motorConfigurations.motorConfiguration", "vehicle", "motor");
local fallbackConfigKey = "vehicle.motorConfigurations.motorConfiguration(0)";
local fallbackOldKey = "vehicle";
self.motorType = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#type", getXMLString, "vehicle", fallbackConfigKey, fallbackOldKey);
self.fuelCapacity = Vehicle.getConfigurationValue(xmlFile, key, ".fuelCapacity", "", getXMLFloat, 500, fallbackConfigKey, fallbackOldKey);
local wheelKey, _ = Vehicle.getXMLConfigurationKey(xmlFile, self.configurations["wheel"], "vehicle.wheelConfigurations.wheelConfiguration", "vehicle", "wheels");
self.fuelCapacity = Utils.getNoNil(Vehicle.getConfigurationValue(xmlFile, wheelKey, ".fuelCapacity", "", getXMLInt, nil, nil, ""), self.fuelCapacity);
local fuelUsage = Vehicle.getConfigurationValue(xmlFile, key, ".fuelUsage", "", getXMLFloat, nil, fallbackConfigKey, fallbackOldKey);
if fuelUsage == nil then
fuelUsage = self.fuelCapacity / 5; -- default fuel usage: full->empty: 5h
end
self.fuelUsage = fuelUsage / (60*60*1000); -- from l/h to l/ms
ObjectChangeUtil.updateObjectChanges(xmlFile, "vehicle.motorConfigurations.motorConfiguration", motorId, self.components, self);
local motorMinRpm = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#minRpm", getXMLFloat, 1000, fallbackConfigKey, fallbackOldKey);
local motorMaxRpm = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#maxRpm", getXMLFloat, 1800, fallbackConfigKey, fallbackOldKey);
local minSpeed = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#minSpeed", getXMLFloat, 1, fallbackConfigKey, fallbackOldKey);
local maxForwardSpeed = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#maxForwardSpeed", getXMLFloat, nil, fallbackConfigKey, fallbackOldKey);
local maxBackwardSpeed = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#maxBackwardSpeed", getXMLFloat, nil, fallbackConfigKey, fallbackOldKey);
if maxForwardSpeed ~= nil then
maxForwardSpeed = maxForwardSpeed/3.6;
end
if maxBackwardSpeed ~= nil then
maxBackwardSpeed = maxBackwardSpeed/3.6;
end
local maxWheelSpeed = Vehicle.getConfigurationValue(xmlFile, wheelKey, ".wheels", "#maxForwardSpeed", getXMLFloat, nil, nil, "vehicle.wheels");
if maxWheelSpeed ~= nil then
maxForwardSpeed = maxWheelSpeed/3.6;
end
local brakeForce = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#brakeForce", getXMLFloat, 10, fallbackConfigKey, fallbackOldKey)*2;
local lowBrakeForceScale = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#lowBrakeForceScale", getXMLFloat, 0.5, fallbackConfigKey, fallbackOldKey);
local lowBrakeForceSpeedLimit = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#lowBrakeForceSpeedLimit", getXMLFloat, 20, fallbackConfigKey, fallbackOldKey)/3600;
local forwardGearRatio = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#forwardGearRatio", getXMLFloat, 2, fallbackConfigKey, fallbackOldKey);
local backwardGearRatio = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#backwardGearRatio", getXMLFloat, 1.5, fallbackConfigKey, fallbackOldKey);
local maxForwardGearRatio = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#maxForwardGearRatio", getXMLFloat, nil, fallbackConfigKey, fallbackOldKey);
local minForwardGearRatio = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#minForwardGearRatio", getXMLFloat, nil, fallbackConfigKey, fallbackOldKey);
local maxBackwardGearRatio = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#maxBackwardGearRatio", getXMLFloat, nil, fallbackConfigKey, fallbackOldKey);
local minBackwardGearRatio = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#minBackwardGearRatio", getXMLFloat, nil, fallbackConfigKey, fallbackOldKey);
local rpmFadeOutRange = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#rpmFadeOutRange", getXMLFloat, 20, fallbackConfigKey, fallbackOldKey);
local torqueScale = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#torqueScale", getXMLFloat, 1, fallbackConfigKey, fallbackOldKey);
local ptoMotorRpmRatio = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#ptoMotorRpmRatio", getXMLFloat, 4, fallbackConfigKey, fallbackOldKey);
--local maxTorque = 0;
local maxMotorPower = 0;
local torqueCurve = AnimCurve:new(linearInterpolator1);
local torqueI = 0;
local torqueBase = fallbackOldKey..".motor.torque"; -- fallback to old motor setup
if key ~= nil and hasXMLProperty(xmlFile, fallbackConfigKey..".motor.torque(0)") then -- using default motor configuration
torqueBase = fallbackConfigKey..".motor.torque";
end
if key ~= nil and hasXMLProperty(xmlFile, key..".motor.torque(0)") then -- using selected motor configuration
torqueBase = key..".motor.torque";
end
while true do
local torqueKey = string.format(torqueBase.."(%d)", torqueI);
local normRpm = getXMLFloat(xmlFile, torqueKey.."#normRpm");
local rpm;
if normRpm == nil then
rpm = getXMLFloat(xmlFile, torqueKey.."#rpm");
else
rpm = normRpm * motorMaxRpm;
end
local torque = getXMLFloat(xmlFile, torqueKey.."#torque");
if torque == nil or rpm == nil then
break;
end
torqueCurve:addKeyframe({v=torque*torqueScale, time = rpm});
torqueI = torqueI +1;
local motorPower = 1000 * ( rpm*math.pi/30*(torque*torqueScale) );
if motorPower > maxMotorPower then
maxMotorPower = motorPower;
end
end
if self.motorType == "locomotive" then
self.motor = LocomotiveMotor:new(self, motorMinRpm, motorMaxRpm, maxForwardSpeed, maxBackwardSpeed, torqueCurve, brakeForce, forwardGearRatio, backwardGearRatio, minForwardGearRatio, maxForwardGearRatio, minBackwardGearRatio, maxBackwardGearRatio, ptoMotorRpmRatio, rpmFadeOutRange, 0, maxMotorPower);
else
self.motor = VehicleMotor:new(self, motorMinRpm, motorMaxRpm, maxForwardSpeed, maxBackwardSpeed, torqueCurve, brakeForce, forwardGearRatio, backwardGearRatio, minForwardGearRatio, maxForwardGearRatio, minBackwardGearRatio, maxBackwardGearRatio, ptoMotorRpmRatio, rpmFadeOutRange, 0, maxMotorPower, minSpeed);
end
local rotInertia = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#rotInertia", getXMLFloat, self.motor:getRotInertia(), fallbackConfigKey, fallbackOldKey);
local dampingRate = Vehicle.getConfigurationValue(xmlFile, key, ".motor", "#dampingRate", getXMLFloat, self.motor:getDampingRate(), fallbackConfigKey, fallbackOldKey);
self.motor:setRotInertia(rotInertia);
self.motor:setDampingRate(dampingRate);
self.motor:setLowBrakeForce(lowBrakeForceScale, lowBrakeForceSpeedLimit);
end
--======================================================================================================
-- loadSounds
--======================================================================================================
-- Description
-- Load sounds from xml file
-- Definition
-- loadSounds(integer xmlFile)
-- Arguments
-- integer xmlFile id of xml object
--======================================================================================================
-- Code
function Motorized:loadSounds(xmlFile, motorId)
if self.isClient then
self.sampleRefuel = SoundUtil.loadSample(xmlFile, {}, "vehicle.refuelSound", "$data/maps/sounds/refuel.wav", self.baseDirectory, self.components[1].node);
self.sampleMotorStart = SoundUtil.loadSample(xmlFile, {}, "vehicle.motorStartSound", nil, self.baseDirectory);
self.sampleMotorStop = SoundUtil.loadSample(xmlFile, {}, "vehicle.motorStopSound", nil, self.baseDirectory);
self.sampleMotor = SoundUtil.loadSample(xmlFile, {}, "vehicle.motorSound", nil, self.baseDirectory, self.components[1].node);
self.sampleMotorRun = SoundUtil.loadSample(xmlFile, {}, "vehicle.motorSoundRun", nil, self.baseDirectory, self.components[1].node);
self.sampleMotorLoad = SoundUtil.loadSample(xmlFile, {}, "vehicle.motorSoundLoad", nil, self.baseDirectory, self.components[1].node);
self.sampleGearbox = SoundUtil.loadSample(xmlFile, {}, "vehicle.gearboxSound", nil, self.baseDirectory, self.components[1].node);
self.sampleRetarder = SoundUtil.loadSample(xmlFile, {}, "vehicle.retarderSound", nil, self.baseDirectory, self.components[1].node);
self.sampleBrakeCompressorStart = SoundUtil.loadSample(xmlFile, {}, "vehicle.brakeCompressorStartSound", nil, self.baseDirectory);
self.sampleBrakeCompressorRun = SoundUtil.loadSample(xmlFile, {}, "vehicle.brakeCompressorRunSound", nil, self.baseDirectory);
self.sampleBrakeCompressorStop = SoundUtil.loadSample(xmlFile, {}, "vehicle.brakeCompressorStopSound", nil, self.baseDirectory);
self.sampleReverseDrive = SoundUtil.loadSample(xmlFile, {}, "vehicle.reverseDriveSound", nil, self.baseDirectory);
self.sampleCompressedAir = SoundUtil.loadSample(xmlFile, {}, "vehicle.compressedAirSound", nil, self.baseDirectory);
self.sampleAirReleaseValve = SoundUtil.loadSample(xmlFile, {}, "vehicle.airReleaseValveSound", nil, self.baseDirectory);
local maxRpmDelta = (self.motor:getMaxRpm() - self.motor:getMinRpm());
local maxRpsDelta = maxRpmDelta / 60;
if self.sampleMotor.sample ~= nil then
self.motorSoundPitchMax = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorSound#pitchMax"), 2.0);
self.motorSoundPitchScale = getXMLFloat(xmlFile, "vehicle.motorSound#pitchScale");
if self.motorSoundPitchScale == nil then
self.motorSoundPitchScale = (self.motorSoundPitchMax - self.sampleMotor.pitchOffset) / maxRpsDelta;
end
self.motorSoundVolumeMin = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorSound#volumeMin"), self.sampleMotor.volume);
self.motorSoundVolumeMinSpeed = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorSound#volumeMinSpeed"), math.huge);
end
if self.sampleMotorRun.sample ~= nil then
self.motorSoundRunPitchMax = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorSoundRun#pitchMax"), 2.0);
self.motorSoundRunPitchScale = getXMLFloat(xmlFile, "vehicle.motorSoundRun#pitchScale");
if self.motorSoundRunPitchScale == nil then
self.motorSoundRunPitchScale = (self.motorSoundRunPitchMax - self.sampleMotorRun.pitchOffset) / maxRpsDelta;
end
self.motorSoundRunMinimalVolumeFactor = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorSoundRun#minimalVolumeFactor"), 0.0);
end
if self.sampleMotorLoad.sample ~= nil then
self.motorSoundLoadPitchMax = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorSoundLoad#pitchMax"), 2.0);
self.motorSoundLoadPitchScale = getXMLFloat(xmlFile, "vehicle.motorSoundLoad#pitchScale");
if self.motorSoundLoadPitchScale == nil then
self.motorSoundLoadPitchScale = (self.motorSoundLoadPitchMax - self.sampleMotorLoad.pitchOffset) / maxRpsDelta;
end
self.motorSoundLoadMinimalVolumeFactor = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorSoundLoad#minimalVolumeFactor"), 0.0);
self.motorSoundLoadFactor = 0;
end
if self.sampleGearbox.sample ~= nil then
self.gearboxSoundVolumeMax = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.gearboxSound#volumeMax"), 2.0);
self.gearboxSoundPitchMax = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.gearboxSound#pitchMax"), 2.0);
self.gearboxSoundReverseVolumeMax = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.gearboxSound#reverseVolumeMax"), self.gearboxSoundVolumeMax);
self.gearboxSoundReversePitchMax = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.gearboxSound#reversePitchMax"), self.gearboxSoundPitchMax);
self.gearboxSoundPitchExponent = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.gearboxSound#pitchExponent"), 1.0);
end
if self.sampleRetarder.sample ~= nil then
self.retarderSoundVolumeMax = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.retarderSound#volumeMax"), 2.0);
self.retarderSoundPitchMax = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.retarderSound#pitchMax"), 2.0);
self.retarderSoundMinSpeed = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.retarderSound#minSpeed"), 5.0);
self.retarderSoundActualVolume = 0.0;
end
self.pitchInfluenceFromWheels = 0;
self.volumeInfluenceFromWheels = 0;
self.wheelInfluenceOnGearboxSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.gearboxSound#wheelInfluenceOnVolume"), 0.1);
self.wheelInfluenceOnGearboxSoundPitch = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.gearboxSound#wheelInfluenceOnPitch"), 0.2);
self.wheelInfluenceOnRetarderSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.retarderSound#wheelInfluenceOnVolume"), 0.1);
self.wheelInfluenceOnRetarderSoundPitch = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.retarderSound#wheelInfluenceOnPitch"), 0.2);
if self.sampleBrakeCompressorRun.sample ~= nil then
self.brakeCompressorRunSoundPitchMax = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.brakeCompressorRunSound#pitchMax"), 2.0);
self.brakeCompressorRunSoundPitchScale = getXMLFloat(xmlFile, "vehicle.brakeCompressorRunSound#pitchScale");
if self.brakeCompressorRunSoundPitchScale == nil then
self.brakeCompressorRunSoundPitchScale = (self.brakeCompressorRunSoundPitchMax - self.sampleBrakeCompressorRun.pitchOffset) / maxRpsDelta;
end
end
self.brakeCompressor = {};
self.brakeCompressor.capacity = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.brakeCompressor#capacity"), 6);
self.brakeCompressor.refillFilllevel = math.min(self.brakeCompressor.capacity, Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.brakeCompressor#refillFillLevel"), self.brakeCompressor.capacity/2));
self.brakeCompressor.fillSpeed = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.brakeCompressor#fillSpeed"), 0.6) / 1000;
self.brakeCompressor.fillLevel = 0;
self.brakeCompressor.doFill = true;
self.soundsAdjustedToIndoorCamera = false;
self.compressedAirSoundEnabled = false;
self.compressionSoundTime = 0;
end
end
--======================================================================================================
-- delete
--======================================================================================================
-- Description
-- Called on deleting
-- Definition
-- delete()
--======================================================================================================
-- Code
function Motorized:delete()
if self.timeHud ~= nil then
g_currentMission.environment:removeMinuteChangeListener(self);
end
for _, trigger in pairs(self.fuelFillTriggers) do
trigger:onVehicleDeleted(self);
end
g_currentMission:removeActivatableObject(self.motorizedFillActivatable);
if self.isClient then
if self.exhaustEffects ~= nil then
for _, effect in pairs(self.exhaustEffects) do
Utils.releaseSharedI3DFile(effect.filename, self.baseDirectory, true);
end
end
ParticleUtil.deleteParticleSystems(self.exhaustParticleSystems)
SoundUtil.deleteSample(self.sampleRefuel);
SoundUtil.deleteSample(self.sampleCompressedAir);
SoundUtil.deleteSample(self.sampleAirReleaseValve);
SoundUtil.deleteSample(self.sampleMotor);
SoundUtil.deleteSample(self.sampleMotorRun);
SoundUtil.deleteSample(self.sampleMotorLoad);
SoundUtil.deleteSample(self.sampleGearbox);
SoundUtil.deleteSample(self.sampleRetarder);
SoundUtil.deleteSample(self.sampleMotorStart);
SoundUtil.deleteSample(self.sampleMotorStop);
SoundUtil.deleteSample(self.sampleReverseDrive);
SoundUtil.deleteSample(self.sampleBrakeCompressorStart);
SoundUtil.deleteSample(self.sampleBrakeCompressorRun);
SoundUtil.deleteSample(self.sampleBrakeCompressorStop);
end
end
--======================================================================================================
-- readStream
--======================================================================================================
-- Description
-- Called on client side on join
-- Definition
-- readStream(integer streamId, integer connection)
-- Arguments
-- integer streamId streamId
-- integer connection connection
--======================================================================================================
-- Code
function Motorized:readStream(streamId, connection)
local isMotorStarted = streamReadBool(streamId);
if isMotorStarted then
self:startMotor(true);
else
self:stopMotor(true);
end
local isFuelFilling = streamReadBool(streamId);
self:setIsFuelFilling(isFuelFilling, true);
local newFuelFillLevel=streamReadFloat32(streamId);
self:setFuelFillLevel(newFuelFillLevel);
end
--======================================================================================================
-- writeStream
--======================================================================================================
-- Description
-- Called on server side on join
-- Definition
-- writeStream(integer streamId, integer connection)
-- Arguments
-- integer streamId streamId
-- integer connection connection
--======================================================================================================
-- Code
function Motorized:writeStream(streamId, connection)
streamWriteBool(streamId, self.isMotorStarted);
streamWriteBool(streamId, self.isFuelFilling);
streamWriteFloat32(streamId, self.fuelFillLevel);
end
--======================================================================================================
-- readUpdateStream
--======================================================================================================
-- Description
-- Called on on update
-- Definition
-- readUpdateStream(integer streamId, integer timestamp, table connection)
-- Arguments
-- integer streamId stream ID
-- integer timestamp timestamp
-- table connection connection
--======================================================================================================
-- Code
function Motorized:readUpdateStream(streamId, timestamp, connection)
if connection.isServer then
local rpm = streamReadUIntN(streamId, 11);
rpm = rpm / 2047;
local rpmRange = self.motor:getMaxRpm()- self.motor:getMinRpm();
self.motor:setEqualizedMotorRpm( (rpm * rpmRange) + self.motor:getMinRpm() );
local loadPercentage = streamReadUIntN(streamId, 7);
self.actualLoadPercentage = loadPercentage / 127;
if streamReadBool(streamId) then
local fuelFillLevel = streamReadUIntN(streamId, 15)/32767*self.fuelCapacity;
self:setFuelFillLevel(fuelFillLevel);
end
end
end
--======================================================================================================
-- writeUpdateStream
--======================================================================================================
-- Description
-- Called on on update
-- Definition
-- writeUpdateStream(integer streamId, table connection, integer dirtyMask)
-- Arguments
-- integer streamId stream ID
-- table connection connection
-- integer dirtyMask dirty mask
--======================================================================================================
-- Code
function Motorized:writeUpdateStream(streamId, connection, dirtyMask)
if not connection.isServer then
local rpmRange = self.motor:getMaxRpm() - self.motor:getMinRpm();
local rpm = (self.motor:getEqualizedMotorRpm() - self.motor:getMinRpm()) / rpmRange;
rpm = math.floor(rpm * 2047);
streamWriteUIntN(streamId, rpm, 11);
streamWriteUIntN(streamId, 127 * self.actualLoadPercentage, 7);
if streamWriteBool(streamId, bitAND(dirtyMask, self.motorizedDirtyFlag) ~= 0) then
local percent = 0;
if self.fuelCapacity ~= 0 then
percent = Utils.clamp(self.fuelFillLevel / self.fuelCapacity, 0, 1);
end
streamWriteUIntN(streamId, math.floor(percent*32767), 15);
end
end
end
--======================================================================================================
-- getSaveAttributesAndNodes
--======================================================================================================
-- Description
-- Returns attributes and nodes to save
-- Definition
-- getSaveAttributesAndNodes(table nodeIdent)
-- Arguments
-- table nodeIdent node ident
-- Return Values
-- string attributes attributes
-- string nodes nodes
--======================================================================================================
-- Code
function Motorized:getSaveAttributesAndNodes(nodeIdent)
local attributes = 'fuelFillLevel="'..self.fuelFillLevel..'"';
return attributes, nil;
end
--======================================================================================================
-- update
--======================================================================================================
-- Description
-- Called on update
-- Definition
-- update(float dt)
-- Arguments
-- float dt time since last call in ms
--======================================================================================================
-- Code
function Motorized:update(dt)
if self.isClient then
if InputBinding.hasEvent(InputBinding.TOGGLE_MOTOR_STATE) then
if self.isEntered and self:getIsActiveForInput(false) and not g_currentMission.missionInfo.automaticMotorStartEnabled then
if not self:getIsHired() then
if self.isMotorStarted then
self:stopMotor()
else
self:startMotor()
end
end
end
end
end
Utils.updateRotationNodes(self, self.motorTurnedOnRotationNodes, dt, self:getIsMotorStarted());
if self:getIsMotorStarted() then
local accInput = 0;
if self.axisForward ~= nil then
accInput = -self.axisForward;
end
if self.cruiseControl ~= nil and self.cruiseControl.state ~= Drivable.CRUISECONTROL_STATE_OFF then
accInput = 1;
end
if self.isClient then
if self:getIsActiveForSound() then
if not SoundUtil.isSamplePlaying(self.sampleMotorStart, 1.5*dt) then
SoundUtil.playSample(self.sampleMotor, 0, 0, nil);
SoundUtil.playSample(self.sampleMotorRun, 0, 0, 0);
SoundUtil.playSample(self.sampleMotorLoad, 0, 0, 0);
SoundUtil.playSample(self.sampleGearbox, 0, 0, 0);
SoundUtil.playSample(self.sampleRetarder, 0, 0, 0);
if self.brakeLightsVisibility then
self.brakeLightsVisibilityWasActive = true;
self.maxDecelerationDuringBrake = math.max(self.maxDecelerationDuringBrake, math.abs(accInput));
end
if self.brakeLightsVisibilityWasActive and not self.brakeLightsVisibility then
self.brakeLightsVisibilityWasActive = false;
local factor = self.maxDecelerationDuringBrake;
self.maxDecelerationDuringBrake = 0;
local airConsumption = self:getMaximalAirConsumptionPerFullStop();
-- print( string.format(" -----> factor = %.2f // %.2f ", factor, airConsumption) );
airConsumption = factor * airConsumption;
self.brakeCompressor.fillLevel = math.max(0, self.brakeCompressor.fillLevel - airConsumption); --implementCount * self.brakeCompressor.capacity * 0.05);
end
if self.brakeCompressor.fillLevel < self.brakeCompressor.refillFilllevel then
self.brakeCompressor.doFill = true;
end
if self.brakeCompressor.doFill and self.brakeCompressor.fillLevel == self.brakeCompressor.capacity then
self.brakeCompressor.doFill = false;
end
if self.brakeCompressor.doFill then
self.brakeCompressor.fillLevel = math.min(self.brakeCompressor.capacity, self.brakeCompressor.fillLevel + self.brakeCompressor.fillSpeed * dt);
end
if Vehicle.debugRendering then
renderText(0.3, 0.16, getCorrectTextSize(0.02), string.format("brakeCompressor.fillLevel = %.1f", 100*(self.brakeCompressor.fillLevel / self.brakeCompressor.capacity) ));
end
if not self.brakeCompressor.doFill then
if self.brakeCompressor.runSoundActive then
SoundUtil.stopSample(self.sampleBrakeCompressorRun, true);
SoundUtil.playSample(self.sampleBrakeCompressorStop, 1, 0, nil);
self.brakeCompressor.startSoundPlayed = false;
self.brakeCompressor.runSoundActive = false;
end
elseif not SoundUtil.isSamplePlaying(self.sampleBrakeCompressorStop, 1.5*dt) then
if not self.brakeCompressor.startSoundPlayed then
self.brakeCompressor.startSoundPlayed = true;
SoundUtil.playSample(self.sampleBrakeCompressorStart, 1, 0, nil);
else
if not SoundUtil.isSamplePlaying(self.sampleBrakeCompressorStart, 1.5*dt) and not self.brakeCompressor.runSoundActive then
self.brakeCompressor.runSoundActive = true;
SoundUtil.playSample(self.sampleBrakeCompressorRun, 0, 0, nil);
end
end
end
end
if self.compressionSoundTime <= g_currentMission.time then
SoundUtil.playSample(self.sampleAirReleaseValve, 1, 0, nil);
self.compressionSoundTime = g_currentMission.time + math.random(10000, 40000);
end
if self.sampleCompressedAir.sample ~= nil then
if self.movingDirection > 0 and self.lastSpeed > self.motor:getMaximumForwardSpeed()*0.0002 then -- faster than 20% of max speed
if accInput < -0.05 then
-- play the compressor sound if we drive fast enough and brake
if not self.compressedAirSoundEnabled then
SoundUtil.playSample(self.sampleCompressedAir, 1, 0, nil);
self.compressedAirSoundEnabled = true;
end
else
self.compressedAirSoundEnabled = false;
end
end
end
SoundUtil.stop3DSample(self.sampleMotor);
SoundUtil.stop3DSample(self.sampleMotorRun);
SoundUtil.stop3DSample(self.sampleGearbox);
SoundUtil.stop3DSample(self.sampleRetarder);
else
SoundUtil.play3DSample(self.sampleMotor);
SoundUtil.play3DSample(self.sampleMotorRun);
end
-- adjust pitch and volume of samples
if (self.wheels ~= nil and table.getn(self.wheels) > 0) or (self.dummyWheels ~= nil and table.getn(self.dummyWheels) > 0) then
if self.sampleReverseDrive.sample ~= nil then
if (accInput < 0 or accInput == 0) and (self:getLastSpeed() > 3 and self.movingDirection ~= self.reverserDirection) then
if self:getIsActiveForSound() then
SoundUtil.playSample(self.sampleReverseDrive, 0, 0, nil);
end
else
SoundUtil.stopSample(self.sampleReverseDrive);
end
end
local minRpm = self.motor:getMinRpm();
local maxRpm = self.motor:getMaxRpm();
local maxSpeed;
if self.movingDirection >= 0 then
maxSpeed = self.motor:getMaximumForwardSpeed()*0.001;
else
maxSpeed = self.motor:getMaximumBackwardSpeed()*0.001;
end
local motorRpm = self.motor:getEqualizedMotorRpm();
-- Increase the motor rpm to the max rpm if faster than 75% of the full speed
if self.movingDirection > 0 and self.lastSpeed > 0.75*maxSpeed and motorRpm < maxRpm then
motorRpm = motorRpm + (maxRpm - motorRpm) * math.min((self.lastSpeed-0.75*maxSpeed) / (0.25*maxSpeed), 1);
end
-- The actual rpm offset is 50% from the motor and 50% from the speed
local targetRpmOffset = (motorRpm - minRpm)*0.5 + math.min(self.lastSpeed/maxSpeed, 1)*(maxRpm-minRpm)*0.5;
if Vehicle.debugRendering then
renderText(0.3, 0.14, getCorrectTextSize(0.02), string.format("getLastMotorRpm() = %.2f", self.motor:getLastMotorRpm() ));
renderText(0.3, 0.12, getCorrectTextSize(0.02), string.format("getEqualziedMotorRpm() = %.2f", self.motor:getEqualizedMotorRpm() ));
renderText(0.3, 0.10, getCorrectTextSize(0.02), string.format("targetRpmOffset = %.2f", targetRpmOffset ));
end
local alpha = math.pow(0.01, dt*0.001);
local roundPerMinute = targetRpmOffset + alpha*(self.lastRoundPerMinute-targetRpmOffset);
self.lastRoundPerMinute = roundPerMinute;
local roundPerSecondSmoothed = roundPerMinute / 60;
if self.sampleMotor.sample ~= nil then
local motorSoundPitch = math.min(self.sampleMotor.pitchOffset + self.motorSoundPitchScale*math.abs(roundPerSecondSmoothed), self.motorSoundPitchMax);
SoundUtil.setSamplePitch(self.sampleMotor, motorSoundPitch);
local deltaVolume = (self.sampleMotor.volume - self.motorSoundVolumeMin) * math.max(0.0, math.min(1.0, self:getLastSpeed()/self.motorSoundVolumeMinSpeed))
SoundUtil.setSampleVolume(self.sampleMotor, math.max(self.motorSoundVolumeMin, self.sampleMotor.volume - deltaVolume));
end;
if self.sampleMotorRun.sample ~= nil then
local motorSoundRunPitch = math.min(self.sampleMotorRun.pitchOffset + self.motorSoundRunPitchScale*math.abs(roundPerSecondSmoothed), self.motorSoundRunPitchMax);
SoundUtil.setSamplePitch(self.sampleMotorRun, motorSoundRunPitch);
local runVolume = roundPerMinute/(maxRpm - minRpm);
if math.abs(accInput) < 0.01 or Utils.sign(accInput) ~= self.movingDirection or ptoVolume == 0 then
runVolume = runVolume * 0.9;
end;
runVolume = Utils.clamp(runVolume, 0.0, 1.0);
if Vehicle.debugRendering then
renderText(0.3, 0.08, getCorrectTextSize(0.02), string.format("runVolume = %.2f", runVolume) );
end
if self.sampleMotorLoad.sample == nil then
SoundUtil.setSampleVolume(self.sampleMotorRun, runVolume * self.sampleMotorRun.volume);
else
local motorSoundLoadPitch = math.min(self.sampleMotorLoad.pitchOffset + self.motorSoundLoadPitchScale*math.abs(roundPerSecondSmoothed), self.motorSoundLoadPitchMax);
SoundUtil.setSamplePitch(self.sampleMotorLoad, motorSoundLoadPitch);
if self.motorSoundLoadFactor < self.actualLoadPercentage then
self.motorSoundLoadFactor = math.min(self.actualLoadPercentage, self.motorSoundLoadFactor + dt/500);
elseif self.motorSoundLoadFactor > self.actualLoadPercentage then
self.motorSoundLoadFactor = math.max(self.actualLoadPercentage, self.motorSoundLoadFactor - dt/750);
end
if Vehicle.debugRendering then
renderText(0.3, 0.06, getCorrectTextSize(0.02), string.format("motorSoundLoadFactor = %.2f", self.motorSoundLoadFactor) );
end
SoundUtil.setSampleVolume(self.sampleMotorRun, math.max(self.motorSoundRunMinimalVolumeFactor, (1.0 - self.motorSoundLoadFactor) * runVolume * self.sampleMotorRun.volume) );
SoundUtil.setSampleVolume(self.sampleMotorLoad, math.max(self.motorSoundLoadMinimalVolumeFactor, self.motorSoundLoadFactor * runVolume * self.sampleMotorLoad.volume) );
end
end
--
local pitchInfluence = 0;
local volumeInfluence = 0;
for i,wheel in pairs(self.wheels) do
-- as in debug rendering, is this still correct?
local susp = (wheel.netInfo.y - wheel.netInfo.yMin)/wheel.suspTravel - 0.2; -- If at yMin, we have -20% compression
if wheel.netInfo.lastSusp == nil then
wheel.netInfo.lastSusp = susp;
end
local delta = susp - wheel.netInfo.lastSusp;
pitchInfluence = pitchInfluence + delta;
volumeInfluence = volumeInfluence + math.abs(delta);
end
pitchInfluence = pitchInfluence / table.getn(self.wheels);
volumeInfluence = volumeInfluence / table.getn(self.wheels);
if pitchInfluence > self.pitchInfluenceFromWheels then
self.pitchInfluenceFromWheels = math.min(pitchInfluence, self.pitchInfluenceFromWheels + dt/300);
elseif pitchInfluence < self.pitchInfluenceFromWheels then
self.pitchInfluenceFromWheels = math.max(pitchInfluence, self.pitchInfluenceFromWheels - dt/300);
end
if volumeInfluence > self.volumeInfluenceFromWheels then
self.volumeInfluenceFromWheels = math.min(volumeInfluence, self.volumeInfluenceFromWheels + dt/300);
elseif volumeInfluence < self.volumeInfluenceFromWheels then
self.volumeInfluenceFromWheels = math.max(volumeInfluence, self.volumeInfluenceFromWheels - dt/300);
end
--renderText(0.8, 0.48, getCorrectTextSize(0.02), string.format("pitchInfluence = %.2f", pitchInfluence ));
--renderText(0.7, 0.60, getCorrectTextSize(0.02), string.format("self.pitchInfluenceFromWheels = %.5f", self.pitchInfluenceFromWheels ));
--renderText(0.7, 0.58, getCorrectTextSize(0.02), string.format("self.volumeInfluenceFromWheels = %.5f", self.volumeInfluenceFromWheels ));
--
if self.sampleGearbox.sample ~= nil then
local speedFactor = Utils.clamp( (self:getLastSpeed() - 1) / math.ceil(self.motor:getMaximumForwardSpeed()*3.6), 0, 1);
local pitchGearbox = Utils.lerp(self.sampleGearbox.pitchOffset, self.gearboxSoundPitchMax, speedFactor^self.gearboxSoundPitchExponent);
local volumeGearbox = Utils.lerp(self.sampleGearbox.volume, self.gearboxSoundVolumeMax, speedFactor);
if self.reverserDirection ~= self.movingDirection then
speedFactor = Utils.clamp( (self:getLastSpeed() - 1) / math.ceil(self.motor:getMaximumBackwardSpeed()*3.6), 0, 1);
pitchGearbox = Utils.lerp(self.sampleGearbox.pitchOffset, self.gearboxSoundReversePitchMax, speedFactor^self.gearboxSoundPitchExponent);
volumeGearbox = Utils.lerp(self.sampleGearbox.volume, self.gearboxSoundReverseVolumeMax, speedFactor);
end
SoundUtil.setSamplePitch(self.sampleGearbox, pitchGearbox);
SoundUtil.setSampleVolume(self.sampleGearbox, volumeGearbox);
end
if self.sampleRetarder.sample ~= nil then
local speedFactor = Utils.clamp( (self:getLastSpeed() - self.retarderSoundMinSpeed) / math.ceil(self.motor:getMaximumForwardSpeed()*3.6), 0, 1);
local pitchGearbox = Utils.lerp(self.sampleRetarder.pitchOffset, self.retarderSoundPitchMax, speedFactor);
SoundUtil.setSamplePitch(self.sampleRetarder, pitchGearbox);
local volumeRetarder = Utils.lerp(self.sampleRetarder.volume, self.retarderSoundVolumeMax, speedFactor);
local targetVolume = 0.0;
if accInput <= 0.0 and self:getLastSpeed() > self.retarderSoundMinSpeed and self.reverserDirection == self.movingDirection then
if accInput > -0.9 then
targetVolume = volumeRetarder;
else
targetVolume = self.sampleRetarder.volume;
end
end
if self.retarderSoundActualVolume < targetVolume then
self.retarderSoundActualVolume = math.min(targetVolume, self.retarderSoundActualVolume + dt/self.axisSmoothTime);
elseif self.retarderSoundActualVolume > targetVolume then
self.retarderSoundActualVolume = math.max(targetVolume, self.retarderSoundActualVolume - dt/self.axisSmoothTime);
end
SoundUtil.setSampleVolume(self.sampleRetarder, self.retarderSoundActualVolume);
if Vehicle.debugRendering then
renderText(0.8, 0.44, getCorrectTextSize(0.02), string.format("retarderSoundActualVolume = %.2f", self.retarderSoundActualVolume ));
renderText(0.8, 0.42, getCorrectTextSize(0.02), string.format("getLastSpeed() = %.2f", self:getLastSpeed() ));
end
end
if self.sampleBrakeCompressorRun.sample ~= nil then
local pitchCompressor = math.min(self.sampleBrakeCompressorRun.pitchOffset + self.brakeCompressorRunSoundPitchScale*math.abs(roundPerSecondSmoothed), self.brakeCompressorRunSoundPitchMax);
SoundUtil.setSamplePitch(self.sampleBrakeCompressorRun, pitchCompressor);
end
end
end
if self.isServer then
if not self:getIsHired() then
if self.lastMovedDistance > 0 then
g_currentMission.missionStats:updateStats("traveledDistance", self.lastMovedDistance*0.001);
end
end
self:updateFuelUsage(dt)
end
end
end
--======================================================================================================
-- updateTick
--======================================================================================================
-- Description
-- Called on update tick
-- Definition
-- updateTick(float dt)
-- Arguments
-- float dt time since last call in ms
--======================================================================================================
-- Code
function Motorized:updateTick(dt)
if self.isServer then
-- compare power
--local torque,_ = self.motor:getTorque(1, false)*1000;
--local motorPower = self.motor:getNonClampedMotorRpm()*math.pi/30*torque -- [kW]
--
--self.actualLoadPercentage = motorPower / self.motor.maxMotorPower;
-- compare torque I
self.actualLoadPercentage = self.motor:getMotorLoad() / self.motor.maxMotorTorque;
-- compare torque II
--local torque,_ = self.motor:getTorque(1, false)*1000;
--self.actualLoadPercentage = (self.motor:getMotorLoad() * 1000 / torque);
if self:getIsActive() then
--print(" --------------------- ");
--print( string.format(" %.2f <= %.2f / %.2f", self.actualLoadPercentage, motorPower, self.motor.maxMotorPower) );
--print( string.format(" %.2f <= %.2f / %.2f", self.actualLoadPercentage, self.motor:getMotorLoad(), self.motor.maxMotorTorque) );
--print( string.format(" %.2f <= %.2f / %.2f", self.actualLoadPercentage, self.motor:getMotorLoad() * 1000, torque) );
end
local neededPtoTorque = PowerConsumer.getTotalConsumedPtoTorque(self);
if neededPtoTorque > 0 then
local ptoLoad = (neededPtoTorque / self.motor.ptoMotorRpmRatio) / self.motor.maxMotorTorque;
self.actualLoadPercentage = math.min(1.0, self.actualLoadPercentage + ptoLoad);
end
if math.abs(self.fuelFillLevel-self.sentFuelFillLevel) > 0.001 then
self:raiseDirtyFlags(self.motorizedDirtyFlag);
self.sentFuelFillLevel = self.fuelFillLevel;
end
if self.isMotorStarted and not self.isControlled and not self.isEntered and not self:getIsHired() and not g_currentMission.missionInfo.automaticMotorStartEnabled then
local isPlayerInRange = false
local vx, vy, vz = getWorldTranslation(self.rootNode);
for _, player in pairs(g_currentMission.players) do
if player.isControlled then
local px, py, pz = getWorldTranslation(player.rootNode);
local distance = Utils.vector3Length(px-vx, py-vy, pz-vz);
if distance < 250 then
isPlayerInRange = true
break
end
end;
end;
if not isPlayerInRange then
for _, steerable in pairs(g_currentMission.steerables) do
if steerable.isControlled then
local px, py, pz = getWorldTranslation(steerable.rootNode);
local distance = Utils.vector3Length(px-vx, py-vy, pz-vz);
if distance < 250 then
isPlayerInRange = true
break
end
end;
end;
end
if isPlayerInRange then
self.motorStopTimer = g_motorStopTimerDuration
else
self.motorStopTimer = self.motorStopTimer - dt
if self.motorStopTimer <= 0 then
self:stopMotor()
end
end
end
end
if self.isClient then
if self:getIsMotorStarted() then
if self.rpmHud ~= nil then
VehicleHudUtils.setHudValue(self, self.rpmHud, self.motor:getEqualizedMotorRpm(), self.motor:getMaxRpm());
end
if self.speedHud ~= nil then
local maxSpeed = 30;
if self.cruiseControl ~= nil then
maxSpeed = self.cruiseControl.maxSpeed;
end
VehicleHudUtils.setHudValue(self, self.speedHud, g_i18n:getSpeed(self:getLastSpeed() * self.speedDisplayScale), g_i18n:getSpeed(maxSpeed));
end
if self.exhaustParticleSystems ~= nil then
for _, ps in pairs(self.exhaustParticleSystems) do
local scale = Utils.lerp(self.exhaustParticleSystems.minScale, self.exhaustParticleSystems.maxScale, self.motor:getEqualizedMotorRpm() / self.motor:getMaxRpm());
ParticleUtil.setEmitCountScale(self.exhaustParticleSystems, scale);
ParticleUtil.setParticleLifespan(ps, ps.originalLifespan * scale)
end
end
if self.exhaustFlap ~= nil then
local minRandom = -0.1;
local maxRandom = 0.1;
local angle = Utils.lerp(minRandom, maxRandom, math.random()) + self.exhaustFlap.maxRot * (self.motor:getEqualizedMotorRpm() / self.motor:getMaxRpm());
angle = Utils.clamp(angle, 0, self.exhaustFlap.maxRot);
setRotation(self.exhaustFlap.node, angle, 0, 0);
end
if self.exhaustEffects ~= nil then
local lastSpeed = self:getLastSpeed();
self.currentDirection = {localDirectionToWorld(self.rootNode, 0, 0, 1)};
if self.lastDirection == nil then
self.lastDirection = self.currentDirection;
end
local x,y,z = worldDirectionToLocal(self.rootNode, self.lastDirection[1], self.lastDirection[2], self.lastDirection[3]);
local dot = z;
dot = dot / Utils.vector2Length(x,z);
local angle = math.acos(dot);
if x < 0 then
angle = -angle;
end
local steeringPercent = math.abs((angle / dt) / self.exhaustEffectMaxSteeringSpeed);
self.lastDirection = self.currentDirection;
for _, effect in pairs(self.exhaustEffects) do
local rpmScale = self.motor:getEqualizedMotorRpm() / self.motor:getMaxRpm();
local scale = Utils.lerp(effect.minRpmScale, effect.maxRpmScale, rpmScale);
local forwardXRot = 0;
local forwardZRot = 0;
local steerXRot = 0;
local steerZRot = 0;
local r = Utils.lerp(effect.minRpmColor[1], effect.maxRpmColor[1], rpmScale);
local g = Utils.lerp(effect.minRpmColor[2], effect.maxRpmColor[2], rpmScale);
local b = Utils.lerp(effect.minRpmColor[3], effect.maxRpmColor[3], rpmScale);
local a = Utils.lerp(effect.minRpmColor[4], effect.maxRpmColor[4], rpmScale);
setShaderParameter(effect.effectNode, "exhaustColor", r, g, b, a, false);
-- speed rotation
if self.movingDirection == 1 then
local percent = Utils.clamp(lastSpeed/effect.maxForwardSpeed, 0, 1);
forwardXRot = effect.xzRotationsForward[1] * percent;
forwardZRot = effect.xzRotationsForward[2] * percent;
elseif self.movingDirection == -1 then
local percent = Utils.clamp(lastSpeed/effect.maxBackwardSpeed, 0, 1);
forwardXRot = effect.xzRotationsBackward[1] * percent;
forwardZRot = effect.xzRotationsBackward[2] * percent;
end
-- steering rotation
if angle > 0 then
steerXRot = effect.xzRotationsRight[1] * steeringPercent;
steerZRot = effect.xzRotationsRight[2] * steeringPercent;
elseif angle < 0 then
steerXRot = effect.xzRotationsLeft[1] * steeringPercent;
steerZRot = effect.xzRotationsLeft[2] * steeringPercent;
end
-- target rotations
local targetXRot = effect.xzRotationsOffset[1] + forwardXRot + steerXRot;
local targetZRot = effect.xzRotationsOffset[2] + forwardZRot + steerZRot;
-- damping
if targetXRot > effect.xRot then
effect.xRot = math.min(effect.xRot + 0.003*dt, targetXRot);
else
effect.xRot = math.max(effect.xRot - 0.003*dt, targetXRot);
end
if targetZRot > effect.xRot then
effect.zRot = math.min(effect.zRot + 0.003*dt, targetZRot);
else
effect.zRot = math.max(effect.zRot - 0.003*dt, targetZRot);
end
setShaderParameter(effect.effectNode, "param", effect.xRot, effect.zRot, 0, scale, false);
end
end
end
end
if self.isFuelFilling then
if self.isServer then
local delta = 0;
if self.fuelFillTrigger ~= nil then
delta = self.fuelFillLitersPerSecond*dt*0.001;
delta = self.fuelFillTrigger:fillFuel(self, delta);
end
if delta <= 0.001 then
self:setIsFuelFilling(false);
end
end
end
end
--======================================================================================================
-- draw
--======================================================================================================
-- Description
-- Called on draw
-- Definition
-- draw()
--======================================================================================================
-- Code
function Motorized:draw()
if self.isEntered and self.isClient and not self:getIsHired() then
if not g_currentMission.missionInfo.automaticMotorStartEnabled then
if self.isMotorStarted then
g_currentMission:addHelpButtonText(g_i18n:getText("action_stopMotor"), InputBinding.TOGGLE_MOTOR_STATE, nil, GS_PRIO_VERY_HIGH);
else
g_currentMission:addHelpButtonText(g_i18n:getText("action_startMotor"), InputBinding.TOGGLE_MOTOR_STATE, nil, GS_PRIO_VERY_HIGH);
end
end
end
end
--======================================================================================================
-- startMotor
--======================================================================================================
-- Description
-- Start motor
-- Definition
-- startMotor(boolean noEventSend)
-- Arguments
-- boolean noEventSend no event send
--======================================================================================================
-- Code
function Motorized:startMotor(noEventSend)
if noEventSend == nil or noEventSend == false then
if g_server ~= nil then
g_server:broadcastEvent(SetMotorTurnedOnEvent:new(self, true), nil, nil, self);
else
g_client:getServerConnection():sendEvent(SetMotorTurnedOnEvent:new(self, true));
end
end
if not self.isMotorStarted then
self.isMotorStarted = true;
if self.isClient then
if self.exhaustParticleSystems ~= nil then
for _, ps in pairs(self.exhaustParticleSystems) do
ParticleUtil.setEmittingState(ps, true)
end
end
if self:getIsActiveForSound() then
SoundUtil.playSample(self.sampleMotorStart, 1, 0, nil);
end
if self.exhaustEffects ~= nil then
for _, effect in pairs(self.exhaustEffects) do
setVisibility(effect.effectNode, true);
effect.xRot = effect.xzRotationsOffset[1];
effect.zRot = effect.xzRotationsOffset[2];
setShaderParameter(effect.effectNode, "param", effect.xRot, effect.zRot, 0, 0, false);
local color = effect.minRpmColor;
setShaderParameter(effect.effectNode, "exhaustColor", color[1], color[2], color[3], color[4], false);
end
end
end
self.motorStartTime = g_currentMission.time + self.motorStartDuration;
self.compressionSoundTime = g_currentMission.time + math.random(5000, 20000);
self.lastRoundPerMinute=0;
if self.fuelFillLevelHud ~= nil then
VehicleHudUtils.setHudValue(self, self.fuelFillLevelHud, self.fuelFillLevel, self.fuelCapacity);
end
end
end
--======================================================================================================
-- stopMotor
--======================================================================================================
-- Description
-- Stop motor
-- Definition
-- stopMotor(boolean noEventSend)
-- Arguments
-- boolean noEventSend no event send
--======================================================================================================
-- Code
function Motorized:stopMotor(noEventSend)
if noEventSend == nil or noEventSend == false then
if g_server ~= nil then
g_server:broadcastEvent(SetMotorTurnedOnEvent:new(self, false), nil, nil, self);
else
g_client:getServerConnection():sendEvent(SetMotorTurnedOnEvent:new(self, false));
end
end
self.isMotorStarted = false;
Motorized.onDeactivateSounds(self);
if self.isClient then
if self.exhaustParticleSystems ~= nil then
for _, ps in pairs(self.exhaustParticleSystems) do
ParticleUtil.setEmittingState(ps, false)
end
end
if self:getIsActiveForSound() then
SoundUtil.playSample(self.sampleMotorStop, 1, 0, nil);
SoundUtil.playSample(self.sampleBrakeCompressorStop, 1, 0, nil);
end
local airConsumption = self:getMaximalAirConsumptionPerFullStop();
self.brakeCompressor.fillLevel = math.max(0, self.brakeCompressor.fillLevel - airConsumption);
self.brakeCompressor.startSoundPlayed = false;
self.brakeCompressor.runSoundActive = false;
if self.exhaustEffects ~= nil then
for _, effect in pairs(self.exhaustEffects) do
setVisibility(effect.effectNode, false);
end
end
if self.exhaustFlap ~= nil then
setRotation(self.exhaustFlap.node, 0, 0, 0);
end
if self.rpmHud ~= nil then
VehicleHudUtils.setHudValue(self, self.rpmHud, 0, self.motor:getMaxRpm());
end
if self.speedHud ~= nil then
VehicleHudUtils.setHudValue(self, self.speedHud, 0, g_i18n:getSpeed(self.motor:getMaximumForwardSpeed()));
end
if self.fuelFillLevelHud ~= nil then
VehicleHudUtils.setHudValue(self, self.fuelFillLevelHud, 0, self.fuelCapacity);
end
end
Motorized.turnOffImplement(self);
end
--======================================================================================================
-- turnOffImplement
--======================================================================================================
-- Description
-- Turn off implement and childs of implement
-- Definition
-- turnOffImplement(table object)
-- Arguments
-- table object object to turn off
--======================================================================================================
-- Code
function Motorized.turnOffImplement(object)
if object.setIsTurnedOn ~= nil then
object:setIsTurnedOn(false, true);
end
for _,implement in pairs(object.attachedImplements) do
if implement.object ~= nil then
Motorized.turnOffImplement(implement.object);
end
end
end
--======================================================================================================
-- onDeactivateSounds
--======================================================================================================
-- Description
-- Called on deactivating sounds
-- Definition
-- onDeactivateSounds()
--======================================================================================================
-- Code
function Motorized:onDeactivateSounds()
if self.isClient then
SoundUtil.stopSample(self.sampleMotor, true);
SoundUtil.stopSample(self.sampleMotorRun, true);
SoundUtil.stopSample(self.sampleMotorLoad, true);
SoundUtil.stopSample(self.sampleGearbox, true);
SoundUtil.stopSample(self.sampleRetarder, true);
SoundUtil.stopSample(self.sampleMotorStart, true);
SoundUtil.stopSample(self.sampleBrakeCompressorStart, true);
SoundUtil.stopSample(self.sampleBrakeCompressorRun, true);
SoundUtil.stopSample(self.sampleAirReleaseValve, true);
SoundUtil.stopSample(self.sampleReverseDrive, true);
SoundUtil.stop3DSample(self.sampleMotor, true);
SoundUtil.stop3DSample(self.sampleMotorRun, true);
end
end
--======================================================================================================
-- onEnter
--======================================================================================================
-- Description
-- Called on enter vehicle
-- Definition
-- onEnter(boolean isControlling)
-- Arguments
-- boolean isControlling is player controlling the vehicle
--======================================================================================================
-- Code
function Motorized:onEnter(isControlling)
if g_currentMission.missionInfo.automaticMotorStartEnabled then
self:startMotor(true)
end
end
--======================================================================================================
-- onLeave
--======================================================================================================
-- Description
-- Called on leaving the vehicle
-- Definition
-- onLeave()
--======================================================================================================
-- Code
function Motorized:onLeave()
if self.stopMotorOnLeave and g_currentMission.missionInfo.automaticMotorStartEnabled then
self:stopMotor(true);
end
Motorized.onDeactivateSounds(self);
end
--======================================================================================================
-- setFuelFillLevel
--======================================================================================================
-- Description
-- Set fuel fill level
-- Definition
-- setFuelFillLevel(float newFillLevel)
-- Arguments
-- float newFillLevel new fuel fill level
--======================================================================================================
-- Code
function Motorized:setFuelFillLevel(newFillLevel)
self.fuelFillLevel = math.max(math.min(newFillLevel, self.fuelCapacity), 0);
if self.fuelFillLevelHud ~= nil and math.abs(self.lastFuelFillLevel-self.fuelFillLevel) > 0.1 then
VehicleHudUtils.setHudValue(self, self.fuelFillLevelHud, self.fuelFillLevel, self.fuelCapacity);
self.lastFuelFillLevel = self.fuelFillLevel;
end
if self.fuelFillLevel == 0 and self:getIsHired() then
self:stopAIVehicle(AIVehicle.STOP_REASON_OUT_OF_FUEL)
end
end
--======================================================================================================
-- updateFuelUsage
--======================================================================================================
-- Description
-- Update fuel usage
-- Definition
-- updateFuelUsage(float dt)
-- Arguments
-- float dt time since last call in ms
-- Return Values
-- boolean success success
--======================================================================================================
-- Code
function Motorized:updateFuelUsage(superFunc, dt)
if superFunc ~= nil then
if not superFunc(self, dt) then
return false
end
end
local rpmFactor = math.max(0.02, (self.motor:getLastMotorRpm()-self.motor:getMinRpm())/(self.motor:getMaxRpm()-self.motor:getMinRpm()));
local loadFactor = self.motorSoundLoadFactor
local fuelUsageFactor = 1
if g_currentMission.missionInfo.fuelUsageLow then
fuelUsageFactor = 0.7
end
local fuelUsed = fuelUsageFactor * rpmFactor * (self.fuelUsage * dt);
if fuelUsed > 0 then
if not self:getIsHired() or not g_currentMission.missionInfo.helperBuyFuel then
self:setFuelFillLevel(self.fuelFillLevel-fuelUsed);
g_currentMission.missionStats:updateStats("fuelUsage", fuelUsed);
elseif self:getIsHired() and g_currentMission.missionInfo.helperBuyFuel then
local delta = fuelUsed * g_currentMission.economyManager:getPricePerLiter(FillUtil.FILLTYPE_FUEL)
g_currentMission.missionStats:updateStats("expenses", delta);
g_currentMission:addSharedMoney(-delta, "purchaseFuel");
end
end
if self.fuelUsageHud ~= nil then
VehicleHudUtils.setHudValue(self, self.fuelUsageHud, fuelUsed*1000/dt*60*60);
end
return true
end
--======================================================================================================
-- setIsFuelFilling
--======================================================================================================
-- Description
-- Set is fuel filling
-- Definition
-- setIsFuelFilling(boolean isFilling, boolean noEventSend)
-- Arguments
-- boolean isFilling new is filling state
-- boolean noEventSend no event send
--======================================================================================================
-- Code
function Motorized:setIsFuelFilling(isFilling, noEventSend)
if isFilling ~= self.isFuelFilling then
if noEventSend == nil or noEventSend == false then
if g_server ~= nil then
g_server:broadcastEvent(SteerableToggleRefuelEvent:new(self, isFilling), nil, nil, self);
else
g_client:getServerConnection():sendEvent(SteerableToggleRefuelEvent:new(self, isFilling));
end
end
self.isFuelFilling = isFilling;
if isFilling then
-- find the first trigger which is activable
self.fuelFillTrigger = nil;
for i=1, table.getn(self.fuelFillTriggers) do
local trigger = self.fuelFillTriggers[i];
if trigger:getIsActivatable(self) then
self.fuelFillTrigger = trigger;
break;
end
end
end
if self.isClient and self.sampleRefuel ~= nil then
if isFilling then
SoundUtil.play3DSample(self.sampleRefuel);
else
SoundUtil.stop3DSample(self.sampleRefuel);
end
end
end
end
--======================================================================================================
-- addFuelFillTrigger
--======================================================================================================
-- Description
-- Adds fuel fill trigger if vehicle enters one
-- Definition
-- addFuelFillTrigger(table trigger)
-- Arguments
-- table trigger trigger
--======================================================================================================
-- Code
function Motorized:addFuelFillTrigger(trigger)
if table.getn(self.fuelFillTriggers) == 0 then
g_currentMission:addActivatableObject(self.motorizedFillActivatable);
end
table.insert(self.fuelFillTriggers, trigger);
end
--======================================================================================================
-- removeFuelFillTrigger
--======================================================================================================
-- Description
-- Removes fuel fill trigger if vehicle leaves one
-- Definition
-- removeFuelFillTrigger(table trigger)
-- Arguments
-- table trigger trigger
--======================================================================================================
-- Code
function Motorized:removeFuelFillTrigger(trigger)
for i=1, table.getn(self.fuelFillTriggers) do
if self.fuelFillTriggers[i] == trigger then
table.remove(self.fuelFillTriggers, i);
break;
end
end
if table.getn(self.fuelFillTriggers) == 0 or trigger == self.fuelFillTrigger then
if self.isServer then
self:setIsFuelFilling(false);
end
if table.getn(self.fuelFillTriggers) == 0 then
g_currentMission:removeActivatableObject(self.motorizedFillActivatable);
end
end
end
--======================================================================================================
-- getIsMotorStarted
--======================================================================================================
-- Description
-- Returns if motor is stated
-- Definition
-- getIsMotorStarted()
-- Return Values
-- boolean isStarted motor is started
--======================================================================================================
-- Code
function Motorized:getIsMotorStarted(superFunc)
local parent = true;
if superFunc ~= nil then
parent = parent and superFunc(self);
end
return parent and self.isMotorStarted
end;
--======================================================================================================
-- getDeactivateOnLeave
--======================================================================================================
-- Description
-- Returns if vehicle deactivates on leave
-- Definition
-- getDeactivateOnLeave()
-- Return Values
-- boolean deactivate vehicle deactivates on leave
--======================================================================================================
-- Code
function Motorized:getDeactivateOnLeave(superFunc)
local deactivate = true
if superFunc ~= nil then
deactivate = deactivate and superFunc(self)
end
return deactivate and g_currentMission.missionInfo.automaticMotorStartEnabled
end;
--======================================================================================================
-- getDeactivateLights
--======================================================================================================
-- Description
-- Returns if light deactivate on leaving
-- Definition
-- getDeactivateLights()
-- Return Values
-- boolean deactivate deactivate on leaving
--======================================================================================================
-- Code
function Motorized:getDeactivateLights(superFunc)
local deactivate = true
if superFunc ~= nil then
deactivate = deactivate and superFunc(self)
end
return deactivate and g_currentMission.missionInfo.automaticMotorStartEnabled
end;
--======================================================================================================
-- minuteChanged
--======================================================================================================
-- Description
-- Called if ingame minute changes
-- Definition
-- minuteChanged()
--======================================================================================================
-- Code
function Motorized:minuteChanged()
local minutes = g_currentMission.environment.currentMinute;
local hours = g_currentMission.environment.currentHour;
local minutesString = string.format("%02d", minutes);
VehicleHudUtils.setHudValue(self, self.timeHud, tonumber(hours.."."..minutesString), 9999);
end | gpl-3.0 |
dvv/u-gotta-luvit | example.lua | 1 | 3586 | require('lib/util')
local Stack = require('lib/stack')
--[[
*
* Application
*
]]--
local function authenticate(session, credentials, cb)
-- N.B. this is simple "toggle" logic.
-- in real world you should check credentials passed in `credentials`
-- to decide whether to let user in.
-- just assign `null` to session in case of error.
-- session already set? drop session
if session then
session = nil
-- no session so far? get new session
else
session = {
uid = tostring(require('math').random()):sub(3),
}
end
-- set the session
cb(session)
end
local function authorize(session, cb)
-- N.B. this is a simple wrapper for static context
-- in real world you should vary capabilities depending on the
-- current user defined in `session`
if session and session.uid then
cb({
uid = session.uid,
-- GET /foo?bar=baz ==> this.foo.query('bar=baz')
foo = {
query = function(query, cb)
cb(nil, {['you are'] = 'an authorized user!'})
end
},
bar = {
baz = {
add = function(data, cb)
cb({['nope'] = 'nomatter you are an authorized user ;)'})
end
}
},
context = {
query = function(query, cb)
cb(nil, session or {})
end
},
})
else
cb({
-- GET /foo?bar=baz ==> this.foo.query('bar=baz')
foo = {
query = function(query, cb)
cb(nil, {['you are'] = 'a guest!'})
end
},
context = {
query = function(query, cb)
cb(nil, session or {})
end
},
})
end
end
local function layers() return {
-- test serving requested amount of octets
function(req, res, nxt)
local n = tonumber(req.url:sub(2), 10)
if not n then nxt() return end
local s = String.rep(' ', n)
res:write_head(200, {
['Content-Type'] = 'text/plain',
['Content-Length'] = s:len()
})
res:safe_write(s, function()
res:finish()
end)
end,
-- serve static files
Stack.use('static')('/public/', 'public/', {
-- should the `file` contents be cached?
--is_cacheable = function(file) return file.size <= 65536 end,
is_cacheable = function(file) return true end,
}),
-- handle session
Stack.use('session')({
secret = 'change-me-in-production',
ttl = 15 * 60 * 1000,
-- called to get current user capabilities
authorize = authorize,
}),
-- parse request body
Stack.use('body')(),
-- process custom routes
Stack.use('route')({
-- serve chrome page
['GET /'] = function(req, res, params, nxt)
res:render('index.html', req.context, {renderer = String.interp})
end,
['GET /foo'] = function(req, res, params, nxt)
res:send(200, 'FOOO', {})
end,
}),
-- handle authentication
Stack.use('auth')('/rpc/auth', {
-- called to get current user capabilities
authenticate = authenticate,
}),
-- RPC & REST
Stack.use('rest')('/rpc/'),
-- GET
function (req, res, nxt)
--d(req)
local data = req.session and req.session.uid or 'Мир'
local s = ('Привет, ' .. data) --:rep(100)
res:write_head(200, {
['Content-Type'] = 'text/plain',
['Content-Length'] = s:len()
})
res:write(s)
res:close()
end,
-- report health status to load balancer
Stack.use('health')(),
}end
Stack(layers()):run(65401)
print('Server listening at http://localhost:65401/')
--Stack.create_server(stack(), 65402)
--Stack.create_server(stack(), 65403)
--Stack.create_server(stack(), 65404)
| mit |
firedtoad/skynet | service/multicastd.lua | 16 | 5570 | local skynet = require "skynet"
local mc = require "skynet.multicast.core"
local datacenter = require "skynet.datacenter"
local harbor_id = skynet.harbor(skynet.self())
local command = {}
local channel = {}
local channel_n = {}
local channel_remote = {}
local channel_id = harbor_id
local NORET = {}
local function get_address(t, id)
local v = assert(datacenter.get("multicast", id))
t[id] = v
return v
end
local node_address = setmetatable({}, { __index = get_address })
-- new LOCAL channel , The low 8bit is the same with harbor_id
function command.NEW()
while channel[channel_id] do
channel_id = mc.nextid(channel_id)
end
channel[channel_id] = {}
channel_n[channel_id] = 0
local ret = channel_id
channel_id = mc.nextid(channel_id)
return ret
end
-- MUST call by the owner node of channel, delete a remote channel
function command.DELR(source, c)
channel[c] = nil
channel_n[c] = nil
return NORET
end
-- delete a channel, if the channel is remote, forward the command to the owner node
-- otherwise, delete the channel, and call all the remote node, DELR
function command.DEL(source, c)
local node = c % 256
if node ~= harbor_id then
skynet.send(node_address[node], "lua", "DEL", c)
return NORET
end
local remote = channel_remote[c]
channel[c] = nil
channel_n[c] = nil
channel_remote[c] = nil
if remote then
for node in pairs(remote) do
skynet.send(node_address[node], "lua", "DELR", c)
end
end
return NORET
end
-- forward multicast message to a node (channel id use the session field)
local function remote_publish(node, channel, source, ...)
skynet.redirect(node_address[node], source, "multicast", channel, ...)
end
-- publish a message, for local node, use the message pointer (call mc.bind to add the reference)
-- for remote node, call remote_publish. (call mc.unpack and skynet.tostring to convert message pointer to string)
local function publish(c , source, pack, size)
local remote = channel_remote[c]
if remote then
-- remote publish should unpack the pack, because we should not publish the pointer out.
local _, msg, sz = mc.unpack(pack, size)
local msg = skynet.tostring(msg,sz)
for node in pairs(remote) do
remote_publish(node, c, source, msg)
end
end
local group = channel[c]
if group == nil or next(group) == nil then
-- dead channel, delete the pack. mc.bind returns the pointer in pack and free the pack (struct mc_package **)
local pack = mc.bind(pack, 1)
mc.close(pack)
return
end
local msg = skynet.tostring(pack, size) -- copy (pack,size) to a string
mc.bind(pack, channel_n[c]) -- mc.bind will free the pack(struct mc_package **)
for k in pairs(group) do
-- the msg is a pointer to the real message, publish pointer in local is ok.
skynet.redirect(k, source, "multicast", c , msg)
end
end
skynet.register_protocol {
name = "multicast",
id = skynet.PTYPE_MULTICAST,
unpack = function(msg, sz)
return mc.packremote(msg, sz)
end,
dispatch = publish,
}
-- publish a message, if the caller is remote, forward the message to the owner node (by remote_publish)
-- If the caller is local, call publish
function command.PUB(source, c, pack, size)
assert(skynet.harbor(source) == harbor_id)
local node = c % 256
if node ~= harbor_id then
-- remote publish
remote_publish(node, c, source, mc.remote(pack))
else
publish(c, source, pack,size)
end
end
-- the node (source) subscribe a channel
-- MUST call by channel owner node (assert source is not local and channel is create by self)
-- If channel is not exist, return true
-- Else set channel_remote[channel] true
function command.SUBR(source, c)
local node = skynet.harbor(source)
if not channel[c] then
-- channel none exist
return true
end
assert(node ~= harbor_id and c % 256 == harbor_id)
local group = channel_remote[c]
if group == nil then
group = {}
channel_remote[c] = group
end
group[node] = true
end
-- the service (source) subscribe a channel
-- If the channel is remote, node subscribe it by send a SUBR to the owner .
function command.SUB(source, c)
local node = c % 256
if node ~= harbor_id then
-- remote group
if channel[c] == nil then
if skynet.call(node_address[node], "lua", "SUBR", c) then
return
end
if channel[c] == nil then
-- double check, because skynet.call whould yield, other SUB may occur.
channel[c] = {}
channel_n[c] = 0
end
end
end
local group = channel[c]
if group and not group[source] then
channel_n[c] = channel_n[c] + 1
group[source] = true
end
end
-- MUST call by a node, unsubscribe a channel
function command.USUBR(source, c)
local node = skynet.harbor(source)
assert(node ~= harbor_id)
local group = assert(channel_remote[c])
group[node] = nil
return NORET
end
-- Unsubscribe a channel, if the subscriber is empty and the channel is remote, send USUBR to the channel owner
function command.USUB(source, c)
local group = assert(channel[c])
if group[source] then
group[source] = nil
channel_n[c] = channel_n[c] - 1
if channel_n[c] == 0 then
local node = c % 256
if node ~= harbor_id then
-- remote group
channel[c] = nil
channel_n[c] = nil
skynet.send(node_address[node], "lua", "USUBR", c)
end
end
end
return NORET
end
skynet.start(function()
skynet.dispatch("lua", function(_,source, cmd, ...)
local f = assert(command[cmd])
local result = f(source, ...)
if result ~= NORET then
skynet.ret(skynet.pack(result))
end
end)
local self = skynet.self()
local id = skynet.harbor(self)
assert(datacenter.set("multicast", id, self) == nil)
end)
| mit |
tehran98/Team-Spammer | plugins/id.lua | 355 | 2795 | local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
--local chat_id = "chat#id"..result.id
local chat_id = result.id
local chatname = result.print_name
local text = 'IDs for chat '..chatname
..' ('..chat_id..')\n'
..'There are '..result.members_num..' members'
..'\n---------\n'
i = 0
for k,v in pairs(result.members) do
i = i+1
text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.id .. ")\n"
end
send_large_msg(receiver, text)
end
local function username_id(cb_extra, success, result)
local receiver = cb_extra.receiver
local qusername = cb_extra.qusername
local text = 'User '..qusername..' not found in this group!'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == qusername then
text = 'ID for username\n'..vusername..' : '..v.id
end
end
send_large_msg(receiver, text)
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == "!id" then
local text = 'Name : '.. string.gsub(user_print_name(msg.from),'_', ' ') .. '\nID : ' .. msg.from.id
if is_chat_msg(msg) then
text = text .. "\n\nYou are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') .. " (ID: " .. msg.to.id .. ")"
end
return text
elseif matches[1] == "chat" then
-- !ids? (chat) (%d+)
if matches[2] and is_sudo(msg) then
local chat = 'chat#id'..matches[2]
chat_info(chat, returnids, {receiver=receiver})
else
if not is_chat_msg(msg) then
return "You are not in a group."
end
local chat = get_receiver(msg)
chat_info(chat, returnids, {receiver=receiver})
end
else
if not is_chat_msg(msg) then
return "Only works in group"
end
local qusername = string.gsub(matches[1], "@", "")
local chat = get_receiver(msg)
chat_info(chat, username_id, {receiver=receiver, qusername=qusername})
end
end
return {
description = "Know your id or the id of a chat members.",
usage = {
"!id: Return your ID and the chat id if you are in one.",
"!ids chat: Return the IDs of the current chat members.",
"!ids chat <chat_id>: Return the IDs of the <chat_id> members.",
"!id <username> : Return the id from username given."
},
patterns = {
"^!id$",
"^!ids? (chat) (%d+)$",
"^!ids? (chat)$",
"^!id (.*)$"
},
run = run
}
| gpl-2.0 |
bmscoordinators/FFXI-Server | scripts/zones/Arrapago_Reef/mobs/Zareehkl_the_Jubilant.lua | 23 | 1703 | -----------------------------------
-- Area: Arrapago Reef
-- NPC: Zareehkl the Jubilant
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob, target)
local swapTimer = mob:getLocalVar("swapTime");
if (os.time() > swapTimer) then
if (mob:AnimationSub() == 1) then -- swap from fists to second weapon
mob:AnimationSub(2);
mob:setLocalVar("swapTime", os.time() + 60)
elseif (mob:AnimationSub() == 2) then -- swap from second weapon to fists
mob:AnimationSub(1);
mob:setLocalVar("swapTime", os.time() + 60)
end
end
end;
-----------------------------------
-- onCriticalHit
-----------------------------------
function onCriticalHit(mob)
if (math.random(100) < 5) then -- Wiki seems to imply that this thing's weapon is harder to break...
if (mob:AnimationSub() == 0) then -- first weapon
mob:AnimationSub(1);
mob:setLocalVar("swapTime", os.time() + 60) -- start the timer for swapping between fists and the second weapon
elseif (mob:AnimationSub() == 2) then -- second weapon
mob:AnimationSub(3);
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end; | gpl-3.0 |
PraveerSINGH/nn | SpatialSubtractiveNormalization.lua | 18 | 4314 | local SpatialSubtractiveNormalization, parent = torch.class('nn.SpatialSubtractiveNormalization','nn.Module')
function SpatialSubtractiveNormalization:__init(nInputPlane, kernel)
parent.__init(self)
-- get args
self.nInputPlane = nInputPlane or 1
self.kernel = kernel or torch.Tensor(9,9):fill(1)
local kdim = self.kernel:nDimension()
-- check args
if kdim ~= 2 and kdim ~= 1 then
error('<SpatialSubtractiveNormalization> averaging kernel must be 2D or 1D')
end
if (self.kernel:size(1) % 2) == 0 or (kdim == 2 and (self.kernel:size(2) % 2) == 0) then
error('<SpatialSubtractiveNormalization> averaging kernel must have ODD dimensions')
end
-- normalize kernel
self.kernel:div(self.kernel:sum() * self.nInputPlane)
-- padding values
local padH = math.floor(self.kernel:size(1)/2)
local padW = padH
if kdim == 2 then
padW = math.floor(self.kernel:size(2)/2)
end
-- create convolutional mean extractor
self.meanestimator = nn.Sequential()
self.meanestimator:add(nn.SpatialZeroPadding(padW, padW, padH, padH))
if kdim == 2 then
self.meanestimator:add(nn.SpatialConvolution(self.nInputPlane, 1, self.kernel:size(2), self.kernel:size(1)))
else
self.meanestimator:add(nn.SpatialConvolutionMap(nn.tables.oneToOne(self.nInputPlane), self.kernel:size(1), 1))
self.meanestimator:add(nn.SpatialConvolution(self.nInputPlane, 1, 1, self.kernel:size(1)))
end
self.meanestimator:add(nn.Replicate(self.nInputPlane,1,3))
-- set kernel and bias
if kdim == 2 then
for i = 1,self.nInputPlane do
self.meanestimator.modules[2].weight[1][i] = self.kernel
end
self.meanestimator.modules[2].bias:zero()
else
for i = 1,self.nInputPlane do
self.meanestimator.modules[2].weight[i]:copy(self.kernel)
self.meanestimator.modules[3].weight[1][i]:copy(self.kernel)
end
self.meanestimator.modules[2].bias:zero()
self.meanestimator.modules[3].bias:zero()
end
-- other operation
self.subtractor = nn.CSubTable()
self.divider = nn.CDivTable()
-- coefficient array, to adjust side effects
self.coef = torch.Tensor(1,1,1)
end
function SpatialSubtractiveNormalization:updateOutput(input)
-- compute side coefficients
local dim = input:dim()
if input:dim()+1 ~= self.coef:dim() or (input:size(dim) ~= self.coef:size(dim)) or (input:size(dim-1) ~= self.coef:size(dim-1)) then
self.ones = self.ones or input.new()
self._coef = self._coef or self.coef.new()
if dim == 4 then
-- batch mode
self.ones:resizeAs(input[1]):fill(1)
local coef = self.meanestimator:updateOutput(self.ones)
self._coef:resizeAs(coef):copy(coef) -- make contiguous for view
local size = coef:size():totable()
table.insert(size,1,input:size(1))
self.coef = self._coef:view(1,table.unpack(self._coef:size():totable())):expand(table.unpack(size))
else
self.ones:resizeAs(input):fill(1)
local coef = self.meanestimator:updateOutput(self.ones)
self._coef:resizeAs(coef):copy(coef) -- copy meanestimator.output as it will be used below
self.coef = self._coef
end
end
-- compute mean
self.localsums = self.meanestimator:updateOutput(input)
self.adjustedsums = self.divider:updateOutput{self.localsums, self.coef}
self.output = self.subtractor:updateOutput{input, self.adjustedsums}
-- done
return self.output
end
function SpatialSubtractiveNormalization:updateGradInput(input, gradOutput)
-- resize grad
self.gradInput:resizeAs(input):zero()
-- backprop through all modules
local gradsub = self.subtractor:updateGradInput({input, self.adjustedsums}, gradOutput)
local graddiv = self.divider:updateGradInput({self.localsums, self.coef}, gradsub[2])
local size = self.meanestimator:updateGradInput(input, graddiv[1]):size()
self.gradInput:add(self.meanestimator:updateGradInput(input, graddiv[1]))
self.gradInput:add(gradsub[1])
-- done
return self.gradInput
end
function SpatialSubtractiveNormalization:clearState()
if self.ones then self.ones:set() end
if self._coef then self._coef:set() end
self.meanestimator:clearState()
return parent.clearState(self)
end
| bsd-3-clause |
albanD/adaptive-neural-compilation | adaptation/examples/increment.lua | 1 | 3025 | -- This is a config for the increment task
local config = {}
-- For conversion to distributions
local distUtils = require 'nc.distUtils'
local f = distUtils.flatDist
-- Name of the algorithm
config.name = "Increment"
-- Number of available registers (excluding the RI)
config.nb_registers = 6
-- Number of instructions this program uses
config.nb_existing_ops = 11
-- Size of the memory tape and largest number addressable
config.memory_size = 7
-- Initial state of the registers
config.registers_init = torch.Tensor{0, f, 6, 0, 0, f}
config.registers_init = distUtils.toDistTensor(config.registers_init, config.memory_size)
-- Program
config.nb_states = 7
config.program = {
torch.Tensor{0, 1, 1, 0, 0, 4, f}, -- first arguments
torch.Tensor{f, 2, f, 1, f, 3, f}, -- second arguments
torch.Tensor{1, 5, 1, 5, 0, 5, 5}, -- target register
torch.Tensor{8,10, 2, 9, 2,10, 0} -- instruction to operate
}
-- Sample input memory
-- We increment all elements of the list
-- Our input list is {4, 5, 6, 7}
-- The output should be, inplace {5, 6, 7, 8}
config.example_input = torch.zeros(config.memory_size)
config.example_input[1] = 4
config.example_input[2] = 5
config.example_input[3] = 6
config.example_input[4] = 7
config.example_output = config.example_input:clone()
config.example_output[1] = 5
config.example_output[2] = 6
config.example_output[3] = 7
config.example_output[4] = 8
config.example_input = distUtils.toDistTensor(config.example_input, config.memory_size)
config.example_output = distUtils.toDistTensor(config.example_output, config.memory_size)
config.example_loss_mask = torch.ones(config.memory_size, config.memory_size)
config.gen_sample = function()
local list_length = 1 + math.floor(torch.uniform()*(config.memory_size-2))
local input = torch.floor(torch.rand(config.memory_size) * (config.memory_size-1))+1
input:narrow(1, list_length + 1, config.memory_size - list_length):fill(0)
local output = input:clone()
output:copy(output+1)
output:narrow(1, list_length + 1, config.memory_size - list_length):fill(0)
local loss_mask = torch.zeros(config.memory_size, config.memory_size)
loss_mask:narrow(1,1, list_length+1):fill(1)
input = distUtils.toDistTensor(input, config.memory_size)
output = distUtils.toDistTensor(output, config.memory_size)
return input, output, loss_mask
end
config.gen_biased_sample = function()
-- This is biased because we the lists are always composed of the same value so we don't need to always read
local val = 1 + math.floor(torch.uniform()*(config.memory_size-2))
local input = torch.ones(config.memory_size) * val
input[config.memory_size] = 0
local output = torch.ones(config.memory_size) * (val + 1)
output[config.memory_size] = 0
input = distUtils.toDistTensor(input, config.memory_size)
output = distUtils.toDistTensor(output, config.memory_size)
local loss_mask = torch.ones(config.memory_size, config.memory_size)
return input, output, loss_mask
end
return config
| gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/zones/Jugner_Forest/npcs/Alexius.lua | 14 | 1619 | -----------------------------------
-- Area: Jugner Forest
-- NPC: Alexius
-- Involved in Quest: A purchase of Arms & Sin Hunting
-- @pos 105 1 382 104
-----------------------------------
package.loaded["scripts/zones/Jugner_Forest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Jugner_Forest/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local SinHunting = player:getVar("sinHunting"); -- RNG AF1
if (player:hasKeyItem(WEAPONS_ORDER) == true) then
player:startEvent(0x0005);
elseif (SinHunting == 3) then
player:startEvent(0x000a);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0005) then
player:delKeyItem(WEAPONS_ORDER);
player:addKeyItem(WEAPONS_RECEIPT);
player:messageSpecial(KEYITEM_OBTAINED,WEAPONS_RECEIPT);
elseif (csid == 0x000a) then
player:setVar("sinHunting",4);
end
end; | gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/zones/Eastern_Altepa_Desert/npcs/Field_Manual.lua | 29 | 1067 | -----------------------------------
-- Field Manual
-- Area: Eastern Altepa Desert
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/fieldsofvalor");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startFov(FOV_EVENT_EAST_ALTEPA,player);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
updateFov(player,csid,menuchoice,109,110,111,112,113);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
finishFov(player,csid,option,109,110,111,112,113,FOV_MSG_EAST_ALTEPA);
end;
| gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/zones/Chamber_of_Oracles/Zone.lua | 30 | 1741 | -----------------------------------
--
-- Zone: Chamber_of_Oracles (168)
--
-----------------------------------
package.loaded["scripts/zones/Chamber_of_Oracles/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Chamber_of_Oracles/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-177.804,-2.765,-37.893,179);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
jsenellart/OpenNMT | tools/build_vocab.lua | 7 | 1515 | require('onmt.init')
local cmd = onmt.utils.ExtendedCmdLine.new('build_vocab.lua')
local options = {
{
'-data', '',
[[Data file.]],
{
valid = onmt.utils.ExtendedCmdLine.fileExists
}
},
{
'-save_vocab', '',
[[Vocabulary dictionary prefix.]],
{
valid = onmt.utils.ExtendedCmdLine.nonEmpty
}
},
{
'-vocab_size', { 50000 },
[[List of source vocabularies size: `word[ feat1[ feat2[ ...] ] ]`.
If = 0, vocabularies are not pruned.]]
},
{
'-words_min_frequency', { 0 },
[[List of source words min frequency: `word[ feat1[ feat2[ ...] ] ]`.
If = 0, vocabularies are pruned by size.]]
},
{
'-keep_frequency', false,
[[Keep frequency of words in dictionary.]]
},
{
'-idx_files', false,
[[If set, each line of the data file starts with a first field which is the index of the sentence.]]
}
}
cmd:setCmdLineOptions(options, 'Vocabulary')
onmt.utils.Logger.declareOpts(cmd)
local function isValid(sent)
return #sent > 0
end
local function main()
local opt = cmd:parse(arg)
_G.logger = onmt.utils.Logger.new(opt.log_file, opt.disable_logs, opt.log_level)
local vocab = onmt.data.Vocabulary.init('source', opt.data, '', opt.vocab_size, opt.words_min_frequency, '', isValid, opt.keep_frequency, opt.idx_files)
onmt.data.Vocabulary.save('source', vocab.words, opt.save_vocab .. '.dict')
onmt.data.Vocabulary.saveFeatures('source', vocab.features, opt.save_vocab)
_G.logger:shutDown()
end
main()
| mit |
wingo/snabb | lib/ljsyscall/syscall/linux/errors.lua | 24 | 5242 | -- Linux error messages
return {
PERM = "Operation not permitted",
NOENT = "No such file or directory",
SRCH = "No such process",
INTR = "Interrupted system call",
IO = "Input/output error",
NXIO = "No such device or address",
["2BIG"] = "Argument list too long",
NOEXEC = "Exec format error",
BADF = "Bad file descriptor",
CHILD = "No child processes",
AGAIN = "Resource temporarily unavailable",
NOMEM = "Cannot allocate memory",
ACCES = "Permission denied",
FAULT = "Bad address",
NOTBLK = "Block device required",
BUSY = "Device or resource busy",
EXIST = "File exists",
XDEV = "Invalid cross-device link",
NODEV = "No such device",
NOTDIR = "Not a directory",
ISDIR = "Is a directory",
INVAL = "Invalid argument",
NFILE = "Too many open files in system",
MFILE = "Too many open files",
NOTTY = "Inappropriate ioctl for device",
TXTBSY = "Text file busy",
FBIG = "File too large",
NOSPC = "No space left on device",
SPIPE = "Illegal seek",
ROFS = "Read-only file system",
MLINK = "Too many links",
PIPE = "Broken pipe",
DOM = "Numerical argument out of domain",
RANGE = "Numerical result out of range",
DEADLK = "Resource deadlock avoided",
NAMETOOLONG = "File name too long",
NOLCK = "No locks available",
NOSYS = "Function not implemented",
NOTEMPTY = "Directory not empty",
LOOP = "Too many levels of symbolic links",
NOMSG = "No message of desired type",
IDRM = "Identifier removed",
CHRNG = "Channel number out of range",
L2NSYNC = "Level 2 not synchronized",
L3HLT = "Level 3 halted",
L3RST = "Level 3 reset",
LNRNG = "Link number out of range",
UNATCH = "Protocol driver not attached",
NOCSI = "No CSI structure available",
L2HLT = "Level 2 halted",
BADE = "Invalid exchange",
BADR = "Invalid request descriptor",
XFULL = "Exchange full",
NOANO = "No anode",
BADRQC = "Invalid request code",
BADSLT = "Invalid slot",
BFONT = "Bad font file format",
NOSTR = "Device not a stream",
NODATA = "No data available",
TIME = "Timer expired",
NOSR = "Out of streams resources",
NONET = "Machine is not on the network",
NOPKG = "Package not installed",
REMOTE = "Object is remote",
NOLINK = "Link has been severed",
ADV = "Advertise error",
SRMNT = "Srmount error",
COMM = "Communication error on send",
PROTO = "Protocol error",
MULTIHOP = "Multihop attempted",
DOTDOT = "RFS specific error",
BADMSG = "Bad message",
OVERFLOW = "Value too large for defined data type",
NOTUNIQ = "Name not unique on network",
BADFD = "File descriptor in bad state",
REMCHG = "Remote address changed",
LIBACC = "Can not access a needed shared library",
LIBBAD = "Accessing a corrupted shared library",
LIBSCN = ".lib section in a.out corrupted",
LIBMAX = "Attempting to link in too many shared libraries",
LIBEXEC = "Cannot exec a shared library directly",
ILSEQ = "Invalid or incomplete multibyte or wide character",
RESTART = "Interrupted system call should be restarted",
STRPIPE = "Streams pipe error",
USERS = "Too many users",
NOTSOCK = "Socket operation on non-socket",
DESTADDRREQ = "Destination address required",
MSGSIZE = "Message too long",
PROTOTYPE = "Protocol wrong type for socket",
NOPROTOOPT = "Protocol not available",
PROTONOSUPPORT = "Protocol not supported",
SOCKTNOSUPPORT = "Socket type not supported",
OPNOTSUPP = "Operation not supported",
PFNOSUPPORT = "Protocol family not supported",
AFNOSUPPORT = "Address family not supported by protocol",
ADDRINUSE = "Address already in use",
ADDRNOTAVAIL = "Cannot assign requested address",
NETDOWN = "Network is down",
NETUNREACH = "Network is unreachable",
NETRESET = "Network dropped connection on reset",
CONNABORTED = "Software caused connection abort",
CONNRESET = "Connection reset by peer",
NOBUFS = "No buffer space available",
ISCONN = "Transport endpoint is already connected",
NOTCONN = "Transport endpoint is not connected",
SHUTDOWN = "Cannot send after transport endpoint shutdown",
TOOMANYREFS = "Too many references: cannot splice",
TIMEDOUT = "Connection timed out",
CONNREFUSED = "Connection refused",
HOSTDOWN = "Host is down",
HOSTUNREACH = "No route to host",
ALREADY = "Operation already in progress",
INPROGRESS = "Operation now in progress",
STALE = "Stale NFS file handle",
UCLEAN = "Structure needs cleaning",
NOTNAM = "Not a XENIX named type file",
NAVAIL = "No XENIX semaphores available",
ISNAM = "Is a named type file",
REMOTEIO = "Remote I/O error",
DQUOT = "Disk quota exceeded",
NOMEDIUM = "No medium found",
MEDIUMTYPE = "Wrong medium type",
CANCELED = "Operation canceled",
NOKEY = "Required key not available",
KEYEXPIRED = "Key has expired",
KEYREVOKED = "Key has been revoked",
KEYREJECTED = "Key was rejected by service",
OWNERDEAD = "Owner died",
NOTRECOVERABLE = "State not recoverable",
RFKILL = "Operation not possible due to RF-kill",
-- only on some platforms
DEADLOCK = "File locking deadlock error",
INIT = "Reserved EINIT", -- what is correct message?
REMDEV = "Remote device", -- what is correct message?
HWPOISON = "Reserved EHWPOISON", -- what is correct message?
}
| apache-2.0 |
bmscoordinators/FFXI-Server | scripts/zones/Abyssea-Konschtat/npcs/qm14.lua | 4 | 1761 | -----------------------------------
-- Zone: Abyssea-Konschtat
-- NPC: qm14 (???)
-- Spawns Kukulkan
-- @pos ? ? ? 15
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(16838872) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(TATTERED_HIPPOGRYPH_WING) and player:hasKeyItem(CRACKED_WIVRE_HORN)
and player:hasKeyItem(MUCID_AHRIMAN_EYEBALL)) then -- I broke it into 3 lines at the 'and' because it was so long.
player:startEvent(1020, TATTERED_HIPPOGRYPH_WING, CRACKED_WIVRE_HORN, MUCID_AHRIMAN_EYEBALL); -- Ask if player wants to use KIs
else
player:startEvent(1021, TATTERED_HIPPOGRYPH_WING, CRACKED_WIVRE_HORN, MUCID_AHRIMAN_EYEBALL); -- Do not ask, because player is missing at least 1.
end
end
]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 1020 and option == 1) then
SpawnMob(16838872):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(TATTERED_HIPPOGRYPH_WING);
player:delKeyItem(CRACKED_WIVRE_HORN);
player:delKeyItem(MUCID_AHRIMAN_EYEBALL);
end
end;
| gpl-3.0 |
wingo/snabb | src/dasm_x86.lua | 11 | 74171 | ------------------------------------------------------------------------------
-- DynASM x86/x64 module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- See dynasm.lua for full copyright notice.
------------------------------------------------------------------------------
local x64 = rawget(_G, "x64") --rawget so it works with strict.lua
-- Module information:
local _info = {
arch = x64 and "x64" or "x86",
description = "DynASM x86/x64 module",
version = "1.4.0_luamode",
vernum = 10400,
release = "2015-10-18",
author = "Mike Pall",
license = "MIT",
}
-- Exported glue functions for the arch-specific module.
local _M = { _info = _info }
-- Cache library functions.
local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs
local assert, unpack, setmetatable = assert, unpack or table.unpack, setmetatable
local _s = string
local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char
local find, match, gmatch, gsub = _s.find, _s.match, _s.gmatch, _s.gsub
local concat, sort, remove = table.concat, table.sort, table.remove
local bit = bit or require("bit")
local band, bxor, shl, shr = bit.band, bit.bxor, bit.lshift, bit.rshift
-- Inherited tables and callbacks.
local g_opt, g_arch, g_map_def
local wline, werror, wfatal, wwarn
-- Global flag to generate Lua code instead of C code.
local luamode
-- Action name list.
-- CHECK: Keep this in sync with the C code!
local action_names = {
-- int arg, 1 buffer pos:
"DISP", "IMM_S", "IMM_B", "IMM_W", "IMM_D", "IMM_WB", "IMM_DB",
-- action arg (1 byte), int arg, 1 buffer pos (reg/num):
"VREG", "SPACE",
-- ptrdiff_t arg, 1 buffer pos (address): !x64
"SETLABEL", "REL_A",
-- action arg (1 byte) or int arg, 2 buffer pos (link, offset):
"REL_LG", "REL_PC",
-- action arg (1 byte) or int arg, 1 buffer pos (link):
"IMM_LG", "IMM_PC",
-- action arg (1 byte) or int arg, 1 buffer pos (offset):
"LABEL_LG", "LABEL_PC",
-- action arg (1 byte), 1 buffer pos (offset):
"ALIGN",
-- action args (2 bytes), no buffer pos.
"EXTERN",
-- action arg (1 byte), no buffer pos.
"ESC",
-- no action arg, no buffer pos.
"MARK",
-- action arg (1 byte), no buffer pos, terminal action:
"SECTION",
-- no args, no buffer pos, terminal action:
"STOP"
}
-- Maximum number of section buffer positions for dasm_put().
-- CHECK: Keep this in sync with the C code!
local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines.
-- Action name -> action number (dynamically generated below).
local map_action = {}
-- First action number. Everything below does not need to be escaped.
local actfirst = 256-#action_names
-- Action list buffer and string (only used to remove dupes).
local actlist, actstr
-- Argument list for next dasm_put().
local actargs
-- Current number of section buffer positions for dasm_put().
local secpos
local function init_actionlist()
actlist = {}
actstr = ""
actargs = { 0 } -- Start with offset 0 into the action list.
secpos = 1
end
-- VREG kind encodings, pre-shifted by 5 bits.
local map_vreg = {
["modrm.rm.m"] = 0x00,
["modrm.rm.r"] = 0x20,
["opcode"] = 0x20,
["sib.base"] = 0x20,
["sib.index"] = 0x40,
["modrm.reg"] = 0x80,
["vex.v"] = 0xa0,
["imm.hi"] = 0xc0,
}
-- Current number of VREG actions contributing to REX/VEX shrinkage.
local vreg_shrink_count = 0
------------------------------------------------------------------------------
-- Compute action numbers for action names.
for n,name in ipairs(action_names) do
local num = actfirst + n - 1
map_action[name] = num
end
-- Dump action names and numbers.
local function dumpactions(out)
out:write("DynASM encoding engine action codes:\n")
for n,name in ipairs(action_names) do
local num = map_action[name]
out:write(format(" %-10s %02X %d\n", name, num, num))
end
out:write("\n")
end
-- Write action list buffer as a huge static C array.
local function writeactions(out, name)
local nn = #actlist
local last = actlist[nn] or 255
actlist[nn] = nil -- Remove last byte.
if nn == 0 then nn = 1 end
if luamode then
out:write("local ", name, " = ffi.new('const uint8_t[", nn, "]', {\n")
else
out:write("static const unsigned char ", name, "[", nn, "] = {\n")
end
local s = " "
for n,b in ipairs(actlist) do
s = s..b..","
if #s >= 75 then
assert(out:write(s, "\n"))
s = " "
end
end
if luamode then
out:write(s, last, "\n})\n\n") -- Add last byte back.
else
out:write(s, last, "\n};\n\n") -- Add last byte back.
end
end
------------------------------------------------------------------------------
-- Add byte to action list.
local function wputxb(n)
assert(n >= 0 and n <= 255 and n % 1 == 0, "byte out of range")
actlist[#actlist+1] = n
end
-- Add action to list with optional arg. Advance buffer pos, too.
local function waction(action, a, num)
wputxb(assert(map_action[action], "bad action name `"..action.."'"))
if a then actargs[#actargs+1] = a end
if a or num then secpos = secpos + (num or 1) end
end
-- Optionally add a VREG action.
local function wvreg(kind, vreg, psz, sk, defer)
if not vreg then return end
waction("VREG", vreg)
local b = assert(map_vreg[kind], "bad vreg kind `"..vreg.."'")
if b < (sk or 0) then
vreg_shrink_count = vreg_shrink_count + 1
end
if not defer then
b = b + vreg_shrink_count * 8
vreg_shrink_count = 0
end
wputxb(b + (psz or 0))
end
-- Add call to embedded DynASM C code.
local function wcall(func, args)
if luamode then
wline(format("dasm.%s(Dst, %s)", func, concat(args, ", ")), true)
else
wline(format("dasm_%s(Dst, %s);", func, concat(args, ", ")), true)
end
end
-- Delete duplicate action list chunks. A tad slow, but so what.
local function dedupechunk(offset)
local al, as = actlist, actstr
local chunk = char(unpack(al, offset+1, #al))
local orig = find(as, chunk, 1, true)
if orig then
actargs[1] = orig-1 -- Replace with original offset.
for i=offset+1,#al do al[i] = nil end -- Kill dupe.
else
actstr = as..chunk
end
end
-- Flush action list (intervening C code or buffer pos overflow).
local function wflush(term)
local offset = actargs[1]
if #actlist == offset then return end -- Nothing to flush.
if not term then waction("STOP") end -- Terminate action list.
dedupechunk(offset)
wcall("put", actargs) -- Add call to dasm_put().
actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put().
secpos = 1 -- The actionlist offset occupies a buffer position, too.
end
-- Put escaped byte.
local function wputb(n)
if n >= actfirst then waction("ESC") end -- Need to escape byte.
wputxb(n)
end
------------------------------------------------------------------------------
-- Global label name -> global label number. With auto assignment on 1st use.
local next_global, map_global
local globals_meta = { __index = function(t, name)
if not match(name, "^[%a_][%w_@]*$") then werror("bad global label") end
local n = next_global
if n > 246 then werror("too many global labels") end
next_global = n + 1
t[name] = n
return n
end}
local function init_map_global()
next_global = 10
map_global = setmetatable({}, globals_meta)
end
-- Dump global labels.
local function dumpglobals(out, lvl)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("Global labels:\n")
for i=10,next_global-1 do
out:write(format(" %s\n", t[i]))
end
out:write("\n")
end
-- Write global label enum.
local function writeglobals(out, prefix)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
if luamode then
local n = 0
for i=10,next_global-1 do
out:write("local ", prefix, gsub(t[i], "@.*", ""), "\t= ", n, "\n")
n = n + 1
end
out:write("local ", prefix, "_MAX\t= ", n, "\n") --for compatibility with the C protocol
out:write("local DASM_MAXGLOBAL\t= ", n, "\n")
else
out:write("enum {\n")
for i=10,next_global-1 do
out:write(" ", prefix, gsub(t[i], "@.*", ""), ",\n")
end
out:write(" ", prefix, "_MAX\n};\n")
end
end
-- Write global label names.
local function writeglobalnames(out, name)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
if luamode then
out:write("local ", name, " = {\n")
for i=10,next_global-1 do
out:write(" ", i == 10 and "[0] = " or "", "\"", t[i], "\",\n")
end
out:write("}\n")
else
out:write("static const char *const ", name, "[] = {\n")
for i=10,next_global-1 do
out:write(" \"", t[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
end
------------------------------------------------------------------------------
-- Extern label name -> extern label number. With auto assignment on 1st use.
local next_extern, map_extern
local extern_meta = { __index = function(t, name)
-- No restrictions on the name for now.
local n = next_extern
if n < -256 then werror("too many extern labels") end
next_extern = n - 1
t[name] = n
return n
end}
local function init_map_extern()
next_extern = -1
map_extern = setmetatable({}, extern_meta)
end
-- Dump extern labels.
local function dumpexterns(out, lvl)
local t = {}
for name, n in pairs(map_extern) do t[-n] = name end
out:write("Extern labels:\n")
for i=1,-next_extern-1 do
out:write(format(" %s\n", t[i]))
end
out:write("\n")
end
-- Write extern label names.
local function writeexternnames(out, name)
local t = {}
for name, n in pairs(map_extern) do t[-n] = name end
if luamode then
out:write("local ", name, " = {\n")
for i=1,-next_extern-1 do
out:write(i==1 and "[0] = " or "", "\"", t[i], "\",\n")
end
out:write("}\n")
else
out:write("static const char *const ", name, "[] = {\n")
for i=1,-next_extern-1 do
out:write(" \"", t[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
end
------------------------------------------------------------------------------
-- Arch-specific maps.
local map_archdef = {} -- Ext. register name -> int. name.
local map_reg_rev = {} -- Int. register name -> ext. name.
local map_reg_num = {} -- Int. register name -> register number.
local map_reg_opsize = {} -- Int. register name -> operand size.
local map_reg_valid_base = {} -- Int. register name -> valid base register?
local map_reg_valid_index = {} -- Int. register name -> valid index register?
local map_reg_needrex = {} -- Int. register name -> need rex vs. no rex.
local reg_list = {} -- Canonical list of int. register names.
local map_type -- Type name -> { ctype, reg }
local ctypenum -- Type number (for _PTx macros).
local function init_map_type()
map_type = {}
ctypenum = 0
end
local addrsize = x64 and "q" or "d" -- Size for address operands.
-- Helper functions to fill register maps.
local function mkrmap(sz, cl, names)
local cname = format("@%s", sz)
reg_list[#reg_list+1] = cname
map_archdef[cl] = cname
map_reg_rev[cname] = cl
map_reg_num[cname] = -1
map_reg_opsize[cname] = sz
if sz == addrsize or sz == "d" then
map_reg_valid_base[cname] = true
map_reg_valid_index[cname] = true
end
if names then
for n,name in ipairs(names) do
local iname = format("@%s%x", sz, n-1)
reg_list[#reg_list+1] = iname
map_archdef[name] = iname
map_reg_rev[iname] = name
map_reg_num[iname] = n-1
map_reg_opsize[iname] = sz
if sz == "b" and n > 4 then map_reg_needrex[iname] = false end
if sz == addrsize or sz == "d" then
map_reg_valid_base[iname] = true
map_reg_valid_index[iname] = true
end
end
end
for i=0,(x64 and sz ~= "f") and 15 or 7 do
local needrex = sz == "b" and i > 3
local iname = format("@%s%x%s", sz, i, needrex and "R" or "")
if needrex then map_reg_needrex[iname] = true end
local name
if sz == "o" or sz == "y" then name = format("%s%d", cl, i)
elseif sz == "f" then name = format("st%d", i)
else name = format("r%d%s", i, sz == addrsize and "" or sz) end
map_archdef[name] = iname
if not map_reg_rev[iname] then
reg_list[#reg_list+1] = iname
map_reg_rev[iname] = name
map_reg_num[iname] = i
map_reg_opsize[iname] = sz
if sz == addrsize or sz == "d" then
map_reg_valid_base[iname] = true
map_reg_valid_index[iname] = true
end
end
end
reg_list[#reg_list+1] = ""
end
-- Integer registers (qword, dword, word and byte sized).
if x64 then
mkrmap("q", "Rq", {"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi"})
end
mkrmap("d", "Rd", {"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"})
mkrmap("w", "Rw", {"ax", "cx", "dx", "bx", "sp", "bp", "si", "di"})
mkrmap("b", "Rb", {"al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"})
map_reg_valid_index[map_archdef.esp] = false
if x64 then map_reg_valid_index[map_archdef.rsp] = false end
if x64 then map_reg_needrex[map_archdef.Rb] = true end
map_archdef["Ra"] = "@"..addrsize
-- FP registers (internally tword sized, but use "f" as operand size).
mkrmap("f", "Rf")
-- SSE registers (oword sized, but qword and dword accessible).
mkrmap("o", "xmm")
-- AVX registers (yword sized, but oword, qword and dword accessible).
mkrmap("y", "ymm")
-- Operand size prefixes to codes.
local map_opsize = {
byte = "b", word = "w", dword = "d", qword = "q", oword = "o", yword = "y",
tword = "t", aword = addrsize,
}
-- Operand size code to number.
local map_opsizenum = {
b = 1, w = 2, d = 4, q = 8, o = 16, y = 32, t = 10,
}
-- Operand size code to name.
local map_opsizename = {
b = "byte", w = "word", d = "dword", q = "qword", o = "oword", y = "yword",
t = "tword", f = "fpword",
}
-- Valid index register scale factors.
local map_xsc = {
["1"] = 0, ["2"] = 1, ["4"] = 2, ["8"] = 3,
}
-- Condition codes.
local map_cc = {
o = 0, no = 1, b = 2, nb = 3, e = 4, ne = 5, be = 6, nbe = 7,
s = 8, ns = 9, p = 10, np = 11, l = 12, nl = 13, le = 14, nle = 15,
c = 2, nae = 2, nc = 3, ae = 3, z = 4, nz = 5, na = 6, a = 7,
pe = 10, po = 11, nge = 12, ge = 13, ng = 14, g = 15,
}
-- Reverse defines for registers.
function _M.revdef(s)
return gsub(s, "@%w+", map_reg_rev)
end
-- Dump register names and numbers
local function dumpregs(out)
out:write("Register names, sizes and internal numbers:\n")
for _,reg in ipairs(reg_list) do
if reg == "" then
out:write("\n")
else
local name = map_reg_rev[reg]
local num = map_reg_num[reg]
local opsize = map_opsizename[map_reg_opsize[reg]]
out:write(format(" %-5s %-8s %s\n", name, opsize,
num < 0 and "(variable)" or num))
end
end
end
------------------------------------------------------------------------------
-- Put action for label arg (IMM_LG, IMM_PC, REL_LG, REL_PC).
local function wputlabel(aprefix, imm, num)
if type(imm) == "number" then
if imm < 0 then
waction("EXTERN")
wputxb(aprefix == "IMM_" and 0 or 1)
imm = -imm-1
else
waction(aprefix.."LG", nil, num);
end
wputxb(imm)
else
waction(aprefix.."PC", imm, num)
end
end
-- Put signed byte or arg.
local function wputsbarg(n)
if type(n) == "number" then
if n < -128 or n > 127 then
werror("signed immediate byte out of range")
end
if n < 0 then n = n + 256 end
wputb(n)
else waction("IMM_S", n) end
end
-- Put unsigned byte or arg.
local function wputbarg(n)
if type(n) == "number" then
if n < 0 or n > 255 then
werror("unsigned immediate byte out of range")
end
wputb(n)
else waction("IMM_B", n) end
end
-- Put unsigned word or arg.
local function wputwarg(n)
if type(n) == "number" then
if shr(n, 16) ~= 0 then
werror("unsigned immediate word out of range")
end
wputb(band(n, 255)); wputb(shr(n, 8));
else waction("IMM_W", n) end
end
-- Put signed or unsigned dword or arg.
local function wputdarg(n)
local tn = type(n)
if tn == "number" then
wputb(band(n, 255))
wputb(band(shr(n, 8), 255))
wputb(band(shr(n, 16), 255))
wputb(shr(n, 24))
elseif tn == "table" then
wputlabel("IMM_", n[1], 1)
else
waction("IMM_D", n)
end
end
-- Put operand-size dependent number or arg (defaults to dword).
local function wputszarg(sz, n)
if not sz or sz == "d" or sz == "q" then wputdarg(n)
elseif sz == "w" then wputwarg(n)
elseif sz == "b" then wputbarg(n)
elseif sz == "s" then wputsbarg(n)
else werror("bad operand size") end
end
-- Put multi-byte opcode with operand-size dependent modifications.
local function wputop(sz, op, rex, vex, vregr, vregxb)
local psz, sk = 0, nil
if vex then
local tail
if vex.m == 1 and band(rex, 11) == 0 then
if x64 and vregxb then
sk = map_vreg["modrm.reg"]
else
wputb(0xc5)
tail = shl(bxor(band(rex, 4), 4), 5)
psz = 3
end
end
if not tail then
wputb(0xc4)
wputb(shl(bxor(band(rex, 7), 7), 5) + vex.m)
tail = shl(band(rex, 8), 4)
psz = 4
end
local reg, vreg = 0, nil
if vex.v then
reg = vex.v.reg
if not reg then werror("bad vex operand") end
if reg < 0 then reg = 0; vreg = vex.v.vreg end
end
if sz == "y" or vex.l then tail = tail + 4 end
wputb(tail + shl(bxor(reg, 15), 3) + vex.p)
wvreg("vex.v", vreg)
rex = 0
if op >= 256 then werror("bad vex opcode") end
else
if rex ~= 0 then
if not x64 then werror("bad operand size") end
elseif (vregr or vregxb) and x64 then
rex = 0x10
sk = map_vreg["vex.v"]
end
end
local r
if sz == "w" then wputb(102) end
-- Needs >32 bit numbers, but only for crc32 eax, word [ebx]
if op >= 4294967296 then r = op%4294967296 wputb((op-r)/4294967296) op = r end
if op >= 16777216 then wputb(shr(op, 24)); op = band(op, 0xffffff) end
if op >= 65536 then
if rex ~= 0 then
local opc3 = band(op, 0xffff00)
if opc3 == 0x0f3a00 or opc3 == 0x0f3800 then
wputb(64 + band(rex, 15)); rex = 0; psz = 2
end
end
wputb(shr(op, 16)); op = band(op, 0xffff); psz = psz + 1
end
if op >= 256 then
local b = shr(op, 8)
if b == 15 and rex ~= 0 then wputb(64 + band(rex, 15)); rex = 0; psz = 2 end
wputb(b); op = band(op, 255); psz = psz + 1
end
if rex ~= 0 then wputb(64 + band(rex, 15)); psz = 2 end
if sz == "b" then op = op - 1 end
wputb(op)
return psz, sk
end
-- Put ModRM or SIB formatted byte.
local function wputmodrm(m, s, rm, vs, vrm)
assert(m < 4 and s < 16 and rm < 16, "bad modrm operands")
wputb(shl(m, 6) + shl(band(s, 7), 3) + band(rm, 7))
end
-- Put ModRM/SIB plus optional displacement.
local function wputmrmsib(t, imark, s, vsreg, psz, sk)
local vreg, vxreg
local reg, xreg = t.reg, t.xreg
if reg and reg < 0 then reg = 0; vreg = t.vreg end
if xreg and xreg < 0 then xreg = 0; vxreg = t.vxreg end
if s < 0 then s = 0 end
-- Register mode.
if sub(t.mode, 1, 1) == "r" then
wputmodrm(3, s, reg)
wvreg("modrm.reg", vsreg, psz+1, sk, vreg)
wvreg("modrm.rm.r", vreg, psz+1, sk)
return
end
local disp = t.disp
local tdisp = type(disp)
-- No base register?
if not reg then
local riprel = false
if xreg then
-- Indexed mode with index register only.
-- [xreg*xsc+disp] -> (0, s, esp) (xsc, xreg, ebp)
wputmodrm(0, s, 4)
if imark == "I" then waction("MARK") end
wvreg("modrm.reg", vsreg, psz+1, sk, vxreg)
wputmodrm(t.xsc, xreg, 5)
wvreg("sib.index", vxreg, psz+2, sk)
else
-- Pure 32 bit displacement.
if x64 and tdisp ~= "table" then
wputmodrm(0, s, 4) -- [disp] -> (0, s, esp) (0, esp, ebp)
wvreg("modrm.reg", vsreg, psz+1, sk)
if imark == "I" then waction("MARK") end
wputmodrm(0, 4, 5)
else
riprel = x64
wputmodrm(0, s, 5) -- [disp|rip-label] -> (0, s, ebp)
wvreg("modrm.reg", vsreg, psz+1, sk)
if imark == "I" then waction("MARK") end
end
end
if riprel then -- Emit rip-relative displacement.
if match("UWSiI", imark) then
werror("NYI: rip-relative displacement followed by immediate")
end
-- The previous byte in the action buffer cannot be 0xe9 or 0x80-0x8f.
wputlabel("REL_", disp[1], 2)
else
wputdarg(disp)
end
return
end
local m
if tdisp == "number" then -- Check displacement size at assembly time.
if disp == 0 and band(reg, 7) ~= 5 then -- [ebp] -> [ebp+0] (in SIB, too)
if not vreg then m = 0 end -- Force DISP to allow [Rd(5)] -> [ebp+0]
elseif disp >= -128 and disp <= 127 then m = 1
else m = 2 end
elseif tdisp == "table" then
m = 2
end
-- Index register present or esp as base register: need SIB encoding.
if xreg or band(reg, 7) == 4 then
wputmodrm(m or 2, s, 4) -- ModRM.
if m == nil or imark == "I" then waction("MARK") end
wvreg("modrm.reg", vsreg, psz+1, sk, vxreg or vreg)
wputmodrm(t.xsc or 0, xreg or 4, reg) -- SIB.
wvreg("sib.index", vxreg, psz+2, sk, vreg)
wvreg("sib.base", vreg, psz+2, sk)
else
wputmodrm(m or 2, s, reg) -- ModRM.
if (imark == "I" and (m == 1 or m == 2)) or
(m == nil and (vsreg or vreg)) then waction("MARK") end
wvreg("modrm.reg", vsreg, psz+1, sk, vreg)
wvreg("modrm.rm.m", vreg, psz+1, sk)
end
-- Put displacement.
if m == 1 then wputsbarg(disp)
elseif m == 2 then wputdarg(disp)
elseif m == nil then waction("DISP", disp) end
end
------------------------------------------------------------------------------
-- Return human-readable operand mode string.
local function opmodestr(op, args)
local m = {}
for i=1,#args do
local a = args[i]
m[#m+1] = sub(a.mode, 1, 1)..(a.opsize or "?")
end
return op.." "..concat(m, ",")
end
-- Convert number to valid integer or nil.
local function toint(expr)
local n = tonumber(expr)
if n then
if n % 1 ~= 0 or n < -2147483648 or n > 4294967295 then
werror("bad integer number `"..expr.."'")
end
return n
end
end
-- Parse immediate expression.
local function immexpr(expr)
-- &expr (pointer)
if sub(expr, 1, 1) == "&" then
return "iPJ", format(luamode and "(%s)" or "(ptrdiff_t)(%s)", sub(expr,2))
end
local prefix = sub(expr, 1, 2)
-- =>expr (pc label reference)
if prefix == "=>" then
return "iJ", sub(expr, 3)
end
-- ->name (global label reference)
if prefix == "->" then
return "iJ", map_global[sub(expr, 3)]
end
-- [<>][1-9] (local label reference)
local dir, lnum = match(expr, "^([<>])([1-9])$")
if dir then -- Fwd: 247-255, Bkwd: 1-9.
return "iJ", lnum + (dir == ">" and 246 or 0)
end
local extname = match(expr, "^extern%s+(%S+)$")
if extname then
return "iJ", map_extern[extname]
end
-- expr (interpreted as immediate)
return "iI", expr
end
-- Parse displacement expression: +-num, +-expr, +-opsize*num
local function dispexpr(expr)
local disp = expr == "" and 0 or toint(expr)
if disp then return disp end
local c, dispt = match(expr, "^([+-])%s*(.+)$")
if c == "+" then
expr = dispt
elseif not c then
werror("bad displacement expression `"..expr.."'")
end
local opsize, tailops = match(dispt, "^(%w+)%s*%*%s*(.+)$")
local ops, imm = map_opsize[opsize], toint(tailops)
if ops and imm then
if c == "-" then imm = -imm end
return imm*map_opsizenum[ops]
end
local mode, iexpr = immexpr(dispt)
if mode == "iJ" then
if c == "-" then werror("cannot invert label reference") end
return { iexpr }
end
return expr -- Need to return original signed expression.
end
-- Parse register or type expression.
local function rtexpr(expr)
if not expr then return end
local tname, ovreg = match(expr, "^([%w_]+):(@[%w_]+)$")
local tp = map_type[tname or expr]
if tp then
local reg = ovreg or tp.reg
local rnum = map_reg_num[reg]
if not rnum then
werror("type `"..(tname or expr).."' needs a register override")
end
if not map_reg_valid_base[reg] then
werror("bad base register override `"..(map_reg_rev[reg] or reg).."'")
end
return reg, rnum, tp
end
return expr, map_reg_num[expr]
end
-- Parse operand and return { mode, opsize, reg, xreg, xsc, disp, imm }.
local function parseoperand(param)
local t = {}
local expr = param
local opsize, tailops = match(param, "^(%w+)%s*(.+)$")
if opsize then
t.opsize = map_opsize[opsize]
if t.opsize then expr = tailops end
end
local br = match(expr, "^%[%s*(.-)%s*%]$")
repeat
if br then
t.mode = "xm"
-- [disp]
t.disp = toint(br)
if t.disp then
t.mode = x64 and "xm" or "xmO"
break
end
-- [reg...]
local tp
local reg, tailr = match(br, "^([@%w_:]+)%s*(.*)$")
reg, t.reg, tp = rtexpr(reg)
if not t.reg then
-- [expr]
t.mode = x64 and "xm" or "xmO"
t.disp = dispexpr("+"..br)
break
end
if t.reg == -1 then
t.vreg, tailr = match(tailr, "^(%b())(.*)$")
if not t.vreg then werror("bad variable register expression") end
end
-- [xreg*xsc] or [xreg*xsc+-disp] or [xreg*xsc+-expr]
local xsc, tailsc = match(tailr, "^%*%s*([1248])%s*(.*)$")
if xsc then
if not map_reg_valid_index[reg] then
werror("bad index register `"..map_reg_rev[reg].."'")
end
t.xsc = map_xsc[xsc]
t.xreg = t.reg
t.vxreg = t.vreg
t.reg = nil
t.vreg = nil
t.disp = dispexpr(tailsc)
break
end
if not map_reg_valid_base[reg] then
werror("bad base register `"..map_reg_rev[reg].."'")
end
-- [reg] or [reg+-disp]
t.disp = toint(tailr) or (tailr == "" and 0)
if t.disp then break end
-- [reg+xreg...]
local xreg, tailx = match(tailr, "^+%s*([@%w_:]+)%s*(.*)$")
xreg, t.xreg, tp = rtexpr(xreg)
if not t.xreg then
-- [reg+-expr]
t.disp = dispexpr(tailr)
break
end
if not map_reg_valid_index[xreg] then
werror("bad index register `"..map_reg_rev[xreg].."'")
end
if t.xreg == -1 then
t.vxreg, tailx = match(tailx, "^(%b())(.*)$")
if not t.vxreg then werror("bad variable register expression") end
end
-- [reg+xreg*xsc...]
local xsc, tailsc = match(tailx, "^%*%s*([1248])%s*(.*)$")
if xsc then
t.xsc = map_xsc[xsc]
tailx = tailsc
end
-- [...] or [...+-disp] or [...+-expr]
t.disp = dispexpr(tailx)
else
-- imm or opsize*imm
local imm = toint(expr)
if not imm and sub(expr, 1, 1) == "*" and t.opsize then
imm = toint(sub(expr, 2))
if imm then
imm = imm * map_opsizenum[t.opsize]
t.opsize = nil
end
end
if imm then
if t.opsize then werror("bad operand size override") end
local m = "i"
if imm == 1 then m = m.."1" end
if imm >= 4294967168 and imm <= 4294967295 then imm = imm-4294967296 end
if imm >= -128 and imm <= 127 then m = m.."S" end
t.imm = imm
t.mode = m
break
end
local tp
local reg, tailr = match(expr, "^([@%w_:]+)%s*(.*)$")
reg, t.reg, tp = rtexpr(reg)
if t.reg then
if t.reg == -1 then
t.vreg, tailr = match(tailr, "^(%b())(.*)$")
if not t.vreg then werror("bad variable register expression") end
end
-- reg
if tailr == "" then
if t.opsize then werror("bad operand size override") end
t.opsize = map_reg_opsize[reg]
if t.opsize == "f" then
t.mode = t.reg == 0 and "fF" or "f"
else
if reg == "@w4" or (x64 and reg == "@d4") then
wwarn("bad idea, try again with `"..(x64 and "rsp'" or "esp'"))
end
t.mode = t.reg == 0 and "rmR" or (reg == "@b1" and "rmC" or "rm")
end
t.needrex = map_reg_needrex[reg]
break
end
-- type[idx], type[idx].field, type->field -> [reg+offset_expr]
if not tp then werror("bad operand `"..param.."'") end
t.mode = "xm"
if luamode then
t.disp = tp.ctypefmt(tailr)
else
t.disp = format(tp.ctypefmt, tailr)
end
else
t.mode, t.imm = immexpr(expr)
if sub(t.mode, -1) == "J" then
if t.opsize and t.opsize ~= addrsize then
werror("bad operand size override")
end
t.opsize = addrsize
end
end
end
until true
return t
end
------------------------------------------------------------------------------
-- x86 Template String Description
-- ===============================
--
-- Each template string is a list of [match:]pattern pairs,
-- separated by "|". The first match wins. No match means a
-- bad or unsupported combination of operand modes or sizes.
--
-- The match part and the ":" is omitted if the operation has
-- no operands. Otherwise the first N characters are matched
-- against the mode strings of each of the N operands.
--
-- The mode string for each operand type is (see parseoperand()):
-- Integer register: "rm", +"R" for eax, ax, al, +"C" for cl
-- FP register: "f", +"F" for st0
-- Index operand: "xm", +"O" for [disp] (pure offset)
-- Immediate: "i", +"S" for signed 8 bit, +"1" for 1,
-- +"I" for arg, +"P" for pointer
-- Any: +"J" for valid jump targets
--
-- So a match character "m" (mixed) matches both an integer register
-- and an index operand (to be encoded with the ModRM/SIB scheme).
-- But "r" matches only a register and "x" only an index operand
-- (e.g. for FP memory access operations).
--
-- The operand size match string starts right after the mode match
-- characters and ends before the ":". "dwb" or "qdwb" is assumed, if empty.
-- The effective data size of the operation is matched against this list.
--
-- If only the regular "b", "w", "d", "q", "t" operand sizes are
-- present, then all operands must be the same size. Unspecified sizes
-- are ignored, but at least one operand must have a size or the pattern
-- won't match (use the "byte", "word", "dword", "qword", "tword"
-- operand size overrides. E.g.: mov dword [eax], 1).
--
-- If the list has a "1" or "2" prefix, the operand size is taken
-- from the respective operand and any other operand sizes are ignored.
-- If the list contains only ".", all operand sizes are ignored.
-- If the list has a "/" prefix, the concatenated (mixed) operand sizes
-- are compared to the match.
--
-- E.g. "rrdw" matches for either two dword registers or two word
-- registers. "Fx2dq" matches an st0 operand plus an index operand
-- pointing to a dword (float) or qword (double).
--
-- Every character after the ":" is part of the pattern string:
-- Hex chars are accumulated to form the opcode (left to right).
-- "n" disables the standard opcode mods
-- (otherwise: -1 for "b", o16 prefix for "w", rex.w for "q")
-- "X" Force REX.W.
-- "r"/"R" adds the reg. number from the 1st/2nd operand to the opcode.
-- "m"/"M" generates ModRM/SIB from the 1st/2nd operand.
-- The spare 3 bits are either filled with the last hex digit or
-- the result from a previous "r"/"R". The opcode is restored.
-- "u" Use VEX encoding, vvvv unused.
-- "v"/"V" Use VEX encoding, vvvv from 1st/2nd operand (the operand is
-- removed from the list used by future characters).
-- "L" Force VEX.L
--
-- All of the following characters force a flush of the opcode:
-- "o"/"O" stores a pure 32 bit disp (offset) from the 1st/2nd operand.
-- "s" stores a 4 bit immediate from the last register operand,
-- followed by 4 zero bits.
-- "S" stores a signed 8 bit immediate from the last operand.
-- "U" stores an unsigned 8 bit immediate from the last operand.
-- "W" stores an unsigned 16 bit immediate from the last operand.
-- "i" stores an operand sized immediate from the last operand.
-- "I" dito, but generates an action code to optionally modify
-- the opcode (+2) for a signed 8 bit immediate.
-- "J" generates one of the REL action codes from the last operand.
--
------------------------------------------------------------------------------
-- Template strings for x86 instructions. Ordered by first opcode byte.
-- Unimplemented opcodes (deliberate omissions) are marked with *.
local map_op = {
-- 00-05: add...
-- 06: *push es
-- 07: *pop es
-- 08-0D: or...
-- 0E: *push cs
-- 0F: two byte opcode prefix
-- 10-15: adc...
-- 16: *push ss
-- 17: *pop ss
-- 18-1D: sbb...
-- 1E: *push ds
-- 1F: *pop ds
-- 20-25: and...
es_0 = "26",
-- 27: *daa
-- 28-2D: sub...
cs_0 = "2E",
-- 2F: *das
-- 30-35: xor...
ss_0 = "36",
-- 37: *aaa
-- 38-3D: cmp...
ds_0 = "3E",
-- 3F: *aas
inc_1 = x64 and "m:FF0m" or "rdw:40r|m:FF0m",
dec_1 = x64 and "m:FF1m" or "rdw:48r|m:FF1m",
push_1 = (x64 and "rq:n50r|rw:50r|mq:nFF6m|mw:FF6m" or
"rdw:50r|mdw:FF6m").."|S.:6AS|ib:n6Ai|i.:68i",
pop_1 = x64 and "rq:n58r|rw:58r|mq:n8F0m|mw:8F0m" or "rdw:58r|mdw:8F0m",
-- 60: *pusha, *pushad, *pushaw
-- 61: *popa, *popad, *popaw
-- 62: *bound rdw,x
-- 63: x86: *arpl mw,rw
movsxd_2 = x64 and "rm/qd:63rM",
fs_0 = "64",
gs_0 = "65",
o16_0 = "66",
a16_0 = not x64 and "67" or nil,
a32_0 = x64 and "67",
-- 68: push idw
-- 69: imul rdw,mdw,idw
-- 6A: push ib
-- 6B: imul rdw,mdw,S
-- 6C: *insb
-- 6D: *insd, *insw
-- 6E: *outsb
-- 6F: *outsd, *outsw
-- 70-7F: jcc lb
-- 80: add... mb,i
-- 81: add... mdw,i
-- 82: *undefined
-- 83: add... mdw,S
test_2 = "mr:85Rm|rm:85rM|Ri:A9ri|mi:F70mi",
-- 86: xchg rb,mb
-- 87: xchg rdw,mdw
-- 88: mov mb,r
-- 89: mov mdw,r
-- 8A: mov r,mb
-- 8B: mov r,mdw
-- 8C: *mov mdw,seg
lea_2 = "rx1dq:8DrM",
-- 8E: *mov seg,mdw
-- 8F: pop mdw
nop_0 = "90",
xchg_2 = "Rrqdw:90R|rRqdw:90r|rm:87rM|mr:87Rm",
cbw_0 = "6698",
cwde_0 = "98",
cdqe_0 = "4898",
cwd_0 = "6699",
cdq_0 = "99",
cqo_0 = "4899",
-- 9A: *call iw:idw
wait_0 = "9B",
fwait_0 = "9B",
pushf_0 = "9C",
pushfd_0 = not x64 and "9C",
pushfq_0 = x64 and "9C",
popf_0 = "9D",
popfd_0 = not x64 and "9D",
popfq_0 = x64 and "9D",
sahf_0 = "9E",
lahf_0 = "9F",
mov_2 = "OR:A3o|RO:A1O|mr:89Rm|rm:8BrM|rib:nB0ri|ridw:B8ri|mi:C70mi",
movsb_0 = "A4",
movsw_0 = "66A5",
movsd_0 = "A5",
cmpsb_0 = "A6",
cmpsw_0 = "66A7",
cmpsd_0 = "A7",
-- A8: test Rb,i
-- A9: test Rdw,i
stosb_0 = "AA",
stosw_0 = "66AB",
stosd_0 = "AB",
lodsb_0 = "AC",
lodsw_0 = "66AD",
lodsd_0 = "AD",
scasb_0 = "AE",
scasw_0 = "66AF",
scasd_0 = "AF",
-- B0-B7: mov rb,i
-- B8-BF: mov rdw,i
-- C0: rol... mb,i
-- C1: rol... mdw,i
ret_1 = "i.:nC2W",
ret_0 = "C3",
-- C4: *les rdw,mq
-- C5: *lds rdw,mq
-- C6: mov mb,i
-- C7: mov mdw,i
-- C8: *enter iw,ib
leave_0 = "C9",
-- CA: *retf iw
-- CB: *retf
int3_0 = "CC",
int_1 = "i.:nCDU",
into_0 = "CE",
-- CF: *iret
-- D0: rol... mb,1
-- D1: rol... mdw,1
-- D2: rol... mb,cl
-- D3: rol... mb,cl
-- D4: *aam ib
-- D5: *aad ib
-- D6: *salc
-- D7: *xlat
-- D8-DF: floating point ops
-- E0: *loopne
-- E1: *loope
-- E2: *loop
-- E3: *jcxz, *jecxz
-- E4: *in Rb,ib
-- E5: *in Rdw,ib
-- E6: *out ib,Rb
-- E7: *out ib,Rdw
call_1 = x64 and "mq:nFF2m|J.:E8nJ" or "md:FF2m|J.:E8J",
jmp_1 = x64 and "mq:nFF4m|J.:E9nJ" or "md:FF4m|J.:E9J", -- short: EB
-- EA: *jmp iw:idw
-- EB: jmp ib
-- EC: *in Rb,dx
-- ED: *in Rdw,dx
-- EE: *out dx,Rb
-- EF: *out dx,Rdw
lock_0 = "F0",
int1_0 = "F1",
repne_0 = "F2",
repnz_0 = "F2",
rep_0 = "F3",
repe_0 = "F3",
repz_0 = "F3",
-- F4: *hlt
cmc_0 = "F5",
-- F6: test... mb,i; div... mb
-- F7: test... mdw,i; div... mdw
clc_0 = "F8",
stc_0 = "F9",
-- FA: *cli
cld_0 = "FC",
std_0 = "FD",
-- FE: inc... mb
-- FF: inc... mdw
-- misc ops
not_1 = "m:F72m",
neg_1 = "m:F73m",
mul_1 = "m:F74m",
imul_1 = "m:F75m",
div_1 = "m:F76m",
idiv_1 = "m:F77m",
imul_2 = "rmqdw:0FAFrM|rIqdw:69rmI|rSqdw:6BrmS|riqdw:69rmi",
imul_3 = "rmIqdw:69rMI|rmSqdw:6BrMS|rmiqdw:69rMi",
movzx_2 = "rm/db:0FB6rM|rm/qb:|rm/wb:0FB6rM|rm/dw:0FB7rM|rm/qw:",
movsx_2 = "rm/db:0FBErM|rm/qb:|rm/wb:0FBErM|rm/dw:0FBFrM|rm/qw:",
bswap_1 = "rqd:0FC8r",
bsf_2 = "rmqdw:0FBCrM",
bsr_2 = "rmqdw:0FBDrM",
bt_2 = "mrqdw:0FA3Rm|miqdw:0FBA4mU",
btc_2 = "mrqdw:0FBBRm|miqdw:0FBA7mU",
btr_2 = "mrqdw:0FB3Rm|miqdw:0FBA6mU",
bts_2 = "mrqdw:0FABRm|miqdw:0FBA5mU",
shld_3 = "mriqdw:0FA4RmU|mrC/qq:0FA5Rm|mrC/dd:|mrC/ww:",
shrd_3 = "mriqdw:0FACRmU|mrC/qq:0FADRm|mrC/dd:|mrC/ww:",
rdtsc_0 = "0F31", -- P1+
rdpmc_0 = "0F33", -- P6+
cpuid_0 = "0FA2", -- P1+
-- floating point ops
fst_1 = "ff:DDD0r|xd:D92m|xq:nDD2m",
fstp_1 = "ff:DDD8r|xd:D93m|xq:nDD3m|xt:DB7m",
fld_1 = "ff:D9C0r|xd:D90m|xq:nDD0m|xt:DB5m",
fpop_0 = "DDD8", -- Alias for fstp st0.
fist_1 = "xw:nDF2m|xd:DB2m",
fistp_1 = "xw:nDF3m|xd:DB3m|xq:nDF7m",
fild_1 = "xw:nDF0m|xd:DB0m|xq:nDF5m",
fxch_0 = "D9C9",
fxch_1 = "ff:D9C8r",
fxch_2 = "fFf:D9C8r|Fff:D9C8R",
fucom_1 = "ff:DDE0r",
fucom_2 = "Fff:DDE0R",
fucomp_1 = "ff:DDE8r",
fucomp_2 = "Fff:DDE8R",
fucomi_1 = "ff:DBE8r", -- P6+
fucomi_2 = "Fff:DBE8R", -- P6+
fucomip_1 = "ff:DFE8r", -- P6+
fucomip_2 = "Fff:DFE8R", -- P6+
fcomi_1 = "ff:DBF0r", -- P6+
fcomi_2 = "Fff:DBF0R", -- P6+
fcomip_1 = "ff:DFF0r", -- P6+
fcomip_2 = "Fff:DFF0R", -- P6+
fucompp_0 = "DAE9",
fcompp_0 = "DED9",
fldenv_1 = "x.:D94m",
fnstenv_1 = "x.:D96m",
fstenv_1 = "x.:9BD96m",
fldcw_1 = "xw:nD95m",
fstcw_1 = "xw:n9BD97m",
fnstcw_1 = "xw:nD97m",
fstsw_1 = "Rw:n9BDFE0|xw:n9BDD7m",
fnstsw_1 = "Rw:nDFE0|xw:nDD7m",
fclex_0 = "9BDBE2",
fnclex_0 = "DBE2",
fnop_0 = "D9D0",
-- D9D1-D9DF: unassigned
fchs_0 = "D9E0",
fabs_0 = "D9E1",
-- D9E2: unassigned
-- D9E3: unassigned
ftst_0 = "D9E4",
fxam_0 = "D9E5",
-- D9E6: unassigned
-- D9E7: unassigned
fld1_0 = "D9E8",
fldl2t_0 = "D9E9",
fldl2e_0 = "D9EA",
fldpi_0 = "D9EB",
fldlg2_0 = "D9EC",
fldln2_0 = "D9ED",
fldz_0 = "D9EE",
-- D9EF: unassigned
f2xm1_0 = "D9F0",
fyl2x_0 = "D9F1",
fptan_0 = "D9F2",
fpatan_0 = "D9F3",
fxtract_0 = "D9F4",
fprem1_0 = "D9F5",
fdecstp_0 = "D9F6",
fincstp_0 = "D9F7",
fprem_0 = "D9F8",
fyl2xp1_0 = "D9F9",
fsqrt_0 = "D9FA",
fsincos_0 = "D9FB",
frndint_0 = "D9FC",
fscale_0 = "D9FD",
fsin_0 = "D9FE",
fcos_0 = "D9FF",
-- SSE, SSE2
andnpd_2 = "rmo:660F55rM",
andnps_2 = "rmo:0F55rM",
andpd_2 = "rmo:660F54rM",
andps_2 = "rmo:0F54rM",
fxsave_1 = "x.:0FAE0m",
fxrstor_1 = "x.:0FAE1m",
clflush_1 = "x.:0FAE7m",
cmppd_3 = "rmio:660FC2rMU",
cmpps_3 = "rmio:0FC2rMU",
cmpsd_3 = "rrio:F20FC2rMU|rxi/oq:",
cmpss_3 = "rrio:F30FC2rMU|rxi/od:",
comisd_2 = "rro:660F2FrM|rx/oq:",
comiss_2 = "rro:0F2FrM|rx/od:",
cvtdq2pd_2 = "rro:F30FE6rM|rx/oq:",
cvtdq2ps_2 = "rmo:0F5BrM",
cvtpd2dq_2 = "rmo:F20FE6rM",
cvtpd2ps_2 = "rmo:660F5ArM",
cvtpi2pd_2 = "rx/oq:660F2ArM",
cvtpi2ps_2 = "rx/oq:0F2ArM",
cvtps2dq_2 = "rmo:660F5BrM",
cvtps2pd_2 = "rro:0F5ArM|rx/oq:",
cvtsd2si_2 = "rr/do:F20F2DrM|rr/qo:|rx/dq:|rxq:",
cvtsd2ss_2 = "rro:F20F5ArM|rx/oq:",
cvtsi2sd_2 = "rm/od:F20F2ArM|rm/oq:F20F2ArXM",
cvtsi2ss_2 = "rm/od:F30F2ArM|rm/oq:F30F2ArXM",
cvtss2sd_2 = "rro:F30F5ArM|rx/od:",
cvtss2si_2 = "rr/do:F30F2DrM|rr/qo:|rxd:|rx/qd:",
cvttpd2dq_2 = "rmo:660FE6rM",
cvttps2dq_2 = "rmo:F30F5BrM",
cvttsd2si_2 = "rr/do:F20F2CrM|rr/qo:|rx/dq:|rxq:",
cvttss2si_2 = "rr/do:F30F2CrM|rr/qo:|rxd:|rx/qd:",
fxsave_1 = "x.:0FAE0m",
fxrstor_1 = "x.:0FAE1m",
ldmxcsr_1 = "xd:0FAE2m",
lfence_0 = "0FAEE8",
maskmovdqu_2 = "rro:660FF7rM",
mfence_0 = "0FAEF0",
movapd_2 = "rmo:660F28rM|mro:660F29Rm",
movaps_2 = "rmo:0F28rM|mro:0F29Rm",
movd_2 = "rm/od:660F6ErM|rm/oq:660F6ErXM|mr/do:660F7ERm|mr/qo:",
movdqa_2 = "rmo:660F6FrM|mro:660F7FRm",
movdqu_2 = "rmo:F30F6FrM|mro:F30F7FRm",
movhlps_2 = "rro:0F12rM",
movhpd_2 = "rx/oq:660F16rM|xr/qo:n660F17Rm",
movhps_2 = "rx/oq:0F16rM|xr/qo:n0F17Rm",
movlhps_2 = "rro:0F16rM",
movlpd_2 = "rx/oq:660F12rM|xr/qo:n660F13Rm",
movlps_2 = "rx/oq:0F12rM|xr/qo:n0F13Rm",
movmskpd_2 = "rr/do:660F50rM",
movmskps_2 = "rr/do:0F50rM",
movntdq_2 = "xro:660FE7Rm",
movnti_2 = "xrqd:0FC3Rm",
movntpd_2 = "xro:660F2BRm",
movntps_2 = "xro:0F2BRm",
movq_2 = "rro:F30F7ErM|rx/oq:|xr/qo:n660FD6Rm",
movsd_2 = "rro:F20F10rM|rx/oq:|xr/qo:nF20F11Rm",
movss_2 = "rro:F30F10rM|rx/od:|xr/do:F30F11Rm",
movupd_2 = "rmo:660F10rM|mro:660F11Rm",
movups_2 = "rmo:0F10rM|mro:0F11Rm",
orpd_2 = "rmo:660F56rM",
orps_2 = "rmo:0F56rM",
pause_0 = "F390",
pextrw_3 = "rri/do:660FC5rMU|xri/wo:660F3A15nRmU", -- Mem op: SSE4.1 only.
pinsrw_3 = "rri/od:660FC4rMU|rxi/ow:",
pmovmskb_2 = "rr/do:660FD7rM",
prefetchnta_1 = "xb:n0F180m",
prefetcht0_1 = "xb:n0F181m",
prefetcht1_1 = "xb:n0F182m",
prefetcht2_1 = "xb:n0F183m",
pshufd_3 = "rmio:660F70rMU",
pshufhw_3 = "rmio:F30F70rMU",
pshuflw_3 = "rmio:F20F70rMU",
pslld_2 = "rmo:660FF2rM|rio:660F726mU",
pslldq_2 = "rio:660F737mU",
psllq_2 = "rmo:660FF3rM|rio:660F736mU",
psllw_2 = "rmo:660FF1rM|rio:660F716mU",
psrad_2 = "rmo:660FE2rM|rio:660F724mU",
psraw_2 = "rmo:660FE1rM|rio:660F714mU",
psrld_2 = "rmo:660FD2rM|rio:660F722mU",
psrldq_2 = "rio:660F733mU",
psrlq_2 = "rmo:660FD3rM|rio:660F732mU",
psrlw_2 = "rmo:660FD1rM|rio:660F712mU",
rcpps_2 = "rmo:0F53rM",
rcpss_2 = "rro:F30F53rM|rx/od:",
rsqrtps_2 = "rmo:0F52rM",
rsqrtss_2 = "rmo:F30F52rM",
sfence_0 = "0FAEF8",
shufpd_3 = "rmio:660FC6rMU",
shufps_3 = "rmio:0FC6rMU",
stmxcsr_1 = "xd:0FAE3m",
ucomisd_2 = "rro:660F2ErM|rx/oq:",
ucomiss_2 = "rro:0F2ErM|rx/od:",
unpckhpd_2 = "rmo:660F15rM",
unpckhps_2 = "rmo:0F15rM",
unpcklpd_2 = "rmo:660F14rM",
unpcklps_2 = "rmo:0F14rM",
xorpd_2 = "rmo:660F57rM",
xorps_2 = "rmo:0F57rM",
-- SSE3 ops
fisttp_1 = "xw:nDF1m|xd:DB1m|xq:nDD1m",
addsubpd_2 = "rmo:660FD0rM",
addsubps_2 = "rmo:F20FD0rM",
haddpd_2 = "rmo:660F7CrM",
haddps_2 = "rmo:F20F7CrM",
hsubpd_2 = "rmo:660F7DrM",
hsubps_2 = "rmo:F20F7DrM",
lddqu_2 = "rxo:F20FF0rM",
movddup_2 = "rmo:F20F12rM",
movshdup_2 = "rmo:F30F16rM",
movsldup_2 = "rmo:F30F12rM",
-- SSSE3 ops
pabsb_2 = "rmo:660F381CrM",
pabsd_2 = "rmo:660F381ErM",
pabsw_2 = "rmo:660F381DrM",
palignr_3 = "rmio:660F3A0FrMU",
phaddd_2 = "rmo:660F3802rM",
phaddsw_2 = "rmo:660F3803rM",
phaddw_2 = "rmo:660F3801rM",
phsubd_2 = "rmo:660F3806rM",
phsubsw_2 = "rmo:660F3807rM",
phsubw_2 = "rmo:660F3805rM",
pmaddubsw_2 = "rmo:660F3804rM",
pmulhrsw_2 = "rmo:660F380BrM",
pshufb_2 = "rmo:660F3800rM",
psignb_2 = "rmo:660F3808rM",
psignd_2 = "rmo:660F380ArM",
psignw_2 = "rmo:660F3809rM",
-- SSE4.1 ops
blendpd_3 = "rmio:660F3A0DrMU",
blendps_3 = "rmio:660F3A0CrMU",
blendvpd_3 = "rmRo:660F3815rM",
blendvps_3 = "rmRo:660F3814rM",
dppd_3 = "rmio:660F3A41rMU",
dpps_3 = "rmio:660F3A40rMU",
extractps_3 = "mri/do:660F3A17RmU|rri/qo:660F3A17RXmU",
insertps_3 = "rrio:660F3A41rMU|rxi/od:",
movntdqa_2 = "rxo:660F382ArM",
mpsadbw_3 = "rmio:660F3A42rMU",
packusdw_2 = "rmo:660F382BrM",
pblendvb_3 = "rmRo:660F3810rM",
pblendw_3 = "rmio:660F3A0ErMU",
pcmpeqq_2 = "rmo:660F3829rM",
pextrb_3 = "rri/do:660F3A14nRmU|rri/qo:|xri/bo:",
pextrd_3 = "mri/do:660F3A16RmU",
pextrq_3 = "mri/qo:660F3A16RmU",
-- pextrw is SSE2, mem operand is SSE4.1 only
phminposuw_2 = "rmo:660F3841rM",
pinsrb_3 = "rri/od:660F3A20nrMU|rxi/ob:",
pinsrd_3 = "rmi/od:660F3A22rMU",
pinsrq_3 = "rmi/oq:660F3A22rXMU",
pmaxsb_2 = "rmo:660F383CrM",
pmaxsd_2 = "rmo:660F383DrM",
pmaxud_2 = "rmo:660F383FrM",
pmaxuw_2 = "rmo:660F383ErM",
pminsb_2 = "rmo:660F3838rM",
pminsd_2 = "rmo:660F3839rM",
pminud_2 = "rmo:660F383BrM",
pminuw_2 = "rmo:660F383ArM",
pmovsxbd_2 = "rro:660F3821rM|rx/od:",
pmovsxbq_2 = "rro:660F3822rM|rx/ow:",
pmovsxbw_2 = "rro:660F3820rM|rx/oq:",
pmovsxdq_2 = "rro:660F3825rM|rx/oq:",
pmovsxwd_2 = "rro:660F3823rM|rx/oq:",
pmovsxwq_2 = "rro:660F3824rM|rx/od:",
pmovzxbd_2 = "rro:660F3831rM|rx/od:",
pmovzxbq_2 = "rro:660F3832rM|rx/ow:",
pmovzxbw_2 = "rro:660F3830rM|rx/oq:",
pmovzxdq_2 = "rro:660F3835rM|rx/oq:",
pmovzxwd_2 = "rro:660F3833rM|rx/oq:",
pmovzxwq_2 = "rro:660F3834rM|rx/od:",
pmuldq_2 = "rmo:660F3828rM",
pmulld_2 = "rmo:660F3840rM",
ptest_2 = "rmo:660F3817rM",
roundpd_3 = "rmio:660F3A09rMU",
roundps_3 = "rmio:660F3A08rMU",
roundsd_3 = "rrio:660F3A0BrMU|rxi/oq:",
roundss_3 = "rrio:660F3A0ArMU|rxi/od:",
-- SSE4.2 ops
crc32_2 = "rmqd:F20F38F1rM|rm/dw:66F20F38F1rM|rm/db:F20F38F0rM|rm/qb:",
pcmpestri_3 = "rmio:660F3A61rMU",
pcmpestrm_3 = "rmio:660F3A60rMU",
pcmpgtq_2 = "rmo:660F3837rM",
pcmpistri_3 = "rmio:660F3A63rMU",
pcmpistrm_3 = "rmio:660F3A62rMU",
popcnt_2 = "rmqdw:F30FB8rM",
-- SSE4a
extrq_2 = "rro:660F79rM",
extrq_3 = "riio:660F780mUU",
insertq_2 = "rro:F20F79rM",
insertq_4 = "rriio:F20F78rMUU",
lzcnt_2 = "rmqdw:F30FBDrM",
movntsd_2 = "xr/qo:nF20F2BRm",
movntss_2 = "xr/do:F30F2BRm",
-- popcnt is also in SSE4.2
-- AES-NI
aesdec_2 = "rmo:660F38DErM",
aesdeclast_2 = "rmo:660F38DFrM",
aesenc_2 = "rmo:660F38DCrM",
aesenclast_2 = "rmo:660F38DDrM",
aesimc_2 = "rmo:660F38DBrM",
aeskeygenassist_3 = "rmio:660F3ADFrMU",
pclmulqdq_3 = "rmio:660F3A44rMU",
-- AVX FP ops
vaddsubpd_3 = "rrmoy:660FVD0rM",
vaddsubps_3 = "rrmoy:F20FVD0rM",
vandpd_3 = "rrmoy:660FV54rM",
vandps_3 = "rrmoy:0FV54rM",
vandnpd_3 = "rrmoy:660FV55rM",
vandnps_3 = "rrmoy:0FV55rM",
vblendpd_4 = "rrmioy:660F3AV0DrMU",
vblendps_4 = "rrmioy:660F3AV0CrMU",
vblendvpd_4 = "rrmroy:660F3AV4BrMs",
vblendvps_4 = "rrmroy:660F3AV4ArMs",
vbroadcastf128_2 = "rx/yo:660F38u1ArM",
vcmppd_4 = "rrmioy:660FVC2rMU",
vcmpps_4 = "rrmioy:0FVC2rMU",
vcmpsd_4 = "rrrio:F20FVC2rMU|rrxi/ooq:",
vcmpss_4 = "rrrio:F30FVC2rMU|rrxi/ood:",
vcomisd_2 = "rro:660Fu2FrM|rx/oq:",
vcomiss_2 = "rro:0Fu2FrM|rx/od:",
vcvtdq2pd_2 = "rro:F30FuE6rM|rx/oq:|rm/yo:",
vcvtdq2ps_2 = "rmoy:0Fu5BrM",
vcvtpd2dq_2 = "rmoy:F20FuE6rM",
vcvtpd2ps_2 = "rmoy:660Fu5ArM",
vcvtps2dq_2 = "rmoy:660Fu5BrM",
vcvtps2pd_2 = "rro:0Fu5ArM|rx/oq:|rm/yo:",
vcvtsd2si_2 = "rr/do:F20Fu2DrM|rx/dq:|rr/qo:|rxq:",
vcvtsd2ss_3 = "rrro:F20FV5ArM|rrx/ooq:",
vcvtsi2sd_3 = "rrm/ood:F20FV2ArM|rrm/ooq:F20FVX2ArM",
vcvtsi2ss_3 = "rrm/ood:F30FV2ArM|rrm/ooq:F30FVX2ArM",
vcvtss2sd_3 = "rrro:F30FV5ArM|rrx/ood:",
vcvtss2si_2 = "rr/do:F30Fu2DrM|rxd:|rr/qo:|rx/qd:",
vcvttpd2dq_2 = "rmo:660FuE6rM|rm/oy:660FuLE6rM",
vcvttps2dq_2 = "rmoy:F30Fu5BrM",
vcvttsd2si_2 = "rr/do:F20Fu2CrM|rx/dq:|rr/qo:|rxq:",
vcvttss2si_2 = "rr/do:F30Fu2CrM|rxd:|rr/qo:|rx/qd:",
vdppd_4 = "rrmio:660F3AV41rMU",
vdpps_4 = "rrmioy:660F3AV40rMU",
vextractf128_3 = "mri/oy:660F3AuL19RmU",
vextractps_3 = "mri/do:660F3Au17RmU",
vhaddpd_3 = "rrmoy:660FV7CrM",
vhaddps_3 = "rrmoy:F20FV7CrM",
vhsubpd_3 = "rrmoy:660FV7DrM",
vhsubps_3 = "rrmoy:F20FV7DrM",
vinsertf128_4 = "rrmi/yyo:660F3AV18rMU",
vinsertps_4 = "rrrio:660F3AV21rMU|rrxi/ood:",
vldmxcsr_1 = "xd:0FuAE2m",
vmaskmovps_3 = "rrxoy:660F38V2CrM|xrroy:660F38V2ERm",
vmaskmovpd_3 = "rrxoy:660F38V2DrM|xrroy:660F38V2FRm",
vmovapd_2 = "rmoy:660Fu28rM|mroy:660Fu29Rm",
vmovaps_2 = "rmoy:0Fu28rM|mroy:0Fu29Rm",
vmovd_2 = "rm/od:660Fu6ErM|rm/oq:660FuX6ErM|mr/do:660Fu7ERm|mr/qo:",
vmovq_2 = "rro:F30Fu7ErM|rx/oq:|xr/qo:660FuD6Rm",
vmovddup_2 = "rmy:F20Fu12rM|rro:|rx/oq:",
vmovhlps_3 = "rrro:0FV12rM",
vmovhpd_2 = "xr/qo:660Fu17Rm",
vmovhpd_3 = "rrx/ooq:660FV16rM",
vmovhps_2 = "xr/qo:0Fu17Rm",
vmovhps_3 = "rrx/ooq:0FV16rM",
vmovlhps_3 = "rrro:0FV16rM",
vmovlpd_2 = "xr/qo:660Fu13Rm",
vmovlpd_3 = "rrx/ooq:660FV12rM",
vmovlps_2 = "xr/qo:0Fu13Rm",
vmovlps_3 = "rrx/ooq:0FV12rM",
vmovmskpd_2 = "rr/do:660Fu50rM|rr/dy:660FuL50rM",
vmovmskps_2 = "rr/do:0Fu50rM|rr/dy:0FuL50rM",
vmovntpd_2 = "xroy:660Fu2BRm",
vmovntps_2 = "xroy:0Fu2BRm",
vmovsd_2 = "rx/oq:F20Fu10rM|xr/qo:F20Fu11Rm",
vmovsd_3 = "rrro:F20FV10rM",
vmovshdup_2 = "rmoy:F30Fu16rM",
vmovsldup_2 = "rmoy:F30Fu12rM",
vmovss_2 = "rx/od:F30Fu10rM|xr/do:F30Fu11Rm",
vmovss_3 = "rrro:F30FV10rM",
vmovupd_2 = "rmoy:660Fu10rM|mroy:660Fu11Rm",
vmovups_2 = "rmoy:0Fu10rM|mroy:0Fu11Rm",
vorpd_3 = "rrmoy:660FV56rM",
vorps_3 = "rrmoy:0FV56rM",
vpermilpd_3 = "rrmoy:660F38V0DrM|rmioy:660F3Au05rMU",
vpermilps_3 = "rrmoy:660F38V0CrM|rmioy:660F3Au04rMU",
vperm2f128_4 = "rrmiy:660F3AV06rMU",
vptestpd_2 = "rmoy:660F38u0FrM",
vptestps_2 = "rmoy:660F38u0ErM",
vrcpps_2 = "rmoy:0Fu53rM",
vrcpss_3 = "rrro:F30FV53rM|rrx/ood:",
vrsqrtps_2 = "rmoy:0Fu52rM",
vrsqrtss_3 = "rrro:F30FV52rM|rrx/ood:",
vroundpd_3 = "rmioy:660F3AV09rMU",
vroundps_3 = "rmioy:660F3AV08rMU",
vroundsd_4 = "rrrio:660F3AV0BrMU|rrxi/ooq:",
vroundss_4 = "rrrio:660F3AV0ArMU|rrxi/ood:",
vshufpd_4 = "rrmioy:660FVC6rMU",
vshufps_4 = "rrmioy:0FVC6rMU",
vsqrtps_2 = "rmoy:0Fu51rM",
vsqrtss_2 = "rro:F30Fu51rM|rx/od:",
vsqrtpd_2 = "rmoy:660Fu51rM",
vsqrtsd_2 = "rro:F20Fu51rM|rx/oq:",
vstmxcsr_1 = "xd:0FuAE3m",
vucomisd_2 = "rro:660Fu2ErM|rx/oq:",
vucomiss_2 = "rro:0Fu2ErM|rx/od:",
vunpckhpd_3 = "rrmoy:660FV15rM",
vunpckhps_3 = "rrmoy:0FV15rM",
vunpcklpd_3 = "rrmoy:660FV14rM",
vunpcklps_3 = "rrmoy:0FV14rM",
vxorpd_3 = "rrmoy:660FV57rM",
vxorps_3 = "rrmoy:0FV57rM",
vzeroall_0 = "0FuL77",
vzeroupper_0 = "0Fu77",
-- AVX2 FP ops
vbroadcastss_2 = "rx/od:660F38u18rM|rx/yd:|rro:|rr/yo:",
vbroadcastsd_2 = "rx/yq:660F38u19rM|rr/yo:",
-- *vgather* (!vsib)
vpermpd_3 = "rmiy:660F3AuX01rMU",
vpermps_3 = "rrmy:660F38V16rM",
-- AVX, AVX2 integer ops
-- In general, xmm requires AVX, ymm requires AVX2.
vaesdec_3 = "rrmo:660F38VDErM",
vaesdeclast_3 = "rrmo:660F38VDFrM",
vaesenc_3 = "rrmo:660F38VDCrM",
vaesenclast_3 = "rrmo:660F38VDDrM",
vaesimc_2 = "rmo:660F38uDBrM",
vaeskeygenassist_3 = "rmio:660F3AuDFrMU",
vlddqu_2 = "rxoy:F20FuF0rM",
vmaskmovdqu_2 = "rro:660FuF7rM",
vmovdqa_2 = "rmoy:660Fu6FrM|mroy:660Fu7FRm",
vmovdqu_2 = "rmoy:F30Fu6FrM|mroy:F30Fu7FRm",
vmovntdq_2 = "xroy:660FuE7Rm",
vmovntdqa_2 = "rxoy:660F38u2ArM",
vmpsadbw_4 = "rrmioy:660F3AV42rMU",
vpabsb_2 = "rmoy:660F38u1CrM",
vpabsd_2 = "rmoy:660F38u1ErM",
vpabsw_2 = "rmoy:660F38u1DrM",
vpackusdw_3 = "rrmoy:660F38V2BrM",
vpalignr_4 = "rrmioy:660F3AV0FrMU",
vpblendvb_4 = "rrmroy:660F3AV4CrMs",
vpblendw_4 = "rrmioy:660F3AV0ErMU",
vpclmulqdq_4 = "rrmio:660F3AV44rMU",
vpcmpeqq_3 = "rrmoy:660F38V29rM",
vpcmpestri_3 = "rmio:660F3Au61rMU",
vpcmpestrm_3 = "rmio:660F3Au60rMU",
vpcmpgtq_3 = "rrmoy:660F38V37rM",
vpcmpistri_3 = "rmio:660F3Au63rMU",
vpcmpistrm_3 = "rmio:660F3Au62rMU",
vpextrb_3 = "rri/do:660F3Au14nRmU|rri/qo:|xri/bo:",
vpextrw_3 = "rri/do:660FuC5rMU|xri/wo:660F3Au15nRmU",
vpextrd_3 = "mri/do:660F3Au16RmU",
vpextrq_3 = "mri/qo:660F3Au16RmU",
vphaddw_3 = "rrmoy:660F38V01rM",
vphaddd_3 = "rrmoy:660F38V02rM",
vphaddsw_3 = "rrmoy:660F38V03rM",
vphminposuw_2 = "rmo:660F38u41rM",
vphsubw_3 = "rrmoy:660F38V05rM",
vphsubd_3 = "rrmoy:660F38V06rM",
vphsubsw_3 = "rrmoy:660F38V07rM",
vpinsrb_4 = "rrri/ood:660F3AV20rMU|rrxi/oob:",
vpinsrw_4 = "rrri/ood:660FVC4rMU|rrxi/oow:",
vpinsrd_4 = "rrmi/ood:660F3AV22rMU",
vpinsrq_4 = "rrmi/ooq:660F3AVX22rMU",
vpmaddubsw_3 = "rrmoy:660F38V04rM",
vpmaxsb_3 = "rrmoy:660F38V3CrM",
vpmaxsd_3 = "rrmoy:660F38V3DrM",
vpmaxuw_3 = "rrmoy:660F38V3ErM",
vpmaxud_3 = "rrmoy:660F38V3FrM",
vpminsb_3 = "rrmoy:660F38V38rM",
vpminsd_3 = "rrmoy:660F38V39rM",
vpminuw_3 = "rrmoy:660F38V3ArM",
vpminud_3 = "rrmoy:660F38V3BrM",
vpmovmskb_2 = "rr/do:660FuD7rM|rr/dy:660FuLD7rM",
vpmovsxbw_2 = "rroy:660F38u20rM|rx/oq:|rx/yo:",
vpmovsxbd_2 = "rroy:660F38u21rM|rx/od:|rx/yq:",
vpmovsxbq_2 = "rroy:660F38u22rM|rx/ow:|rx/yd:",
vpmovsxwd_2 = "rroy:660F38u23rM|rx/oq:|rx/yo:",
vpmovsxwq_2 = "rroy:660F38u24rM|rx/od:|rx/yq:",
vpmovsxdq_2 = "rroy:660F38u25rM|rx/oq:|rx/yo:",
vpmovzxbw_2 = "rroy:660F38u30rM|rx/oq:|rx/yo:",
vpmovzxbd_2 = "rroy:660F38u31rM|rx/od:|rx/yq:",
vpmovzxbq_2 = "rroy:660F38u32rM|rx/ow:|rx/yd:",
vpmovzxwd_2 = "rroy:660F38u33rM|rx/oq:|rx/yo:",
vpmovzxwq_2 = "rroy:660F38u34rM|rx/od:|rx/yq:",
vpmovzxdq_2 = "rroy:660F38u35rM|rx/oq:|rx/yo:",
vpmuldq_3 = "rrmoy:660F38V28rM",
vpmulhrsw_3 = "rrmoy:660F38V0BrM",
vpmulld_3 = "rrmoy:660F38V40rM",
vpshufb_3 = "rrmoy:660F38V00rM",
vpshufd_3 = "rmioy:660Fu70rMU",
vpshufhw_3 = "rmioy:F30Fu70rMU",
vpshuflw_3 = "rmioy:F20Fu70rMU",
vpsignb_3 = "rrmoy:660F38V08rM",
vpsignw_3 = "rrmoy:660F38V09rM",
vpsignd_3 = "rrmoy:660F38V0ArM",
vpslldq_3 = "rrioy:660Fv737mU",
vpsllw_3 = "rrmoy:660FVF1rM|rrioy:660Fv716mU",
vpslld_3 = "rrmoy:660FVF2rM|rrioy:660Fv726mU",
vpsllq_3 = "rrmoy:660FVF3rM|rrioy:660Fv736mU",
vpsraw_3 = "rrmoy:660FVE1rM|rrioy:660Fv714mU",
vpsrad_3 = "rrmoy:660FVE2rM|rrioy:660Fv724mU",
vpsrldq_3 = "rrioy:660Fv733mU",
vpsrlw_3 = "rrmoy:660FVD1rM|rrioy:660Fv712mU",
vpsrld_3 = "rrmoy:660FVD2rM|rrioy:660Fv722mU",
vpsrlq_3 = "rrmoy:660FVD3rM|rrioy:660Fv732mU",
vptest_2 = "rmoy:660F38u17rM",
-- AVX2 integer ops
vbroadcasti128_2 = "rx/yo:660F38u5ArM",
vinserti128_4 = "rrmi/yyo:660F3AV38rMU",
vextracti128_3 = "mri/oy:660F3AuL39RmU",
vpblendd_4 = "rrmioy:660F3AV02rMU",
vpbroadcastb_2 = "rro:660F38u78rM|rx/ob:|rr/yo:|rx/yb:",
vpbroadcastw_2 = "rro:660F38u79rM|rx/ow:|rr/yo:|rx/yw:",
vpbroadcastd_2 = "rro:660F38u58rM|rx/od:|rr/yo:|rx/yd:",
vpbroadcastq_2 = "rro:660F38u59rM|rx/oq:|rr/yo:|rx/yq:",
vpermd_3 = "rrmy:660F38V36rM",
vpermq_3 = "rmiy:660F3AuX00rMU",
-- *vpgather* (!vsib)
vperm2i128_4 = "rrmiy:660F3AV46rMU",
vpmaskmovd_3 = "rrxoy:660F38V8CrM|xrroy:660F38V8ERm",
vpmaskmovq_3 = "rrxoy:660F38VX8CrM|xrroy:660F38VX8ERm",
vpsllvd_3 = "rrmoy:660F38V47rM",
vpsllvq_3 = "rrmoy:660F38VX47rM",
vpsravd_3 = "rrmoy:660F38V46rM",
vpsrlvd_3 = "rrmoy:660F38V45rM",
vpsrlvq_3 = "rrmoy:660F38VX45rM",
}
------------------------------------------------------------------------------
-- Arithmetic ops.
for name,n in pairs{ add = 0, ["or"] = 1, adc = 2, sbb = 3,
["and"] = 4, sub = 5, xor = 6, cmp = 7 } do
local n8 = shl(n, 3)
map_op[name.."_2"] = format(
"mr:%02XRm|rm:%02XrM|mI1qdw:81%XmI|mS1qdw:83%XmS|Ri1qdwb:%02Xri|mi1qdwb:81%Xmi",
1+n8, 3+n8, n, n, 5+n8, n)
end
-- Shift ops.
for name,n in pairs{ rol = 0, ror = 1, rcl = 2, rcr = 3,
shl = 4, shr = 5, sar = 7, sal = 4 } do
map_op[name.."_2"] = format("m1:D1%Xm|mC1qdwb:D3%Xm|mi:C1%XmU", n, n, n)
end
-- Conditional ops.
for cc,n in pairs(map_cc) do
map_op["j"..cc.."_1"] = format("J.:n0F8%XJ", n) -- short: 7%X
map_op["set"..cc.."_1"] = format("mb:n0F9%X2m", n)
map_op["cmov"..cc.."_2"] = format("rmqdw:0F4%XrM", n) -- P6+
end
-- FP arithmetic ops.
for name,n in pairs{ add = 0, mul = 1, com = 2, comp = 3,
sub = 4, subr = 5, div = 6, divr = 7 } do
local nc = 0xc0 + shl(n, 3)
local nr = nc + (n < 4 and 0 or (n % 2 == 0 and 8 or -8))
local fn = "f"..name
map_op[fn.."_1"] = format("ff:D8%02Xr|xd:D8%Xm|xq:nDC%Xm", nc, n, n)
if n == 2 or n == 3 then
map_op[fn.."_2"] = format("Fff:D8%02XR|Fx2d:D8%XM|Fx2q:nDC%XM", nc, n, n)
else
map_op[fn.."_2"] = format("Fff:D8%02XR|fFf:DC%02Xr|Fx2d:D8%XM|Fx2q:nDC%XM", nc, nr, n, n)
map_op[fn.."p_1"] = format("ff:DE%02Xr", nr)
map_op[fn.."p_2"] = format("fFf:DE%02Xr", nr)
end
map_op["fi"..name.."_1"] = format("xd:DA%Xm|xw:nDE%Xm", n, n)
end
-- FP conditional moves.
for cc,n in pairs{ b=0, e=1, be=2, u=3, nb=4, ne=5, nbe=6, nu=7 } do
local nc = 0xdac0 + shl(band(n, 3), 3) + shl(band(n, 4), 6)
map_op["fcmov"..cc.."_1"] = format("ff:%04Xr", nc) -- P6+
map_op["fcmov"..cc.."_2"] = format("Fff:%04XR", nc) -- P6+
end
-- SSE / AVX FP arithmetic ops.
for name,n in pairs{ sqrt = 1, add = 8, mul = 9,
sub = 12, min = 13, div = 14, max = 15 } do
map_op[name.."ps_2"] = format("rmo:0F5%XrM", n)
map_op[name.."ss_2"] = format("rro:F30F5%XrM|rx/od:", n)
map_op[name.."pd_2"] = format("rmo:660F5%XrM", n)
map_op[name.."sd_2"] = format("rro:F20F5%XrM|rx/oq:", n)
if n ~= 1 then
map_op["v"..name.."ps_3"] = format("rrmoy:0FV5%XrM", n)
map_op["v"..name.."ss_3"] = format("rrro:F30FV5%XrM|rrx/ood:", n)
map_op["v"..name.."pd_3"] = format("rrmoy:660FV5%XrM", n)
map_op["v"..name.."sd_3"] = format("rrro:F20FV5%XrM|rrx/ooq:", n)
end
end
-- SSE2 / AVX / AVX2 integer arithmetic ops (66 0F leaf).
for name,n in pairs{
paddb = 0xFC, paddw = 0xFD, paddd = 0xFE, paddq = 0xD4,
paddsb = 0xEC, paddsw = 0xED, packssdw = 0x6B,
packsswb = 0x63, packuswb = 0x67, paddusb = 0xDC,
paddusw = 0xDD, pand = 0xDB, pandn = 0xDF, pavgb = 0xE0,
pavgw = 0xE3, pcmpeqb = 0x74, pcmpeqd = 0x76,
pcmpeqw = 0x75, pcmpgtb = 0x64, pcmpgtd = 0x66,
pcmpgtw = 0x65, pmaddwd = 0xF5, pmaxsw = 0xEE,
pmaxub = 0xDE, pminsw = 0xEA, pminub = 0xDA,
pmulhuw = 0xE4, pmulhw = 0xE5, pmullw = 0xD5,
pmuludq = 0xF4, por = 0xEB, psadbw = 0xF6, psubb = 0xF8,
psubw = 0xF9, psubd = 0xFA, psubq = 0xFB, psubsb = 0xE8,
psubsw = 0xE9, psubusb = 0xD8, psubusw = 0xD9,
punpckhbw = 0x68, punpckhwd = 0x69, punpckhdq = 0x6A,
punpckhqdq = 0x6D, punpcklbw = 0x60, punpcklwd = 0x61,
punpckldq = 0x62, punpcklqdq = 0x6C, pxor = 0xEF
} do
map_op[name.."_2"] = format("rmo:660F%02XrM", n)
map_op["v"..name.."_3"] = format("rrmoy:660FV%02XrM", n)
end
------------------------------------------------------------------------------
local map_vexarg = { u = false, v = 1, V = 2 }
-- Process pattern string.
local function dopattern(pat, args, sz, op, needrex)
local digit, addin, vex
local opcode = 0
local szov = sz
local narg = 1
local rex = 0
-- Limit number of section buffer positions used by a single dasm_put().
-- A single opcode needs a maximum of 6 positions.
if secpos+6 > maxsecpos then wflush() end
-- Process each character.
for c in gmatch(pat.."|", ".") do
if match(c, "%x") then -- Hex digit.
digit = byte(c) - 48
if digit > 48 then digit = digit - 39
elseif digit > 16 then digit = digit - 7 end
opcode = opcode*16 + digit
addin = nil
elseif c == "n" then -- Disable operand size mods for opcode.
szov = nil
elseif c == "X" then -- Force REX.W.
rex = 8
elseif c == "L" then -- Force VEX.L.
vex.l = true
elseif c == "r" then -- Merge 1st operand regno. into opcode.
addin = args[1]; opcode = opcode + (addin.reg % 8)
if narg < 2 then narg = 2 end
elseif c == "R" then -- Merge 2nd operand regno. into opcode.
addin = args[2]; opcode = opcode + (addin.reg % 8)
narg = 3
elseif c == "m" or c == "M" then -- Encode ModRM/SIB.
local s
if addin then
s = addin.reg
opcode = opcode - band(s, 7) -- Undo regno opcode merge.
else
s = band(opcode, 15) -- Undo last digit.
opcode = shr(opcode, 4)
end
local nn = c == "m" and 1 or 2
local t = args[nn]
if narg <= nn then narg = nn + 1 end
if szov == "q" and rex == 0 then rex = rex + 8 end
if t.reg and t.reg > 7 then rex = rex + 1 end
if t.xreg and t.xreg > 7 then rex = rex + 2 end
if s > 7 then rex = rex + 4 end
if needrex then rex = rex + 16 end
local psz, sk = wputop(szov, opcode, rex, vex, s < 0, t.vreg or t.vxreg)
opcode = nil
local imark = sub(pat, -1) -- Force a mark (ugly).
-- Put ModRM/SIB with regno/last digit as spare.
wputmrmsib(t, imark, s, addin and addin.vreg, psz, sk)
addin = nil
elseif map_vexarg[c] ~= nil then -- Encode using VEX prefix
local b = band(opcode, 255); opcode = shr(opcode, 8)
local m = 1
if b == 0x38 then m = 2
elseif b == 0x3a then m = 3 end
if m ~= 1 then b = band(opcode, 255); opcode = shr(opcode, 8) end
if b ~= 0x0f then
werror("expected `0F', `0F38', or `0F3A' to precede `"..c..
"' in pattern `"..pat.."' for `"..op.."'")
end
local v = map_vexarg[c]
if v then v = remove(args, v) end
b = band(opcode, 255)
local p = 0
if b == 0x66 then p = 1
elseif b == 0xf3 then p = 2
elseif b == 0xf2 then p = 3 end
if p ~= 0 then opcode = shr(opcode, 8) end
if opcode ~= 0 then wputop(nil, opcode, 0); opcode = 0 end
vex = { m = m, p = p, v = v }
else
if opcode then -- Flush opcode.
if szov == "q" and rex == 0 then rex = rex + 8 end
if needrex then rex = rex + 16 end
if addin and addin.reg == -1 then
local psz, sk = wputop(szov, opcode - 7, rex, vex, true)
wvreg("opcode", addin.vreg, psz, sk)
else
if addin and addin.reg > 7 then rex = rex + 1 end
wputop(szov, opcode, rex, vex)
end
opcode = nil
end
if c == "|" then break end
if c == "o" then -- Offset (pure 32 bit displacement).
wputdarg(args[1].disp); if narg < 2 then narg = 2 end
elseif c == "O" then
wputdarg(args[2].disp); narg = 3
else
-- Anything else is an immediate operand.
local a = args[narg]
narg = narg + 1
local mode, imm = a.mode, a.imm
if mode == "iJ" and not match("iIJ", c) then
werror("bad operand size for label")
end
if c == "S" then
wputsbarg(imm)
elseif c == "U" then
wputbarg(imm)
elseif c == "W" then
wputwarg(imm)
elseif c == "i" or c == "I" then
if mode == "iJ" then
wputlabel("IMM_", imm, 1)
elseif mode == "iI" and c == "I" then
waction(sz == "w" and "IMM_WB" or "IMM_DB", imm)
else
wputszarg(sz, imm)
end
elseif c == "J" then
if mode == "iPJ" then
waction("REL_A", imm) -- !x64 (secpos)
else
wputlabel("REL_", imm, 2)
end
elseif c == "s" then
local reg = a.reg
if reg < 0 then
wputb(0)
wvreg("imm.hi", a.vreg)
else
wputb(shl(reg, 4))
end
else
werror("bad char `"..c.."' in pattern `"..pat.."' for `"..op.."'")
end
end
end
end
end
------------------------------------------------------------------------------
-- Mapping of operand modes to short names. Suppress output with '#'.
local map_modename = {
r = "reg", R = "eax", C = "cl", x = "mem", m = "mrm", i = "imm",
f = "stx", F = "st0", J = "lbl", ["1"] = "1",
I = "#", S = "#", O = "#",
}
-- Return a table/string showing all possible operand modes.
local function templatehelp(template, nparams)
if nparams == 0 then return "" end
local t = {}
for tm in gmatch(template, "[^%|]+") do
local s = map_modename[sub(tm, 1, 1)]
s = s..gsub(sub(tm, 2, nparams), ".", function(c)
return ", "..map_modename[c]
end)
if not match(s, "#") then t[#t+1] = s end
end
return t
end
-- Match operand modes against mode match part of template.
local function matchtm(tm, args)
for i=1,#args do
if not match(args[i].mode, sub(tm, i, i)) then return end
end
return true
end
-- Handle opcodes defined with template strings.
map_op[".template__"] = function(params, template, nparams)
if not params then return templatehelp(template, nparams) end
local args = {}
-- Zero-operand opcodes have no match part.
if #params == 0 then
dopattern(template, args, "d", params.op, nil)
return
end
-- Determine common operand size (coerce undefined size) or flag as mixed.
local sz, szmix, needrex
for i,p in ipairs(params) do
args[i] = parseoperand(p)
local nsz = args[i].opsize
if nsz then
if sz and sz ~= nsz then szmix = true else sz = nsz end
end
local nrex = args[i].needrex
if nrex ~= nil then
if needrex == nil then
needrex = nrex
elseif needrex ~= nrex then
werror("bad mix of byte-addressable registers")
end
end
end
-- Try all match:pattern pairs (separated by '|').
local gotmatch, lastpat
for tm in gmatch(template, "[^%|]+") do
-- Split off size match (starts after mode match) and pattern string.
local szm, pat = match(tm, "^(.-):(.*)$", #args+1)
if pat == "" then pat = lastpat else lastpat = pat end
if matchtm(tm, args) then
local prefix = sub(szm, 1, 1)
if prefix == "/" then -- Exactly match leading operand sizes.
for i = #szm,1,-1 do
if i == 1 then
dopattern(pat, args, sz, params.op, needrex) -- Process pattern.
return
elseif args[i-1].opsize ~= sub(szm, i, i) then
break
end
end
else -- Match common operand size.
local szp = sz
if szm == "" then szm = x64 and "qdwb" or "dwb" end -- Default sizes.
if prefix == "1" then szp = args[1].opsize; szmix = nil
elseif prefix == "2" then szp = args[2].opsize; szmix = nil end
if not szmix and (prefix == "." or match(szm, szp or "#")) then
dopattern(pat, args, szp, params.op, needrex) -- Process pattern.
return
end
end
gotmatch = true
end
end
local msg = "bad operand mode"
if gotmatch then
if szmix then
msg = "mixed operand size"
else
msg = sz and "bad operand size" or "missing operand size"
end
end
werror(msg.." in `"..opmodestr(params.op, args).."'")
end
------------------------------------------------------------------------------
-- x64-specific opcode for 64 bit immediates and displacements.
if x64 then
function map_op.mov64_2(params)
if not params then return { "reg, imm", "reg, [disp]", "[disp], reg" } end
if secpos+2 > maxsecpos then wflush() end
local opcode, op64, sz, rex, vreg
local op64 = match(params[1], "^%[%s*(.-)%s*%]$")
if op64 then
local a = parseoperand(params[2])
if a.mode ~= "rmR" then werror("bad operand mode") end
sz = a.opsize
rex = sz == "q" and 8 or 0
opcode = 0xa3
else
op64 = match(params[2], "^%[%s*(.-)%s*%]$")
local a = parseoperand(params[1])
if op64 then
if a.mode ~= "rmR" then werror("bad operand mode") end
sz = a.opsize
rex = sz == "q" and 8 or 0
opcode = 0xa1
else
if sub(a.mode, 1, 1) ~= "r" or a.opsize ~= "q" then
werror("bad operand mode")
end
op64 = params[2]
if a.reg == -1 then
vreg = a.vreg
opcode = 0xb8
else
opcode = 0xb8 + band(a.reg, 7)
end
rex = a.reg > 7 and 9 or 8
end
end
local psz, sk = wputop(sz, opcode, rex, nil, vreg)
wvreg("opcode", vreg, psz, sk)
if luamode then
waction("IMM_D", format("ffi.cast(\"uintptr_t\", %s) %% 2^32", op64))
waction("IMM_D", format("ffi.cast(\"uintptr_t\", %s) / 2^32", op64))
else
waction("IMM_D", format("(unsigned int)(%s)", op64))
waction("IMM_D", format("(unsigned int)((%s)>>32)", op64))
end
end
end
------------------------------------------------------------------------------
-- Pseudo-opcodes for data storage.
local function op_data(params)
if not params then return "imm..." end
local sz = sub(params.op, 2, 2)
if sz == "a" then sz = addrsize end
for _,p in ipairs(params) do
local a = parseoperand(p)
if sub(a.mode, 1, 1) ~= "i" or (a.opsize and a.opsize ~= sz) then
werror("bad mode or size in `"..p.."'")
end
if a.mode == "iJ" then
wputlabel("IMM_", a.imm, 1)
else
wputszarg(sz, a.imm)
end
if secpos+2 > maxsecpos then wflush() end
end
end
map_op[".byte_*"] = op_data
map_op[".sbyte_*"] = op_data
map_op[".word_*"] = op_data
map_op[".dword_*"] = op_data
map_op[".aword_*"] = op_data
------------------------------------------------------------------------------
-- Pseudo-opcode to mark the position where the action list is to be emitted.
map_op[".actionlist_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeactions(out, name) end)
end
-- Pseudo-opcode to mark the position where the global enum is to be emitted.
map_op[".globals_1"] = function(params)
if not params then return "prefix" end
local prefix = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobals(out, prefix) end)
end
-- Pseudo-opcode to mark the position where the global names are to be emitted.
map_op[".globalnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobalnames(out, name) end)
end
-- Pseudo-opcode to mark the position where the extern names are to be emitted.
map_op[".externnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeexternnames(out, name) end)
end
------------------------------------------------------------------------------
-- Label pseudo-opcode (converted from trailing colon form).
map_op[".label_2"] = function(params)
if not params then return "[1-9] | ->global | =>pcexpr [, addr]" end
if secpos+2 > maxsecpos then wflush() end
local a = parseoperand(params[1])
local mode, imm = a.mode, a.imm
if type(imm) == "number" and (mode == "iJ" or (imm >= 1 and imm <= 9)) then
-- Local label (1: ... 9:) or global label (->global:).
waction("LABEL_LG", nil, 1)
wputxb(imm)
elseif mode == "iJ" then
-- PC label (=>pcexpr:).
waction("LABEL_PC", imm)
else
werror("bad label definition")
end
-- SETLABEL must immediately follow LABEL_LG/LABEL_PC.
local addr = params[2]
if addr then
local a = parseoperand(addr)
if a.mode == "iPJ" then
waction("SETLABEL", a.imm)
else
werror("bad label assignment")
end
end
end
map_op[".label_1"] = map_op[".label_2"]
------------------------------------------------------------------------------
-- Alignment pseudo-opcode.
map_op[".align_1"] = function(params)
if not params then return "numpow2" end
if secpos+1 > maxsecpos then wflush() end
local align = tonumber(params[1]) or map_opsizenum[map_opsize[params[1]]]
if align then
local x = align
-- Must be a power of 2 in the range (2 ... 256).
for i=1,8 do
x = x / 2
if x == 1 then
waction("ALIGN", nil, 1)
wputxb(align-1) -- Action byte is 2**n-1.
return
end
end
end
werror("bad alignment")
end
-- Spacing pseudo-opcode.
map_op[".space_2"] = function(params)
if not params then return "num [, filler]" end
if secpos+1 > maxsecpos then wflush() end
waction("SPACE", params[1])
local fill = params[2]
if fill then
fill = tonumber(fill)
if not fill or fill < 0 or fill > 255 then werror("bad filler") end
end
wputxb(fill or 0)
end
map_op[".space_1"] = map_op[".space_2"]
------------------------------------------------------------------------------
-- Pseudo-opcode for (primitive) type definitions (map to C types).
map_op[".type_3"] = function(params, nparams)
if not params then
return nparams == 2 and "name, ctype" or "name, ctype, reg"
end
local name, ctype, reg = params[1], params[2], params[3]
if not match(name, "^[%a_][%w_]*$") then
werror("bad type name `"..name.."'")
end
local tp = map_type[name]
if tp then
werror("duplicate type `"..name.."'")
end
if reg and not map_reg_valid_base[reg] then
werror("bad base register `"..(map_reg_rev[reg] or reg).."'")
end
-- Add #type to current defines table.
g_map_def["#"..name] = luamode and "ffi.sizeof(\""..ctype.."\")" or "sizeof("..ctype..")"
-- Add new type and emit shortcut define.
local num = ctypenum + 1
local ctypefmt
if luamode then
ctypefmt = function(tailr)
local index, field
index, field = match(tailr, "^(%b[])(.*)")
index = index and sub(index, 2, -2)
field = field or tailr
field = match(field, "^%->(.*)") or match(field, "^%.(.*)")
if not (index or field) then
werror("invalid syntax `"..tailr.."`")
end
local Da = index and format("Da%X(%s)", num, index)
local Dt = field and format("Dt%X(\"%s\")", num, field)
return Da and Dt and Da.."+"..Dt or Da or Dt
end
else
ctypefmt = format("Dt%X(%%s)", num)
end
map_type[name] = {
ctype = ctype,
ctypefmt = ctypefmt,
reg = reg,
}
if luamode then
wline(format("local Dt%X; do local ct=ffi.typeof(\"%s\"); function Dt%X(f) return ffi.offsetof(ct,f) or error(string.format(\"'struct %s' has no member named '%%s'\", f)) end; end",
num, ctype, num, ctype))
wline(format("local Da%X; do local sz=ffi.sizeof(\"%s\"); function Da%X(i) return i*sz end; end",
num, ctype, num))
else
wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype))
end
ctypenum = num
end
map_op[".type_2"] = map_op[".type_3"]
-- Dump type definitions.
local function dumptypes(out, lvl)
local t = {}
for name in pairs(map_type) do t[#t+1] = name end
sort(t)
out:write("Type definitions:\n")
for _,name in ipairs(t) do
local tp = map_type[name]
local reg = tp.reg and map_reg_rev[tp.reg] or ""
out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg))
end
out:write("\n")
end
------------------------------------------------------------------------------
-- Set the current section.
function _M.section(num)
waction("SECTION")
wputxb(num)
wflush(true) -- SECTION is a terminal action.
end
------------------------------------------------------------------------------
-- Dump architecture description.
function _M.dumparch(out)
out:write(format("DynASM %s version %s, released %s\n\n",
_info.arch, _info.version, _info.release))
dumpregs(out)
dumpactions(out)
end
-- Dump all user defined elements.
function _M.dumpdef(out, lvl)
dumptypes(out, lvl)
dumpglobals(out, lvl)
dumpexterns(out, lvl)
end
------------------------------------------------------------------------------
-- Pass callbacks from/to the DynASM core.
function _M.passcb(wl, we, wf, ww)
wline, werror, wfatal, wwarn = wl, we, wf, ww
return wflush
end
-- Setup the arch-specific module.
function _M.setup(arch, opt)
g_arch, g_opt = arch, opt
luamode = g_opt.lang == "lua"
init_actionlist()
init_map_global()
init_map_extern()
init_map_type()
end
-- Merge the core maps and the arch-specific maps.
function _M.mergemaps(map_coreop, map_def)
setmetatable(map_op, { __index = map_coreop })
setmetatable(map_def, { __index = map_archdef })
-- Hold a ref. to map_def to store `#type` defines in.
g_map_def = map_def
return map_op, map_def
end
return _M
------------------------------------------------------------------------------
| apache-2.0 |
groupforspeed/TeleSpeed-Tg | plugins/location.lua | 93 | 1704 | -- Implement a command !loc [area] which uses
-- the static map API to get a location image
-- Not sure if this is the proper way
-- Intent: get_latlong is in time.lua, we need it here
-- loadfile "time.lua"
-- Globals
-- If you have a google api key for the geocoding/timezone api
do
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
function get_staticmap(area)
local api = base_api .. "/staticmap?"
-- Get a sense of scale
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale=="locality" then zoom=8
elseif scale=="country" then zoom=4
else zoom = 13 end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~=nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
function run(msg, matches)
local receiver = get_receiver(msg)
local lat,lng,url = get_staticmap(matches[1])
-- Send the actual location, is a google maps link
send_location(receiver, lat, lng, ok_cb, false)
-- Send a picture of the map, which takes scale into account
send_photo_from_url(receiver, url)
-- Return a link to the google maps stuff is now not needed anymore
return nil
end
return {
description = "Gets information about a location, maplink and overview",
usage = "!loc (location): Gets information about a location, maplink and overview",
patterns = {"^!loc (.*)$"},
run = run
}
end
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
groupforspeed/TeleSpeed-Tg | plugins/boobs.lua | 90 | 1731 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. 🔞",
"!butts: Get a butts NSFW image. 🔞"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
--Copyright; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
bmscoordinators/FFXI-Server | scripts/zones/Port_San_dOria/npcs/Avandale.lua | 14 | 1052 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Avandale
-- Type: Standard NPC
-- @zone 232
-- @pos -105.524 -9 -125.274
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x022b);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Trebek/ComputerCraft | Funhouse/Archived/Funhouse_v0.3.2.lua | 1 | 22464 | --[[ INFO ]] --
-- Name: Tales from the Funhouse
-- Version: 0.3.2
-- Date: 25/08/2013
-- Author: Alex Crawford
-- Notes: N/A
--[[
TABLE OF CONTENTS
S1 - Tables
S1.1 - Error Message Table
S1.2 - Room Table
S1.3 - Player Table
S1.3.1 - Inventory Table
S1.4 - Action Table
S2 - 'Core' Functions
S2.1 - Print Title
S2.2 - Print Story
S2.3 - Print Menu
S2.4 - Print Room Info
S2.5 - Check Inventory
S2.6 - Print Player Info
S2.7 - Get User Input
S2.8 - 'Passive' Functions
S2.8.1 - Look Conditions
S2.8.1.1 - Inventory Look Conditions
S2.8.2 - Get Conditions
S2.8.3 - Misc Conditions
S2.8.4 - Help Conditions
S2.9 - Quit Function
S2.10 - Save/Load Functions
S2.10.1 - Save Function
S2.10.2 - Load Function
S2.11 - Score Check Function
S3 - Room Functions
S3.1 - Room 1 (Your Bedroom)
S3.1.1 - Room 1 Look Conditions
S3.1.2 - Room 1 Get Conditions
S3.1.3 - Room 1 Path Conditions
S3.2 - Room 2 (Your Bathroom)
S3.2.1 - Room 2 Look Conditions
S3.2.2 - Room 2 Get Conditions
S3.2.3 - Room 2 Open Conditions
S3.2.4 - Room 2 Close Conditions
S3.2.5 - Room 2 Path Conditions
S3.3 - Room 3 (Upstaris Hall of Your House)
S4 - Loops
S4.1 - Room 1 (Your Bedroom) Loop
S4.2 - Room 2 (Your Bathroom) Loop
S4.3 - Room 3 (Upstairs Hall in Your House) Loop
]]--
--[[ S1 - TABLES ]]--
--[[ S1.1 - Error Message Table ]]--
local ErrMess_Table = {
NoPath = "Invalid path.",
}
--[[ S1.2 - Room Table ]]--
local Room_Table = {
[1] = {
Name = "Your Bedroom",
Descrip = "You are standing in your bedroom. It is, like most teenager's rooms, a mess. There are posters all over the walls, and clothes all over the floor. Against the west wall is your (unmade) bed, and against the east wall, under a window, is a messy desk, and chair." .. "\n\n" .. "There is a door to the upstairs hall to the north, and a door to your bathroom to the south",
Obj = {
Obj_Desk = {
[1] = false,
[2] = "You look at the desk. It is cluttered. There appears to be a book under some of the papers.\n",
[3] = "You look at the desk. It is cluttered. There are papers all over the place.\n",
},
Obj_Papers = {
[1] = false,
[2] = "Just some papers. Mostly school work. Nothing of interest.\n",
},
Obj_Walls = {
[1] = false,
[2] = "The walls are a little grungy, and covered in posters. You can't remember the last time they were cleaned, or repainted.\n",
},
Obj_Floor = {
[1] = false,
[2] = "The floor is carpeted, and could really use a vacuuming. There is dirty laundry strewn about, and one large pile at the foot of your bed.\n",
},
Obj_Posters = {
[1] = false,
[2] = "There are posters for various horror, sci-fi, and action movies covering the wall (A Bad Dream on Elk Street, Escape from New Jersey, 2013: A Spaced Odyssey, etc.). There are also some band posters as well (Megaded, AD/BC, Rawmones, etc.).\n",
},
Obj_Chair = {
[1] = false,
[2] = "It's just a run-of-the-mill office chair. There is a nice butt groove in it, from years of use.\n",
},
Obj_Laundry = {
[1] = false,
[2] = "Just some dirty (and smelly) laundry.\n",
},
},
},
[2] = {
Name = "Your Bathroom",
Descrip = "Your bathroom is only slightly cleaner than your bedroom. There is a toilet in the southeast corner, and a sink to the left of the toilet. Above the sink is a mirror/medicine cabinet.",
Obj = {
Obj_Toilet = {
[1] = false,
[2] = "Yuck. When was the last time you cleaned your toilet? You can't recall. Maybe never? At least you flushed last time.\n",
},
Obj_Sink = {
[1] = false,
[2] = "The faucet drips slowly. There appears to be a bit of toothpaste scum in the sink.\n",
},
Obj_MedCab = {
[1] = false,
[2] = "You look into the mirror on the cabinet. Mirror mirror on the wall, who's the raddest of them all?\n",
[3] = "Your medicine cabinet contains toothpaste, a toothbrush, hair gel, and some acne medication.\n",
},
Obj_MedCabOpen = {
[1] = false,
[2] = "You look into the mirror on the cabinet. Mirror mirror on the wall, who's the raddest of them all?\n",
[3] = "Your medicine cabinet contains toothpaste, a toothbrush, hair gel, and some acne medication.\n",
},
Obj_Toothpaste = {
[1] = false,
[2] = "A half squeezed tube of toothpaste. Good for keeping your chompers clean. Maybe you should use it more often?\n",
},
Obj_Toothbrush = {
[1] = false,
[2] = "A tool for brushing your teeth. Amazing.\n",
},
Obj_AcneMed = {
[1] = false,
[2] = "An old tube of acne cream. Luckily your acne is starting to subside.\n",
},
},
},
[3] = {
Name = "Upstairs Hall of Your House",
Descrip = "This is the description for Room Two.",
},
}
--[[ S1.3 - Player Table ]]--
local Player_Table = {
Location = Room_Table[1]["Name"],
Score = 0,
}
--[[ S1.3.1 - Inventory Table ]]--
local Inv_Table = {
[1] = {
[1] = "Journal",
[2] = "A journal. It is a bit ratty looking.\n",
[3] = false,
},
[2] = {
[1] = "Key",
[2] = "A key.",
[3] = false,
},
[3] = {
[1] = "Item Three",
[2] = "An item.",
[3] = false,
},
[4] = {
[1] = "Item Four",
[2] = "Another item.",
[3] = false,
},
}
--[[ S1.4 - Action Table ]]--
local Act_Table = {
[1] = {
[1] = "close",
[2] = "Closes a specified object." .. "\n\n" .. "Usage: close <OBJECT>" .. "\n",
},
[2] = {
[1] = "get",
[2] = "If possible, picks up the specified object, and adds it to your inventory." .. "\n\n" .. "Usage: get <OBJECT>" .. "\n",
},
[3] = {
[1] = "give",
[2] = "Gives a specified object to a specified person" .. "\n\n" .. "Usage: give <OBJECT> <PERSON>" .. "\n",
},
[4] = {
[1] = "go",
[2] = "Move in a specified direction, usually out of the current room." .. "\n\n" .. "Usage: go <DIRECTION>" .. "\n",
},
[5] = {
[1] = "help",
[2] = "Displays some helpful information." .. "\n\n" .. "Usage: \"help\", or \"help <ACTION/COMMAND>\"" .. "\n",
},
[6] = {
[1] = "info",
[2] = "Displays your location, score, and inventory." .. "\n\n" .. "Usage: info" .. "\n",
},
[7] = {
[1] = "look",
[2] = "Look at a specified object, whether held or in the world." .. "\n\n" .. "Usage: look <OBJECT>" .. "\n",
},
[8] = {
[1] = "open",
[2] = "Opens a specified object." .. "\n\n" .. "Usage: open <OBJECT>" .. "\n",
},
[9] = {
[1] = "pull",
[2] = "Pull a specified object." .. "\n\n" .. "Usage: pull <OBJECT>" .. "\n",
},
[10] = {
[1] = "push",
[2] = "Push a specified object." .. "\n\n" .. "Usage: push <OBJECT>" .. "\n",
},
[11] = {
[1] = "read",
[2] = "Read a specified object." .. "\n\n" .. "." .. "\n" .. "Usage: read <OBJECT>" .. "\n",
},
[12] = {
[1] = "save",
[2] = "Save your current game." .. "\n\n" .. "Usage: save" .. "\n",
},
[13] = {
[1] = "talk",
[2] = "Talk to a specified person, or thing." .. "\n\n" .. "Usage: close <OBJECT>" .. "\n",
},
[14] = {
[1] = "quit",
[2] = "Quit the game." .. "\n\n" .. "Usage: \"quit\", or \"exit\"" .. "\n",
},
[15] = {
[1] = "use",
[2] = "Use a specified object you are carrying, or an object in the world." .. "\n\n" .. "Usage: \"use <OBJECT>\", or \"use <OBJECT> with <OBJECT>\"" .."\n",
},
}
--[[ S2 - 'CORE' FUNCTIONS ]]--
--[[ S2.1 - Print Title ]]--
function PrintTitle()
term.clear()
term.setCursorPos(10,4)
write("--------------------------------")
term.setCursorPos(14,6)
print("TALES FROM THE FUNHOUSE")
term.setCursorPos(10,8)
write("--------------------------------")
term.setCursorPos(21,10)
write("A GAME BY")
term.setCursorPos(19,11)
write("ALEX CRAWFORD")
os.pullEvent()
end
--[[ S2.2 - Print Story ]]--
function PrintStory()
term.clear()
term.setCursorPos(1,1)
print("You are Jack. You are a relatively regular teenager, living a relatively regular life, in a relatively regular little town, where not much ever happens.\n\nOne day, while strolling down the street, on the way to meet your friends at the mall, a poster on a telephone poll catches your eye. It's for a fair coming through the town. You figure it might be a good time, or at the very least better than sitting around at home. You tear the poster from the pole, stuff it in your pocket, where you promptly forget about it, and contiue on your way.\n\nThat evening you rediscover the crumpled up poster in your pocket, and decide to call up a couple of friends, and to meet up at the fair, after dinner.")
os.pullEvent()
end
--[[ S2.3 - Print Menu ]]--
function PrintMenu()
term.clear()
term.setCursorPos(1,1)
term.setTextColor(colors.lightGray)
write("--------------------------------\n")
term.setTextColor(colors.white)
write("Main Menu\n")
term.setTextColor(colors.lightGray)
write("--------------------------------\n\n")
term.setTextColor(colors.white)
write("1. New Game" .. "\n")
write("2. Load Game" .. "\n")
write("3. Credits" .. "\n\n")
write("4. Quit" .. "\n")
local event, param = os.pullEvent("char")
if param == "1" then
return
elseif param == "2" then
LoadGame()
elseif param == "3" then
return
elseif param == "4" then
term.clear()
term.setCursorPos(1,1)
error()
else
return
end
end
--[[ S2.4 - Print Room Info ]]--
function PrintRoomInfo()
local UserLoc = Player_Table.Location
local UserLocDescrip = Player_Table.Location
term.setTextColor(colors.lightGray)
write("--------------------------------\n")
term.setTextColor(colors.white)
write(UserLoc .. "\n")
term.setTextColor(colors.lightGray)
write("--------------------------------\n\n")
term.setTextColor(colors.white)
for i, v in ipairs(Room_Table) do
if UserLoc == Room_Table[i]["Name"] then
write(Room_Table[i]["Descrip"] .. "\n\n")
end
end
end
--[[ S2.5 - Check Inventory ]]--
function GetInv()
write("Inventory:\n")
term.setTextColor(colors.lightGray)
if Inv_Table[1][3] == true then
print(Inv_Table[1][1])
end
if Inv_Table[2][3] == true then
print(tostring(Inv_Table[2][1]))
end
if Inv_Table[3][3] == true then
print(Inv_Table[3][1])
end
if Inv_Table[4][3] == true then
print(Inv_Table[4][1])
end
print()
term.setTextColor(colors.white)
end
--[[ S2.6 - Print Player Info ]]--
function PlayerInfo()
local UserLoc = Player_Table.Location
local UserScore = Player_Table.Score
write("Location: ")
term.setTextColor(colors.lightGray)
write(UserLoc .. "\n")
term.setTextColor(colors.white)
write("Score: ")
term.setTextColor(colors.lightGray)
write(UserScore .. "\n\n")
term.setTextColor(colors.white)
GetInv()
end
--[[ S2.7 - Get User Input ]]--
function GetInput()
term.setTextColor(colors.lightGray)
write("--------------------------------\n")
print()
term.setTextColor(colors.green)
write("-> ")
term.setTextColor(colors.white)
local Input = string.lower(read())
print()
return Input
end
--[[ S2.8 - 'Passive' Functions ]]--
function PassiveFunc(Input)
local UserLoc = Player_Table.Location
--[[ S2.8.1 - Look Conditions ]]--
--[[ S2.8.1.1 - Inventory Look Conditions ]]--
if Player_Table.Location ~= Room_Table[1] then
if string.find(Input, Act_Table[7][1]) then
if string.find(Input, "journal") then
if Inv_Table[1][3] == true then
print(Inv_Table[1][2])
elseif Inv_Table[1][3] == false then
print("\nYou don't have a journal.\n\n")
end
end
end
end
if string.find(Input, Act_Table[9][1]) then
if string.find(Input, "journal") and Inv_Table[1][3] == true then
print("You read the journal.\n")
print("18/08/1990")
print("The password is 'password'. Great password, I know.\n")
elseif string.find(Input, "journal") and Inv_Table[1][3] == false then
print("\nYou don't have a journal.\n\n")
end
end
if Input == "look" then
for i, v in ipairs(Room_Table) do
if UserLoc == Room_Table[i]["Name"] then
write(Room_Table[i]["Descrip"] .. "\n\n")
end
end
end
--[[ S2.8.2 - Get Conditions ]]--
if string.find(Input, Act_Table[2][1]) then
if Input == "get" then
write("Get what?\n\n")
end
end
--[[ S2.8.3 - Misc Conditions ]]--
if Input == "info" then
PlayerInfo()
end
if string.find(Input, "fuck") or string.find(Input, "shit") or string.find(Input, "cunt") then
print("There is no need for that kind of language.\n")
end
if Input == "die" then
Player_Table.Location = "dead"
end
if Input == "save" then
SaveMode = true
end
--[[ S2.8.4 - Help Conditions ]]--
if string.find(Input, "help") or string.find(Input, "?") then
if Input == "help" or Input == "?" then
print("Actions:")
term.setTextColor(colors.lightGray)
write("Close Get Give Go Look Open\n")
write("Pull Push Read Talk Use\n\n")
term.setTextColor(colors.white)
print("Misc. Actions:")
term.setTextColor(colors.lightGray)
write("Help Info Save Quit\n\n")
term.setTextColor(colors.white)
write("Type 'Help <ACTION>' to see action descriptions, and usage instructions.\n\n")
end
for i, v in ipairs(Act_Table) do
if Input == "help " .. Act_Table[i][1] or Input == "? " .. Act_Table[i][1]then
print(Act_Table[i][2])
end
end
end
end
--[[ S2.9 - Quit Function ]]--
function QuitGame(Input)
if Input == "exit" or Input == "quit" then
print("Hope you enjoyed playing Tales from the Funhouse! Goodbye!\n")
error()
end
end
--[[ S2.10 - Save/Load Functions ]]--
--[[ S2.10.1 - Save Function ]]--
function SaveGame()
write("\nWhat would you like to name the save file?\n\n")
local FileName = string.lower(read())
local file = fs.open(FileName, "w")
for k, v in pairs(Room_Table[1]["Obj"]) do
file.writeLine(textutils.serialize(Room_Table[1]["Obj"][k][1]))
end
for i, v in ipairs(Inv_Table) do
file.writeLine(textutils.serialize(Inv_Table[i][3]))
end
for k, v in pairs(Player_Table) do
file.writeLine(textutils.serialize(Player_Table[k]))
end
file.close()
print("\n" .. "File " .. "\"" .. FileName .. "\"" .. " saved." .. "\n\n")
SaveMode = false
end
--[[ S2.10.2 - Load Function ]]--
function LoadGame()
write("\nWhat save file would you like to load?\n\n")
local FileName = string.lower(read())
local file = fs.open(FileName, "r")
for k, v in pairs(Room_Table[1]["Obj"]) do
local RoomData = file.readLine()
Room_Table[1]["Obj"][k][1] = textutils.unserialize(RoomData)
end
for i, v in ipairs(Inv_Table) do
local InvData = file.readLine()
Inv_Table[i][3] = textutils.unserialize(InvData)
end
for k, v in pairs(Player_Table) do
local PlayerData = file.readLine()
Player_Table[k] = textutils.unserialize(PlayerData)
end
file.close()
print("\n" .. "File " .. "\"" .. FileName .. "\"" .. " loaded." .. "\n\n")
FirstPlay = false
end
--[[ S2.11 - Score Check Function ]]--
function ScoreCheck()
if Player_Table.Score > 22 then
print("Cheater! That score is too damn high.\n")
error()
end
end
--[[ S3 - ROOM FUNCTIONS ]]--
--[[ S3.1 - Room 1 (Your Bedroom) ]]--
function Room1_Func(Input)
--[[ S3.1.1 - Room 1 Look Conditions ]]--
if string.find(Input, Act_Table[7][1]) then -- If "look" then
if string.find(Input, "room") then -- If "look room" then
print(Room_Table[1]["Descrip"] .. "\n")
elseif string.find(Input, "desk") and Inv_Table[1][3] == true then -- If "look desk", and have Journal then
print(Room_Table[1]["Obj"]["Obj_Desk"][3])
if Room_Table[1]["Obj"]["Obj_Desk"][1] == false then -- If haven't looked then
Player_Table.Score = Player_Table.Score + 2
Room_Table[1]["Obj"]["Obj_Desk"][1] = true
end
elseif string.find(Input, "desk") and Inv_Table[1][3] == false then -- If "look desk", and no Journal then
print(Room_Table[1]["Obj"]["Obj_Desk"][2])
if Room_Table[1]["Obj"]["Obj_Desk"][1] == false then -- If haven't looked then
Player_Table.Score = Player_Table.Score + 2
Room_Table[1]["Obj"]["Obj_Desk"][1] = true
end
elseif string.find(Input, "papers")or string.find(Input, "paper") then
print(Room_Table[1]["Obj"]["Obj_Papers"][2])
if Room_Table[1]["Obj"]["Obj_Papers"][1] == false then
Player_Table.Score = Player_Table.Score + 2
Room_Table[1]["Obj"]["Obj_Papers"][1] = true
end
elseif string.find(Input, "walls") or string.find(Input, "wall") then
print(Room_Table[1]["Obj"]["Obj_Walls"][2])
if Room_Table[1]["Obj"]["Obj_Walls"][1] == false then
Player_Table.Score = Player_Table.Score + 2
Room_Table[1]["Obj"]["Obj_Walls"][1] = true
end
elseif string.find(Input, "floor") or string.find(Input, "floors") then
print(Room_Table[1]["Obj"]["Obj_Floor"][2])
if Room_Table[1]["Obj"]["Obj_Floor"][1] == false then
Player_Table.Score = Player_Table.Score + 2
Room_Table[1]["Obj"]["Obj_Floor"][1] = true
end
elseif string.find(Input, "poster") or string.find(Input, "posters") then
print(Room_Table[1]["Obj"]["Obj_Posters"][2])
if Room_Table[1]["Obj"]["Obj_Posters"][1] == false then
Player_Table.Score = Player_Table.Score + 2
Room_Table[1]["Obj"]["Obj_Posters"][1] = true
end
elseif string.find(Input, "chair") then
print(Room_Table[1]["Obj"]["Obj_Chair"][2])
if Room_Table[1]["Obj"]["Obj_Chair"][1] == false then
Player_Table.Score = Player_Table.Score + 2
Room_Table[1]["Obj"]["Obj_Chair"][1] = true
end
elseif string.find(Input, "clothes") or string.find(Input, "laundry") then
print(Room_Table[1]["Obj"]["Obj_Laundry"][2])
if Room_Table[1]["Obj"]["Obj_Laundry"][1] == false then
Player_Table.Score = Player_Table.Score + 2
Room_Table[1]["Obj"]["Obj_Laundry"][1] = true
end
elseif string.find(Input, "book") or string.find(Input, "journal") then
print(Inv_Table[1][2])
end
end
--[[ S3.1.2 - Room 1 Get Conditions ]]--
if string.find(Input, Act_Table[2][1]) then
if string.find(Input, "journal") or string.find(Input, "notebook") or string.find(Input, "book") then
if Inv_Table[1][3] == true then
print("You already have the journal.\n")
elseif Inv_Table[1][3] == false then
print("You take the journal. Maybe it contains some useful information.\n")
Inv_Table[1][3] = true
Player_Table.Score = Player_Table.Score + 8
end
end
end
--[[ S3.1.3 - Room 1 Path Conditions ]]--
if string.find(Input, Act_Table[4][1]) then
if Input == "go north" or Input == "go n" then
write("What is the password?\n\n")
local Input = string.lower(GetInput())
if Input == "password" then
Player_Table.Location = Room_Table[3]["Name"]
else
write("Wrong password.\n\n")
end
elseif Input == "go south" or Input == "go s" then
Player_Table.Location = Room_Table[2]["Name"]
end
end
end
--[[ S3.2 - Room 2 (Your Bathroom) ]]--
function Room2_Func(Input)
--[[ S3.2.1 - Room 2 Look Conditions ]]--
if string.find(Input, Act_Table[7][1]) then
if string.find(Input, "room") then
print(Room_Table[2]["Descrip"] .. "\n")
elseif string.find(Input, "toilet") then
print(Room_Table[2]["Obj"]["Obj_Toilet"][2])
if Room_Table[2]["Obj"]["Obj_Toilet"][1] == false then
Player_Table.Score = Player_Table.Score + 2
Room_Table[2]["Obj"]["Obj_Toilet"][1] = true
end
elseif string.find(Input, "sink") then
print(Room_Table[2]["Obj"]["Obj_Sink"][2])
if Room_Table[2]["Obj"]["Obj_Sink"][1] == false then
Player_Table.Score = Player_Table.Score + 2
Room_Table[2]["Obj"]["Obj_Sink"][1] = true
end
elseif string.find(Input, "cabinet") or string.find(Input, "mirror") then
if Obj_MedCab_State == false then
print(Room_Table[2]["Obj"]["Obj_MedCab"][2])
if Room_Table[2]["Obj"]["Obj_MedCab"][1] == false then
Player_Table.Score = Player_Table.Score + 2
Room_Table[2]["Obj"]["Obj_MedCab"][1] = true
end
elseif Obj_MedCab_State == true then
print(Room_Table[2]["Obj"]["Obj_MedCab"][3])
if Room_Table[2]["Obj"]["Obj_MedCab"][1] == false then
Player_Table.Score = Player_Table.Score + 2
Room_Table[2]["Obj"]["Obj_MedCab"][1] = true
end
end
elseif string.find(Input, "toothpaste") or string.find(Input, "paste") then
if Obj_MedCab_State == false then
return
elseif Obj_MedCab_State == true then
print(Room_Table[2]["Obj"]["Obj_Toothpaste"][2])
if Room_Table[2]["Obj"]["Obj_Toothpaste"][1] == false then
Player_Table.Score = Player_Table.Score + 2
Room_Table[2]["Obj"]["Obj_Toothpaste"][1] = true
end
end
end
end
--[[ S3.2.2 - Room 2 Get Conditions ]]--
--[[ S3.2.3 - Room 2 Open Conditions ]]--
if string.find(Input, Act_Table[8][1]) then
if string.find(Input, "cabinet") then
if Obj_MedCab_State == false then
Obj_MedCab_State = true
print("You open the medicine cabinet." .. "\n")
return
elseif Obj_MedCab_State == true then
print("The medicine cabinet is already open." .. "\n")
end
end
end
--[[ S3.2.4 - Room 2 Close Conditions ]]--
--[[ S3.2.5 - Room 2 Path Conditions ]]--
if string.find(Input, Act_Table[4][1]) then
if Input == "go north" or Input == "go n" then
Player_Table.Location = Room_Table[1]["Name"]
end
end
end
--[[ S4 - LOOPS ]]--
GameRun = true
FirstPlay = true
InMenu = true
SaveMode = false
Obj_MedCab_State = false
while GameRun == true do
while InMenu == true do
PrintTitle()
PrintMenu()
InMenu = false
end
while FirstPlay == true do
PrintStory()
FirstPlay = false
end
while FirstPlay == false do
--[[ S4.1 - Room 1 (Your Bedroom) Loop ]]--
if Player_Table.Location == Room_Table[1]["Name"] then
term.clear()
term.setCursorPos(1,1)
PrintRoomInfo()
repeat
local CoPassiveFunc = coroutine.create(PassiveFunc)
local Input = GetInput()
coroutine.resume(CoPassiveFunc, Input)
Room1_Func(Input)
while SaveMode == true do
SaveGame()
end
QuitGame(Input)
ScoreCheck()
until Player_Table.Location ~= Room_Table[1]["Name"]
end
--[[ S4.2 - Room 2 (Your Bathroom) Loop ]]--
if Player_Table.Location == Room_Table[2]["Name"] then
term.clear()
term.setCursorPos(1,1)
PrintRoomInfo()
repeat
local CoPassiveFunc = coroutine.create(PassiveFunc)
local Input = GetInput()
coroutine.resume(CoPassiveFunc, Input)
Room2_Func(Input)
while SaveMode == true do
SaveGame()
end
QuitGame(Input)
ScoreCheck()
until Player_Table.Location ~= Room_Table[2]["Name"]
end
if Player_Table.Location == "dead" then
GameRun = false
end
end
end
while GameRun == false do
print("You died! How unfortunate. Be sure to try again though!\n")
error()
end
| mit |
bmscoordinators/FFXI-Server | scripts/globals/abilities/jump.lua | 14 | 2211 | -----------------------------------
-- Ability: Jump
-- Delivers a short jumping attack on a targeted enemy.
-- Obtained: Dragoon Level 10
-- Recast Time: 1:00
-- Duration: Instant
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/weaponskills");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
return 0,0;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability,action)
local params = {};
params.numHits = 1;
local ftp = 1 + (player:getStat(MOD_VIT) / 256);
params.ftp100 = ftp; params.ftp200 = ftp; params.ftp300 = ftp;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; 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;
if (player:getMod(MOD_FORCE_JUMP_CRIT) > 0) then
params.crit100 = 1.0; params.crit200 = 1.0; params.crit300 = 1.0;
end
params.canCrit = true;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = (player:getMod(MOD_JUMP_ATT_BONUS) + 100) / 100
params.bonusTP = player:getMod(MOD_JUMP_TP_BONUS)
local taChar = player:getTrickAttackChar(target);
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, 0, 0, true, action, taChar, params);
if (tpHits + extraHits > 0) then
-- Under Spirit Surge, Jump also decreases target defence by 20% for 60 seconds
if (player:hasStatusEffect(EFFECT_SPIRIT_SURGE) == true) then
if (target:hasStatusEffect(EFFECT_DEFENSE_DOWN) == false) then
target:addStatusEffect(EFFECT_DEFENSE_DOWN, 20, 0, 60);
end
end
if (criticalHit) then
action:speceffect(target:getID(), 38)
end
action:speceffect(target:getID(), 32)
else
ability:setMsg(MSGBASIC_USES_BUT_MISSES)
action:speceffect(target:getID(), 0)
end
return damage;
end;
| gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/globals/items/wild_onion.lua | 12 | 1180 | -----------------------------------------
-- ID: 4387
-- Item: wild_onion
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility 4
-- Vitality -6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4387);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 4);
target:addMod(MOD_VIT, -6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 4);
target:delMod(MOD_VIT, -6);
end;
| gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/zones/Port_Windurst/npcs/Kususu.lua | 17 | 1729 | -----------------------------------
-- Area: Port Windurst
-- NPC: Kususu
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,KUSUSU_SHOP_DIALOG);
stock = {
0x1221, 1165,1, --Diaga
0x1236, 7025,1, --Stoneskin
0x1238, 837,1, --Slow
0x1202, 585,2, --Cure II
0x121c, 140,2, --Banish
0x1226, 1165,2, --Banishga
0x1235, 2097,2, --Blink
0x1201, 61,3, --Cure
0x1207, 1363,3, --Curaga
0x120e, 180,3, --Poisona
0x120f, 324,3, --Paralyna
0x1210, 990,3, --Blindna
0x1217, 82,3, --Dia
0x122b, 219,3, --Protect
0x1230, 1584,3, --Shell
0x1237, 360,3 --Aquaveil
}
showNationShop(player, NATION_WINDURST, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/zones/Meriphataud_Mountains/npcs/Muzeze.lua | 14 | 1049 | -----------------------------------
-- Area: Meriphataud Mountains
-- NPC: Muzeze
-- Type: Armor Storer
-- @pos -6.782 -18.428 208.185 119
-----------------------------------
package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Meriphataud_Mountains/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x002c);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/globals/items/konigskuchen.lua | 12 | 1443 | -----------------------------------------
-- ID: 5614
-- Item: konigskuchen
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Health 8
-- Magic % 3
-- Magic Cap 13
-- Intelligence 2
-- hMP +1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5614);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 8);
target:addMod(MOD_FOOD_MPP, 3);
target:addMod(MOD_FOOD_MP_CAP, 13);
target:addMod(MOD_INT, 2);
target:addMod(MOD_MPHEAL, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 8);
target:delMod(MOD_FOOD_MPP, 3);
target:delMod(MOD_FOOD_MP_CAP, 13);
target:delMod(MOD_INT, 2);
target:delMod(MOD_MPHEAL, 1);
end;
| gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/globals/spells/bluemagic/grand_slam.lua | 33 | 1713 | -----------------------------------------
-- Spell: Grand Slam
-- Delivers an area attack. Damage varies with TP
-- Spell cost: 24 MP
-- Monster Type: Beastmen
-- Spell Type: Physical (Blunt)
-- Blue Magic Points: 2
-- Stat Bonus: INT+1
-- Level: 30
-- Casting Time: 1 seconds
-- Recast Time: 14.25 seconds
-- Skillchain Element(s): Ice (can open Impaction, Compression, or Fragmentation; can close Induration)
-- Combos: Defense Bonus
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_ATTACK;
params.dmgtype = DMGTYPE_BLUNT;
params.scattr = SC_INDURATION;
params.numhits = 1;
params.multiplier = 1.0;
params.tp150 = 1.0;
params.tp300 = 1.0;
params.azuretp = 1.0;
params.duppercap = 133;
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.3;
params.agi_wsc = 0.0;
params.int_wsc = 0.1;
params.mnd_wsc = 0.1;
params.chr_wsc = 0.1;
damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
return damage;
end; | gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/zones/Garlaige_Citadel/npcs/Mashira.lua | 14 | 2139 | -----------------------------------
-- Area: Garlaige Citadel
-- NPC: Mashira
-- Involved in Quests: Rubbish day, Making Amens!
-- @pos 141 -6 138 200
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Garlaige_Citadel/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(JEUNO,RUBBISH_DAY) == QUEST_ACCEPTED and player:getVar("RubbishDayVar") == 0) then
player:startEvent(0x000b,1); -- For the quest "Rubbish day"
elseif (player:getQuestStatus(WINDURST,MAKING_AMENS) == QUEST_ACCEPTED) then
if (player:hasKeyItem(128) == true) then
player:startEvent(0x000b,3);
else player:startEvent(0x000b,0); -- Making Amens dialogue
end
else
player:startEvent(0x000b,3); -- Standard dialog and menu
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
RubbishDay = player:getQuestStatus(JEUNO,RUBBISH_DAY);
MakingAmens = player:getQuestStatus(WINDURST,MAKING_AMENS);
if (csid == 0x000b and option == 1 and RubbishDay == QUEST_ACCEPTED) then
player:delKeyItem(MAGIC_TRASH);
player:setVar("RubbishDayVar",1);
elseif (csid == 0x000b and option == 0 and MakingAmens == QUEST_ACCEPTED) then
player:addKeyItem(128); --Broken Wand
player:messageSpecial(KEYITEM_OBTAINED,128);
player:tradeComplete();
end
end;
| gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/zones/Al_Zahbi/npcs/Talruf.lua | 14 | 1033 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Talruf
-- Type: Standard NPC
-- @zone 48
-- @pos 100.878 -7 14.291
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00f3);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
tuxun/smw-funwiki | extensions/Scribunto/tests/engines/LuaCommon/SiteLibraryTests.lua | 4 | 5124 | local testframework = require 'Module:TestFramework'
local function nsTest( ... )
local args = { ... }
local t = mw.site.namespaces
local path = 'mw.site.namespaces'
for i = 1, #args do
t = t[args[i]]
path = path .. string.format( '[%q]', args[i] )
if t == nil then
error( path .. ' is nil!' )
end
end
return t
end
local function isNonEmptyString( val )
return type( val ) == 'string' and val ~= ''
end
local function isValidInterwikiMap( map )
assert( type( map ) == 'table', "mw.site.interwikiMap did not return a table" )
local stringKeys = { 'prefix', 'url' }
local boolKeys = {
'isProtocolRelative',
'isLocal',
'isTranscludable',
'isCurrentWiki',
'isExtraLanguageLink'
}
local maybeStringKeys = { 'displayText', 'tooltip' }
for prefix, data in pairs( map ) do
for _, key in ipairs( stringKeys ) do
assert( isNonEmptyString( data[key] ),
key .. " is not a string or is the empty string"
)
end
assert( prefix == data.prefix, string.format(
"table key '%s' and prefix '%s' do not match",
tostring( prefix ), tostring( data.prefix )
) )
for _, key in ipairs( boolKeys ) do
assert( type( data[key] ) == 'boolean', key .. " is not a boolean" )
end
for _, key in ipairs( maybeStringKeys ) do
assert( data[key] == nil or isNonEmptyString( data[key] ),
key .. " is not a string or is the empty string, and is not nil"
)
end
end
return true
end
return testframework.getTestProvider( {
{ name = 'parameter: siteName',
func = type, args = { mw.site.siteName },
expect = { 'string' }
},
{ name = 'parameter: server',
func = type, args = { mw.site.server },
expect = { 'string' }
},
{ name = 'parameter set: scriptPath',
func = type, args = { mw.site.scriptPath },
expect = { 'string' }
},
{ name = 'parameter set: stats.pages',
func = type, args = { mw.site.stats.pages },
expect = { 'number' }
},
{ name = 'pagesInCategory',
func = type, args = { mw.site.stats.pagesInCategory( "Example" ) },
expect = { 'number' }
},
{ name = 'pagesInNamespace',
func = type, args = { mw.site.stats.pagesInNamespace( 0 ) },
expect = { 'number' }
},
{ name = 'usersInGroup',
func = type, args = { mw.site.stats.usersInGroup( 'sysop' ) },
expect = { 'number' }
},
{ name = 'Project namespace by number',
func = nsTest, args = { 4, 'canonicalName' },
expect = { 'Project' }
},
{ name = 'Project namespace by name',
func = nsTest, args = { 'Project', 'id' },
expect = { 4 }
},
{ name = 'Project namespace by name (2)',
func = nsTest, args = { 'PrOjEcT', 'canonicalName' },
expect = { 'Project' }
},
{ name = 'Project namespace subject is itself',
func = nsTest, args = { 'Project', 'subject', 'canonicalName' },
expect = { 'Project' }
},
{ name = 'Project talk namespace via Project',
func = nsTest, args = { 'Project', 'talk', 'canonicalName' },
expect = { 'Project talk' }
},
{ name = 'Project namespace via Project talk',
func = nsTest, args = { 'Project_talk', 'subject', 'canonicalName' },
expect = { 'Project' }
},
{ name = 'Project talk namespace via Project (associated)',
func = nsTest, args = { 'Project', 'associated', 'canonicalName' },
expect = { 'Project talk' }
},
{ name = 'Project talk namespace by name (standard caps, no underscores)',
func = nsTest, args = { 'Project talk', 'id' },
expect = { 5 }
},
{ name = 'Project talk namespace by name (standard caps, underscores)',
func = nsTest, args = { 'Project_talk', 'id' },
expect = { 5 }
},
{ name = 'Project talk namespace by name (odd caps, no underscores)',
func = nsTest, args = { 'pRoJeCt tAlK', 'id' },
expect = { 5 }
},
{ name = 'Project talk namespace by name (odd caps, underscores)',
func = nsTest, args = { 'pRoJeCt_tAlK', 'id' },
expect = { 5 }
},
{ name = 'Project talk namespace by name (extraneous spaces and underscores)',
func = nsTest, args = { '_ _ _Project_ _talk_ _ _', 'id' },
expect = { 5 }
},
{ name = 'interwikiMap (all prefixes)',
func = isValidInterwikiMap, args = { mw.site.interwikiMap() },
expect = { true }
},
{ name = 'interwikiMap (local prefixes)',
func = isValidInterwikiMap, args = { mw.site.interwikiMap( 'local' ) },
expect = { true }
},
{ name = 'interwikiMap (non-local prefixes)',
func = isValidInterwikiMap, args = { mw.site.interwikiMap( '!local' ) },
expect = { true }
},
{ name = 'interwikiMap (type error 1)',
func = mw.site.interwikiMap, args = { 123 },
expect = "bad argument #1 to 'interwikiMap' (string expected, got number)"
},
{ name = 'interwikiMap (type error 2)',
func = mw.site.interwikiMap, args = { false },
expect = "bad argument #1 to 'interwikiMap' (string expected, got boolean)"
},
{ name = 'interwikiMap (unknown filter 1)',
func = mw.site.interwikiMap, args = { '' },
expect = "bad argument #1 to 'interwikiMap' (unknown filter '')"
},
{ name = 'interwikiMap (unknown filter 2)',
func = mw.site.interwikiMap, args = { 'foo' },
expect = "bad argument #1 to 'interwikiMap' (unknown filter 'foo')"
},
} )
| gpl-2.0 |
xushiwei/rapidjson | build/premake4.lua | 3 | 3520 | function setTargetObjDir(outDir)
for _, cfg in ipairs(configurations()) do
for _, plat in ipairs(platforms()) do
local action = _ACTION or ""
local prj = project()
--"_debug_win32_vs2008"
local suffix = "_" .. cfg .. "_" .. plat .. "_" .. action
targetPath = outDir
suffix = string.lower(suffix)
local obj_path = "../intermediate/" .. cfg .. "/" .. action .. "/" .. prj.name
obj_path = string.lower(obj_path)
configuration {cfg, plat}
targetdir(targetPath)
objdir(obj_path)
targetsuffix(suffix)
end
end
end
function linkLib(libBaseName)
for _, cfg in ipairs(configurations()) do
for _, plat in ipairs(platforms()) do
local action = _ACTION or ""
local prj = project()
local cfgName = cfg
--"_debug_win32_vs2008"
local suffix = "_" .. cfgName .. "_" .. plat .. "_" .. action
libFullName = libBaseName .. string.lower(suffix)
configuration {cfg, plat}
links(libFullName)
end
end
end
solution "test"
configurations { "debug", "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
configuration "debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "release"
defines { "NDEBUG" }
flags { "Optimize" }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "gmake"
buildoptions "-msse4.2"
project "gtest"
kind "StaticLib"
defines { "GTEST_HAS_PTHREAD=0" }
files {
"../thirdparty/gtest/src/gtest-all.cc",
"../thirdparty/gtest/src/**.h",
}
includedirs {
"../thirdparty/gtest/",
"../thirdparty/gtest/include",
}
setTargetObjDir("../thirdparty/lib")
project "unittest"
kind "ConsoleApp"
files {
"../include/**.h",
"../test/unittest/**.cpp",
"../test/unittest/**.h",
}
includedirs {
"../include/",
"../thirdparty/gtest/include/",
}
libdirs "../thirdparty/lib"
setTargetObjDir("../bin")
linkLib "gtest"
links "gtest"
project "perftest"
kind "ConsoleApp"
files {
"../include/**.h",
"../test/perftest/**.cpp",
"../test/perftest/**.c",
"../test/perftest/**.h",
}
includedirs {
"../include/",
"../thirdparty/gtest/include/",
"../thirdparty/",
"../thirdparty/jsoncpp/include/",
"../thirdparty/libjson/",
"../thirdparty/yajl/include/",
}
libdirs "../thirdparty/lib"
setTargetObjDir("../bin")
linkLib "gtest"
links "gtest"
solution "example"
configurations { "debug", "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
includedirs "../include/"
configuration "debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "release"
defines { "NDEBUG" }
flags { "Optimize", "EnableSSE2" }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
project "condense"
kind "ConsoleApp"
files "../example/condense/*"
setTargetObjDir("../bin")
project "pretty"
kind "ConsoleApp"
files "../example/pretty/*"
setTargetObjDir("../bin")
project "prettyauto"
kind "ConsoleApp"
files "../example/prettyauto/*"
setTargetObjDir("../bin")
project "tutorial"
kind "ConsoleApp"
files "../example/tutorial/*"
setTargetObjDir("../bin")
project "serialize"
kind "ConsoleApp"
files "../example/serialize/*"
setTargetObjDir("../bin")
| mit |
bmscoordinators/FFXI-Server | scripts/zones/Lower_Jeuno/npcs/Parike-Poranke.lua | 14 | 1121 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Parike-Poranke
-- Type: Adventurer's Assistant
-- @zone 245
-- @pos -33.161 -1 -61.303
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(PARIKE_PORANKE_DIALOG);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/zones/Hall_of_Transference/npcs/_0e0.lua | 14 | 1356 | -----------------------------------
-- Area: Hall of Transference
-- NPC: Cermet Gate - Holla
-- @pos -219 -6 280 14
-----------------------------------
package.loaded["scripts/zones/Hall_of_Transference/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Hall_of_Transference/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) > BELOW_THE_ARKS) then
player:startEvent(0x0096);
else
player:messageSpecial(NO_RESPONSE_OFFSET+1); -- The door is firmly shut.
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0096 and option == 1) then
player:setPos(92.033, 0, 80.380, 255, 16); -- To Promyvion Holla {R}
end
end; | gpl-3.0 |
victorholt/Urho3D | bin/Data/LuaScripts/48_Hello3DUI.lua | 19 | 9612 | -- A 3D UI demonstration based on the HelloGUI sample. Renders UI alternatively
-- either to a 3D scene object using UIComponent, or directly to the backbuffer.
require "LuaScripts/Utilities/Sample"
local window = nil
local dragBeginPosition = IntVector2(0, 0)
local textureRoot = nil
local current = nil
local renderOnCube = false
local drawDebug = false
local animateCube = true
function Start()
-- Execute the common startup for samples
SampleStart()
-- Enable OS cursor
input.mouseVisible = true
-- Load XML file containing default UI style sheet
local style = cache:GetResource("XMLFile", "UI/DefaultStyle.xml")
-- Set the loaded style as default style
ui.root.defaultStyle = style
-- Initialize Scene
InitScene()
-- Initialize Window
InitWindow()
-- Create and add some controls to the Window
InitControls()
-- Create a draggable Fish
CreateDraggableFish()
-- Create 3D UI rendered on a cube.
Init3DUI()
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_FREE)
end
function InitControls()
-- Create a CheckBox
local checkBox = CheckBox:new()
checkBox:SetName("CheckBox")
-- Create a Button
local button = Button:new()
button:SetName("Button")
button.minHeight = 24
-- Create a LineEdit
local lineEdit = LineEdit:new()
lineEdit:SetName("LineEdit")
lineEdit.minHeight = 24
-- Add controls to Window
window:AddChild(checkBox)
window:AddChild(button)
window:AddChild(lineEdit)
-- Apply previously set default style
checkBox:SetStyleAuto()
button:SetStyleAuto()
lineEdit:SetStyleAuto()
local instructions = Text:new()
instructions:SetStyleAuto()
instructions.text = "[TAB] - toggle between rendering on screen or cube.\n"..
"[Space] - toggle cube rotation."
ui.root:AddChild(instructions)
end
function InitScene()
scene_ = Scene()
scene_:CreateComponent("Octree")
local zone = scene_:CreateComponent("Zone")
zone.boundingBox = BoundingBox(-1000.0, 1000.0)
zone.fogColor = Color(0.5, 0.5, 0.5)
zone.fogStart = 100.0
zone.fogEnd = 300.0
-- Create a child scene node (at world origin) and a StaticModel component into it.
local boxNode = scene_:CreateChild("Box")
boxNode.scale = Vector3(5.0, 5.0, 5.0)
boxNode.rotation = Quaternion(90, Vector3(1, 0, 0))
-- Create a box model and hide it initially.
local boxModel = boxNode:CreateComponent("StaticModel")
boxModel.model = cache:GetResource("Model", "Models/Box.mdl")
boxNode.enabled = false
-- Create a camera.
cameraNode = scene_:CreateChild("Camera")
cameraNode:CreateComponent("Camera")
-- Set an initial position for the camera scene node.
cameraNode.position = Vector3(0.0, 0.0, -10.0)
-- Set up a viewport so 3D scene can be visible.
local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
renderer:SetViewport(0, viewport)
-- Subscribe to update event and animate cube and handle input.
SubscribeToEvent("Update", "HandleUpdate")
end
function InitWindow()
-- Create the Window and add it to the UI's root node
window = Window:new()
ui.root:AddChild(window)
-- Set Window size and layout settings
window.minWidth = 384
window:SetLayout(LM_VERTICAL, 6, IntRect(6, 6, 6, 6))
window:SetAlignment(HA_CENTER, VA_CENTER)
window:SetName("Window")
-- Create Window 'titlebar' container
local titleBar = UIElement:new()
titleBar:SetMinSize(0, 24)
titleBar.verticalAlignment = VA_TOP
titleBar.layoutMode = LM_HORIZONTAL
-- Create the Window title Text
local windowTitle = Text:new()
windowTitle.name = "WindowTitle"
windowTitle.text = "Hello GUI!"
-- Create the Window's close button
local buttonClose = Button:new()
buttonClose:SetName("CloseButton")
-- Add the controls to the title bar
titleBar:AddChild(windowTitle)
titleBar:AddChild(buttonClose)
-- Add the title bar to the Window
window:AddChild(titleBar)
-- Create a list.
local list = window:CreateChild("ListView")
list.selectOnClickEnd = true
list.highlightMode = HM_ALWAYS
list.minHeight = 200
for i = 0, 31 do
local text = Text:new()
text:SetStyleAuto()
text.text = "List item " .. i
text.name = "Item " .. i
list:AddItem(text)
end
-- Apply styles
window:SetStyleAuto()
list:SetStyleAuto()
windowTitle:SetStyleAuto()
buttonClose:SetStyle("CloseButton")
-- Subscribe to buttonClose release (following a 'press') events
SubscribeToEvent(buttonClose, "Released",
function (eventType, eventData)
engine:Exit()
end)
-- Subscribe also to all UI mouse clicks just to see where we have clicked
SubscribeToEvent("UIMouseClick", HandleControlClicked)
end
function CreateDraggableFish()
-- Create a draggable Fish button
local draggableFish = ui.root:CreateChild("Button", "Fish")
draggableFish.texture = cache:GetResource("Texture2D", "Textures/UrhoDecal.dds") -- Set texture
draggableFish.blendMode = BLEND_ADD
draggableFish:SetSize(128, 128)
draggableFish:SetPosition((GetGraphics().width - draggableFish.width) / 2, 200)
-- Add a tooltip to Fish button
local toolTip = draggableFish:CreateChild("ToolTip")
toolTip.position = IntVector2(draggableFish.width + 5, draggableFish.width/2) -- Slightly offset from fish
local textHolder = toolTip:CreateChild("BorderImage")
textHolder:SetStyle("ToolTipBorderImage")
local toolTipText = textHolder:CreateChild("Text")
toolTipText:SetStyle("ToolTipText")
toolTipText.text = "Please drag me!"
-- Subscribe draggableFish to Drag Events (in order to make it draggable)
-- See "Event list" in documentation's Main Page for reference on available Events and their eventData
SubscribeToEvent(draggableFish, "DragBegin",
function (eventType, eventData)
-- Get UIElement relative position where input (touch or click) occurred (top-left = IntVector2(0,0))
dragBeginPosition = IntVector2(eventData["ElementX"]:GetInt(), eventData["ElementY"]:GetInt())
end)
SubscribeToEvent(draggableFish, "DragMove",
function (eventType, eventData)
local dragCurrentPosition = IntVector2(eventData["X"]:GetInt(), eventData["Y"]:GetInt())
-- Get the dragged fish element
-- Note difference to C++: in C++ we would call GetPtr() and cast the pointer to UIElement, here we must specify
-- what kind of object we are getting. Null will be returned on type mismatch
local draggedElement = eventData["Element"]:GetPtr("UIElement")
draggedElement:SetPosition(dragCurrentPosition - dragBeginPosition)
end)
SubscribeToEvent(draggableFish, "DragEnd",
function (eventType, eventData)
end)
end
function HandleControlClicked(eventType, eventData)
-- Get the Text control acting as the Window's title
local element = window:GetChild("WindowTitle", true)
local windowTitle = tolua.cast(element, 'Text')
-- Get control that was clicked
local clicked = eventData["Element"]:GetPtr("UIElement")
local name = "...?"
if clicked ~= nil then
-- Get the name of the control that was clicked
name = clicked.name
end
-- Update the Window's title text
windowTitle.text = "Hello " .. name .. "!"
end
function Init3DUI()
-- Node that will get UI rendered on it.
local boxNode = scene_:GetChild("Box")
-- Create a component that sets up UI rendering. It sets material to StaticModel of the node.
local component = boxNode:CreateComponent("UIComponent")
-- Optionally modify material. Technique is changed so object is visible without any lights.
component.material:SetTechnique(0, cache:GetResource("Technique", "Techniques/DiffUnlit.xml"))
-- Save root element of texture UI for later use.
textureRoot = component.root
-- Set size of root element. This is size of texture as well.
textureRoot:SetSize(512, 512)
end
function HandleUpdate(eventType, eventData)
local timeStep = eventData["TimeStep"]:GetFloat()
local node = scene_:GetChild("Box")
if current ~= nil and drawDebug then
ui:DebugDraw(current)
end
if input:GetMouseButtonPress(MOUSEB_LEFT) then
current = ui:GetElementAt(input.mousePosition)
end
if input:GetKeyPress(KEY_TAB) then
renderOnCube = not renderOnCube
-- Toggle between rendering on screen or to texture.
if renderOnCube then
node.enabled = true
textureRoot:AddChild(window)
else
node.enabled = false
ui.root:AddChild(window)
end
end
if input:GetKeyPress(KEY_SPACE) then
animateCube = not animateCube
end
if input:GetKeyPress(KEY_F2) then
drawDebug = not drawDebug
end
if animateCube then
node:Yaw(6.0 * timeStep * 1.5)
node:Roll(-6.0 * timeStep * 1.5)
node:Pitch(-6.0 * timeStep * 1.5)
end
end
-- Create XML patch instructions for screen joystick layout specific to this sample app
function GetScreenJoystickPatchString()
return
"<patch>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" ..
" <attribute name=\"Is Visible\" value=\"false\" />" ..
" </add>" ..
"</patch>"
end
| mit |
bmscoordinators/FFXI-Server | scripts/zones/Southern_San_dOria_[S]/Zone.lua | 10 | 2560 | -----------------------------------
--
-- Zone: Southern_San_dOria_[S] (80)
--
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/missions");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (prevZone == 81) then
if (player:getQuestStatus(CRYSTAL_WAR, KNOT_QUITE_THERE) == QUEST_ACCEPTED and player:getVar("KnotQuiteThere") == 2) then
cs = 0x003E;
elseif (player:getQuestStatus(CRYSTAL_WAR, DOWNWARD_HELIX) == QUEST_ACCEPTED and player:getVar("DownwardHelix") == 0) then
cs = 0x0041;
elseif (player:getCurrentMission(WOTG) == CAIT_SITH and
(player:getQuestStatus(CRYSTAL_WAR, WRATH_OF_THE_GRIFFON) == QUEST_COMPLETED or
player:getQuestStatus(CRYSTAL_WAR, A_MANIFEST_PROBLEM) == QUEST_COMPLETED or
player:getQuestStatus(CRYSTAL_WAR, BURDEN_OF_SUSPICION) == QUEST_COMPLETED)) then
cs = 0x0043;
end
end
-- MOG HOUSE EXIT
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(161,-2,161,94);
if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then
cs = 0x7534;
end
player:setVar("PlayerMainJob",0);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x003E) then
player:setVar("KnotQuiteThere",3);
elseif (csid == 0x0041) then
player:setVar("DownwardHelix",1);
elseif (csid == 0x0043) then
player:completeMission(WOTG, CAIT_SITH);
player:addMission(WOTG, THE_QUEEN_OF_THE_DANCE);
end
end; | gpl-3.0 |
Element-Research/rnn | BiSequencer.lua | 10 | 2488 | ------------------------------------------------------------------------
--[[ BiSequencer ]]--
-- Encapsulates forward, backward and merge modules.
-- Input is a sequence (a table) of tensors.
-- Output is a sequence (a table) of tensors of the same length.
-- Applies a forward rnn to each element in the sequence in
-- forward order and applies a backward rnn in reverse order.
-- For each step, the outputs of both rnn are merged together using
-- the merge module (defaults to nn.JoinTable(1,1)).
-- The sequences in a batch must have the same size.
-- But the sequence length of each batch can vary.
-- It is implemented by decorating a structure of modules that makes
-- use of 3 Sequencers for the forward, backward and merge modules.
------------------------------------------------------------------------
local BiSequencer, parent = torch.class('nn.BiSequencer', 'nn.AbstractSequencer')
function BiSequencer:__init(forward, backward, merge)
if not torch.isTypeOf(forward, 'nn.Module') then
error"BiSequencer: expecting nn.Module instance at arg 1"
end
self.forwardModule = forward
self.backwardModule = backward
if not self.backwardModule then
self.backwardModule = forward:clone()
self.backwardModule:reset()
end
if not torch.isTypeOf(self.backwardModule, 'nn.Module') then
error"BiSequencer: expecting nn.Module instance at arg 2"
end
if torch.type(merge) == 'number' then
self.mergeModule = nn.JoinTable(1, merge)
elseif merge == nil then
self.mergeModule = nn.JoinTable(1, 1)
elseif torch.isTypeOf(merge, 'nn.Module') then
self.mergeModule = merge
else
error"BiSequencer: expecting nn.Module or number instance at arg 3"
end
self.fwdSeq = nn.Sequencer(self.forwardModule)
self.bwdSeq = nn.Sequencer(self.backwardModule)
self.mergeSeq = nn.Sequencer(self.mergeModule)
local backward = nn.Sequential()
backward:add(nn.ReverseTable()) -- reverse
backward:add(self.bwdSeq)
backward:add(nn.ReverseTable()) -- unreverse
local concat = nn.ConcatTable()
concat:add(self.fwdSeq):add(backward)
local brnn = nn.Sequential()
brnn:add(concat)
brnn:add(nn.ZipTable())
brnn:add(self.mergeSeq)
parent.__init(self)
self.output = {}
self.gradInput = {}
self.module = brnn
-- so that it can be handled like a Container
self.modules[1] = brnn
end
-- multiple-inheritance
nn.Decorator.decorate(BiSequencer)
| bsd-3-clause |
diamondo25/Vana | scripts/npcs/con1.lua | 2 | 2622 | --[[
Copyright (C) 2008-2016 Vana Development Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2
of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--]]
-- Konpei (warps to Showa Hideout)
dofile("scripts/utils/npcHelper.lua");
choices = {
makeChoiceHandler("Gather up some information on the hideout. ", function()
addText("I can take you to the hideout, but the place is infested with thugs looking for trouble. ");
addText("You'll need to be both incredibly strong and brave to enter the premise. ");
addText("At the hideaway, you'll find the Boss that controls all the other bosses around this area. ");
addText("It's easy to get to the hideout, but the room on the top floor of the place can only be entered ONCE a day. ");
addText("The Boss's Room is not a place to mess around. ");
addText("I suggest you don't stay there for too long; you'll need to swiftly take care of the business once inside. ");
addText("The boss himself is a difficult foe, but you'll run into some incredibly powerful enemies on your way to meeting the boss! ");
addText("It ain't going to be easy. ");
sendNext();
end),
makeChoiceHandler("Take me to the hideout.", function()
addText("Oh, the brave one. ");
addText("I've been awaiting your arrival. ");
addText("If these thugs are left unchecked, there's no telling what going to happen in this neighborhood. ");
addText("Before that happens, I hope you take care of all of them and beat the boss, who resides on the 5th floor. ");
addText("You'll need to be on alert at all times, since the boss is too tough for even the wisemen to handle. ");
addText("Looking at your eyes, however, I can see that eye of the tiger, the eyes that tell me you can do this. ");
addText("Let's go!");
sendNext();
setMap(801040000);
end),
makeChoiceHandler("Nothing. ", function()
addText("I'm a busy person! ");
addText("Leave me alone if that's all you need!");
sendOk();
end),
};
addText("What do you want from me? \r\n");
addText(blue(choiceRef(choices)));
choice = askChoice();
selectChoice(choices, choice); | gpl-2.0 |
P1sec/LTE_monitor_c2xx | wireshark/epan/wslua/template-init.lua | 1 | 2650 | -- init.lua
--
-- initialize wireshark's lua
--
-- This file is going to be executed before any other lua script.
-- It can be used to load libraries, disable functions and more.
--
-- $Id: template-init.lua 49608 2013-05-29 06:50:28Z lego $
--
-- Wireshark - Network traffic analyzer
-- By Gerald Combs <gerald@wireshark.org>
-- Copyright 1998 Gerald Combs
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-- Set disable_lua to true to disable Lua support.
disable_lua = false
if disable_lua then
return
end
-- If set and we are running with special privileges this setting
-- tells whether scripts other than this one are to be run.
run_user_scripts_when_superuser = false
-- disable potentialy harmful lua functions when running superuser
if running_superuser then
local hint = "has been disabled due to running Wireshark as superuser. See http://wiki.wireshark.org/CaptureSetup/CapturePrivileges for help in running Wireshark as an unprivileged user."
local disabled_lib = {}
setmetatable(disabled_lib,{ __index = function() error("this package ".. hint) end } );
dofile = function() error("dofile " .. hint) end
loadfile = function() error("loadfile " .. hint) end
loadlib = function() error("loadlib " .. hint) end
require = function() error("require " .. hint) end
os = disabled_lib
io = disabled_lib
file = disabled_lib
end
-- to avoid output to stdout which can cause problems lua's print ()
-- has been suppresed so that it yields an error.
-- have print() call info() instead.
if gui_enabled() then
print = info
end
function typeof(obj)
local mt = getmetatable(obj)
return mt and mt.__typeof or type(obj)
end
-- %WTAP_ENCAPS%
-- %WTAP_FILETYPES%
-- %FT_TYPES%
-- %BASES%
-- %ENCODINGS%
-- %EXPERT%
-- %MENU_GROUPS%
-- other useful constants
GUI_ENABLED = gui_enabled()
DATA_DIR = datafile_path()
USER_DIR = persconffile_path()
dofile(DATA_DIR.."console.lua")
--dofile(DATA_DIR.."dtd_gen.lua")
| gpl-2.0 |
bmscoordinators/FFXI-Server | scripts/globals/effects/aftermath_lv1.lua | 30 | 1130 | -----------------------------------
--
-- EFFECT_AFTERMATH_LV1
--
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
local power = effect:getPower();
if (effect:getSubPower() == 1) then
target:addMod(MOD_ACC,power);
elseif (effect:getSubPower() == 2) then
target:addMod(MOD_MACC,power)
elseif (effect:getSubPower() == 3) then
target:addMod(MOD_RACC,power)
end
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
local power = effect:getPower();
if (effect:getSubPower() == 1) then
target:delMod(MOD_ACC,power);
elseif (effect:getSubPower() == 2) then
target:delMod(MOD_MACC,power)
elseif (effect:getSubPower() == 3) then
target:delMod(MOD_RACC,power)
end
end; | gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/zones/The_Eldieme_Necropolis/npcs/qm9.lua | 57 | 2181 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: qm9 (??? - Ancient Papyrus Shreds)
-- Involved in Quest: In Defiant Challenge
-- @pos 92.272 -32 -64.676 195
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (OldSchoolG1 == false) then
if (player:hasItem(1088) == false and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3) == false
and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then
player:addKeyItem(ANCIENT_PAPYRUS_SHRED3);
player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_PAPYRUS_SHRED3);
end
if (player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3)) then
if (player:getFreeSlotsCount() >= 1) then
player:addItem(1088, 1);
player:messageSpecial(ITEM_OBTAINED, 1088);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1088);
end
end
if (player:hasItem(1088)) then
player:delKeyItem(ANCIENT_PAPYRUS_SHRED1);
player:delKeyItem(ANCIENT_PAPYRUS_SHRED2);
player:delKeyItem(ANCIENT_PAPYRUS_SHRED3);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
tuxology/bcc | src/lua/bpf/cdef.lua | 4 | 9392 | --[[
Copyright 2016 Marek Vavrusa <mvavrusa@cloudflare.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
local ffi = require('ffi')
local bit = require('bit')
local has_syscall, S = pcall(require, 'syscall')
local M = {}
ffi.cdef [[
struct bpf {
/* Instruction classes */
static const int LD = 0x00;
static const int LDX = 0x01;
static const int ST = 0x02;
static const int STX = 0x03;
static const int ALU = 0x04;
static const int JMP = 0x05;
static const int ALU64 = 0x07;
/* ld/ldx fields */
static const int W = 0x00;
static const int H = 0x08;
static const int B = 0x10;
static const int ABS = 0x20;
static const int IND = 0x40;
static const int MEM = 0x60;
static const int LEN = 0x80;
static const int MSH = 0xa0;
/* alu/jmp fields */
static const int ADD = 0x00;
static const int SUB = 0x10;
static const int MUL = 0x20;
static const int DIV = 0x30;
static const int OR = 0x40;
static const int AND = 0x50;
static const int LSH = 0x60;
static const int RSH = 0x70;
static const int NEG = 0x80;
static const int MOD = 0x90;
static const int XOR = 0xa0;
static const int JA = 0x00;
static const int JEQ = 0x10;
static const int JGT = 0x20;
static const int JGE = 0x30;
static const int JSET = 0x40;
static const int K = 0x00;
static const int X = 0x08;
static const int JNE = 0x50; /* jump != */
static const int JSGT = 0x60; /* SGT is signed '>', GT in x86 */
static const int JSGE = 0x70; /* SGE is signed '>=', GE in x86 */
static const int CALL = 0x80; /* function call */
static const int EXIT = 0x90; /* function return */
/* ld/ldx fields */
static const int DW = 0x18; /* double word */
static const int XADD = 0xc0; /* exclusive add */
/* alu/jmp fields */
static const int MOV = 0xb0; /* mov reg to reg */
static const int ARSH = 0xc0; /* sign extending arithmetic shift right */
/* change endianness of a register */
static const int END = 0xd0; /* flags for endianness conversion: */
static const int TO_LE = 0x00; /* convert to little-endian */
static const int TO_BE = 0x08; /* convert to big-endian */
/* misc */
static const int PSEUDO_MAP_FD = 0x01;
/* helper functions */
static const int F_CURRENT_CPU = 0xffffffff;
static const int F_USER_STACK = 1 << 8;
static const int F_FAST_STACK_CMP = 1 << 9;
static const int F_REUSE_STACKID = 1 << 10;
/* special offsets for ancillary data */
static const int NET_OFF = -0x100000;
static const int LL_OFF = -0x200000;
};
/* eBPF commands */
struct bpf_cmd {
static const int MAP_CREATE = 0;
static const int MAP_LOOKUP_ELEM = 1;
static const int MAP_UPDATE_ELEM = 2;
static const int MAP_DELETE_ELEM = 3;
static const int MAP_GET_NEXT_KEY = 4;
static const int PROG_LOAD = 5;
static const int OBJ_PIN = 6;
static const int OBJ_GET = 7;
};
/* eBPF helpers */
struct bpf_func_id {
static const int unspec = 0;
static const int map_lookup_elem = 1;
static const int map_update_elem = 2;
static const int map_delete_elem = 3;
static const int probe_read = 4;
static const int ktime_get_ns = 5;
static const int trace_printk = 6;
static const int get_prandom_u32 = 7;
static const int get_smp_processor_id = 8;
static const int skb_store_bytes = 9;
static const int l3_csum_replace = 10;
static const int l4_csum_replace = 11;
static const int tail_call = 12;
static const int clone_redirect = 13;
static const int get_current_pid_tgid = 14;
static const int get_current_uid_gid = 15;
static const int get_current_comm = 16;
static const int get_cgroup_classid = 17;
static const int skb_vlan_push = 18;
static const int skb_vlan_pop = 19;
static const int skb_get_tunnel_key = 20;
static const int skb_set_tunnel_key = 21;
static const int perf_event_read = 22;
static const int redirect = 23;
static const int get_route_realm = 24;
static const int perf_event_output = 25;
static const int skb_load_bytes = 26;
static const int get_stackid = 27;
};
/* BPF_MAP_STACK_TRACE structures and constants */
static const int BPF_MAX_STACK_DEPTH = 127;
struct bpf_stacktrace {
uint64_t ip[BPF_MAX_STACK_DEPTH];
};
]]
-- Compatibility: ljsyscall doesn't have support for BPF syscall
if not has_syscall or not S.bpf then
error("ljsyscall doesn't support bpf(), must be updated")
else
local strflag = require('syscall.helpers').strflag
-- Compatibility: ljsyscall<=0.12
if not S.c.BPF_MAP.LRU_HASH then
S.c.BPF_MAP = strflag {
UNSPEC = 0,
HASH = 1,
ARRAY = 2,
PROG_ARRAY = 3,
PERF_EVENT_ARRAY = 4,
PERCPU_HASH = 5,
PERCPU_ARRAY = 6,
STACK_TRACE = 7,
CGROUP_ARRAY = 8,
LRU_HASH = 9,
LRU_PERCPU_HASH = 10,
LPM_TRIE = 11,
ARRAY_OF_MAPS = 12,
HASH_OF_MAPS = 13,
DEVMAP = 14,
SOCKMAP = 15,
CPUMAP = 16,
}
end
if not S.c.BPF_PROG.TRACEPOINT then
S.c.BPF_PROG = strflag {
UNSPEC = 0,
SOCKET_FILTER = 1,
KPROBE = 2,
SCHED_CLS = 3,
SCHED_ACT = 4,
TRACEPOINT = 5,
XDP = 6,
PERF_EVENT = 7,
CGROUP_SKB = 8,
CGROUP_SOCK = 9,
LWT_IN = 10,
LWT_OUT = 11,
LWT_XMIT = 12,
SOCK_OPS = 13,
SK_SKB = 14,
CGROUP_DEVICE = 15,
SK_MSG = 16,
RAW_TRACEPOINT = 17,
CGROUP_SOCK_ADDR = 18,
}
end
end
-- Compatibility: metatype for stacktrace
local function stacktrace_iter(t, i)
i = i + 1
if i < #t and t.ip[i] > 0 then
return i, t.ip[i]
end
end
ffi.metatype('struct bpf_stacktrace', {
__len = function (t) return ffi.sizeof(t.ip) / ffi.sizeof(t.ip[0]) end,
__ipairs = function (t) return stacktrace_iter, t, -1 end,
})
-- Reflect cdata type
function M.typename(v)
if not v or type(v) ~= 'cdata' then return nil end
return string.match(tostring(ffi.typeof(v)), '<([^>]+)')
end
-- Reflect if cdata type can be pointer (accepts array or pointer)
function M.isptr(v, noarray)
local ctname = M.typename(v)
if ctname then
ctname = string.sub(ctname, -1)
ctname = ctname == '*' or (not noarray and ctname == ']')
end
return ctname
end
-- Return true if variable is a non-nil constant that can be used as immediate value
-- e.g. result of KSHORT and KNUM
function M.isimmconst(v)
return (type(v.const) == 'number' and not ffi.istype(v.type, ffi.typeof('void')))
or type(v.const) == 'cdata' and ffi.istype(v.type, ffi.typeof('uint64_t')) -- Lua numbers are at most 52 bits
or type(v.const) == 'cdata' and ffi.istype(v.type, ffi.typeof('int64_t'))
end
function M.osversion()
-- We have no better way to extract current kernel hex-string other
-- than parsing headers, compiling a helper function or reading /proc
local ver_str, count = S.sysctl('kernel.version'):match('%d+.%d+.%d+'), 2
if not ver_str then -- kernel.version is freeform, fallback to kernel.osrelease
ver_str = S.sysctl('kernel.osrelease'):match('%d+.%d+.%d+')
end
local version = 0
for i in ver_str:gmatch('%d+') do -- Convert 'X.Y.Z' to 0xXXYYZZ
version = bit.bor(version, bit.lshift(tonumber(i), 8*count))
count = count - 1
end
return version
end
function M.event_reader(reader, event_type)
-- Caller can specify event message binary format
if event_type then
assert(type(event_type) == 'string' and ffi.typeof(event_type), 'not a valid type for event reader')
event_type = ffi.typeof(event_type .. '*') -- Convert type to pointer-to-type
end
-- Wrap reader in interface that can interpret read event messages
return setmetatable({reader=reader,type=event_type}, {__index = {
block = function(_ --[[self]])
return S.select { readfds = {reader.fd} }
end,
next = function(_ --[[self]], k)
local len, ev = reader:next(k)
-- Filter out only sample frames
while ev and ev.type ~= S.c.PERF_RECORD.SAMPLE do
len, ev = reader:next(len)
end
if ev and event_type then
-- The perf event reader returns framed data with header and variable length
-- This is going skip the frame header and cast data to given type
ev = ffi.cast(event_type, ffi.cast('char *', ev) + ffi.sizeof('struct perf_event_header') + ffi.sizeof('uint32_t'))
end
return len, ev
end,
read = function(self)
return self.next, self, nil
end,
}})
end
function M.tracepoint_type(tp)
-- Read tracepoint format string
local fp = assert(io.open('/sys/kernel/debug/tracing/events/'..tp..'/format', 'r'))
local fmt = fp:read '*a'
fp:close()
-- Parse struct fields
local fields = {}
for f in fmt:gmatch 'field:([^;]+;)' do
table.insert(fields, f)
end
return string.format('struct { %s }', table.concat(fields))
end
return M
| apache-2.0 |
bmscoordinators/FFXI-Server | scripts/globals/items/plate_of_royal_sautee.lua | 12 | 1839 | -----------------------------------------
-- ID: 4295
-- Item: plate_of_royal_sautee
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Strength 5
-- Agility 1
-- Intelligence -2
-- Attack +22% (cap 80)
-- Ranged Attack +22% (cap 80)
-- Stun Resist +4
-- HP recovered while healing +1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,4295);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 5);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_INT, -2);
target:addMod(MOD_FOOD_ATTP, 22);
target:addMod(MOD_FOOD_ATT_CAP, 80);
target:addMod(MOD_FOOD_RATTP, 22);
target:addMod(MOD_FOOD_RATT_CAP, 80);
target:addMod(MOD_STUNRES, 4);
target:addMod(MOD_HPHEAL, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 5);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_INT, -2);
target:delMod(MOD_FOOD_ATTP, 22);
target:delMod(MOD_FOOD_ATT_CAP, 80);
target:delMod(MOD_FOOD_RATTP, 22);
target:delMod(MOD_FOOD_RATT_CAP, 80);
target:delMod(MOD_STUNRES, 4);
target:delMod(MOD_HPHEAL, 1);
end;
| gpl-3.0 |
firedtoad/skynet | service/gate.lua | 16 | 2079 | local skynet = require "skynet"
local gateserver = require "snax.gateserver"
local watchdog
local connection = {} -- fd -> connection : { fd , client, agent , ip, mode }
local forwarding = {} -- agent -> connection
skynet.register_protocol {
name = "client",
id = skynet.PTYPE_CLIENT,
}
local handler = {}
function handler.open(source, conf)
watchdog = conf.watchdog or source
end
function handler.message(fd, msg, sz)
-- recv a package, forward it
local c = connection[fd]
local agent = c.agent
if agent then
-- It's safe to redirect msg directly , gateserver framework will not free msg.
skynet.redirect(agent, c.client, "client", fd, msg, sz)
else
skynet.send(watchdog, "lua", "socket", "data", fd, skynet.tostring(msg, sz))
-- skynet.tostring will copy msg to a string, so we must free msg here.
skynet.trash(msg,sz)
end
end
function handler.connect(fd, addr)
local c = {
fd = fd,
ip = addr,
}
connection[fd] = c
skynet.send(watchdog, "lua", "socket", "open", fd, addr)
end
local function unforward(c)
if c.agent then
forwarding[c.agent] = nil
c.agent = nil
c.client = nil
end
end
local function close_fd(fd)
local c = connection[fd]
if c then
unforward(c)
connection[fd] = nil
end
end
function handler.disconnect(fd)
close_fd(fd)
skynet.send(watchdog, "lua", "socket", "close", fd)
end
function handler.error(fd, msg)
close_fd(fd)
skynet.send(watchdog, "lua", "socket", "error", fd, msg)
end
function handler.warning(fd, size)
skynet.send(watchdog, "lua", "socket", "warning", fd, size)
end
local CMD = {}
function CMD.forward(source, fd, client, address)
local c = assert(connection[fd])
unforward(c)
c.client = client or 0
c.agent = address or source
forwarding[c.agent] = c
gateserver.openclient(fd)
end
function CMD.accept(source, fd)
local c = assert(connection[fd])
unforward(c)
gateserver.openclient(fd)
end
function CMD.kick(source, fd)
gateserver.closeclient(fd)
end
function handler.command(cmd, source, ...)
local f = assert(CMD[cmd])
return f(source, ...)
end
gateserver.start(handler)
| mit |
bmscoordinators/FFXI-Server | scripts/zones/Norg/npcs/_700.lua | 14 | 2994 | -----------------------------------
-- Area: Norg
-- NPC: Oaken door (Gilgamesh's room)
-- @pos 97 -7 -12 252
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/settings")
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local ZilartMission = player:getCurrentMission(ZILART);
local currentMission = player:getCurrentMission(BASTOK);
local ZilartStatus = player:getVar("ZilartStatus");
-- Checked here to be fair to new players
local DMEarrings = 0;
for i=14739, 14743 do
if (player:hasItem(i)) then
DMEarrings = DMEarrings + 1;
end
end
if (ZilartMission == WELCOME_TNORG) then
player:startEvent(0x0002); -- Zilart Missions 2
elseif (ZilartMission == ROMAEVE and player:getVar("ZilartStatus") <= 1) then
player:startEvent(0x0003); -- Zilart Missions 9
elseif (ZilartMission == THE_HALL_OF_THE_GODS) then
player:startEvent(0x00a9); -- Zilart Missions 11
elseif (currentMission == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 1) then
player:startEvent(0x0062); -- Bastok Mission 6-2
elseif (ZilartMission == THE_SEALED_SHRINE and ZilartStatus == 0 and DMEarrings <= NUMBER_OF_DM_EARRINGS) then
player:startEvent(0x00ac);
else
player:startEvent(0x0005);
end
return 1;
end;
-- 0x00af 0x0005 0x0002 0x0003 0x00a9 0x00ac 0x00ce 0x00eb
-- 0x00af 0x0000 0x0002 0x0003 0x0004 0x0007 0x0008 0x0009 0x000a 0x0062 0x0063 0x001d 0x000c 0x000d
-- 0x0092 0x009e 0x00a4 0x00a9 0x00aa 0x00ab 0x00ac 0x00ad 0x00b0 0x00b1 0x00e8 0x00e9 0x00ea
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
printf("CSID: %u",csid);
printf("RESULT: %u",option);
if (csid == 0x0002 and option == 0) then
player:completeMission(ZILART,WELCOME_TNORG);
player:addMission(ZILART,KAZAMS_CHIEFTAINESS);
elseif (csid == 0x0003 and option == 0) then
player:setVar("ZilartStatus",0);
player:completeMission(ZILART,ROMAEVE);
player:addMission(ZILART,THE_TEMPLE_OF_DESOLATION);
elseif (csid == 0x00a9 and option == 0) then
player:completeMission(ZILART,THE_HALL_OF_THE_GODS);
player:addMission(ZILART,THE_MITHRA_AND_THE_CRYSTAL);
elseif (csid == 0x0062) then
player:setVar("MissionStatus",2);
elseif (csid == 0x00ac and bit.band(option, 0x40000000) == 0) then
player:setVar("ZilartStatus",1);
end
end; | gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/globals/items/baked_apple.lua | 12 | 1271 | -----------------------------------------
-- ID: 4406
-- Item: Baked Apple
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Magic 20
-- Agility -1
-- Intelligence 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,4406);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 20);
target:addMod(MOD_AGI,-1);
target:addMod(MOD_INT, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 20);
target:delMod(MOD_AGI,-1);
target:delMod(MOD_INT, 3);
end;
| gpl-3.0 |
deepak78/luci | libs/nixio/lua/nixio/util.lua | 179 | 5824 | --[[
nixio - Linux I/O library for lua
Copyright 2009 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local table = require "table"
local nixio = require "nixio"
local getmetatable, assert, pairs, type = getmetatable, assert, pairs, type
local tostring = tostring
module "nixio.util"
local BUFFERSIZE = nixio.const.buffersize
local ZIOBLKSIZE = 65536
local socket = nixio.meta_socket
local tls_socket = nixio.meta_tls_socket
local file = nixio.meta_file
local uname = nixio.uname()
local ZBUG = uname.sysname == "Linux" and uname.release:sub(1, 3) == "2.4"
function consume(iter, append)
local tbl = append or {}
if iter then
for obj in iter do
tbl[#tbl+1] = obj
end
end
return tbl
end
local meta = {}
function meta.is_socket(self)
return (getmetatable(self) == socket)
end
function meta.is_tls_socket(self)
return (getmetatable(self) == tls_socket)
end
function meta.is_file(self)
return (getmetatable(self) == file)
end
function meta.readall(self, len)
local block, code, msg = self:read(len or BUFFERSIZE)
if not block then
return nil, code, msg, ""
elseif #block == 0 then
return "", nil, nil, ""
end
local data, total = {block}, #block
while not len or len > total do
block, code, msg = self:read(len and (len - total) or BUFFERSIZE)
if not block then
return nil, code, msg, table.concat(data)
elseif #block == 0 then
break
end
data[#data+1], total = block, total + #block
end
local data = #data > 1 and table.concat(data) or data[1]
return data, nil, nil, data
end
meta.recvall = meta.readall
function meta.writeall(self, data)
data = tostring(data)
local sent, code, msg = self:write(data)
if not sent then
return nil, code, msg, 0
end
local total = sent
while total < #data do
sent, code, msg = self:write(data, total)
if not sent then
return nil, code, msg, total
end
total = total + sent
end
return total, nil, nil, total
end
meta.sendall = meta.writeall
function meta.linesource(self, limit)
limit = limit or BUFFERSIZE
local buffer = ""
local bpos = 0
return function(flush)
local line, endp, _
if flush then
line = buffer:sub(bpos + 1)
buffer = type(flush) == "string" and flush or ""
bpos = 0
return line
end
while not line do
_, endp, line = buffer:find("(.-)\r?\n", bpos + 1)
if line then
bpos = endp
return line
elseif #buffer < limit + bpos then
local newblock, code, msg = self:read(limit + bpos - #buffer)
if not newblock then
return nil, code, msg
elseif #newblock == 0 then
return nil
end
buffer = buffer:sub(bpos + 1) .. newblock
bpos = 0
else
return nil, 0
end
end
end
end
function meta.blocksource(self, bs, limit)
bs = bs or BUFFERSIZE
return function()
local toread = bs
if limit then
if limit < 1 then
return nil
elseif limit < toread then
toread = limit
end
end
local block, code, msg = self:read(toread)
if not block then
return nil, code, msg
elseif #block == 0 then
return nil
else
if limit then
limit = limit - #block
end
return block
end
end
end
function meta.sink(self, close)
return function(chunk, src_err)
if not chunk and not src_err and close then
if self.shutdown then
self:shutdown()
end
self:close()
elseif chunk and #chunk > 0 then
return self:writeall(chunk)
end
return true
end
end
function meta.copy(self, fdout, size)
local source = self:blocksource(nil, size)
local sink = fdout:sink()
local sent, chunk, code, msg = 0
repeat
chunk, code, msg = source()
sink(chunk, code, msg)
sent = chunk and (sent + #chunk) or sent
until not chunk
return not code and sent or nil, code, msg, sent
end
function meta.copyz(self, fd, size)
local sent, lsent, code, msg = 0
local splicable
if not ZBUG and self:is_file() then
local ftype = self:stat("type")
if nixio.sendfile and fd:is_socket() and ftype == "reg" then
repeat
lsent, code, msg = nixio.sendfile(fd, self, size or ZIOBLKSIZE)
if lsent then
sent = sent + lsent
size = size and (size - lsent)
end
until (not lsent or lsent == 0 or (size and size == 0))
if lsent or (not lsent and sent == 0 and
code ~= nixio.const.ENOSYS and code ~= nixio.const.EINVAL) then
return lsent and sent, code, msg, sent
end
elseif nixio.splice and not fd:is_tls_socket() and ftype == "fifo" then
splicable = true
end
end
if nixio.splice and fd:is_file() and not splicable then
splicable = not self:is_tls_socket() and fd:stat("type") == "fifo"
end
if splicable then
repeat
lsent, code, msg = nixio.splice(self, fd, size or ZIOBLKSIZE)
if lsent then
sent = sent + lsent
size = size and (size - lsent)
end
until (not lsent or lsent == 0 or (size and size == 0))
if lsent or (not lsent and sent == 0 and
code ~= nixio.const.ENOSYS and code ~= nixio.const.EINVAL) then
return lsent and sent, code, msg, sent
end
end
return self:copy(fd, size)
end
if tls_socket then
function tls_socket.close(self)
return self.socket:close()
end
function tls_socket.getsockname(self)
return self.socket:getsockname()
end
function tls_socket.getpeername(self)
return self.socket:getpeername()
end
function tls_socket.getsockopt(self, ...)
return self.socket:getsockopt(...)
end
tls_socket.getopt = tls_socket.getsockopt
function tls_socket.setsockopt(self, ...)
return self.socket:setsockopt(...)
end
tls_socket.setopt = tls_socket.setsockopt
end
for k, v in pairs(meta) do
file[k] = v
socket[k] = v
if tls_socket then
tls_socket[k] = v
end
end
| apache-2.0 |
DarkWanderer/DW.Lua | DW.Lua.UnitTests/Code/Fixtures/tpack.lua | 6 | 10603 | -- $Id: tpack.lua,v 1.13 2016/11/07 13:11:28 roberto Exp $
-- See Copyright Notice in file all.lua
local pack = string.pack
local packsize = string.packsize
local unpack = string.unpack
print "testing pack/unpack"
-- maximum size for integers
local NB = 16
local sizeshort = packsize("h")
local sizeint = packsize("i")
local sizelong = packsize("l")
local sizesize_t = packsize("T")
local sizeLI = packsize("j")
local sizefloat = packsize("f")
local sizedouble = packsize("d")
local sizenumber = packsize("n")
local little = (pack("i2", 1) == "\1\0")
local align = packsize("!xXi16")
assert(1 <= sizeshort and sizeshort <= sizeint and sizeint <= sizelong and
sizefloat <= sizedouble)
print("platform:")
print(string.format(
"\tshort %d, int %d, long %d, size_t %d, float %d, double %d,\n\z
\tlua Integer %d, lua Number %d",
sizeshort, sizeint, sizelong, sizesize_t, sizefloat, sizedouble,
sizeLI, sizenumber))
print("\t" .. (little and "little" or "big") .. " endian")
print("\talignment: " .. align)
-- check errors in arguments
function checkerror (msg, f, ...)
local status, err = pcall(f, ...)
-- print(status, err, msg)
assert(not status and string.find(err, msg))
end
-- minimum behavior for integer formats
assert(unpack("B", pack("B", 0xff)) == 0xff)
assert(unpack("b", pack("b", 0x7f)) == 0x7f)
assert(unpack("b", pack("b", -0x80)) == -0x80)
assert(unpack("H", pack("H", 0xffff)) == 0xffff)
assert(unpack("h", pack("h", 0x7fff)) == 0x7fff)
assert(unpack("h", pack("h", -0x8000)) == -0x8000)
assert(unpack("L", pack("L", 0xffffffff)) == 0xffffffff)
assert(unpack("l", pack("l", 0x7fffffff)) == 0x7fffffff)
assert(unpack("l", pack("l", -0x80000000)) == -0x80000000)
for i = 1, NB do
-- small numbers with signal extension ("\xFF...")
local s = string.rep("\xff", i)
assert(pack("i" .. i, -1) == s)
assert(packsize("i" .. i) == #s)
assert(unpack("i" .. i, s) == -1)
-- small unsigned number ("\0...\xAA")
s = "\xAA" .. string.rep("\0", i - 1)
assert(pack("<I" .. i, 0xAA) == s)
assert(unpack("<I" .. i, s) == 0xAA)
assert(pack(">I" .. i, 0xAA) == s:reverse())
assert(unpack(">I" .. i, s:reverse()) == 0xAA)
end
do
local lnum = 0x13121110090807060504030201
local s = pack("<j", lnum)
assert(unpack("<j", s) == lnum)
assert(unpack("<i" .. sizeLI + 1, s .. "\0") == lnum)
assert(unpack("<i" .. sizeLI + 1, s .. "\0") == lnum)
for i = sizeLI + 1, NB do
local s = pack("<j", -lnum)
assert(unpack("<j", s) == -lnum)
-- strings with (correct) extra bytes
assert(unpack("<i" .. i, s .. ("\xFF"):rep(i - sizeLI)) == -lnum)
assert(unpack(">i" .. i, ("\xFF"):rep(i - sizeLI) .. s:reverse()) == -lnum)
assert(unpack("<I" .. i, s .. ("\0"):rep(i - sizeLI)) == -lnum)
-- overflows
checkerror("does not fit", unpack, "<I" .. i, ("\x00"):rep(i - 1) .. "\1")
checkerror("does not fit", unpack, ">i" .. i, "\1" .. ("\x00"):rep(i - 1))
end
end
for i = 1, sizeLI do
local lstr = "\1\2\3\4\5\6\7\8\9\10\11\12\13"
local lnum = 0x13121110090807060504030201
local n = lnum & (~(-1 << (i * 8)))
local s = string.sub(lstr, 1, i)
assert(pack("<i" .. i, n) == s)
assert(pack(">i" .. i, n) == s:reverse())
assert(unpack(">i" .. i, s:reverse()) == n)
end
-- sign extension
do
local u = 0xf0
for i = 1, sizeLI - 1 do
assert(unpack("<i"..i, "\xf0"..("\xff"):rep(i - 1)) == -16)
assert(unpack(">I"..i, "\xf0"..("\xff"):rep(i - 1)) == u)
u = u * 256 + 0xff
end
end
-- mixed endianness
do
assert(pack(">i2 <i2", 10, 20) == "\0\10\20\0")
local a, b = unpack("<i2 >i2", "\10\0\0\20")
assert(a == 10 and b == 20)
assert(pack("=i4", 2001) == pack("i4", 2001))
end
print("testing invalid formats")
checkerror("out of limits", pack, "i0", 0)
checkerror("out of limits", pack, "i" .. NB + 1, 0)
checkerror("out of limits", pack, "!" .. NB + 1, 0)
checkerror("%(17%) out of limits %[1,16%]", pack, "Xi" .. NB + 1)
checkerror("invalid format option 'r'", pack, "i3r", 0)
checkerror("16%-byte integer", unpack, "i16", string.rep('\3', 16))
checkerror("not power of 2", pack, "!4i3", 0);
checkerror("missing size", pack, "c", "")
checkerror("variable%-length format", packsize, "s")
checkerror("variable%-length format", packsize, "z")
-- overflow in option size (error will be in digit after limit)
checkerror("invalid format", packsize, "c1" .. string.rep("0", 40))
if packsize("i") == 4 then
-- result would be 2^31 (2^3 repetitions of 2^28 strings)
local s = string.rep("c268435456", 2^3)
checkerror("too large", packsize, s)
-- one less is OK
s = string.rep("c268435456", 2^3 - 1) .. "c268435455"
assert(packsize(s) == 0x7fffffff)
end
-- overflow in packing
for i = 1, sizeLI - 1 do
local umax = (1 << (i * 8)) - 1
local max = umax >> 1
local min = ~max
checkerror("overflow", pack, "<I" .. i, -1)
checkerror("overflow", pack, "<I" .. i, min)
checkerror("overflow", pack, ">I" .. i, umax + 1)
checkerror("overflow", pack, ">i" .. i, umax)
checkerror("overflow", pack, ">i" .. i, max + 1)
checkerror("overflow", pack, "<i" .. i, min - 1)
assert(unpack(">i" .. i, pack(">i" .. i, max)) == max)
assert(unpack("<i" .. i, pack("<i" .. i, min)) == min)
assert(unpack(">I" .. i, pack(">I" .. i, umax)) == umax)
end
-- Lua integer size
assert(unpack(">j", pack(">j", math.maxinteger)) == math.maxinteger)
assert(unpack("<j", pack("<j", math.mininteger)) == math.mininteger)
assert(unpack("<J", pack("<j", -1)) == -1) -- maximum unsigned integer
if little then
assert(pack("f", 24) == pack("<f", 24))
else
assert(pack("f", 24) == pack(">f", 24))
end
print "testing pack/unpack of floating-point numbers"
for _, n in ipairs{0, -1.1, 1.9, 1/0, -1/0, 1e20, -1e20, 0.1, 2000.7} do
assert(unpack("n", pack("n", n)) == n)
assert(unpack("<n", pack("<n", n)) == n)
assert(unpack(">n", pack(">n", n)) == n)
assert(pack("<f", n) == pack(">f", n):reverse())
assert(pack(">d", n) == pack("<d", n):reverse())
end
-- for non-native precisions, test only with "round" numbers
for _, n in ipairs{0, -1.5, 1/0, -1/0, 1e10, -1e9, 0.5, 2000.25} do
assert(unpack("<f", pack("<f", n)) == n)
assert(unpack(">f", pack(">f", n)) == n)
assert(unpack("<d", pack("<d", n)) == n)
assert(unpack(">d", pack(">d", n)) == n)
end
print "testing pack/unpack of strings"
do
local s = string.rep("abc", 1000)
assert(pack("zB", s, 247) == s .. "\0\xF7")
local s1, b = unpack("zB", s .. "\0\xF9")
assert(b == 249 and s1 == s)
s1 = pack("s", s)
assert(unpack("s", s1) == s)
checkerror("does not fit", pack, "s1", s)
checkerror("contains zeros", pack, "z", "alo\0");
for i = 2, NB do
local s1 = pack("s" .. i, s)
assert(unpack("s" .. i, s1) == s and #s1 == #s + i)
end
end
do
local x = pack("s", "alo")
checkerror("too short", unpack, "s", x:sub(1, -2))
checkerror("too short", unpack, "c5", "abcd")
checkerror("out of limits", pack, "s100", "alo")
end
do
assert(pack("c0", "") == "")
assert(packsize("c0") == 0)
assert(unpack("c0", "") == "")
assert(pack("<! c3", "abc") == "abc")
assert(packsize("<! c3") == 3)
assert(pack(">!4 c6", "abcdef") == "abcdef")
assert(pack("c3", "123") == "123")
assert(pack("c0", "") == "")
assert(pack("c8", "123456") == "123456\0\0")
assert(pack("c88", "") == string.rep("\0", 88))
assert(pack("c188", "ab") == "ab" .. string.rep("\0", 188 - 2))
local a, b, c = unpack("!4 z c3", "abcdefghi\0xyz")
assert(a == "abcdefghi" and b == "xyz" and c == 14)
checkerror("longer than", pack, "c3", "1234")
end
-- testing multiple types and sequence
do
local x = pack("<b h b f d f n i", 1, 2, 3, 4, 5, 6, 7, 8)
assert(#x == packsize("<b h b f d f n i"))
local a, b, c, d, e, f, g, h = unpack("<b h b f d f n i", x)
assert(a == 1 and b == 2 and c == 3 and d == 4 and e == 5 and f == 6 and
g == 7 and h == 8)
end
print "testing alignment"
do
assert(pack(" < i1 i2 ", 2, 3) == "\2\3\0") -- no alignment by default
local x = pack(">!8 b Xh i4 i8 c1 Xi8", -12, 100, 200, "\xEC")
assert(#x == packsize(">!8 b Xh i4 i8 c1 Xi8"))
assert(x == "\xf4" .. "\0\0\0" ..
"\0\0\0\100" ..
"\0\0\0\0\0\0\0\xC8" ..
"\xEC" .. "\0\0\0\0\0\0\0")
local a, b, c, d, pos = unpack(">!8 c1 Xh i4 i8 b Xi8 XI XH", x)
assert(a == "\xF4" and b == 100 and c == 200 and d == -20 and (pos - 1) == #x)
x = pack(">!4 c3 c4 c2 z i4 c5 c2 Xi4",
"abc", "abcd", "xz", "hello", 5, "world", "xy")
assert(x == "abcabcdxzhello\0\0\0\0\0\5worldxy\0")
local a, b, c, d, e, f, g, pos = unpack(">!4 c3 c4 c2 z i4 c5 c2 Xh Xi4", x)
assert(a == "abc" and b == "abcd" and c == "xz" and d == "hello" and
e == 5 and f == "world" and g == "xy" and (pos - 1) % 4 == 0)
x = pack(" b b Xd b Xb x", 1, 2, 3)
assert(packsize(" b b Xd b Xb x") == 4)
assert(x == "\1\2\3\0")
a, b, c, pos = unpack("bbXdb", x)
assert(a == 1 and b == 2 and c == 3 and pos == #x)
-- only alignment
assert(packsize("!8 xXi8") == 8)
local pos = unpack("!8 xXi8", "0123456701234567"); assert(pos == 9)
assert(packsize("!8 xXi2") == 2)
local pos = unpack("!8 xXi2", "0123456701234567"); assert(pos == 3)
assert(packsize("!2 xXi2") == 2)
local pos = unpack("!2 xXi2", "0123456701234567"); assert(pos == 3)
assert(packsize("!2 xXi8") == 2)
local pos = unpack("!2 xXi8", "0123456701234567"); assert(pos == 3)
assert(packsize("!16 xXi16") == 16)
local pos = unpack("!16 xXi16", "0123456701234567"); assert(pos == 17)
checkerror("invalid next option", pack, "X")
checkerror("invalid next option", unpack, "XXi", "")
checkerror("invalid next option", unpack, "X i", "")
checkerror("invalid next option", pack, "Xc1")
end
do -- testing initial position
local x = pack("i4i4i4i4", 1, 2, 3, 4)
for pos = 1, 16, 4 do
local i, p = unpack("i4", x, pos)
assert(i == pos//4 + 1 and p == pos + 4)
end
-- with alignment
for pos = 0, 12 do -- will always round position to power of 2
local i, p = unpack("!4 i4", x, pos + 1)
assert(i == (pos + 3)//4 + 1 and p == i*4 + 1)
end
-- negative indices
local i, p = unpack("!4 i4", x, -4)
assert(i == 4 and p == 17)
local i, p = unpack("!4 i4", x, -7)
assert(i == 4 and p == 17)
local i, p = unpack("!4 i4", x, -#x)
assert(i == 1 and p == 5)
-- limits
for i = 1, #x + 1 do
assert(unpack("c0", x, i) == "")
end
checkerror("out of string", unpack, "c0", x, 0)
checkerror("out of string", unpack, "c0", x, #x + 2)
checkerror("out of string", unpack, "c0", x, -(#x + 1))
end
print "OK"
| mit |
midnightviking/simple-rotation | Libs/AceGUI-3.0/widgets/AceGUIContainer-Window.lua | 52 | 9726 | local AceGUI = LibStub("AceGUI-3.0")
-- Lua APIs
local pairs, assert, type = pairs, assert, type
-- WoW APIs
local PlaySound = PlaySound
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: GameFontNormal
----------------
-- Main Frame --
----------------
--[[
Events :
OnClose
]]
do
local Type = "Window"
local Version = 4
local function frameOnClose(this)
this.obj:Fire("OnClose")
end
local function closeOnClick(this)
PlaySound("gsTitleOptionExit")
this.obj:Hide()
end
local function frameOnMouseDown(this)
AceGUI:ClearFocus()
end
local function titleOnMouseDown(this)
this:GetParent():StartMoving()
AceGUI:ClearFocus()
end
local function frameOnMouseUp(this)
local frame = this:GetParent()
frame:StopMovingOrSizing()
local self = frame.obj
local status = self.status or self.localstatus
status.width = frame:GetWidth()
status.height = frame:GetHeight()
status.top = frame:GetTop()
status.left = frame:GetLeft()
end
local function sizerseOnMouseDown(this)
this:GetParent():StartSizing("BOTTOMRIGHT")
AceGUI:ClearFocus()
end
local function sizersOnMouseDown(this)
this:GetParent():StartSizing("BOTTOM")
AceGUI:ClearFocus()
end
local function sizereOnMouseDown(this)
this:GetParent():StartSizing("RIGHT")
AceGUI:ClearFocus()
end
local function sizerOnMouseUp(this)
this:GetParent():StopMovingOrSizing()
end
local function SetTitle(self,title)
self.titletext:SetText(title)
end
local function SetStatusText(self,text)
-- self.statustext:SetText(text)
end
local function Hide(self)
self.frame:Hide()
end
local function Show(self)
self.frame:Show()
end
local function OnAcquire(self)
self.frame:SetParent(UIParent)
self.frame:SetFrameStrata("FULLSCREEN_DIALOG")
self:ApplyStatus()
self:EnableResize(true)
self:Show()
end
local function OnRelease(self)
self.status = nil
for k in pairs(self.localstatus) do
self.localstatus[k] = nil
end
end
-- called to set an external table to store status in
local function SetStatusTable(self, status)
assert(type(status) == "table")
self.status = status
self:ApplyStatus()
end
local function ApplyStatus(self)
local status = self.status or self.localstatus
local frame = self.frame
self:SetWidth(status.width or 700)
self:SetHeight(status.height or 500)
if status.top and status.left then
frame:SetPoint("TOP",UIParent,"BOTTOM",0,status.top)
frame:SetPoint("LEFT",UIParent,"LEFT",status.left,0)
else
frame:SetPoint("CENTER",UIParent,"CENTER")
end
end
local function OnWidthSet(self, width)
local content = self.content
local contentwidth = width - 34
if contentwidth < 0 then
contentwidth = 0
end
content:SetWidth(contentwidth)
content.width = contentwidth
end
local function OnHeightSet(self, height)
local content = self.content
local contentheight = height - 57
if contentheight < 0 then
contentheight = 0
end
content:SetHeight(contentheight)
content.height = contentheight
end
local function EnableResize(self, state)
local func = state and "Show" or "Hide"
self.sizer_se[func](self.sizer_se)
self.sizer_s[func](self.sizer_s)
self.sizer_e[func](self.sizer_e)
end
local function Constructor()
local frame = CreateFrame("Frame",nil,UIParent)
local self = {}
self.type = "Window"
self.Hide = Hide
self.Show = Show
self.SetTitle = SetTitle
self.OnRelease = OnRelease
self.OnAcquire = OnAcquire
self.SetStatusText = SetStatusText
self.SetStatusTable = SetStatusTable
self.ApplyStatus = ApplyStatus
self.OnWidthSet = OnWidthSet
self.OnHeightSet = OnHeightSet
self.EnableResize = EnableResize
self.localstatus = {}
self.frame = frame
frame.obj = self
frame:SetWidth(700)
frame:SetHeight(500)
frame:SetPoint("CENTER",UIParent,"CENTER",0,0)
frame:EnableMouse()
frame:SetMovable(true)
frame:SetResizable(true)
frame:SetFrameStrata("FULLSCREEN_DIALOG")
frame:SetScript("OnMouseDown", frameOnMouseDown)
frame:SetScript("OnHide",frameOnClose)
frame:SetMinResize(240,240)
frame:SetToplevel(true)
local titlebg = frame:CreateTexture(nil, "BACKGROUND")
titlebg:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Title-Background]])
titlebg:SetPoint("TOPLEFT", 9, -6)
titlebg:SetPoint("BOTTOMRIGHT", frame, "TOPRIGHT", -28, -24)
local dialogbg = frame:CreateTexture(nil, "BACKGROUND")
dialogbg:SetTexture([[Interface\Tooltips\UI-Tooltip-Background]])
dialogbg:SetPoint("TOPLEFT", 8, -24)
dialogbg:SetPoint("BOTTOMRIGHT", -6, 8)
dialogbg:SetVertexColor(0, 0, 0, .75)
local topleft = frame:CreateTexture(nil, "BORDER")
topleft:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
topleft:SetWidth(64)
topleft:SetHeight(64)
topleft:SetPoint("TOPLEFT")
topleft:SetTexCoord(0.501953125, 0.625, 0, 1)
local topright = frame:CreateTexture(nil, "BORDER")
topright:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
topright:SetWidth(64)
topright:SetHeight(64)
topright:SetPoint("TOPRIGHT")
topright:SetTexCoord(0.625, 0.75, 0, 1)
local top = frame:CreateTexture(nil, "BORDER")
top:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
top:SetHeight(64)
top:SetPoint("TOPLEFT", topleft, "TOPRIGHT")
top:SetPoint("TOPRIGHT", topright, "TOPLEFT")
top:SetTexCoord(0.25, 0.369140625, 0, 1)
local bottomleft = frame:CreateTexture(nil, "BORDER")
bottomleft:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
bottomleft:SetWidth(64)
bottomleft:SetHeight(64)
bottomleft:SetPoint("BOTTOMLEFT")
bottomleft:SetTexCoord(0.751953125, 0.875, 0, 1)
local bottomright = frame:CreateTexture(nil, "BORDER")
bottomright:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
bottomright:SetWidth(64)
bottomright:SetHeight(64)
bottomright:SetPoint("BOTTOMRIGHT")
bottomright:SetTexCoord(0.875, 1, 0, 1)
local bottom = frame:CreateTexture(nil, "BORDER")
bottom:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
bottom:SetHeight(64)
bottom:SetPoint("BOTTOMLEFT", bottomleft, "BOTTOMRIGHT")
bottom:SetPoint("BOTTOMRIGHT", bottomright, "BOTTOMLEFT")
bottom:SetTexCoord(0.376953125, 0.498046875, 0, 1)
local left = frame:CreateTexture(nil, "BORDER")
left:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
left:SetWidth(64)
left:SetPoint("TOPLEFT", topleft, "BOTTOMLEFT")
left:SetPoint("BOTTOMLEFT", bottomleft, "TOPLEFT")
left:SetTexCoord(0.001953125, 0.125, 0, 1)
local right = frame:CreateTexture(nil, "BORDER")
right:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
right:SetWidth(64)
right:SetPoint("TOPRIGHT", topright, "BOTTOMRIGHT")
right:SetPoint("BOTTOMRIGHT", bottomright, "TOPRIGHT")
right:SetTexCoord(0.1171875, 0.2421875, 0, 1)
local close = CreateFrame("Button", nil, frame, "UIPanelCloseButton")
close:SetPoint("TOPRIGHT", 2, 1)
close:SetScript("OnClick", closeOnClick)
self.closebutton = close
close.obj = self
local titletext = frame:CreateFontString(nil, "ARTWORK")
titletext:SetFontObject(GameFontNormal)
titletext:SetPoint("TOPLEFT", 12, -8)
titletext:SetPoint("TOPRIGHT", -32, -8)
self.titletext = titletext
local title = CreateFrame("Button", nil, frame)
title:SetPoint("TOPLEFT", titlebg)
title:SetPoint("BOTTOMRIGHT", titlebg)
title:EnableMouse()
title:SetScript("OnMouseDown",titleOnMouseDown)
title:SetScript("OnMouseUp", frameOnMouseUp)
self.title = title
local sizer_se = CreateFrame("Frame",nil,frame)
sizer_se:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,0)
sizer_se:SetWidth(25)
sizer_se:SetHeight(25)
sizer_se:EnableMouse()
sizer_se:SetScript("OnMouseDown",sizerseOnMouseDown)
sizer_se:SetScript("OnMouseUp", sizerOnMouseUp)
self.sizer_se = sizer_se
local line1 = sizer_se:CreateTexture(nil, "BACKGROUND")
self.line1 = line1
line1:SetWidth(14)
line1:SetHeight(14)
line1:SetPoint("BOTTOMRIGHT", -8, 8)
line1:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border")
local x = 0.1 * 14/17
line1:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5)
local line2 = sizer_se:CreateTexture(nil, "BACKGROUND")
self.line2 = line2
line2:SetWidth(8)
line2:SetHeight(8)
line2:SetPoint("BOTTOMRIGHT", -8, 8)
line2:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border")
local x = 0.1 * 8/17
line2:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5)
local sizer_s = CreateFrame("Frame",nil,frame)
sizer_s:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-25,0)
sizer_s:SetPoint("BOTTOMLEFT",frame,"BOTTOMLEFT",0,0)
sizer_s:SetHeight(25)
sizer_s:EnableMouse()
sizer_s:SetScript("OnMouseDown",sizersOnMouseDown)
sizer_s:SetScript("OnMouseUp", sizerOnMouseUp)
self.sizer_s = sizer_s
local sizer_e = CreateFrame("Frame",nil,frame)
sizer_e:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,25)
sizer_e:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,0)
sizer_e:SetWidth(25)
sizer_e:EnableMouse()
sizer_e:SetScript("OnMouseDown",sizereOnMouseDown)
sizer_e:SetScript("OnMouseUp", sizerOnMouseUp)
self.sizer_e = sizer_e
--Container Support
local content = CreateFrame("Frame",nil,frame)
self.content = content
content.obj = self
content:SetPoint("TOPLEFT",frame,"TOPLEFT",12,-32)
content:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-12,13)
AceGUI:RegisterAsContainer(self)
return self
end
AceGUI:RegisterWidgetType(Type,Constructor,Version)
end
| gpl-2.0 |
bmscoordinators/FFXI-Server | scripts/globals/spells/hydrohelix.lua | 26 | 1690 | --------------------------------------
-- Spell: Hydrohelix
-- Deals water damage that gradually reduces
-- a target's HP. Damage dealt is greatly affected by the weather.
--------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
-- get helix acc/att merits
local merit = caster:getMerit(MERIT_HELIX_MAGIC_ACC_ATT);
-- calculate raw damage
local dmg = calculateMagicDamage(35,1,caster,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false);
dmg = dmg + caster:getMod(MOD_HELIX_EFFECT);
-- get resist multiplier (1x if no resist)
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL,merit*3);
-- get the resisted damage
dmg = dmg*resist;
-- add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster,spell,target,dmg,merit*2);
-- add in target adjustment
dmg = adjustForTarget(target,dmg,spell:getElement());
local dot = dmg;
-- add in final adjustments
dmg = finalMagicAdjustments(caster,target,spell,dmg);
-- calculate Damage over time
dot = target:magicDmgTaken(dot);
local duration = getHelixDuration(caster) + caster:getMod(MOD_HELIX_DURATION);
duration = duration * (resist/2);
if (dot > 0) then
target:addStatusEffect(EFFECT_HELIX,dot,3,duration);
end;
return dmg;
end; | gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/zones/Al_Zahbi/npcs/Yudi_Yolhbi.lua | 53 | 2326 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Yudi Yolhbi
-- Type: Woodworking Normal/Adv. Image Support
-- @pos -71.584 -7 -56.018 48
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Al_Zahbi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local guildMember = isGuildMember(player,9);
if (guildMember == 1) then
if (trade:hasItemQty(2184,1) and trade:getItemCount() == 1) then
if (player:hasStatusEffect(EFFECT_WOODWORKING_IMAGERY) == false) then
player:tradeComplete();
player:startEvent(0x00EB,8,0,0,0,188,0,1,0);
else
npc:showText(npc, IMAGE_SUPPORT_ACTIVE);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,9);
local SkillLevel = player:getSkillLevel(SKILL_WOODWORKING);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_WOODWORKING_IMAGERY) == false) then
player:startEvent(0x00EA,8,SkillLevel,0,511,188,0,1,2184);
else
player:startEvent(0x00EA,8,SkillLevel,0,511,188,7055,1,2184);
end
else
player:startEvent(0x00EA,0,0,0,0,0,0,1,0); -- Standard Dialogue
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00EA and option == 1) then
player:messageSpecial(IMAGE_SUPPORT,0,1,1);
player:addStatusEffect(EFFECT_WOODWORKING_IMAGERY,1,0,120);
elseif (csid == 0x00EB) then
player:messageSpecial(IMAGE_SUPPORT,0,1,0);
player:addStatusEffect(EFFECT_WOODWORKING_IMAGERY,3,0,480);
end
end; | gpl-3.0 |
RockySeven3161/NewBot | plugins/twitter_send.lua | 627 | 1555 | do
local OAuth = require "OAuth"
local consumer_key = ""
local consumer_secret = ""
local access_token = ""
local access_token_secret = ""
local client = OAuth.new(consumer_key, consumer_secret, {
RequestToken = "https://api.twitter.com/oauth/request_token",
AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"},
AccessToken = "https://api.twitter.com/oauth/access_token"
}, {
OAuthToken = access_token,
OAuthTokenSecret = access_token_secret
})
function run(msg, matches)
if consumer_key:isempty() then
return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua"
end
if consumer_secret:isempty() then
return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua"
end
if access_token:isempty() then
return "Twitter Access Token is empty, write it in plugins/twitter_send.lua"
end
if access_token_secret:isempty() then
return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua"
end
if not is_sudo(msg) then
return "You aren't allowed to send tweets"
end
local response_code, response_headers, response_status_line, response_body =
client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", {
status = matches[1]
})
if response_code ~= 200 then
return "Error: "..response_code
end
return "Tweet sent"
end
return {
description = "Sends a tweet",
usage = "!tw [text]: Sends the Tweet with the configured account.",
patterns = {"^!tw (.+)"},
run = run
}
end
| gpl-2.0 |
deepak78/luci | applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo_config.lua | 80 | 1153 | --[[
LuCI - Lua Configuration Interface
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.controller.luci_diag.devinfo_common")
m = Map("luci_devinfo", translate("Network Device Scanning Configuration"), translate("Configure scanning for devices on specified networks. Decreasing \'Timeout\', \'Repeat Count\', and/or \'Sleep Between Requests\' may speed up scans, but also may fail to find some devices."))
s = m:section(SimpleSection, "", translate("Use Configuration"))
b = s:option(DummyValue, "_scans", translate("Perform Scans (this can take a few minutes)"))
b.value = ""
b.titleref = luci.dispatcher.build_url("admin", "status", "netdiscover_devinfo")
scannet = m:section(TypedSection, "netdiscover_scannet", translate("Scanning Configuration"), translate("Networks to scan for devices"))
scannet.addremove = true
scannet.anonymous = false
luci.controller.luci_diag.devinfo_common.config_devinfo_scan(m, scannet)
return m
| apache-2.0 |
MRAHS/SBSS_Plus | bot/InfernalTG.lua | 1 | 8718 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '1.0'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
-- mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"Help_All",
"Auto_Leave",
"Chat",
"Google",
"Joke",
"Quran",
"google_img",
"hello",
"wlc",
"BLOCK",
"Feedback",
"Member_Manager",
"Group_Manager",
"S2A",
"SUDO",
"all",
"arabic_lock",
"Banhammer",
"download_media",
"get",
"inpm",
"invite",
"leaders",
"leave_ban",
"plugins",
"realmcommands",
"service_entergroup",
"set",
"anti_spam",
"stats",
"Version",
"close_group",
"kickall",
"Maseage",
"tagall",
},
sudo_users = {109722284,99743635,171604508},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[infernalTG v2 - Open Source
An advance Administration bot based on yagop/telegram-bot by @Mr_Ah_S
@Mr_Ah_S {Dev , Founder and Manager}
Our channel
@SBSS_Team
]],
help_text_realm = [[
group admin Commands:
!creategroup [Name]
!createrealm [Name]
!setname [Name]
!setabout [GroupID] [Text]
!setrules [GroupID] [Text]
!lock [GroupID] [setting]
!unlock [GroupID] [setting]
!wholist
!who
!type
!kill chat [GroupID]
!kill realm [RealmID]
!adminprom [id|username]
!admindem [id|username]
!list infernalgroups
!list infernalrealms
!log
!broadcast [text]
!broadcast InfernalTG !
!br [group_id] [text]
!br 123456789 Hello !
**U can use both "/" and "!"
*Only admins and sudo can add bots in group
*Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only admins and sudo can use res, setowner, commands
]],
help_text = [[
tools for SBSS Plus :
>#1.Add_bot
>#2.Anti_Bot
>#3.Auto_Leave
>#4.BLOCK
>#5.Feedback
>#6.Member_Manager
>#7.S2A
>#8.SUDO
>#8.all
>#9.arabic_lock
>#10.banhammer
>#11.down_media
>#12.get
>#13.inpm
>#14.invite
>#15.leaders
>#16.leave_ban
>#17.pluglist
>#18.realmcommands
>#19.service_entergroup
>#20.set
>#21.anti_spam
>#22.stats
>#23.toengsupport
>#24.topersupport
>#25.spammer_a
>#26.Spammer_i
>#27.Version
>#28.close_group
>#29.kickall
>#30.SendPm
>#31.tagall
>#32.share
help all plugin soon :D ,"
You Can Get Bot version by sending !version,"
Master admin : @Mr_Ah_S ,"
our channel : @SBSS_Team ,"
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
bmscoordinators/FFXI-Server | scripts/zones/Konschtat_Highlands/npcs/qm1.lua | 14 | 1374 | -----------------------------------
-- Area: Konschtat Highlands
-- NPC: qm1 (???)
-- Continues Quests: Past Perfect
-- @pos -201 16 80 108
-----------------------------------
package.loaded["scripts/zones/Konschtat_Highlands/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Konschtat_Highlands/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local PastPerfect = player:getQuestStatus(BASTOK,PAST_PERFECT);
if (PastPerfect == QUEST_ACCEPTED) then
player:addKeyItem(0x6d);
player:messageSpecial(KEYITEM_OBTAINED,0x6d); -- Tattered Mission Orders
else
player:messageSpecial(FIND_NOTHING);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/zones/Gusgen_Mines/npcs/Clay.lua | 14 | 1229 | -----------------------------------
-- Area: Gusgen Mines
-- NPC: Clay
-- Involved in Quest: A Potter's Preference
-- @pos 117 -21 432 196
-----------------------------------
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Gusgen_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:addItem(569,1); --569 - dish_of_gusgen_clay
player:messageSpecial(ITEM_OBTAINED,569); -- dish_of_gusgen_clay
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/zones/Horlais_Peak/bcnms/hostile_herbivores.lua | 30 | 1739 | -----------------------------------
-- Area: Horlias peak
-- Name: Hostile Herbivores
-- BCNM50
-----------------------------------
package.loaded["scripts/zones/Horlais_Peak/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Horlais_Peak/TextIDs");
-----------------------------------
-- EXAMPLE SCRIPT
--
-- What should go here:
-- giving key items, playing ENDING cutscenes
--
-- What should NOT go here:
-- Handling of "battlefield" status, spawning of monsters,
-- putting loot into treasure pool,
-- enforcing ANY rules (SJ/number of people/etc), moving
-- chars around, playing entrance CSes (entrance CSes go in bcnm.lua)
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,0);
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
end;
| gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/globals/abilities/beast_roll.lua | 19 | 2633 | -----------------------------------
-- Ability: Beast Roll
-- Enhances pet attacks for party members within area of effect
-- Optimal Job: Beastmaster
-- Lucky Number: 4
-- Unlucky Number: 8
-- Level: 34
--
-- Die Roll |No BST |With BST
-- -------- -------- -----------
-- 1 |16 |41
-- 2 |20 |45
-- 3 |24 |49
-- 4 |64 |89
-- 5 |28 |53
-- 6 |32 |57
-- 7 |40 |65
-- 8 |8 |33
-- 9 |44 |69
-- 10 |48 |73
-- 11 |80 |105
-- Bust |-25 |-25
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/ability");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
local effectID = EFFECT_BEAST_ROLL
ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE));
if (player:hasStatusEffect(effectID)) then
return MSGBASIC_ROLL_ALREADY_ACTIVE,0;
elseif atMaxCorsairBusts(player) then
return MSGBASIC_CANNOT_PERFORM,0;
else
return 0,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(caster,target,ability,action)
if (caster:getID() == target:getID()) then
corsairSetup(caster, ability, action, EFFECT_BEAST_ROLL, JOBS.BST);
end
local total = caster:getLocalVar("corsairRollTotal")
return applyRoll(caster,target,ability,action,total)
end;
function applyRoll(caster,target,ability,action,total)
local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK)
local effectpowers = {4, 5, 7, 19, 8, 9, 11, 2, 13, 14, 23, 7}
local effectpower = effectpowers[total];
if (caster:getLocalVar("corsairRollBonus") == 1 and total < 12) then
effectpower = effectpower + 10
end
if (caster:getMainJob() == JOBS.COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl());
elseif (caster:getSubJob() == JOBS.COR and caster:getSubLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl());
end
if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_BEAST_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_PET_ATTP) == false) then
ability:setMsg(422);
elseif total > 11 then
ability:setMsg(426);
end
return total;
end
| gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/globals/spells/huton_san.lua | 21 | 1271 | -----------------------------------------
-- Spell: Huton: San
-- Deals wind damage to an enemy and lowers its resistance against ice.
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
--doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus)
local duration = 15 + caster:getMerit(MERIT_HUTON_EFFECT) -- T1 bonus debuff duration
local bonusAcc = 0;
local bonusMab = caster:getMerit(MERIT_HUTON_EFFECT); -- T1 mag atk
if(caster:getMerit(MERIT_HUTON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits
bonusMab = bonusMab + caster:getMerit(MERIT_HUTON_SAN) - 5; -- merit gives 5 power but no bonus with one invest, thus subtract 5
bonusAcc = bonusAcc + caster:getMerit(MERIT_HUTON_SAN) - 5;
end
local dmg = doNinjutsuNuke(134,1.5,caster,spell,target,false,bonusAcc,bonusMab);
handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_ICERES);
return dmg;
end; | gpl-3.0 |
bmscoordinators/FFXI-Server | scripts/globals/spells/bluemagic/feather_tickle.lua | 25 | 1164 | -----------------------------------------
-- Spell: Feather Tickle
-- Reduces an enemy's TP
-- Spell cost: 48 MP
-- Monster Type: Birds
-- Spell Type: Magical (Wind)
-- Blue Magic Points: 3
-- Stat Bonus: AGI+1
-- Level: 64
-- Casting Time: 4 seconds
-- Recast Time: 26 seconds
-- Magic Bursts on: Detonation, Fragmentation, and Light
-- Combos: Clear Mind
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local dINT = caster:getStat(MOD_MND) - target:getStat(MOD_MND);
local resist = applyResistance(caster,spell,target,dINT,BLUE_SKILL);
local power = 300 * resist;
if (target:getTP() == 0) then
spell:setMsg(75);
else
target:delTP(power);
spell:setMsg(431);
end
return tp;
end; | gpl-3.0 |
victorholt/Urho3D | bin/Data/LuaScripts/01_HelloWorld.lua | 24 | 1882 | -- This first example, maintaining tradition, prints a "Hello World" message.
-- Furthermore it shows:
-- - Using the Sample utility functions as a base for the application
-- - Adding a Text element to the graphical user interface
-- - Subscribing to and handling of update events
require "LuaScripts/Utilities/Sample"
function Start()
-- Execute the common startup for samples
SampleStart()
-- Create "Hello World" Text
CreateText()
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_FREE)
-- Finally, hook-up this HelloWorld instance to handle update events
SubscribeToEvents()
end
function CreateText()
-- Construct new Text object
local helloText = Text:new()
-- Set String to display
helloText.text = "Hello World from Urho3D!"
-- Set font and text color
helloText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 30)
helloText.color = Color(0.0, 1.0, 0.0)
-- Align Text center-screen
helloText.horizontalAlignment = HA_CENTER
helloText.verticalAlignment = VA_CENTER
-- Add Text instance to the UI root element
ui.root:AddChild(helloText)
end
function SubscribeToEvents()
-- Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate")
end
function HandleUpdate(eventType, eventData)
-- Do nothing for now, could be extended to eg. animate the display
end
-- Create XML patch instructions for screen joystick layout specific to this sample app
function GetScreenJoystickPatchString()
return
"<patch>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" ..
" <attribute name=\"Is Visible\" value=\"false\" />" ..
" </add>" ..
"</patch>"
end
| mit |
victorholt/Urho3D | bin/Data/LuaScripts/Utilities/ScriptCompiler.lua | 29 | 1247 | -- Script to recursively compile lua files located in specified rootFolder to luc (bytecode)
-- Usage: require "LuaScripts/Utilities/LuaScriptCompiler"
-- Set root folder containing lua files to convert
local rootFolder = "Data/LuaScripts/" -- Starting from bin folder
if not fileSystem:DirExists(rootFolder) then log:Write(LOG_WARNING, "Cannot find " .. rootFolder) return end -- Ensure that rootFolder exists
-- Get lua files recursively
local files = fileSystem:ScanDir(fileSystem:GetProgramDir() .. rootFolder, "*.lua", SCAN_FILES, true)
if table.maxn(files) == 0 then log:Write(LOG_WARNING, "No lua file found in " .. rootFolder .. " and subfolders") return end -- Ensure that at least one file was found
-- Compile each lua file found in rootFolder and subfolders to luc
for i=1, table.maxn(files) do
local filename = rootFolder .. files[i] -- Get file with its path
if not fileSystem:FileExists(filename) then log:Write(LOG_WARNING, "Cannot find " .. filename) return end
print(filename .. "\n")
local args = {"-b", filename, ReplaceExtension(filename, ".luc")} -- Set arguments to pass to the luajit command line app
fileSystem:SystemRun(fileSystem:GetProgramDir() .. "luajit", args) -- Compile lua file to luc
end
| mit |
bmscoordinators/FFXI-Server | scripts/globals/items/pork_cutlet.lua | 12 | 1737 | -----------------------------------------
-- ID: 6394
-- Item: pork_cutlet
-- Food Effect: 180Min, All Races
-----------------------------------------
-- HP +40
-- STR +7
-- INT -7
-- Fire resistance +20
-- Attack +20% (cap 120)
-- Ranged Attack +20% (cap 120)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,6394);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 40);
target:addMod(MOD_STR, 7);
target:addMod(MOD_INT, -7);
target:addMod(MOD_FIRERES, 20);
target:addMod(MOD_FOOD_ATTP, 20);
target:addMod(MOD_FOOD_ATT_CAP, 120);
target:addMod(MOD_FOOD_RATTP, 20);
target:addMod(MOD_FOOD_RATT_CAP, 120);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 40);
target:delMod(MOD_STR, 7);
target:delMod(MOD_INT, -7);
target:delMod(MOD_FIRERES, 20);
target:delMod(MOD_FOOD_ATTP, 20);
target:delMod(MOD_FOOD_ATT_CAP, 120);
target:delMod(MOD_FOOD_RATTP, 20);
target:delMod(MOD_FOOD_RATT_CAP, 120);
end;
| gpl-3.0 |
deepak78/luci | applications/luci-diag-devinfo/luasrc/controller/luci_diag/netdiscover_common.lua | 14 | 3181 | --[[
Luci diag - Diagnostics controller module
(c) 2009 Daniel Dickinson
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
]]--
module("luci.controller.luci_diag.netdiscover_common", package.seeall)
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.cbi")
require("luci.model.uci")
local translate = luci.i18n.translate
local DummyValue = luci.cbi.DummyValue
local SimpleSection = luci.cbi.SimpleSection
function index()
return -- no-op
end
function get_params()
local netdiscover_uci = luci.model.uci.cursor()
netdiscover_uci:load("luci_devinfo")
local nettable = netdiscover_uci:get_all("luci_devinfo")
local i
local subnet
local netdout
local outnets = {}
i = next(nettable, nil)
while (i) do
if (netdiscover_uci:get("luci_devinfo", i) == "netdiscover_scannet") then
local scannet = netdiscover_uci:get_all("luci_devinfo", i)
if scannet["subnet"] and (scannet["subnet"] ~= "") and scannet["enable"] and ( scannet["enable"] == "1") then
local output = ""
local outrow = {}
outrow["interface"] = scannet["interface"]
outrow["timeout"] = 10
local timeout = tonumber(scannet["timeout"])
if timeout and ( timeout > 0 ) then
outrow["timeout"] = scannet["timeout"]
end
outrow["repeat_count"] = 1
local repcount = tonumber(scannet["repeat_count"])
if repcount and ( repcount > 0 ) then
outrow["repeat_count"] = scannet["repeat_count"]
end
outrow["sleepreq"] = 100
local repcount = tonumber(scannet["sleepreq"])
if repcount and ( repcount > 0 ) then
outrow["sleepreq"] = scannet["sleepreq"]
end
outrow["subnet"] = scannet["subnet"]
outrow["output"] = output
outnets[i] = outrow
end
end
i = next(nettable, i)
end
return outnets
end
function command_function(outnets, i)
local interface = luci.controller.luci_diag.devinfo_common.get_network_device(outnets[i]["interface"])
return "/usr/bin/netdiscover-to-devinfo " .. outnets[i]["subnet"] .. " " .. interface .. " " .. outnets[i]["timeout"] .. " -r " .. outnets[i]["repeat_count"] .. " -s " .. outnets[i]["sleepreq"] .. " </dev/null"
end
function action_links(netdiscovermap, mini)
luci.i18n.loadc("diag_devinfo")
s = netdiscovermap:section(SimpleSection, "", translate("Actions"))
b = s:option(DummyValue, "_config", translate("Configure Scans"))
b.value = ""
if (mini) then
b.titleref = luci.dispatcher.build_url("mini", "network", "netdiscover_devinfo_config")
else
b.titleref = luci.dispatcher.build_url("admin", "network", "diag_config", "netdiscover_devinfo_config")
end
b = s:option(DummyValue, "_scans", translate("Repeat Scans (this can take a few minutes)"))
b.value = ""
if (mini) then
b.titleref = luci.dispatcher.build_url("mini", "diag", "netdiscover_devinfo")
else
b.titleref = luci.dispatcher.build_url("admin", "status", "netdiscover_devinfo")
end
end
| apache-2.0 |
tuxun/smw-funwiki | extensions/Scribunto/tests/engines/LuaStandalone/StandaloneTests.lua | 9 | 1406 | local testframework = require( 'Module:TestFramework' )
local function setfenv1()
local ok, err = pcall( function()
setfenv( 2, {} )
end )
if not ok then
err = string.gsub( err, '^%S+:%d+: ', '' )
error( err )
end
end
local function getfenv1()
local env
pcall( function()
env = getfenv( 2 )
end )
return env
end
return testframework.getTestProvider( {
{ name = 'setfenv on a C function', func = setfenv1,
expect = "'setfenv' cannot set the requested environment, it is protected",
},
{ name = 'getfenv on a C function', func = getfenv1,
expect = { nil },
},
{ name = 'Invalid array key (table)', func = mw.var_export,
args = { { [{}] = 1 } },
expect = 'Cannot use table as an array key when passing data from Lua to PHP',
},
{ name = 'Invalid array key (boolean)', func = mw.var_export,
args = { { [true] = 1 } },
expect = 'Cannot use boolean as an array key when passing data from Lua to PHP',
},
{ name = 'Invalid array key (function)', func = mw.var_export,
args = { { [tostring] = 1 } },
expect = 'Cannot use function as an array key when passing data from Lua to PHP',
},
{ name = 'Unusual array key (float)', func = mw.var_export,
args = { { [1.5] = 1 } },
expect = { "array ( '1.5' => 1, )" }
},
{ name = 'Unusual array key (inf)', func = mw.var_export,
args = { { [math.huge] = 1 } },
expect = { "array ( 'inf' => 1, )" }
},
} )
| gpl-2.0 |
XtBot/xt | plugins/Abjad.lua | 13 | 4026 | local numbers = {}
numbers['ا'] = 1
numbers['ب'] = 2
numbers['ج'] = 3
numbers['د'] = 4
numbers['ه'] = 5
numbers['و'] = 6
numbers['ز'] = 7
numbers['ح'] = 8
numbers['ط'] = 9
numbers['ی'] = 10
numbers['ک'] = 20
numbers['ل'] = 30
numbers['م'] = 40
numbers['ن'] = 50
numbers['س'] = 60
numbers['ع'] = 70
numbers['ف'] = 80
numbers['ص'] = 90
numbers['ق'] = 100
numbers['ر'] = 200
numbers['ش'] = 300
numbers['ت'] = 400
numbers['ث'] = 500
numbers['خ'] = 600
numbers['ذ'] = 700
numbers['ض'] = 800
numbers['ظ'] = 900
numbers['غ'] = 900
local function convert(text)
local text = text:gsub('ژ','ز')
local text = text:gsub('گ','ک')
local text = text:gsub('چ','ج')
local text = text:gsub('پ','ب')
local text = text:gsub('ئ','ی')
local text = text:gsub('آ','ا')
local text = text:gsub('ۀ','ه')
local text = text:gsub('ي','ی')
local text = text:gsub('ة','ه')
local text = text:gsub('ؤ','و')
return text
end
local function abjad(text,num,str)
local num = num
local text = text
if text:match(str) then
for word in string.gmatch(text, str) do num = num + numbers[str]
end
text = text:gsub(str,'')
end
return text , num
end
local function run(msg, matches)
if not matches[2] or matches[2] == '' then
return [[حروف جمل یا به عبارت دیگر حروف ابجد،نام مجموع صور هشتگانه حروف عرب است. این صور ازین قرار است: ابجد – هوز- حطي - کلمن - سعفص - قرشت - ثخذ - ضظغ.
ترتيب حروف (مراد،حروف صامت است) درين نسق همان ترتيب عبري آرامي است و اين امر با دلايل ديگر مؤید آنست که عرب الفباي خود را از آنان بوساطت نبطيان اقتباس کرده و شش حرف مخصوص عرب در آخر ترتيب ابجدي قرار داده شده است؛ علاوه برين ترتيب هشت کلمه تذکاريه که مفهومي ندارند با عبري و آرامي در اينکه حروف معرف اعدادند نيز شباهت دارد،از «همزه» تا «ی» نماينده ی 1تا10 ،«ک» تا «ق» نماینده ی 20تا100 و نه حرف آخر معرف 200تا1000 باشد. ابجد تجريد نوشتن (تصوف) ترک خواهش و آرزو کردن و از خودي و مزاحمت خواهش آمدن و از ماسوي الله مجرد گرديدن...
ا=1 ک=20 ش=300
ب=2 ل=30 ت=400
ج=3 م=40 ث=500
د=4 ن=50 خ=600
ه=5 س=60 ذ=700
و=6 ع=70 ض=800
ز=7 ف=80 ظ=900
ح=8 ص=90 غ=1000
ط=9 ق=100
ی=10 ر=200
]]
end
local text = convert(matches[2])
local num = 0
text , num = abjad(text,num,'ا')
text , num = abjad(text,num,'ب')
text , num = abjad(text,num,'ج')
text , num = abjad(text,num,'د')
text , num = abjad(text,num,'ه')
text , num = abjad(text,num,'و')
text , num = abjad(text,num,'ز')
text , num = abjad(text,num,'ح')
text , num = abjad(text,num,'ط')
text , num = abjad(text,num,'ی')
text , num = abjad(text,num,'ک')
text , num = abjad(text,num,'ل')
text , num = abjad(text,num,'م')
text , num = abjad(text,num,'ن')
text , num = abjad(text,num,'س')
text , num = abjad(text,num,'ع')
text , num = abjad(text,num,'ف')
text , num = abjad(text,num,'ص')
text , num = abjad(text,num,'ق')
text , num = abjad(text,num,'ر')
text , num = abjad(text,num,'ش')
text , num = abjad(text,num,'ت')
text , num = abjad(text,num,'ث')
text , num = abjad(text,num,'خ')
text , num = abjad(text,num,'ذ')
text , num = abjad(text,num,'ض')
text , num = abjad(text,num,'ظ')
text , num = abjad(text,num,'غ')
if text ~= '' then
return 'فقط زبان فارسی پشتیبانی میشود'
end
return 'عدد ابجد کبیر : '..num
end
return {
patterns = {
"^[!/#]([Aa]bjad) (.*)$",
"^[!/#]([Aa]bjad)$",
"^([Aa]bjad) (.*)$",
"^([Aa]bjad)$"
},
run = run
}
| gpl-2.0 |
rizaumami/tdcliBot | plugins/btc.lua | 1 | 1368 | do
-- See https://bitcoinaverage.com/api
local function run(msg, matches)
local base_url = 'https://api.bitcoinaverage.com/ticker/global/'
local currency = matches[2] and matches[2]:upper() or 'USD'
-- Do request on bitcoinaverage, the final / is critical!
local res, code = https.request(base_url .. currency .. '/')
if code ~= 200 then return nil end
local data = json.decode(res)
local ask = string.gsub(data.ask, '%.', ',')
local bid = string.gsub(data.bid, '%.', ',')
local index = _msg('<b>BTC</b> in <b>%s:</b>\n• Buy: %s\n• Sell: %s'):format(
currency,
util.groupIntoThree(ask),
util.groupIntoThree(bid)
)
sendText(msg.chat_id_, msg.id_, index)
end
--------------------------------------------------------------------------------
return {
description = _msg('Displays the current Bitcoin price.'),
usage = {
user = {
'https://telegra.ph/Bitcoin-02-08',
--'<code>!btc</code>',
--_msg('Displays Bitcoin price in USD'),
--'',
--'<code>!btc [currency]</code>',
--_msg('Displays Bitcoin price in <code>[currency]</code>'),
--_msg('<code>[currency]</code> is in ISO 4217 format.'),
},
},
patterns = {
_config.cmd .. '(btc)$',
_config.cmd .. '(btc) (%a%a%a)$',
},
run = run
}
end
| gpl-3.0 |
TannerRogalsky/GGJ2017 | light/get_line_of_sight_points.lua | 1 | 3296 | local queryBBox = require('light.query_bbox')
local rayCastClosest = require('light.raycast_closest')
local shellsort = require('light.shellsort')
local num_hits = 0
local function rotate(phi, x,y, ox,oy)
x, y = x - ox, y - oy
local c, s = math.cos(phi), math.sin(phi)
return c*x - s*y + ox, s*x + c*y + oy
end
local function getIsLess(a, b)
if a[1] == 0 and a[2] == 0 then
return true
elseif b[1] == 0 and b[2] == 0 then
return false
end
if a[1] >= 0 and b[1] < 0 then return true end
if a[1] < 0 and b[1] >= 0 then return false end
if a[1] == 0 and b[1] == 0 then
if a[2] >= 0 or b[2] >= 0 then return a[2] > b[2] end
return b[2] > a[2]
end
local det = a[1] * b[2] - b[1] * a[2]
if det < 0 then
return true
elseif det > 0 then
return false
end
local d1 = a[1] * a[1] + a[2] * a[2]
local d2 = b[1] * b[1] + b[2] * b[2]
return d1 > d2
end
local function addHitFast(hits, x, y)
num_hits = num_hits + 1
hits[num_hits][1], hits[num_hits][2] = x, y
end
local function addHitSlow(hits, x, y)
table.insert(hits, {x, y})
end
local function rotateAndCast(world, addHit, hits, filter, x1, y1, x2, y2, phi)
x2, y2 = rotate(phi, x2, y2, x1, y1)
local hit = rayCastClosest(world, x1, y1, x2, y2, filter)
if hit then addHit(hits, hit.x - x1, hit.y - y1) end
return hit
end
local function rayCast(world, addHit, hits, filter, x1, y1, body, x2, y2, ...)
if x2 and y2 then
x2, y2 = body:getWorldPoint(x2, y2)
local dx = x2 - x1
local dy = y2 - y1
-- TODO might be possible to optimize the length here
local x4 = x2 + (dx) * 100
local y4 = y2 + (dy) * 100
rotateAndCast(world, addHit, hits, filter, x1, y1, x4, y4, 0)
rotateAndCast(world, addHit, hits, filter, x1, y1, x4, y4, 0.0001)
rotateAndCast(world, addHit, hits, filter, x1, y1, x4, y4, -0.0001)
rayCast(world, addHit, hits, filter, x1, y1, body, ...)
end
end
local function getLineOfSightPoints(hits, x, y, filter)
local world = game.world
local body = game.map.body
num_hits = 1
hits[1][1], hits[1][2] = 0, 0
local bx1, by1 = x - LIGHT_FALLOFF_DISTANCE, y - LIGHT_FALLOFF_DISTANCE
local bx2, by2 = x + LIGHT_FALLOFF_DISTANCE, y + LIGHT_FALLOFF_DISTANCE
for i,fixture in ipairs(queryBBox(world, bx1, by1, bx2, by2)) do
local shape = fixture:getShape()
if shape.getPoints then
rayCast(world, addHitFast, hits, filter, x, y, fixture:getBody(), shape:getPoints())
end
end
shellsort(hits, getIsLess, num_hits)
num_hits = num_hits + 1
hits[num_hits][1], hits[num_hits][2] = hits[2][1], hits[2][2]
return num_hits
end
local function getLineOfSightPointsSlow(x, y)
local world = game.world
local body = game.map.body
local hits = {}
local bx1, by1 = x - LIGHT_FALLOFF_DISTANCE, y - LIGHT_FALLOFF_DISTANCE
local bx2, by2 = x + LIGHT_FALLOFF_DISTANCE, y + LIGHT_FALLOFF_DISTANCE
for i,fixture in ipairs(queryBBox(world, bx1, by1, bx2, by2)) do
local shape = fixture:getShape()
rayCast(world, addHitSlow, hits, filter, x, y, fixture:getBody(), shape:getPoints())
end
table.sort(hits, getIsLess)
table.insert(hits, {hits[1][1], hits[1][2]})
table.insert(hits, 1, {0, 0})
return hits
end
return {
fast = getLineOfSightPoints,
slow = getLineOfSightPointsSlow
}
| mit |
bmscoordinators/FFXI-Server | scripts/zones/Mount_Zhayolm/npcs/HomePoint#1.lua | 27 | 1274 | -----------------------------------
-- Area: Mount Zhayolm
-- NPC: HomePoint#1
-- @pos -540.844 -4.000 70.809 61
-----------------------------------
package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Mount_Zhayolm/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 90);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.