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 |
|---|---|---|---|---|---|
Scavenge/darkstar | scripts/zones/Abyssea-Konschtat/npcs/qm1.lua | 14 | 1358 | -----------------------------------
-- Zone: Abyssea-Konschtat
-- NPC: qm1 (???)
-- Spawns Ashtaerth the Gallavexd
-- @pos ? ? ? 15
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--[[
if (trade:hasItemQty(2914,1) and trade:getItemCount() == 1) then -- Player has all the required items.
if (GetMobAction(16838718) == ACTION_NONE) then -- Mob not already spawned from this
SpawnMob(16838718):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:tradeComplete();
end
end
]]
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(1010, 2914); -- Inform payer what items they need.
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 |
Zero-K-Experiments/Zero-K-Experiments | scripts/armcybr.lua | 4 | 3082 | include "constants.lua"
include "bombers.lua"
include "fixedwingTakeOff.lua"
local flare1 = piece 'flare1'
local flare2 = piece 'flare2'
local base = piece 'base'
local wing1 = piece 'wing1'
local wing2 = piece 'wing2'
local rearthrust = piece 'rearthrust'
local wingthrust1 = piece 'wingthrust1'
local wingthrust2 = piece 'wingthrust2'
local thrust1 = piece 'thrust1'
local thrust2 = piece 'thrust2'
local drop = piece 'drop'
local emit1 = piece 'emit1'
local emit2 = piece 'emit2'
local emit3 = piece 'emit3'
local emit4 = piece 'emit4'
local smokePiece = {base}
--Signal
local SIG_move = 1
local SIG_TAKEOFF = 2
local takeoffHeight = UnitDefNames["armcybr"].wantedHeight
local gun_1 = false
local function Stopping()
Signal(SIG_move)
SetSignalMask(SIG_move)
Move(wing1, x_axis, -0, 1.65)
Move(wing1, z_axis, 0, 0.35)
Move(wing2, x_axis, 0, 1.65)
Move(wing2, z_axis, 0, 0.35)
Turn(wing1, z_axis, 0, math.rad(0.62))
Turn(wing2, z_axis, 0, math.rad(1.85))
end
local function Moving()
Signal(SIG_move)
SetSignalMask(SIG_move)
Move(wing1, x_axis, 2.4, 1.65)
Move(wing1, z_axis, -0.5, 0.35)
Move(wing2, x_axis, -2.4, 1.65)
Move(wing2, z_axis, -0.5, 0.35)
Turn(wing1, z_axis, math.rad(-2.7), math.rad(1.85))
Turn(wing2, z_axis, math.rad(-2.7), math.rad(1.85))
end
function script.StartMoving()
StartThread(Moving)
end
function script.StopMoving()
StartThread(Stopping)
StartThread(TakeOffThread, takeoffHeight, SIG_TAKEOFF)
end
function script.MoveRate(rate)
if rate == 1 then
--Signal(SIG_BARREL)
--SetSignalMask(SIG_BARREL)
Turn(base, z_axis, math.rad(-240), math.rad(120))
WaitForTurn(base, z_axis)
Turn(base, z_axis, math.rad(-(120)), math.rad(180))
WaitForTurn(base, z_axis)
Turn(base, z_axis, 0, math.rad(120))
end
end
function script.Create()
StartThread(TakeOffThread, takeoffHeight, SIG_TAKEOFF)
StartThread(SmokeUnit, smokePiece)
Hide(rearthrust)
Hide(wingthrust1)
Hide(wingthrust2)
Hide(flare1)
Hide(flare2)
Hide(drop)
end
function script.FireWeapon(num)
gun_1 = not gun_1
Sleep(33) -- delay before clearing attack order; else bomb loses target and fails to home
Reload()
end
function script.QueryWeapon(num)
return (gun_1 and flare1) or flare2
end
function script.BlockShot(num)
return (GetUnitValue(COB.CRASHING) == 1) or (Spring.GetUnitRulesParam(unitID, "noammo") == 1)
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity <= .25 then
Explode(base, sfxNone)
Explode(wing1, sfxNone)
Explode(wing2, sfxNone)
return 1
elseif severity <= .50 or ((Spring.GetUnitMoveTypeData(unitID).aircraftState or "") == "crashing") then
Explode(wing1, sfxFall + sfxSmoke + sfxFire)
Explode(wing2, sfxFall + sfxSmoke + sfxFire)
return 1
elseif severity <= .75 then
Explode(wing1, sfxFall + sfxSmoke + sfxFire + sfxExplode)
Explode(wing2, sfxFall + sfxSmoke + sfxFire + sfxExplode)
return 2
else
Explode(wing1, sfxFall + sfxSmoke + sfxFire + sfxExplode)
Explode(wing2, sfxFall + sfxSmoke + sfxFire + sfxExplode)
return 2
end
end
| gpl-2.0 |
Zero-K-Experiments/Zero-K-Experiments | effects/empmissile_explosion.lua | 16 | 4084 | -- empmissile_explosion
-- based on gundam_powerplant_explosion.lua
return {
["empmissile_explosion"] = {
electric1 = {
air = true,
class = [[heatcloud]],
count = 3,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 1.1,
maxheat = 15,
pos = [[r-2 r2, 5, r-2 r2]],
size = 1,
sizegrowth = 15,
speed = [[0, 1 0, 0]],
texture = [[electnovaexplo]],
},
},
electric2 = {
air = true,
class = [[heatcloud]],
count = 1,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 1.3,
maxheat = 15,
pos = [[r-2 r2, 5, r-2 r2]],
size = 3,
sizegrowth = 25,
speed = [[0, 0, 0]],
texture = [[flare]],
},
},
electricarcs1 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 0.8,
alwaysvisible = true,
colormap = [[1.0 1.0 1.0 0.04 0.2 0.5 0.9 0.01 0.1 0.5 0.7 0.01]],
directional = true,
emitrot = 45,
emitrotspread = 32,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.05, 0]],
numparticles = 16,
particlelife = 10,
particlelifespread = 5,
particlesize = 20,
particlesizespread = 0,
particlespeed = 7,
particlespeedspread = 5,
pos = [[0, 2, 0]],
sizegrowth = 1,
sizemod = 1.0,
texture = [[lightening]],
useairlos = false,
},
},
groundflash = {
air = true,
alwaysvisible = true,
circlealpha = 0.6,
circlegrowth = 6,
flashalpha = 0.9,
flashsize = 220,
ground = true,
ttl = 20,
water = true,
color = {
[1] = 0,
[2] = 0.5,
[3] = 1,
},
},
smoke = {
air = true,
count = 8,
ground = true,
water = true,
properties = {
agespeed = 0.01,
alwaysvisible = true,
color = 0.1,
pos = [[r-60 r60, 24, r-60 r60]],
size = 50,
sizeexpansion = 0.6,
speed = [[r-3 r3, 1 r2.3, r-3 r3]],
startsize = 10,
},
},
whiteglow = {
air = true,
class = [[heatcloud]],
count = 2,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 1.1,
maxheat = 15,
pos = [[0, 5, 0]],
size = 10,
sizegrowth = 25,
speed = [[0, 1 0, 0]],
texture = [[laserend]],
},
},
electricstorm = {
air = true,
class = [[CExpGenSpawner]],
count = 150,
ground = true,
water = true,
properties = {
delay = [[5 r200]],
explosiongenerator = [[custom:YELLOW_LIGHTNING_STORMBOLT]],
pos = [[-140 r280, 1, -140 r280]],
},
},
},
}
| gpl-2.0 |
Scavenge/darkstar | scripts/globals/items/orange_kuchen_+1.lua | 12 | 1319 | -----------------------------------------
-- ID: 4332
-- Item: orange_kuchen_+1
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- MP % 13 (cap 80)
-- MP 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,3600,4332);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_MPP, 13);
target:addMod(MOD_FOOD_MP_CAP, 80);
target:addMod(MOD_MPHEAL, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_MPP, 13);
target:delMod(MOD_FOOD_MP_CAP, 80);
target:delMod(MOD_MPHEAL, 1);
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Misareaux_Coast/npcs/HomePoint#1.lua | 9 | 1272 | -----------------------------------
-- Area: Misareaux Coast
-- NPC: HomePoint#1
-- @pos -65 -17.5 563 25
-----------------------------------
package.loaded["scripts/zones/Misareaux_Coast/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Misareaux_Coast/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 117);
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 == 0x21fd) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
Scavenge/darkstar | scripts/globals/spells/carnage_elegy.lua | 22 | 1590 | -----------------------------------------
-- Spell: Carnage Elegy
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local duration = 180;
local power = 512;
local pCHR = caster:getStat(MOD_CHR);
local mCHR = target:getStat(MOD_CHR);
local dCHR = (pCHR - mCHR);
local resm = applyResistanceEffect(caster,spell,target,dCHR,SINGING_SKILL,0,EFFECT_ELEGY);
if (resm < 0.5) then
spell:setMsg(85); -- resist message
else
local iBoost = caster:getMod(MOD_ELEGY_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
power = power + iBoost*10;
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
-- Try to overwrite weaker elegy
if (target:addStatusEffect(EFFECT_ELEGY,power,0,duration)) then
spell:setMsg(237);
else
spell:setMsg(75); -- no effect
end
end
return EFFECT_ELEGY;
end; | gpl-3.0 |
cyclonetm/XmakanX | plugins/sticker_lock.lua | 3 | 19167 | do
local administrators_only = 'For administrator only!'
local moderators_only = 'For moderators only!'
local function create_group(msg)
if not is_admin(msg) then return administrators_only end
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.'
end
local function addgroup(msg)
if not is_admin(msg) then return administrators_only end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
-- create data array in moderation.json
data[tostring(msg.to.id)] = {
moderators ={},
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_bots = 'no',
lock_name = 'no',
lock_photo = 'no',
lock_member = 'no',
anti_flood = 'no',
welcome = 'no',
sticker = 'ok'
}
}
save_data(_config.moderation.data, data)
return 'Group has been added.'
end
local function remgroup(msg)
if not is_admin(msg) then return administrators_only end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return 'Group has been removed'
end
local function export_chat_link_callback(extra, success, result)
local msg = extra.msg
local group_name = msg.to.title
local data = extra.data
local receiver = get_receiver(msg)
if success == 0 then
return send_large_msg(receiver, 'Cannot generate invite link for this group.\nMake sure you are an admin or a sudoer.')
end
data[tostring(msg.to.id)]['link'] = result
save_data(_config.moderation.data, data)
return send_large_msg(receiver,'Newest generated invite link for '..group_name..' is:\n'..result)
end
local function set_description(msg, data)
if not is_mod(msg) then return moderators_only end
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = deskripsi
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..deskripsi
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
return string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
end
local function set_rules(msg, data)
if not is_mod(msg) then return moderators_only end
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules
return rules
end
-- dis/allow APIs bots to enter group. Spam prevention.
local function allow_api_bots(msg, data)
if not is_mod(msg) then return moderators_only end
local group_bot_lock = data[tostring(msg.to.id)]['settings']['lock_bots']
if group_bot_lock == 'no' then
return 'Bots are allowed to enter group.'
else
data[tostring(msg.to.id)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is open for bots.'
end
end
local function disallow_api_bots(msg, data)
if not is_mod(msg) then return moderators_only end
local group_bot_lock = data[tostring(msg.to.id)]['settings']['lock_bots']
if group_bot_lock == 'yes' then
return 'Group is already locked from bots.'
else
data[tostring(msg.to.id)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group is locked from bots.'
end
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data)
if not is_mod(msg) then return moderators_only end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ')
save_data(_config.moderation.data, data)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data)
if not is_mod(msg) then return moderators_only end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data)
if not is_mod(msg) then return moderators_only end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data)
if not is_mod(msg) then return moderators_only end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data)
if not is_mod(msg) then return moderators_only end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data)
if not is_mod(msg) then return moderators_only end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
-- show group settings
local function show_group_settings(msg, data)
if not is_mod(msg) then return moderators_only end
local settings = data[tostring(msg.to.id)]['settings']
if settings.lock_bots == 'yes' then
lock_bots_state = 'ฺูบโโ'
elseif settings.lock_bots == 'no' then
lock_bots_state = 'ฺูบโโ'
end
if settings.lock_name == 'yes' then
lock_name_state = 'ฺูบโโ'
elseif settings.lock_name == 'no' then
lock_name_state = 'ฺูบโโ'
end
if settings.lock_photo == 'yes' then
lock_photo_state = 'ฺูบโโ'
elseif settings.lock_photo == 'no' then
lock_photo_state = 'ฺูบโโ'
end
if settings.lock_member == 'yes' then
lock_member_state = 'ฺูบโโ'
elseif settings.lock_member == 'no' then
lock_member_state = 'ฺูบโโ'
end
if settings.anti_flood ~= 'no' then
antiflood_state = 'ฺูบโโ'
elseif settings.anti_flood == 'no' then
antiflood_state = 'ฺูบโโ'
end
if settings.welcome ~= 'no' then
greeting_state = 'ฺูบโโ'
elseif settings.welcome == 'no' then
greeting_state = 'ฺูบโโ'
end
if settings.sticker ~= 'ok' then
sticker_state = 'ฺูบโโ'
elseif settings.sticker == 'ok' then
sticker_state = 'ฺูบโโ'
end
local text = 'Group settings:\n'
..'\n'..lock_bots_state..' Lock group from bot : '..settings.lock_bots
..'\n'..lock_name_state..' Lock group name : '..settings.lock_name
..'\n'..lock_photo_state..' Lock group photo : '..settings.lock_photo
..'\n'..lock_member_state..' Lock group member : '..settings.lock_member
..'\n'..antiflood_state..' Flood protection : '..settings.anti_flood
..'\n'..greeting_state..' Welcome message : '..settings.welcome
..'\n'..sticker_state..' Sticker policy : '..settings.sticker
return text
end
-- media handler. needed by group_photo_lock
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
return msg
end
function run(msg, matches)
if not is_chat_msg(msg) then
return "This is not a group chat."
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
-- create a group
if matches[1] == 'mkgroup' and matches[2] then
group_name = matches[2]
return create_group(msg)
end
-- add a group to be moderated
if matches[1] == 'addgroup' then
return addgroup(msg)
end
-- remove group from moderation
if matches[1] == 'remgroup' then
return remgroup(msg)
end
if msg.media and is_chat_msg(msg) and is_momod(msg) then
if msg.media.type == 'photo' and data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then
load_photo(msg.id, set_group_photo, msg)
end
end
end
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'setabout' and matches[2] then
deskripsi = matches[2]
return set_description(msg, data)
end
if matches[1] == 'about' then
return get_description(msg, data)
end
if matches[1] == 'setrules' then
rules = matches[2]
return set_rules(msg, data)
end
if matches[1] == 'rules' then
return get_rules(msg, data)
end
-- group link {get|set}
if matches[1] == 'link' then
if matches[2] == 'get' then
if data[tostring(msg.to.id)]['link'] then
local about = get_description(msg, data)
local link = data[tostring(msg.to.id)]['link']
return about.."\n\n"..link
else
return 'Invite link does not exist.\nTry !link set to generate it.'
end
end
if matches[2] == 'set' and is_mod(msg) then
msgr = export_chat_link(receiver, export_chat_link_callback, {data=data, msg=msg})
end
end
if matches[1] == 'group' then
-- lock {bot|name|member|photo|sticker}
if matches[2] == 'lock' then
if matches[3] == 'bot' then
return disallow_api_bots(msg, data)
end
if matches[3] == 'name' then
return lock_group_name(msg, data)
end
if matches[3] == 'member' then
return lock_group_member(msg, data)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data)
end
-- unlock {bot|name|member|photo|sticker}
elseif matches[2] == 'unlock' then
if matches[3] == 'bot' then
return allow_api_bots(msg, data)
end
if matches[3] == 'name' then
return unlock_group_name(msg, data)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data)
end
-- view group settings
elseif matches[2] == 'settings' then
return show_group_settings(msg, data)
end
end
if matches[1] == 'sticker' then
if matches[2] == 'warn' then
if welcome_stat ~= 'warn' then
data[tostring(msg.to.id)]['settings']['sticker'] = 'warn'
save_data(_config.moderation.data, data)
end
return '[Alredy Enabled]\nSticker Sender will be warned first, then kicked for second Sticker.'
end
if matches[2] == 'kick' then
if welcome_stat ~= 'kick' then
data[tostring(msg.to.id)]['settings']['sticker'] = 'kick'
save_data(_config.moderation.data, data)
end
return '[Already Enabled]Sticker Sender will be kicked!'
end
if matches[2] == 'ok' then
if welcome_stat == 'ok' then
return '[Already Disabled]Nothing Will Happend If Sticker Sent!'
else
data[tostring(msg.to.id)]['settings']['sticker'] = 'ok'
save_data(_config.moderation.data, data)
return 'Nothing Will Happend If Sticker Sent! '
end
end
end
-- if group name is renamed
if matches[1] == 'chat_rename' then
if not msg.service then
return 'Are you trying to troll me?'
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
-- set group name
if matches[1] == 'setname' and is_mod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
end
-- set group photo
if matches[1] == 'setphoto' and is_mod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
-- if a user is added to group
if matches[1] == 'chat_add_user' then
if not msg.service then
return 'Are you trying to troll me?'
end
local group_member_lock = settings.lock_member
local group_bot_lock = settings.lock_bots
local user = 'user#id'..msg.action.user.id
if group_member_lock == 'yes' then
chat_del_user(receiver, user, ok_cb, true)
-- no APIs bot are allowed to enter chat group.
elseif group_bot_lock == 'yes' and msg.action.user.flags == 4352 then
chat_del_user(receiver, user, ok_cb, true)
elseif group_bot_lock == 'no' or group_member_lock == 'no' then
return nil
end
end
-- if sticker is sent
if msg.media and msg.media.caption == 'sticker.webp' and not is_momod(msg) then
local user_id = msg.from.id
local chat_id = msg.to.id
local sticker_hash = 'mer_sticker:'..chat_id..':'..user_id
local is_sticker_offender = redis:get(sticker_hash)
if settings.sticker == 'warn' then
if is_sticker_offender then
chat_del_user(receiver, 'user#id'..user_id, ok_cb, true)
redis:del(sticker_hash)
return '[Warned Before]Kicked Because You Have Sent Stickers'
elseif not is_sticker_offender then
redis:set(sticker_hash, true)
return ' Stop Sending Sticker.This Is A Warn Next Time You Will Kicked!'
end
elseif settings.sticker == 'kick' then
chat_del_user(receiver, 'user#id'..user_id, ok_cb, true)
return 'You Kicked Because You Have Sent Stickers??'
elseif settings.sticker == 'ok' then
return nil
end
end
-- if group photo is deleted
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return 'Are you trying to troll me?'
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
-- if group photo is changed
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return 'Are you trying to troll me?'
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
end
end
return {
description = 'Plugin to manage group chat.',
usage = {
admin = {
'!mkgroup <group_name> : Make/create a new group.',
'!addgroup : Add group to moderation list.',
'!remgroup : Remove group from moderation list.'
},
moderator = {
'!group <lock|unlock> bot : {Dis}allow APIs bots.',
'!group <lock|unlock> member : Lock/unlock group member.',
'!group <lock|unlock> name : Lock/unlock group name.',
'!group <lock|unlock> photo : Lock/unlock group photo.',
'!group settings : Show group settings.',
'!link <set> : Generate/revoke invite link.',
'!setabout <description> : Set group description.',
'!setname <new_name> : Set group name.',
'!setphoto : Set group photo.',
'!setrules <rules> : Set group rules.',
'!sticker warn : Sticker restriction, sender will be warned for the first violation.',
'!sticker kick : Sticker restriction, sender will be kick.',
'!sticker ok : Disable sticker restriction.'
},
user = {
'!about : Read group description',
'!rules : Read group rules',
'!link <get> : Print invite link'
},
},
patterns = {
--"^!(about)$",
--"^!(addgroup)$",
"%[(audio)%]",
"%[(document)%]",
--"^!(group) (lock) (.*)$",
--"^!(group) (settings)$",
--"^!(group) (unlock) (.*)$",
--"^!(link) (.*)$",
--"^!(mkgroup) (.*)$",
--"%[(photo)%]",
--"^!(remgroup)$",
--"^!(rules)$",
-- "^!(setabout) (.*)$",
-- "^!(setname) (.*)$",
--"^!(setphoto)$",
--"^!(setrules) (.*)$",
"^[!/](sticker) (.*)$",
"^!!tgservice (.+)$",
"%[(video)%]"
},
run = run,
pre_process = pre_process
}
end
| gpl-2.0 |
mortezamosavy999/monsterTG | plugins/Google_image.lua | 42 | 3165 | do
local mime = require("mime")
local google_config = load_from_file('data/google.lua')
local cache = {}
--[[
local function send_request(url)
local t = {}
local options = {
url = url,
sink = ltn12.sink.table(t),
method = "GET"
}
local a, code, headers, status = http.request(options)
return table.concat(t), code, headers, status
end]]--
local function get_google_data(text)
local url = "http://ajax.googleapis.com/ajax/services/search/images?"
url = url.."v=1.0&rsz=5"
url = url.."&q="..URL.escape(text)
url = url.."&imgsz=small|medium|large"
if google_config.api_keys then
local i = math.random(#google_config.api_keys)
local api_key = google_config.api_keys[i]
if api_key then
url = url.."&key="..api_key
end
end
local res, code = http.request(url)
if code ~= 200 then
print("HTTP Error code:", code)
return nil
end
local google = json:decode(res)
return google
end
-- Returns only the useful google data to save on cache
local function simple_google_table(google)
local new_table = {}
new_table.responseData = {}
new_table.responseDetails = google.responseDetails
new_table.responseStatus = google.responseStatus
new_table.responseData.results = {}
local results = google.responseData.results
for k,result in pairs(results) do
new_table.responseData.results[k] = {}
new_table.responseData.results[k].unescapedUrl = result.unescapedUrl
new_table.responseData.results[k].url = result.url
end
return new_table
end
local function save_to_cache(query, data)
-- Saves result on cache
if string.len(query) <= 7 then
local text_b64 = mime.b64(query)
if not cache[text_b64] then
local simple_google = simple_google_table(data)
cache[text_b64] = simple_google
end
end
end
local function process_google_data(google, receiver, query)
if google.responseStatus == 403 then
local text = 'ERROR: Reached maximum searches per day'
send_msg(receiver, text, ok_cb, false)
elseif google.responseStatus == 200 then
local data = google.responseData
if not data or not data.results or #data.results == 0 then
local text = 'Image not found.'
send_msg(receiver, text, ok_cb, false)
return false
end
-- Random image from table
local i = math.random(#data.results)
local url = data.results[i].unescapedUrl or data.results[i].url
local old_timeout = http.TIMEOUT or 10
http.TIMEOUT = 5
send_photo_from_url(receiver, url)
http.TIMEOUT = old_timeout
save_to_cache(query, google)
else
local text = 'ERROR!'
send_msg(receiver, text, ok_cb, false)
end
end
function run(msg, matches)
local receiver = get_receiver(msg)
local text = matches[1]
local text_b64 = mime.b64(text)
local cached = cache[text_b64]
if cached then
process_google_data(cached, receiver, text)
else
local data = get_google_data(text)
process_google_data(data, receiver, text)
end
end
return {
description = "Search Image With Google",
usage = "/img (item) : search image in google",
patterns = {
"^[!/]img (.*)$"
},
run = run
}
end
| gpl-2.0 |
Zero-K-Experiments/Zero-K-Experiments | LuaRules/Utilities/clusterTool.lua | 17 | 25515 | ---------------------------------------------------------------------------------
-----------C L U S T E R D E T E C T I O N T O O L --------------------------
---------------------------------------------------------------------------------
--[[
Regular usage:
local unitList = Spring.GetAllUnits()
local receivedUnitList = {}
for i=1, #unitList do
local unitID = unitList[i]
receivedUnitList[unitID] ={Spring.GetUnitPosition(unitID)}
end
local orderedObjects = Spring.Utilities.Run_OPTIC(receivedUnitList, 300, 2)
local cluster1, noiseIDList1 = Spring.Utilities.Extract_Cluster (orderedObjects, 50 ) --cluster with 50elmo connection distance
local cluster2, noiseIDList2 = Spring.Utilities.Extract_Cluster (orderedObjects, 150 ) --cluster with 150elmo connection distance
local cluster3, noiseIDList3 = Spring.Utilities.Extract_Cluster (orderedObjects, 300 )--cluster with 300elmo connection distance
local circleList2 = Spring.Utilities.Convert_To_Circle (cluster2, noiseIDList2,receivedUnitList)
Note1: orderedObjects[] contain:
{ ['processed'] = bool,
['reachability_distance'] = numbers (distance squared),
['core_distance'] = numbers (distance squared),
}
Note2: cluster1[] contain:
{ [1] = {unitIDs,}
[2] = {unitIDs,}
}
Note3: circleList2[] contain:
{ [1] = {x,y,z,radius,countOfUnits}
[2] = {x,y,z,radius,countOfUnits}
}
Note4: receivedUnitList[] can be list of coordinate of fake unit (points in empty space).
--]]
function Spring.Utilities.Run_OPTIC(receivedUnitList, neighborhoodRadius, minimumNeighbor)
local objects={}
local orderedObjects = {}
local posListX= {}
--//SORTING unit list by X axis for easier searching, for getting unit in a box thru GetUnitInSquare()
for unitID,pos in pairs(receivedUnitList) do
posListX[#posListX+1] = {unitID,pos[1],pos[3]}
-- posListX = InsertAtOrder(posListX, {unitID,pos[1],pos[3]},function(a,b) return a[2]<b[2] end) --abit slow
end
table.sort(posListX, function(a,b) return a[2]<b[2] end) --//stack ascending
--//SORTING unit list by connections, for extracting cluster information later using ExtractDBSCAN_Clustering()
for unitID,_ in pairs(receivedUnitList) do --//go thru the un-ordered list
objects[unitID] = objects[unitID] or {unitID=unitID,}
if (objects[unitID].processed ~= true) then
orderedObjects, objects = ExpandClusterOrder(orderedObjects,receivedUnitList,unitID, neighborhoodRadius,minimumNeighbor,objects,posListX)
end
end
return orderedObjects
end
function Spring.Utilities.Extract_Cluster (orderedObjects,neighborhoodRadius_alt )
local cluster = {}
local noiseIDList = {}
local currentClusterID = 0
--//CREATE cluster based on desired density (density == neighborhoodRadius_alt).
--//Note: changing cluster view to different density is really cheap when using this function as long as the initial neighborhoodRadius is greater than the new density.
--//if new density (neighborhoodRadius_alt) is greater than initial neighborhoodRadius, then you must recalculate the connections using bigger neighborhoodRadius which incur greater cost.
for i=1, #orderedObjects do
local unitID = orderedObjects[i].unitID
cluster, noiseIDList, currentClusterID = ExtractDBSCAN_Clustering (unitID, currentClusterID, cluster, noiseIDList, orderedObjects[i], neighborhoodRadius_alt)
end
return cluster, noiseIDList
end
function Spring.Utilities.Convert_To_Circle (cluster, noiseIDList,receivedUnitList)
--// extract cluster information and add mapMarker.
local circlePosition = {}
for index=1 , #cluster do
local sumX, sumY,sumZ, unitCount,meanX, meanY, meanZ = 0,0 ,0 ,0 ,0,0,0
local maxX, minX, maxZ, minZ, radiiX, radiiZ, avgRadii = 0,99999,0,99999, 0,0,0
for unitIndex=1, #cluster[index] do
local unitID = cluster[index][unitIndex]
local x,y,z= receivedUnitList[unitID][1],receivedUnitList[unitID][2],receivedUnitList[unitID][3] --// get stored unit position
sumX= sumX+x
sumY = sumY+y
sumZ = sumZ+z
if x> maxX then
maxX= x
end
if x<minX then
minX=x
end
if z> maxZ then
maxZ= z
end
if z<minZ then
minZ=z
end
unitCount=unitCount+1
end
meanX = sumX/unitCount --//calculate center of cluster
meanY = sumY/unitCount
meanZ = sumZ/unitCount
radiiX = ((maxX - meanX)+ (meanX - minX))/2
radiiZ = ((maxZ - meanZ)+ (meanZ - minZ))/2
avgRadii = (radiiX + radiiZ) /2
circlePosition[#circlePosition+1] = {meanX,0,meanZ,avgRadii+100,#cluster[index]}
end
if #noiseIDList>0 then --//IF outlier list is not empty
for j= 1 ,#noiseIDList do
local unitID = noiseIDList[j]
local x,y,z= receivedUnitList[unitID][1],receivedUnitList[unitID][2],receivedUnitList[unitID][3] --// get stored unit position
circlePosition[#circlePosition+1] = {x,0,z,100,1}
end
end
return circlePosition
end
function Spring.Utilities.OPTICS_cluster (receivedUnitList, neighborhoodRadius, minimumNeighbor, neighborhoodRadius_alt)
local objects={}
local orderedObjects = {}
local cluster = {}
local noiseIDList = {}
local currentClusterID = 0
local posListX= {}
--//SORTING unit list by X axis for easier searching, for getting unit in a box thru GetUnitInSquare()
neighborhoodRadius = math.max(neighborhoodRadius_alt,neighborhoodRadius)
for unitID,pos in pairs(receivedUnitList) do
posListX[#posListX+1] = {unitID,pos[1],pos[3]}
-- posListX = InsertAtOrder(posListX, {unitID,pos[1],pos[3]},function(a,b) return a[2]<b[2] end) --abit slow
end
table.sort(posListX, function(a,b) return a[2]<b[2] end) --//stack ascending
--//SORTING unit list by connections, for extracting cluster information later using ExtractDBSCAN_Clustering()
for unitID,_ in pairs(receivedUnitList) do --//go thru the un-ordered list
objects[unitID] = objects[unitID] or {unitID=unitID,}
if (objects[unitID].processed ~= true) then
orderedObjects, objects = ExpandClusterOrder(orderedObjects,receivedUnitList,unitID, neighborhoodRadius,minimumNeighbor,objects,posListX)
end
end
--//CREATE cluster based on desired density (density == neighborhoodRadius_alt).
--//Note: changing cluster view to different density is really cheap when using this function as long as the initial neighborhoodRadius is greater than the new density.
--//if new density (neighborhoodRadius_alt) is greater than initial neighborhoodRadius, then you must recalculate the connections using bigger neighborhoodRadius which incur greater cost.
for i=1, #orderedObjects do
local unitID = orderedObjects[i].unitID
cluster, noiseIDList, currentClusterID = ExtractDBSCAN_Clustering (unitID, currentClusterID, cluster, noiseIDList, orderedObjects[i], neighborhoodRadius_alt)
end
return cluster, noiseIDList
end
----LOW LEVEL FUNCTIONS:-------------------------------------------------
--Note: maintained by msafwan (xponen)
--Positional Functions------------------------------------------------------------
-- 3 function.
local searchCount = 0
local function BinarySearchNaturalOrder(position, orderedList)
local startPos = 1
local endPos = #orderedList
local span = endPos - startPos
local midPos = math.modf((span/2) + startPos + 0.5) --round to nearest integer
local found = false
while (span > 1) do
local difference = position - orderedList[midPos][2]
if difference < 0 then
endPos = midPos
elseif difference > 0 then
startPos = midPos
else
found=true
break;
end
span = endPos - startPos
midPos = math.modf((span/2) + startPos + 0.5) --round to nearest integer
end
if not found then
if(math.abs(position - orderedList[startPos][2]) < math.abs(position - orderedList[endPos][2])) then
midPos = startPos
else
midPos = endPos
end
end
return midPos
end
local distCount = 0
local function GetDistanceSQ(unitID1, unitID2,receivedUnitList)
local x1,x2 = receivedUnitList[unitID1][1],receivedUnitList[unitID2][1]
local z1,z2 = receivedUnitList[unitID1][3],receivedUnitList[unitID2][3]
local distanceSQ = ((x1-x2)^2 + (z1-z2)^2)
return distanceSQ
end
local intersectionCount = 0
local function GetUnitsInSquare(x,z,distance,posListX)
local unitIndX = BinarySearchNaturalOrder(x, posListX)
local unitsX = {}
for i = unitIndX, 1, -1 do --go left
if x - posListX[i][2] > distance then
break
end
unitsX[#unitsX+1]=posListX[i]
end
for i = unitIndX+1, #posListX, 1 do --go right
if posListX[i][2]-x > distance then
break
end
unitsX[#unitsX+1]=posListX[i]
end
if #unitsX == 0 then
return unitsX
end
local unitsInBox = {}
for i=1, #unitsX, 1 do
if (math.abs(unitsX[i][3]-z) <= distance) then
unitsInBox[#unitsInBox+1] = unitsX[i][1]
end
end
return unitsInBox
end
--GetNeigbors--------------------------------------------------------------------
-- 1 function.
local getunitCount = 0
local function GetNeighbor (unitID, myTeamID, neighborhoodRadius, receivedUnitList,posListX) --//return the unitIDs of specific units around a center unit
local x,z = receivedUnitList[unitID][1],receivedUnitList[unitID][3]
local tempList = GetUnitsInSquare(x,z,neighborhoodRadius,posListX) --Get neighbor. Ouput: unitID + my units
return tempList
end
--Pre-SORTING function----------------------------------------------------------------
--3 function
local function InsertAtOrder(posList, newObject,compareFunction) --//stack big values at end of table, and tiny values at start of table.
local insertionIndex = #posList + 1 --//insert data just below that big value
for i = #posList, 1, -1 do
if compareFunction(posList[i],newObject) then-- posList[i] < newObject will sort in ascending order, while posList[i] > newObject will sort in descending order
break
end
insertionIndex=i
end
--//shift table content
local buffer1 = posList[insertionIndex] --backup content of current index
posList[insertionIndex] = newObject --replace current index with new value. eg: {unitID = objects.unitID , x = objects.x, z = objects.z }
for j = insertionIndex, #posList, 1 do --shift content for content less-or-equal-to table lenght
local buffer2 = posList[j+1] --save content of next index
posList[j+1] = buffer1 --put backup value into next index
buffer1 = buffer2 --use saved content as next backup, then repeat process
end
return posList
end
local insertCount = 0
local function InsertOrderSeed (orderSeed, unitID_to_orderSeedMeta, unitID, objects) --//stack tiny values at end of table, and big values at start of table.
local orderSeedLenght = #orderSeed or 0 --//code below can handle both: table of lenght 0 and >1
local insertionIndex = orderSeedLenght + 1 --//insert data just above that big value
for i = orderSeedLenght, 1, -1 do
if orderSeed[i].content.reachability_distance >= objects[unitID].reachability_distance then --//if existing value is abit bigger than to-be-inserted value: break
break
end
insertionIndex=i
end
--//shift table content
local buffer1 = orderSeed[insertionIndex] --backup content of current index
orderSeed[insertionIndex] = {unitID = unitID , content = objects[unitID]} --replace current index with new value
unitID_to_orderSeedMeta[unitID]=insertionIndex --update meta table
for j = insertionIndex, orderSeedLenght, 1 do --shift content for content less-or-equal-to table lenght
local buffer2 = orderSeed[j+1] --save content of next index
orderSeed[j+1] = buffer1 --put backup value into next index
unitID_to_orderSeedMeta[buffer1.unitID]=j+1 -- update meta table
buffer1 = buffer2 --use saved content as next backup, then repeat process
end
return orderSeed, unitID_to_orderSeedMeta
end
local shiftCount = 0
local function ShiftOrderSeed (orderSeed, unitID_to_orderSeedMeta, unitID, objects) --//move values to end of table, and shift big values to beginning of of table.
local oldPosition = unitID_to_orderSeedMeta[unitID]
local newPosition = oldPosition
for i = oldPosition+1, #orderSeed, 1 do
if orderSeed[i].content.reachability_distance < objects[unitID].reachability_distance then --//if existing value is abit lower than to-be-inserted value: add behind it and break
break
end
newPosition = i
end
if newPosition == oldPosition then
orderSeed[oldPosition]={unitID = unitID , content = objects[unitID]}
else
local buffer1 = orderSeed[newPosition] --//backup content of current index
orderSeed[newPosition] = {unitID = unitID , content = objects[unitID]} --//replace current index with new value
unitID_to_orderSeedMeta[unitID]=newPosition --//update meta table
orderSeed[oldPosition] = nil --//delete old position
for j = newPosition-1, oldPosition, -1 do --//shift values toward beginning of table
local buffer2 = orderSeed[j] --//save content of current index
orderSeed[j] = buffer1 --//put backup value into previous index
unitID_to_orderSeedMeta[buffer1.unitID]=j --// update meta table
buffer1 = buffer2 --//use saved content as the following backup, then repeat process
end
end
return orderSeed, unitID_to_orderSeedMeta
end
--Merge-SORTING function----------------------------------------------------------------
--2 function. Reference: http://www.algorithmist.com/index.php/Merge_sort.c
local function merge(left, right, CompareFunction)
local result ={} --var list result
local leftProgress, rightProgress = 1,1
while leftProgress <= #left or rightProgress <= #right do --while length(left) > 0 or length(right) > 0
local leftNotFinish = leftProgress <= #left
local rightNotFinish = rightProgress <= #right
if leftNotFinish and rightNotFinish then --if length(left) > 0 and length(right) > 0
if CompareFunction(left[leftProgress],right[rightProgress]) then --if first(left) < first(right), sort ascending. if first(left) > first(right), sort descending.
result[#result+1] =left[leftProgress]--append first(left) to result
leftProgress = leftProgress + 1 --left = rest(left)
else
result[#result+1] =right[rightProgress]--append first(right) to result
rightProgress = rightProgress + 1 --right = rest(right)
end
elseif leftNotFinish then --else if length(left) > 0
result[#result+1] =left[leftProgress] --append first(left) to result
leftProgress = leftProgress + 1 --left = rest(left)
elseif rightNotFinish then --else if length(right) > 0
result[#result+1] =right[rightProgress] --append first(right) to result
rightProgress = rightProgress + 1 --right = rest(right)
end
end --end while
return result
end
local function merge_sort(m,CompareFunction)
--// if list size is 1, consider it sorted and return it
if #m <=1 then--if length(m) <= 1
return m
end
--// else list size is > 1, so split the list into two sublists
local left, right = {}, {} --var list left, right
local middle = math.modf((#m/2)+0.5) --var integer middle = length(m) / 2
for i= 1, middle, 1 do --for each x in m up to middle
left[#left+1] = m[i] --add x to left
end
for j= #m, middle+1, -1 do--for each x in m after or equal middle
right[(j-middle)] = m[j]--add x to right
end
--// recursively call merge_sort() to further split each sublist
--// until sublist size is 1
left = merge_sort(left,CompareFunction)
right = merge_sort(right,CompareFunction)
--// merge the sublists returned from prior calls to merge_sort()
--// and return the resulting merged sublist
return merge(left, right,CompareFunction)
end
--OPTICS function----------------------------------------------------------------
--5 function
local useMergeSorter_gbl = true --//constant: experiment with merge sorter (slower)
local orderseedCount = 0
local function OrderSeedsUpdate(neighborsID, currentUnitID,objects, orderSeed,unitID_to_orderSeedMeta,receivedUnitList)
local c_dist = objects[currentUnitID].core_distance
for i=1, #neighborsID do
local neighborUnitID = neighborsID[i]
objects[neighborUnitID]=objects[neighborUnitID] or {unitID=neighborUnitID,}
if (objects[neighborUnitID].processed~=true) then
local new_r_dist = math.max(c_dist, GetDistanceSQ(currentUnitID, neighborUnitID,receivedUnitList))
if objects[neighborUnitID].reachability_distance==nil then
objects[neighborUnitID].reachability_distance = new_r_dist
if useMergeSorter_gbl then
orderSeed[#orderSeed+1] = {unitID = neighborUnitID, content = objects[neighborUnitID]}
unitID_to_orderSeedMeta[neighborUnitID] = #orderSeed
else
orderSeed, unitID_to_orderSeedMeta = InsertOrderSeed (orderSeed, unitID_to_orderSeedMeta, neighborUnitID,objects)
end
else --// object already in OrderSeeds
if new_r_dist< objects[neighborUnitID].reachability_distance then
objects[neighborUnitID].reachability_distance = new_r_dist
if useMergeSorter_gbl then
local oldPosition = unitID_to_orderSeedMeta[neighborUnitID]
orderSeed[oldPosition] = {unitID = neighborUnitID, content = objects[neighborUnitID]} -- update values
else
orderSeed, unitID_to_orderSeedMeta = ShiftOrderSeed(orderSeed, unitID_to_orderSeedMeta, neighborUnitID, objects)
end
end
end
end
end
if useMergeSorter_gbl then
-- orderSeed = merge_sort(orderSeed, function(a,b) return a.content.reachability_distance > b.content.reachability_distance end ) --really slow
table.sort(orderSeed, function(a,b) return a.content.reachability_distance > b.content.reachability_distance end) --abit slow
for i= 1, #orderSeed do
unitID_to_orderSeedMeta[orderSeed[i].unitID] = i
end
end
return orderSeed, objects, unitID_to_orderSeedMeta
end
local setcoreCount =0
local function SetCoreDistance(neighborsID, minimumNeighbor, unitID,receivedUnitList)
if (#neighborsID >= minimumNeighbor) then
local neighborsDist= {} --//table to list down neighbor's distance.
for i=1, #neighborsID do
-- local distance = spGetUnitSeparation (unitID, neighborsID[i])
local distanceSQ = GetDistanceSQ(unitID,neighborsID[i],receivedUnitList)
neighborsDist[i]= distanceSQ --//add distance value
end
table.sort(neighborsDist, function(a,b) return a < b end)
-- neighborsDist = merge_sort(neighborsDist, true)
return neighborsDist[minimumNeighbor] --//return the distance of the minimumNeigbor'th unit with respect to the center unit.
else
return nil
end
end
function ExtractDBSCAN_Clustering (unitID, currentClusterID, cluster, noiseIDList, object, neighborhoodRadius_alt)
local reachabilityDist = (object.reachability_distance and math.sqrt(object.reachability_distance)) or 9999
--// Precondition: neighborhoodRadius_alt <= generating dist neighborhoodRadius for Ordered Objects
if reachabilityDist > neighborhoodRadius_alt then --// UNDEFINED > neighborhoodRadius. ie: Not reachable from outside
local coreDistance = (object.core_distance and math.sqrt(object.core_distance)) or 9999
if coreDistance <= neighborhoodRadius_alt then --//has neighbor
currentClusterID = currentClusterID + 1 --//create new cluster
cluster[currentClusterID] = cluster[currentClusterID] or {} --//initialize array
local arrayIndex = #cluster[currentClusterID] + 1
cluster[currentClusterID][arrayIndex] = unitID --//add to new cluster
-- Spring.Echo("CREATE CLUSTER")
else --//if has no neighbor
local arrayIndex = #noiseIDList +1
noiseIDList[arrayIndex]= unitID --//add to noise list
end
else --// object.reachability_distance <= neighborhoodRadius_alt. ie:reachable
local arrayIndex = #cluster[currentClusterID] + 1
cluster[currentClusterID][arrayIndex] = unitID--//add to current cluster
end
return cluster, noiseIDList, currentClusterID
end
function ExpandClusterOrder(orderedObjects,receivedUnitList, unitID, neighborhoodRadius, minimumNeighbor, objects,posListX)
local neighborsID = GetNeighbor (unitID, myTeamID, neighborhoodRadius, receivedUnitList,posListX)
objects[unitID].processed = true
objects[unitID].reachability_distance = nil
objects[unitID].core_distance = SetCoreDistance(neighborsID, minimumNeighbor, unitID,receivedUnitList)
orderedObjects[#orderedObjects+1]=objects[unitID]
if objects[unitID].core_distance ~= nil then --//it have neighbor
local orderSeed ={}
local unitID_to_orderSeedMeta = {}
orderSeed, objects, unitID_to_orderSeedMeta = OrderSeedsUpdate(neighborsID, unitID, objects, orderSeed,unitID_to_orderSeedMeta,receivedUnitList)
while #orderSeed > 0 do
local currentUnitID = orderSeed[#orderSeed].unitID
objects[currentUnitID] = orderSeed[#orderSeed].content
orderSeed[#orderSeed]=nil
local neighborsID_ne = GetNeighbor (currentUnitID, myTeamID, neighborhoodRadius, receivedUnitList,posListX)
objects[currentUnitID].processed = true
objects[currentUnitID].core_distance = SetCoreDistance(neighborsID_ne, minimumNeighbor, currentUnitID,receivedUnitList)
orderedObjects[#orderedObjects+1]=objects[currentUnitID]
if objects[currentUnitID].core_distance~=nil then
orderSeed, objects,unitID_to_orderSeedMeta = OrderSeedsUpdate(neighborsID_ne, currentUnitID, objects, orderSeed, unitID_to_orderSeedMeta,receivedUnitList)
end
end
end
return orderedObjects,objects
end
--DBSCAN function----------------------------------------------------------
--1 function. BUGGY (Not yet debugged)
function Spring.Utilities.DBSCAN_cluster(receivedUnitList,neighborhoodRadius,minimumNeighbor)
local unitID_to_clusterMeta = {}
local visitedUnitID = {}
local currentCluster_global=1
local cluster = {}
local unitIDNoise = {}
local posListX = {}
for unitID,pos in pairs(receivedUnitList) do
posListX[#posListX+1] = {unitID,pos[1],pos[3]}
-- posListX = InsertAtOrder(posListX, {unitID,pos[1],pos[3]},function(a,b) return a[2]<b[2] end) --abit slow
end
table.sort(posListX, function(a,b) return a[2]<b[2] end) --//stack ascending
for unitID,_ in pairs(receivedUnitList) do --//go thru the un-ordered list
if visitedUnitID[unitID] ~= true then --//skip if already visited
visitedUnitID[unitID] = true
local neighborUnits = GetNeighbor (unitID, myTeamID, neighborhoodRadius, receivedUnitList,posListX)
if #neighborUnits ~= nil then
if #neighborUnits <= minimumNeighbor then --//if surrounding units is less-or-just-equal to minimum neighbor then mark current unit as noise or 'outliers'
local noiseIDLenght = #unitIDNoise or 0 --// if table is empty then make sure return table-lenght as 0 (zero) instead of 'nil'
unitIDNoise[noiseIDLenght +1] = unitID
else
--local clusterIndex = #cluster+1 --//lenght of previous cluster table plus 1 new cluster
cluster[currentCluster_global]={} --//initialize new cluster with an empty table for unitID
local unitClusterLenght = #cluster[currentCluster_global] or 0 --// if table is empty then make sure return table-lenght as 0 (zero) instead of 'nil'
cluster[currentCluster_global][unitClusterLenght +1] = unitID --//lenght of the table-in-table containing unit list plus 1 new unit
unitID_to_clusterMeta[unitID] = currentCluster_global
for l=1, #neighborUnits do
local unitID_ne = neighborUnits[l]
if visitedUnitID[unitID_ne] ~= true then --//skip if already visited
visitedUnitID[unitID_ne] = true
local neighborUnits_ne = GetNeighbor (unitID_ne, myTeamID, neighborhoodRadius, receivedUnitList,posListX)
if #neighborUnits_ne ~= nil then
if #neighborUnits_ne > minimumNeighbor then
for m=1, #neighborUnits_ne do
local duplicate = false
for n=1, #neighborUnits do
if neighborUnits[n] == neighborUnits_ne[m] then
duplicate = true
break
end
end
if duplicate== false then
neighborUnits[#neighborUnits +1]=neighborUnits_ne[m]
end
end --//for m=1, m<= #neighborUnits_ne, 1
end --// if #neighborUnits_ne > minimumNeighbor
end --//if #neighborUnits_ne ~= nil
if unitID_to_clusterMeta[unitID_ne] ~= currentCluster_global then
local unitIndex_ne = #cluster[currentCluster_global] +1 --//lenght of the table-in-table containing unit list plus 1 new unit
cluster[currentCluster_global][unitIndex_ne] = unitID_ne
unitID_to_clusterMeta[unitID_ne] = currentCluster_global
end
end --//if visitedUnitID[unitID_ne] ~= true
end --//for l=1, l <= #neighborUnits, 1
currentCluster_global= currentCluster_global + 1
end --//if #neighborUnits <= minimumNeighbor, else
end --//if #neighborUnits ~= nil
end --//if visitedUnitID[unitID] ~= true
end --//for i=1, i <= #receivedUnitList,1
return cluster, unitIDNoise
end
--brief: a clustering algorithm
--algorithm source: Ordering Points To Identify the Clustering Structure (OPTICS) by Mihael Ankerst, Markus M. Breunig, Hans-Peter Kriegel and Jรถrg Sander
--algorithm source: density-based spatial clustering of applications with noise (DBSCAN) by Martin Ester, Hans-Peter Kriegel, Jรถrg Sander and Xiaowei Xu
--Reference:
--http://en.wikipedia.org/wiki/OPTICS_algorithm ;pseudocode
--http://en.wikipedia.org/wiki/DBSCAN ;pseudocode
--http://codingplayground.blogspot.com/2009/11/dbscan-clustering-algorithm.html ;C++ sourcecode
--http://www.google.com.my/search?q=optics%3A+Ordering+Points+To+Identify+the+Clustering+Structure ;article & pseudocode on OPTICS
---------------------------------------------------------------------------------
---------------------------------E N D ------------------------------------------
--------------------------------------------------------------------------------- | gpl-2.0 |
BlockMen/minetest_next | mods/bones/init.lua | 2 | 6567 | local bones_enabled = core.setting_getbool("enable_bones") ~= false
bones = {}
local function is_owner(pos, name)
local owner = minetest.get_meta(pos):get_string("owner")
if owner == "" or owner == name then
return true
end
return false
end
bones.bones_formspec =
"size[8,9]"..
default.gui_bg..
default.gui_bg_img..
default.gui_slots..
"list[current_name;main;0,0.3;8,4;]"..
"list[current_player;main;0,4.85;8,1;]"..
"list[current_player;main;0,6.08;8,3;8]"..
default.get_hotbar_bg(0,4.85)
local share_bones_time = tonumber(minetest.setting_get("share_bones_time") or 1200)
local share_bones_time_early = tonumber(minetest.setting_get("share_bones_time_early") or (share_bones_time/4))
minetest.register_node("bones:bones", {
description = "Bones",
tiles = {
"bones_top.png",
"bones_bottom.png",
"bones_side.png",
"bones_side.png",
"bones_rear.png",
"bones_front.png"
},
paramtype2 = "facedir",
groups = {dig_immediate=2},
sounds = default.node_sound_dirt_defaults({
footstep = {name="default_gravel_footstep", gain=0.5},
dug = {name="default_gravel_footstep", gain=1.0},
}),
can_dig = function(pos, player)
local inv = minetest.get_meta(pos):get_inventory()
return is_owner(pos, player:get_player_name()) and inv:is_empty("main")
end,
allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)
if is_owner(pos, player:get_player_name()) then
return count
end
return 0
end,
allow_metadata_inventory_put = function(pos, listname, index, stack, player)
return 0
end,
allow_metadata_inventory_take = function(pos, listname, index, stack, player)
if is_owner(pos, player:get_player_name()) then
return stack:get_count()
end
return 0
end,
on_metadata_inventory_take = function(pos, listname, index, stack, player)
local meta = minetest.get_meta(pos)
if meta:get_inventory():is_empty("main") then
minetest.remove_node(pos)
end
end,
on_punch = function(pos, node, player)
if(not is_owner(pos, player:get_player_name())) then
return
end
if(minetest.get_meta(pos):get_string("infotext") == "") then
return
end
local inv = minetest.get_meta(pos):get_inventory()
local player_inv = player:get_inventory()
local has_space = true
for i=1,inv:get_size("main") do
local stk = inv:get_stack("main", i)
if player_inv:room_for_item("main", stk) then
inv:set_stack("main", i, nil)
player_inv:add_item("main", stk)
else
has_space = false
break
end
end
-- remove bones if player emptied them
if has_space then
if player_inv:room_for_item("main", {name = "bones:bones"}) then
player_inv:add_item("main", {name = "bones:bones"})
else
minetest.add_item(pos,"bones:bones")
end
minetest.remove_node(pos)
end
end,
on_timer = function(pos, elapsed)
local meta = minetest.get_meta(pos)
local time = meta:get_int("time") + elapsed
if time >= share_bones_time then
meta:set_string("infotext", meta:get_string("owner").."'s old bones")
meta:set_string("owner", "")
else
meta:set_int("time", time)
return true
end
end,
})
local function may_replace(pos, player)
local node_name = minetest.get_node(pos).name
local node_definition = minetest.registered_nodes[node_name]
-- if the node is unknown, we let the protection mod decide
-- this is consistent with when a player could dig or not dig it
-- unknown decoration would often be removed
-- while unknown building materials in use would usually be left
if not node_definition then
-- only replace nodes that are not protected
return not minetest.is_protected(pos, player:get_player_name())
end
-- allow replacing air and liquids
if node_name == "air" or node_definition.liquidtype ~= "none" then
return true
end
-- don't replace filled chests and other nodes that don't allow it
local can_dig_func = node_definition.can_dig
if can_dig_func and not can_dig_func(pos, player) then
return false
end
-- default to each nodes buildable_to; if a placed block would replace it, why shouldn't bones?
-- flowers being squished by bones are more realistical than a squished stone, too
-- exception are of course any protected buildable_to
return node_definition.buildable_to and not minetest.is_protected(pos, player:get_player_name())
end
minetest.register_on_dieplayer(function(player)
if minetest.setting_getbool("creative_mode") or not bones_enabled then
return
end
local player_inv = player:get_inventory()
if player_inv:is_empty("main") and
player_inv:is_empty("craft") then
return
end
local pos = player:getpos()
pos.x = math.floor(pos.x+0.5)
pos.y = math.floor(pos.y+0.5)
pos.z = math.floor(pos.z+0.5)
local param2 = minetest.dir_to_facedir(player:get_look_dir())
local player_name = player:get_player_name()
local player_inv = player:get_inventory()
if (not may_replace(pos, player)) then
if (may_replace({x=pos.x, y=pos.y+1, z=pos.z}, player)) then
-- drop one node above if there's space
-- this should solve most cases of protection related deaths in which players dig straight down
-- yet keeps the bones reachable
pos.y = pos.y+1
else
-- drop items instead of delete
for i=1,player_inv:get_size("main") do
minetest.add_item(pos, player_inv:get_stack("main", i))
end
for i=1,player_inv:get_size("craft") do
minetest.add_item(pos, player_inv:get_stack("craft", i))
end
-- empty lists main and craft
player_inv:set_list("main", {})
player_inv:set_list("craft", {})
return
end
end
minetest.set_node(pos, {name="bones:bones", param2=param2})
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
inv:set_size("main", 8*4)
inv:set_list("main", player_inv:get_list("main"))
for i=1,player_inv:get_size("craft") do
local stack = player_inv:get_stack("craft", i)
if inv:room_for_item("main", stack) then
inv:add_item("main", stack)
else
--drop if no space left
minetest.add_item(pos, stack)
end
end
player_inv:set_list("main", {})
player_inv:set_list("craft", {})
meta:set_string("formspec", bones.bones_formspec)
meta:set_string("owner", player_name)
if share_bones_time ~= 0 then
meta:set_string("infotext", player_name.."'s fresh bones")
if share_bones_time_early == 0 or not minetest.is_protected(pos, player_name) then
meta:set_int("time", 0)
else
meta:set_int("time", (share_bones_time - share_bones_time_early))
end
minetest.get_node_timer(pos):start(10)
else
meta:set_string("infotext", player_name.."'s bones")
end
end)
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/La_Vaule_[S]/Zone.lua | 17 | 1635 | -----------------------------------
--
-- Zone: La_Vaule_[S] (85)
--
-----------------------------------
package.loaded["scripts/zones/La_Vaule_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/La_Vaule_[S]/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/missions");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(236.547,-2.25,20,120);
end
if (prevZone == 82) then
if (player:getCurrentMission(WOTG) == A_TIMESWEPT_BUTTERFLY) then
cs = 0x0001;
end
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 == 0x0001) then
player:completeMission(WOTG, A_TIMESWEPT_BUTTERFLY);
player:addMission(WOTG, PURPLE_THE_NEW_BLACK);
end
end; | gpl-3.0 |
Zero-K-Experiments/Zero-K-Experiments | scripts/blastwing.lua | 3 | 2080 |
-- by Chris Mackey
include "constants.lua"
--pieces
local base = piece "base"
local missile = piece "missile"
local l_wing = piece "l_wing"
local l_fan = piece "l_fan"
local r_wing = piece "r_wing"
local r_fan = piece "r_fan"
local side = 1
local forward = 3
local up = 2
local RIGHT_ANGLE = math.rad(90)
local smokePiece = { base, l_wing, r_wing }
local burrowed = false
local SIG_BURROW = 1
local function Burrow()
Signal(SIG_BURROW)
SetSignalMask(SIG_BURROW)
local x,y,z = Spring.GetUnitPosition(unitID)
local height = Spring.GetGroundHeight(x,z)
while height + 35 < y do
Sleep(500)
x,y,z = Spring.GetUnitPosition(unitID)
height = Spring.GetGroundHeight(x,z)
end
burrowed = true
--Spring.UnitScript.SetUnitValue(firestate, 0)
Turn(base, side, -RIGHT_ANGLE, 5)
Turn(l_wing, side, RIGHT_ANGLE, 5)
Turn(r_wing, side, RIGHT_ANGLE, 5)
Move(base, up, 8, 8)
--Move(base, forward, -4, 5)
end
local function UnBurrow()
Signal(SIG_BURROW)
burrowed = false
Spring.SetUnitCloak(unitID, 0)
Spring.SetUnitStealth(unitID, false)
--Spring.UnitScript.SetUnitValue(firestate, 2)
Turn(base, side, 0, 5)
Turn(l_wing, side,0, 5)
Turn(r_wing, side, 0, 5)
Move(base, up, 0, 10)
--Move(base, forward, 0, 5)
end
function Detonate() -- Giving an order causes recursion.
GG.QueueUnitDescruction(unitID)
end
function script.Create()
StartThread(SmokeUnit, smokePiece)
end
function script.Activate()
StartThread(UnBurrow)
end
function script.Deactivate()
Spring.SetUnitCloak(unitID, 2)
Spring.SetUnitStealth(unitID, true)
end
function script.StopMoving()
StartThread(Burrow)
end
function script.Killed(recentDamage, maxHealth)
Explode(base, SFX.EXPLODE + SFX.FIRE + SFX.SMOKE)
Explode(l_wing, SFX.EXPLODE)
Explode(r_wing, SFX.EXPLODE)
Explode(missile, SFX.SHATTER)
--Explode(l_fan, SFX.EXPLODE)
--Explode(r_fan, SFX.EXPLODE)
local severity = recentDamage / maxHealth
if (severity <= 0.5) or ((Spring.GetUnitMoveTypeData(unitID).aircraftState or "") == "crashing") then
return 1 -- corpsetype
else
return 2 -- corpsetype
end
end
| gpl-2.0 |
smanolache/kong | kong/tools/responses.lua | 1 | 6587 | --- Kong helper methods to send HTTP responses to clients.
-- Can be used in the proxy (core/resolver), plugins or Admin API.
-- Most used HTTP status codes and responses are implemented as helper methods.
--
-- local responses = require "kong.tools.responses"
--
-- -- In an Admin API endpoint handler, or in one of the plugins' phases.
-- -- the `return` keyword is optional since the execution will be stopped
-- -- anyways. It simply improves code readability.
-- return responses.send_HTTP_OK()
--
-- -- Or:
-- return responses.send_HTTP_NOT_FOUND("No entity for given id")
--
-- -- Raw send() helper:
-- return responses.send(418, "This is a teapot")
local cjson = require "cjson"
local meta = require "kong.meta"
--local server_header = _KONG._NAME.."/".._KONG._VERSION
local server_header = meta._NAME.."/"..meta._VERSION
--- Define the most common HTTP status codes for sugar methods.
-- Each of those status will generate a helper method (sugar)
-- attached to this exported module prefixed with `send_`.
-- Final signature of those methods will be `send_<status_code_key>(message, raw, headers)`. See @{send} for more details on those parameters.
-- @field HTTP_OK 200 OK
-- @field HTTP_CREATED 201 Created
-- @field HTTP_NO_CONTENT 204 No Content
-- @field HTTP_BAD_REQUEST 400 Bad Request
-- @field HTTP_UNAUTHORIZED 401 Unauthorized
-- @field HTTP_FORBIDDEN 403 Forbidden
-- @field HTTP_NOT_FOUND 404 Not Found
-- @field HTTP_METHOD_NOT_ALLOWED 405 Method Not Allowed
-- @field HTTP_CONFLICT 409 Conflict
-- @field HTTP_UNSUPPORTED_MEDIA_TYPE 415 Unsupported Media Type
-- @field HTTP_INTERNAL_SERVER_ERROR Internal Server Error
-- @usage return responses.send_HTTP_OK()
-- @usage return responses.HTTP_CREATED("Entity created")
-- @usage return responses.HTTP_INTERNAL_SERVER_ERROR()
-- @table status_codes
local _M = {
status_codes = {
HTTP_OK = 200,
HTTP_CREATED = 201,
HTTP_NO_CONTENT = 204,
HTTP_BAD_REQUEST = 400,
HTTP_UNAUTHORIZED = 401,
HTTP_FORBIDDEN = 403,
HTTP_NOT_FOUND = 404,
HTTP_METHOD_NOT_ALLOWED = 405,
HTTP_CONFLICT = 409,
HTTP_UNSUPPORTED_MEDIA_TYPE = 415,
HTTP_INTERNAL_SERVER_ERROR = 500
}
}
--- Define some default response bodies for some status codes.
-- Some other status codes will have response bodies that cannot be overriden.
-- Example: 204 MUST NOT have content, but if 404 has no content then "Not found" will be set.
-- @field status_codes.HTTP_UNAUTHORIZED Default: Unauthorized
-- @field status_codes.HTTP_NO_CONTENT Always empty.
-- @field status_codes.HTTP_NOT_FOUND Default: Not Found
-- @field status_codes.HTTP_UNAUTHORIZED Default: Unauthorized
-- @field status_codes.HTTP_INTERNAL_SERVER_ERROR Always "Internal Server Error"
-- @field status_codes.HTTP_METHOD_NOT_ALLOWED Always "Method not allowed"
local response_default_content = {
[_M.status_codes.HTTP_UNAUTHORIZED] = function(content)
return content or "Unauthorized"
end,
[_M.status_codes.HTTP_NO_CONTENT] = function(content)
return nil
end,
[_M.status_codes.HTTP_NOT_FOUND] = function(content)
return content or "Not found"
end,
[_M.status_codes.HTTP_INTERNAL_SERVER_ERROR] = function(content)
return "An unexpected error occurred"
end,
[_M.status_codes.HTTP_METHOD_NOT_ALLOWED] = function(content)
return "Method not allowed"
end
}
-- Return a closure which will be usable to respond with a certain status code.
-- @local
-- @param[type=number] status_code The status for which to define a function
local function send_response(status_code)
-- Send a JSON response for the closure's status code with the given content.
-- If the content happens to be an error (>500), it will be logged by ngx.log as an ERR.
-- @see https://github.com/openresty/lua-nginx-module
-- @param content (Optional) The content to send as a response.
-- @param raw (Optional) A boolean defining if the `content` should not be serialized to JSON
-- This useed to send text as JSON in some edge-cases of cjson.
-- @return ngx.exit (Exit current context)
return function(content, raw, headers)
if status_code >= _M.status_codes.HTTP_INTERNAL_SERVER_ERROR then
if content then
ngx.log(ngx.ERR, tostring(content))
end
end
ngx.status = status_code
ngx.header["Content-Type"] = "application/json; charset=utf-8"
ngx.header["Server"] = server_header
if headers then
for k, v in pairs(headers) do
ngx.header[k] = v
end
end
if type(response_default_content[status_code]) == "function" then
content = response_default_content[status_code](content)
end
if raw then
-- When we want to send an empty array, such as "{\"data\":[]}"
-- cjson has a flaw and encodes a Lua `{}` as a JSON `{}`.
-- This allows to send plain string JSON as "[]".
ngx.say(content)
elseif (type(content) == "table") then
ngx.say(cjson.encode(content))
elseif content then
ngx.say(cjson.encode({ message = content }))
end
return ngx.exit(status_code)
end
end
-- Generate sugar methods (closures) for the most used HTTP status codes.
for status_code_name, status_code in pairs(_M.status_codes) do
_M["send_"..status_code_name] = send_response(status_code)
end
local closure_cache = {}
--- Send a response with any status code or body,
-- Not all status codes are available as sugar methods, this function can be
-- used to send any response.
-- If the `status_code` parameter is in the 5xx range, it is expectde that the `content` parameter be the error encountered. It will be logged and the response body will be empty. The user will just receive a 500 status code.
-- Will call `ngx.say` and `ngx.exit`, terminating the current context.
-- @see ngx.say
-- @see ngx.exit
-- @param[type=number] status_code HTTP status code to send
-- @param body A string or table which will be the body of the sent response. If table, the response will be encoded as a JSON object. If string, the response will be a JSON object and the string will be contained in the `message` property. Except if the `raw` parameter is set to `true`.
-- @param[type=boolean] raw If true, send the `body` as it is.
-- @param[type=table] headers Response headers to send.
-- @return ngx.exit (Exit current context)
function _M.send(status_code, body, raw, headers)
local res = closure_cache[status_code]
if not res then
res = send_response(status_code)
closure_cache[status_code] = res
end
return res(body, raw, headers)
end
return _M
| apache-2.0 |
PaulBatchelor/Soundpipe | modules/data/jcrev.lua | 4 | 1140 | sptbl["jcrev"] = {
files = {
module = "jcrev.c",
header = "jcrev.h",
example = "ex_jcrev.c",
},
func = {
create = "sp_jcrev_create",
destroy = "sp_jcrev_destroy",
init = "sp_jcrev_init",
compute = "sp_jcrev_compute",
},
params = {
},
modtype = "module",
description = [[John Chowning reverberator
This is was built using the JC reverb implentation found in FAUST. According to the source code, the specifications for
this implementation were found on an old SAIL DART backup tape.
This class is derived from the CLM JCRev function, which is based on the use of
networks of simple allpass and comb delay filters. This class implements three series
allpass units, followed by four parallel comb filters, and two decorrelation delay lines in
parallel at the output.]],
ninputs = 1,
noutputs = 1,
inputs = {
{
name = "input",
description = "Signal input."
},
},
outputs = {
{
name = "out",
description = "Signal Output."
},
}
}
| mit |
smanolache/kong | kong/plugins/response-ratelimiting/access.lua | 1 | 2576 | local singletons = require "kong.singletons"
local timestamp = require "kong.tools.timestamp"
local responses = require "kong.tools.responses"
local utils = require "kong.tools.utils"
local pairs = pairs
local tostring = tostring
local _M = {}
local RATELIMIT_REMAINING = "X-RateLimit-Remaining"
local function get_identifier()
local identifier
-- Consumer is identified by ip address or authenticated_credential id
if ngx.ctx.authenticated_credential then
identifier = ngx.ctx.authenticated_credential.id
else
identifier = ngx.var.remote_addr
end
return identifier
end
local function get_current_usage(api_id, identifier, current_timestamp, limits)
local usage = {}
for k, v in pairs(limits) do -- Iterate over limit names
for lk, lv in pairs(v) do -- Iterare over periods
local current_metric, err = singletons.dao.response_ratelimiting_metrics:find(api_id, identifier, current_timestamp, lk, k)
if err then
return false, err
end
local current_usage = current_metric and current_metric.value or 0
local remaining = lv - current_usage
if not usage[k] then usage[k] = {} end
if not usage[k][lk] then usage[k][lk] = {} end
usage[k][lk].limit = lv
usage[k][lk].remaining = remaining
end
end
return usage
end
function _M.execute(conf)
if utils.table_size(conf.limits) <= 0 then
return
end
-- Load info
local current_timestamp = timestamp.get_utc()
ngx.ctx.current_timestamp = current_timestamp -- For later use
local api_id = ngx.ctx.api.id
local identifier = get_identifier()
ngx.ctx.identifier = identifier -- For later use
-- Load current metric for configured period
local usage, err = get_current_usage(api_id, identifier, current_timestamp, conf.limits)
if err then
if conf.continue_on_error then
ngx.log(ngx.ERR, "failed to get usage: ", tostring(err))
return
else
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
end
-- Append usage headers to the upstream request. Also checks "block_on_first_violation".
for k, v in pairs(conf.limits) do
local remaining
for lk, lv in pairs(usage[k]) do
if conf.block_on_first_violation and lv.remaining == 0 then
return responses.send(429, "API rate limit exceeded for '"..k.."'")
end
if not remaining or lv.remaining < remaining then
remaining = lv.remaining
end
end
ngx.req.set_header(RATELIMIT_REMAINING.."-"..k, remaining)
end
ngx.ctx.usage = usage -- For later use
end
return _M
| apache-2.0 |
Scavenge/darkstar | scripts/zones/Southern_San_dOria/npcs/Faulpie.lua | 9 | 2889 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Faulpie
-- Type: Leathercraft Guild Master
-- @pos -178.882 -2 9.891 230
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/crafting");
require("scripts/globals/missions");
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local newRank = tradeTestItem(player,npc,trade,SKILL_LEATHERCRAFT);
if (newRank ~= 0) then
player:setSkillRank(SKILL_LEATHERCRAFT,newRank);
player:startEvent(0x0289,0,0,0,0,newRank);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local getNewRank = 0;
local craftSkill = player:getSkillLevel(SKILL_LEATHERCRAFT);
local testItem = getTestItem(player,npc,SKILL_LEATHERCRAFT);
local guildMember = isGuildMember(player,7);
if (guildMember == 1) then guildMember = 150995375; end
if (canGetNewRank(player,craftSkill,SKILL_LEATHERCRAFT) == 1) then getNewRank = 100; end
if (player:getCurrentMission(ASA) == THAT_WHICH_CURDLES_BLOOD and guildMember == 150995375 and
getNewRank ~= 100) then
local item = 0;
local asaStatus = player:getVar("ASA_Status");
-- TODO: Other Enfeebling Kits
if (asaStatus == 0) then
item = 2779;
else
printf("Error: Unknown ASA Status Encountered <%u>", asaStatus);
end
-- The Parameters are Item IDs for the Recipe
player:startEvent(0x03b0, item, 2773, 917, 917, 2776, 4103);
else
player:startEvent(0x0288,testItem,getNewRank,30,guildMember,44,0,0,0);
end
end;
-- 0x0288 0x0289 0x02f8 0x02f9 0x02fa 0x02fb 0x02fc 0x02fd 0x0302 0x0303 0x0304 0x0305 0x0306 0x0307 0x03b0 0x0392
-----------------------------------
-- 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 == 0x0288 and option == 1) then
local crystal = 4103; -- dark crystal
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal);
else
player:addItem(crystal);
player:messageSpecial(ITEM_OBTAINED,crystal);
signupGuild(player, guild.leathercraft);
end
end
end; | gpl-3.0 |
Scavenge/darkstar | scripts/globals/items/piscators_skewer.lua | 12 | 1386 | -----------------------------------------
-- ID: 5983
-- Item: Piscator's Skewer
-- Food Effect: 60 Mins, All Races
-----------------------------------------
-- Dexterity 3
-- Vitality 4
-- Defense % 26 Cap 155
-----------------------------------------
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,3600,5983);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 3);
target:addMod(MOD_VIT, 4);
target:addMod(MOD_FOOD_DEFP, 26);
target:addMod(MOD_FOOD_DEF_CAP, 155);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 3);
target:delMod(MOD_VIT, 4);
target:delMod(MOD_FOOD_DEFP, 26);
target:delMod(MOD_FOOD_DEF_CAP, 155);
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/East_Ronfaure_[S]/Zone.lua | 12 | 1656 | -----------------------------------
--
-- Zone: East_Ronfaure_[S] (81)
--
-----------------------------------
package.loaded["scripts/zones/East_Ronfaure_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/East_Ronfaure_[S]/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/missions");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(86.131,-65.817,273.861,25);
end
if (prevZone == 80) then
if (player:getCurrentMission(WOTG) == WHILE_THE_CAT_IS_AWAY) then
cs = 0x0007;
end
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 == 0x0007) then
player:completeMission(WOTG, WHILE_THE_CAT_IS_AWAY);
player:addMission(WOTG, A_TIMESWEPT_BUTTERFLY);
end
end; | gpl-3.0 |
Scavenge/darkstar | scripts/globals/spells/bluemagic/dimensional_death.lua | 33 | 1738 | -----------------------------------------
-- Spell: Dimensional Death
-- Damage varies with TP
-- Spell cost: 48 MP
-- Monster Type: Undead
-- Spell Type: Physical (Blunt)
-- Blue Magic Points: 5
-- Stat Bonus: DEX+1, CHR+1, HP+5
-- Level: 60
-- Casting Time: 0.5 seconds
-- Recast Time: 23.75 seconds
-- Skillchain Properties: Impaction (can open Liquefaction or Detonation; can close Impaction or Fusion)
-- Combos: Accuracy 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_H2H;
params.scattr = SC_IMPACTION;
params.numhits = 1;
params.multiplier = 2.25;
params.tp150 = 1.2;
params.tp300 = 1.4;
params.azuretp = 1.5;
params.duppercap = 70; --guesstimated attack % bonuses
params.str_wsc = 0.5;
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;
damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
return damage;
end; | gpl-3.0 |
Scavenge/darkstar | scripts/zones/Upper_Jeuno/npcs/Collet.lua | 14 | 2380 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Collet
-- Involved in Quests: A Clock Most Delicate, Save the Clock Tower
-- @zone 244
-- @pos -44 0 107
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Upper_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(555,1) == true and trade:getItemCount() == 1) then
a = player:getVar("saveTheClockTowerNPCz1"); -- NPC zone1
if (a == 0 or (a ~= 2 and a ~= 3 and a ~= 6 and a ~= 10 and a ~= 18 and a ~= 7 and a ~= 26 and a ~= 11 and
a ~= 22 and a ~= 14 and a ~= 19 and a ~= 15 and a ~= 23 and a ~= 27 and a ~= 30 and a ~= 31)) then
player:startEvent(0x0073,10 - player:getVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getFameLevel(JEUNO) >= 5 and aClockMostdelicate == QUEST_AVAILABLE and player:getVar("aClockMostdelicateVar") == 0) then
player:startEvent(0x0070);
elseif (player:getVar("saveTheClockTowerVar") >= 1) then
player:startEvent(0x00a4);
elseif (player:getQuestStatus(JEUNO,THE_CLOCKMASTER) == QUEST_COMPLETED) then
player:startEvent(0x00a3);
else
player:startEvent(0x0072);
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 == 0x0070) then
player:setVar("aClockMostdelicateVar", 1);
elseif (csid == 0x0073) then
player:setVar("saveTheClockTowerVar",player:getVar("saveTheClockTowerVar") + 1);
player:setVar("saveTheClockTowerNPCz1",player:getVar("saveTheClockTowerNPCz1") + 2);
end
end;
| gpl-3.0 |
seblindfors/ConsolePort | ConsolePort_Bar/Core/Lookup.lua | 1 | 15938 | local name, env = ...;
--------------------------------------------------------
env.db = ConsolePort:GetData()
env.bar = ConsolePortBar;
env.libs = { acb = LibStub('CPActionButton') };
--------------------------------------------------------
local r, g, b = CPAPI.NormalizeColor(CPAPI.GetClassColor())
--------------------------------------------------------
local defaultIcons do
local custom = [[Interface\AddOns\ConsolePort_Bar\Textures\Icons\%s]]
local client = [[Interface\Icons\%s]]
local isRetail = CPAPI.IsRetailVersion;
defaultIcons = {
----------------------------
JUMP = custom:format('Jump'),
TOGGLERUN = custom:format('Run'),
OPENALLBAGS = custom:format('Bags'),
TOGGLEGAMEMENU = custom:format('Menu'),
TOGGLEWORLDMAP = custom:format('Map'),
----------------------------
INTERACTTARGET = custom:format('Target'),
----------------------------
TARGETNEARESTENEMY = custom:format('Target'),
TARGETPREVIOUSENEMY = custom:format('Target'),
TARGETSCANENEMY = custom:format('Target'),
TARGETNEARESTFRIEND = custom:format('Target'),
TARGETPREVIOUSFRIEND = custom:format('Target'),
TARGETNEARESTENEMYPLAYER = custom:format('Target'),
TARGETPREVIOUSENEMYPLAYER = custom:format('Target'),
TARGETNEARESTFRIENDPLAYER = custom:format('Target'),
TARGETPREVIOUSFRIENDPLAYER = custom:format('Target'),
----------------------------
TARGETPARTYMEMBER1 = isRetail and client:format('Achievement_PVP_A_01'),
TARGETPARTYMEMBER2 = isRetail and client:format('Achievement_PVP_A_02'),
TARGETPARTYMEMBER3 = isRetail and client:format('Achievement_PVP_A_03'),
TARGETPARTYMEMBER4 = isRetail and client:format('Achievement_PVP_A_04'),
TARGETSELF = isRetail and client:format('Achievement_PVP_A_05'),
TARGETPET = client:format('Spell_Hunter_AspectOfTheHawk'),
----------------------------
ATTACKTARGET = client:format('Ability_SteelMelee'),
STARTATTACK = client:format('Ability_SteelMelee'),
PETATTACK = client:format('ABILITY_HUNTER_INVIGERATION'),
FOCUSTARGET = client:format('Ability_Hunter_MasterMarksman'),
----------------------------
['CLICK ConsolePortFocusButton:LeftButton'] = client:format('VAS_RaceChange'),
['CLICK ConsolePortEasyMotionButton:LeftButton'] = custom:format('Group'),
['CLICK ConsolePortRaidCursorToggle:LeftButton'] = custom:format('Group'),
['CLICK ConsolePortRaidCursorFocus:LeftButton'] = custom:format('Group'),
['CLICK ConsolePortRaidCursorTarget:LeftButton'] = custom:format('Group'),
['CLICK ConsolePortUtilityToggle:LeftButton'] = custom:format('Ring'),
----------------------------
}
end
--------------------------------------------------------
local classArt = {
WARRIOR = {1, 1},
PALADIN = {1, 2},
DRUID = {1, 3},
DEATHKNIGHT = {1, 4},
----------------------------
MAGE = {2, 1},
HUNTER = {2, 2},
ROGUE = {2, 3},
WARLOCK = {2, 4},
----------------------------
SHAMAN = {3, 1},
PRIEST = {3, 2},
DEMONHUNTER = {3, 3},
MONK = {3, 4},
}
--------------------------------------------------------
function env:GetBindingIcon(binding)
return env.manifest.BindingIcons[binding]
end
function env:CreateManifest()
if type(ConsolePortBarManifest) ~= 'table' then
ConsolePortBarManifest = {
BindingIcons = defaultIcons,
}
elseif type(ConsolePortBarManifest.BindingIcons) ~= 'table' then
ConsolePortBarManifest.BindingIcons = defaultIcons
end
defaultIcons = nil
env.manifest = ConsolePortBarManifest
return ConsolePortBarManifest
end
function env:GetCover(class)
local art = class and classArt[class]
if not class and not art then
art = classArt[select(2, UnitClass('player'))]
end
if art then
local index, px = unpack(art)
return [[Interface\AddOns\]]..name..[[\Textures\Covers\]]..index,
{0, 1, (( px - 1 ) * 256 ) / 1024, ( px * 256 ) / 1024 }
end
end
function env:GetBackdrop()
return {
edgeFile = 'Interface\\AddOns\\'..name..'\\Textures\\BarEdge',
edgeSize = 32,
insets = {left = 16, right = 16, top = 16, bottom = 16}
}
end
function env:GetDefaultButtonLayout(button)
local layout = {
---------
PADDLEFT = {point = {'LEFT', 176, 56}, dir = 'left', size = 64},
PADDRIGHT = {point = {'LEFT', 306, 56}, dir = 'right', size = 64},
PADDUP = {point = {'LEFT', 240, 100}, dir = 'up', size = 64},
PADDDOWN = {point = {'LEFT', 240, 16}, dir = 'down', size = 64},
---------
PAD3 = {point = {'RIGHT', -306, 56}, dir = 'left', size = 64},
PAD2 = {point = {'RIGHT', -176, 56}, dir = 'right', size = 64},
PAD4 = {point = {'RIGHT', -240, 100}, dir = 'up', size = 64},
PAD1 = {point = {'RIGHT', -240, 16}, dir = 'down', size = 64},
}
local handle = env.db.UIHandle;
local T1, T2 = handle:GetUIControlBinding('T1'), handle:GetUIControlBinding('T2')
local M1, M2 = handle:GetUIControlBinding('M1'), handle:GetUIControlBinding('M2')
if M1 then layout[M1] = {point = {'LEFT', 456, 56}, dir = 'right', size = 64} end;
if M2 then layout[M2] = {point = {'RIGHT', -456, 56}, dir = 'left', size = 64} end;
if T1 then layout[T1] = {point = {'LEFT', 396, 16}, dir = 'down', size = 64} end;
if T2 then layout[T2] = {point = {'RIGHT', -396, 16}, dir = 'down', size = 64} end;
if button ~= nil then
return layout[button]
else
return layout
end
end
function env:GetOrthodoxButtonLayout()
local layout = {
---------
PADDRIGHT = {dir = 'right', point = {'LEFT', 330, 9}, size = 64},
PADDLEFT = {dir = 'left', point = {'LEFT', 80, 9}, size = 64},
PADDDOWN = {dir = 'down', point = {'LEFT', 165, 9}, size = 64},
PADDUP = {dir = 'up', point = {'LEFT', 250, 9}, size = 64},
---------
PAD2 = {dir = 'right', point = {'RIGHT', -80, 9}, size = 64},
PAD3 = {dir = 'left', point = {'RIGHT', -330, 9}, size = 64},
PAD1 = {dir = 'down', point = {'RIGHT', -250, 9}, size = 64},
PAD4 = {dir = 'up', point = {'RIGHT', -165, 9}, size = 64},
}
local handle = env.db.UIHandle;
local T1, T2 = handle:GetUIControlBinding('T1'), handle:GetUIControlBinding('T2')
local M1, M2 = handle:GetUIControlBinding('M1'), handle:GetUIControlBinding('M2')
if M1 then layout[M1] = {dir = 'up', point = {'LEFT', 405, 75}, size = 64} end;
if M2 then layout[M2] = {dir = 'up', point = {'RIGHT', -405, 75}, size = 64} end;
if T1 then layout[T1] = {dir = 'right', point = {'LEFT', 440, 9}, size = 64} end;
if T2 then layout[T2] = {dir = 'left', point = {'RIGHT', -440, 9}, size = 64} end;
return layout;
end
function env:GetPresets()
return {
Default = self:GetDefaultSettings(),
Orthodox = {
scale = 0.9,
width = 1100,
watchbars = true,
showline = true,
showbuttons = false,
lock = true,
layout = self:GetOrthodoxButtonLayout(),
},
Roleplay = {
scale = 0.9,
width = 1100,
watchbars = true,
showline = true,
showart = true,
showbuttons = false,
lock = true,
layout = self:GetDefaultButtonLayout(),
},
}
end
function env:GetUserPresets()
local presets, copy = {}, env.db.table.copy;
for character, data in env.db:For('Shared/Data') do
if data.Bar and data.Bar.layout then
presets[character] = copy(data.Bar)
end
end
return presets;
end
function env:GetAllPresets()
return env.db.table.merge(self:GetPresets(), self:GetUserPresets())
end
function env:GetRGBColorFor(element, default)
local cfg = env.cfg or {}
local defaultColors = {
art = {1, 1, 1, 1},
tint = {r, g, b, 1},
border = {1, 1, 1, 1},
swipe = {r, g, b, 1},
exp = {r, g, b, 1},
}
if default then
if defaultColors[element] then
return unpack(defaultColors[element])
end
end
local current = {
art = cfg.artRGB or defaultColors.art,
tint = cfg.tintRGB or defaultColors.tint,
border = cfg.borderRGB or defaultColors.border,
swipe = cfg.swipeRGB or defaultColors.swipe,
exp = cfg.expRGB or defaultColors.exp,
}
if current[element] then
return unpack(current[element])
end
end
function env:GetDefaultSettings()
return {
scale = 0.9,
width = 1100,
watchbars = true,
showline = true,
lock = true,
flashart = true,
eye = true,
showbuttons = false,
layout = env:GetDefaultButtonLayout()
}
end
function env:GetColorGradient(red, green, blue)
local gBase = 0.15
local gMulti = 1.2
local startAlpha = 0.25
local endAlpha = 0
local gradient = {
'VERTICAL',
(red + gBase) * gMulti, (green + gBase) * gMulti, (blue + gBase) * gMulti, startAlpha,
1 - (red + gBase) * gMulti, 1 - (green + gBase) * gMulti, 1 - (blue + gBase) * gMulti, endAlpha,
}
return unpack(gradient)
end
function env:GetBooleanSettings() return {
{ name = 'Width/scale on mouse wheel';
cvar = 'mousewheel';
desc = 'Allows you to scroll on the action bar to adjust its proportions.';
note = 'Hold Shift to adjust width, otherwise scale.';
};
---------------------------------------
{ name = 'Visibility & Lock' };
{ name = 'Lock action bar';
cvar = 'lock';
desc = 'Lock/unlock action bar, allowing it to be moved with the mouse.';
};
{ name = 'Hide in combat';
cvar = 'combathide';
desc = 'Hide action bar in combat.';
note = 'Only for the truly insane.';
};
{ name = 'Fade out of combat';
cvar = 'hidebar';
desc = 'Fades out the action bar while not in combat.';
note = 'The action bar will become visible if you bring your cursor over it.';
};
{ name = 'Disable drag and drop';
cvar = 'disablednd';
desc = 'Disables dragging and dropping actions using your mouse cursor.';
};
{ name = 'Always show all buttons';
cvar = 'showbuttons';
desc = 'Shows the entire button cluster at all times, not just abilities on cooldown.';
};
---------------------------------------
{ name = 'Pet Ring' };
{ name = 'Lock pet ring';
cvar = 'lockpet';
desc = 'Lock/unlock pet ring, allowing it to be moved with the mouse.';
};
{ name = 'Disable pet ring';
cvar = 'hidepet';
desc = 'Disables the pet ring entirely.';
};
{ name = 'Hide pet ring in combat';
cvar = 'combatpethide';
desc = 'Hide pet ring in combat.';
};
{ name = 'Always show all buttons';
cvar = 'disablepetfade';
desc = 'Shows the entire pet ring cluster at all times, not just abilities on cooldown.';
};
---------------------------------------
{ name = 'Display' };
{ name = 'The Eye';
cvar = 'eye';
desc = 'Shows an "eye" in the middle of your action bar, to quickly toggle between show/hide all buttons.';
note = 'The Eye can be used to train your gameplay performance.';
};
{ name = 'Disable watch bars';
cvar = 'hidewatchbars';
desc = 'Disables watch bars at the bottom of the action bar.';
note = 'Disables all tracking of experience, honor, reputation and artifacts.';
};
{ name = 'Always show watch bars';
cvar = 'watchbars';
desc = 'When enabled, shows watch bars at all times. When disabled, shows them on mouse over.';
};
{ name = 'Hide main button icons';
cvar = 'hideIcons';
desc = 'Hide binding icons on all large buttons.';
};
{ name = 'Hide modifier icons';
cvar = 'hideModifiers';
desc = 'Hide binding icons on all small buttons.';
};
{ name = 'Use beveled borders';
cvar = 'classicBorders';
desc = 'Use the classic button border texture.';
};
{ name = 'Disable micro menu modifications';
cvar = 'disablemicromenu';
desc = 'Disables micro menu modifications.';
note = 'Check this if you have another addon customizing the micro menu.';
};
---------------------------------------
{ name = 'Cast Bar' };
{ name = 'Show default cast bar';
cvar = 'defaultCastBar';
desc = 'Shows the default cast bar, adjusted to the action bar position.';
};
{ name = 'Disable cast bar modification';
cvar = 'disableCastBarHook';
desc = 'Disables any modifications to the cast bar, including position.';
note = 'This may fix compatibility issues with other addons modifying the cast bar.';
};
---------------------------------------
{ name = 'Artwork' };
{ name = 'Show class art underlay';
cvar = 'showart';
desc = 'Shows a class-based artpiece under your button clusters, to use as anchoring reference.';
};
{ name = 'Blend class art underlay';
cvar = 'blendart';
desc = 'Sets class art underlay to blend colors with the background, resulting in a brighter, less opaque texture.';
};
{ name = 'Flash art underlay on proc';
cvar = 'flashart';
desc = 'Flashes the art underlay whenever a spell procs and starts glowing.';
};
{ name = 'Smaller art underlay';
cvar = 'smallart';
desc = 'Reduces the size of the class art underlay.';
};
{ name = 'Show color tint';
cvar = 'showline';
desc = 'Shows a subtle tint, anchored to the top of the watch bars.';
};
{ name = 'RGB Gaming God';
cvar = 'rainbow';
desc = 'Behold the might of my personal computer, you dirty console peasant. Do you really have enough buttons on that thing to match me?';
note = ('|T%s:64:128:0|t'):format([[Interface\AddOns\ConsolePort_Config\Assets\master.blp]]);
};
} end
function env:GetNumberSettings() return {
---------------------------------------
{ name = 'Size' };
{ name = 'Width';
cvar = 'width';
desc = 'Changes the overall action bar width.';
note = 'Affects button placement.';
step = 10;
};
{ name = 'Scale';
cvar = 'scale';
desc = 'Changes the overall action bar scale.';
note = 'Affects button size - individual size is multiplied by scale.';
step = 0.05;
};
} end
function env:GetColorSettings() return {
---------------------------------------
{ name = 'Colors' };
{ name = 'Border';
cvar = 'borderRGB';
desc = 'Changes the color of your button borders.';
note = 'Right click to reset to default color.';
};
{ name = 'Cooldown';
cvar = 'swipeRGB';
desc = 'Changes the color of your cooldown graphics.';
note = 'Right click to reset to class color.';
};
{ name = 'Tint';
cvar = 'tintRGB';
desc = 'Changes the color of the tint texture above experience bars.';
note = 'Right click to reset to class color.';
};
{ name = 'Experience Bars';
cvar = 'expRGB';
desc = 'Changes the preferred color of your experience bars.';
note = 'Right click to reset to class color.';
};
{ name = 'Artwork';
cvar = 'artRGB';
desc = 'Changes the color of class-based background artwork.';
note = 'Right click to reset to default color.';
};
} end
function env:SetRainbowScript(on)
if on then
local t, i, p, c, w, m = 0, 0, 0, 128, 127, 180
local hz = (math.pi*2) / m;
local r, g, b;
return self.bar:SetScript('OnUpdate', function(_, e)
t = t + e;
if t > 0.1 then
i = i + 1;
r = (math.sin((hz * i) + 0 + p) * w + c) / 255;
g = (math.sin((hz * i) + 2 + p) * w + c) / 255;
b = (math.sin((hz * i) + 4 + p) * w + c) / 255;
if i > m then
i = i - m;
end
t = 0;
self:SetTintColor(r, g, b, 1)
end
end)
end
self.bar:SetScript('OnUpdate', nil)
end
function env:SetTintColor(r, g, b, a) a = a or 1;
local color = CreateColor(r, g, b, a)
local bar, castBar = env.bar, CastingBarFrame;
local buttons = env.libs.registry;
if castBar then
castBar:SetStatusBarColor(r, g, b)
end
bar.WatchBarContainer:SetMainBarColor(r, g, b)
CPAPI.SetGradient(bar.BG, self:GetColorGradient(r, g, b))
bar.BottomLine:SetVertexColor(r, g, b, a)
for _, button in pairs(buttons) do
button:SetSwipeColor(r, g, b, a)
end
if C_GamePad.SetLedColor then
C_GamePad.SetLedColor(color)
end
end
function env:SetArtUnderlay(enabled, flashOnProc)
local bar = env.bar
local cfg = env.cfg
if enabled then
local art, coords = self:GetCover()
if art and coords then
local artScale = cfg.smallart and .75 or 1
bar.CoverArt:SetTexture(art)
bar.CoverArt:SetTexCoord(unpack(coords))
bar.CoverArt:SetVertexColor(unpack(cfg.artRGB or {1,1,1}))
bar.CoverArt:SetBlendMode(cfg.blendart and 'ADD' or 'BLEND')
bar.CoverArt:SetSize(768 * artScale, 192 * artScale)
if cfg.showart then
bar.CoverArt:Show()
else
bar.CoverArt:Hide()
end
end
else
bar.CoverArt:SetTexture(nil)
bar.CoverArt:Hide()
end
bar.CoverArt.flashOnProc = flashOnProc
end | artistic-2.0 |
Scavenge/darkstar | scripts/zones/Apollyon/mobs/Proto-Omega.lua | 16 | 3336 | -----------------------------------
-- Area: Apollyon (Central)
-- MOB: Proto-Omega
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Apollyon/TextIDs");
require("scripts/globals/titles");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID());
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
mob:setMod(MOD_UDMGPHYS, -75);
mob:setMod(MOD_UDMGRANGE, -75);
mob:setMod(MOD_UDMGMAGIC, 0);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
local mobID = mob:getID();
local formTime = mob:getLocalVar("formWait")
local lifePercent = mob:getHPP();
local currentForm = mob:getLocalVar("form")
if (lifePercent < 70 and currentForm < 1) then
currentForm = 1;
mob:setLocalVar("form", currentForm)
mob:AnimationSub(2);
formTime = os.time() + 60;
mob:setMod(MOD_UDMGPHYS, 0);
mob:setMod(MOD_UDMGRANGE, 0);
mob:setMod(MOD_UDMGMAGIC, -75);
end
if (currentForm == 1) then
if (formTime < os.time()) then
if (mob:AnimationSub() == 1) then
mob:AnimationSub(2);
else
mob:AnimationSub(1);
end
mob:setLocalVar("formWait", os.time() + 60);
end
if (lifePercent < 30) then
mob:AnimationSub(2);
mob:setMod(MOD_UDMGPHYS, -50);
mob:setMod(MOD_UDMGRANGE, -50);
mob:setMod(MOD_UDMGMAGIC, -50);
mob:addStatusEffect(EFFECT_REGAIN,7,3,0); -- The final form has Regain,
mob:getStatusEffect(EFFECT_REGAIN):setFlag(32);
currentForm = 2;
mob:setLocalVar("form", currentForm)
end
end
end;
-----------------------------------
-- onAdditionalEffect
-----------------------------------
function onAdditionalEffect(mob, player)
local chance = 20; -- wiki lists ~20% stun chance
local resist = applyResistanceAddEffect(mob,player,ELE_THUNDER,EFFECT_STUN);
if (math.random(0,99) >= chance or resist <= 0.5) then
return 0,0,0;
else
local duration = 5 * resist;
if (player:hasStatusEffect(EFFECT_STUN) == false) then
player:addStatusEffect(EFFECT_STUN, 0, 0, duration);
end
return SUBEFFECT_STUN, MSGBASIC_ADD_EFFECT_STATUS, EFFECT_STUN;
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
player:addTitle(APOLLYON_RAVAGER);
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
GetNPCByID(16932864+39):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+39):setStatus(STATUS_NORMAL);
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/commands/mobhere.lua | 13 | 1275 | ---------------------------------------------------------------------------------------------------
-- func: mobhere <mobId>
-- desc: Spawns a MOB and then moves it to the current position, if in same zone.
-- Errors will despawn the MOB unless "noDepop" was specified (any value works).
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "is"
};
function onTrigger(player, mobId, noDepop)
if (mobId == nil) then
player:PrintToPlayer("You must enter a valid MobID.");
return;
end
local mob = GetMobByID(mobId);
if (mob == nil) then
player:PrintToPlayer( string.format( "Mob with ID '%i' not found!", mobId ) );
return;
end
SpawnMob( mobId );
if (player:getZoneID() == mob:getZoneID()) then
mob:setPos( player:getXPos(), player:getYPos(), player:getZPos(), player:getRotPos(), player:getZoneID() );
else
if (noDepop == nil or noDepop == 0) then
DespawnMob( mobId );
player:PrintToPlayer("Despawned the mob because of an error.");
end
player:PrintToPlayer("Mob could not be moved to current pos - you are probably in the wrong zone.");
end
end; | gpl-3.0 |
Scavenge/darkstar | scripts/zones/Palborough_Mines/npcs/qm1.lua | 14 | 1287 | -----------------------------------
-- Area: Palborough Mines
-- NPC: ???
-- Involved In Quest: The Talekeeper's Truth
-- @zone 143
-- @pos 15 -31 -94
-----------------------------------
package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Palborough_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("theTalekeeperTruthCS") == 3) then
player:messageSpecial(SENSE_OF_FOREBODING);
SpawnMob(17363318):updateClaim(player);
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 |
Scavenge/darkstar | scripts/zones/FeiYin/npcs/Dry_Fountain.lua | 14 | 1467 | -----------------------------------
-- Area: FeiYin
-- NPC: Dry Fountain
-- Involved In Quest: Peace for the Spirit
-- @pos -17 -16 71 204
-----------------------------------
package.loaded["scripts/zones/FeiYin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/FeiYin/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,PEACE_FOR_THE_SPIRIT) == QUEST_ACCEPTED) then
if (trade:hasItemQty(1093,1) and trade:getItemCount() == 1) then -- Trade Antique Coin
player:startEvent(0x0011);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
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 == 0x0011) then
player:tradeComplete();
player:setVar("peaceForTheSpiritCS",2);
end
end; | gpl-3.0 |
Water-Flow/TTTFairTraitorSelection | lua/fairselection/sv_init.lua | 1 | 5988 | FairSelection.Version = "1.1.0"
function FairSelection:LoadConfig()
CONFIG = {}
CONFIG.DB = {}
include("fairselection/sv_config.lua")
FairSelection.CFG = CONFIG
end
function FairSelection:VersionCheck()
http.Fetch("https://raw.githubusercontent.com/Water-Flow/TTTFairTraitorSelection/release/VERSION", function(body)
local msg = nil
local version = "0.0.0"
version = body
local major, minor, patch = version:match("(%d+)%.(%d+)%.(%d+)")
local curmajor, curminor, curpatch = FairSelection.Version:match("(%d+)%.(%d+)%.(%d+)")
major = tonumber(major) or 0
minor = tonumber(minor) or 0
patch = tonumber(patch) or 0
curmajor = tonumber(curmajor) or 0
curminor = tonumber(curminor) or 0
curpatch = tonumber(curpatch) or 0
if (curmajor < major) or (curminor < minor) or (curpatch < patch) then
msg = "A new Version is available (%%%%%%%%)!"
else
msg = "Version: (%%%%%%%%)"
end
if msg then
msg = string.gsub(msg, "%%+", version)
FairSelection:Message(msg)
end
end,
function()
FairSelection:Error("Could not check for new version!")
end)
end
math.randomseed(os.time())
local function shuffleTable(t)
local rand = math.random
local iterations = #t
local j
for i = iterations , 2, -1 do
j = rand(i)
t[i], t[j] = t[j], t[i]
end
return t
end
hook.Add("TTTBeginRound", "TTTFS_BeginRound", function()
-- Set players role count
for _, ply in ipairs(player.GetAll()) do
if ply:GetRole() == ROLE_INNOCENT then
ply:SetInnocentCount(ply:GetInnocentCount() + 1)
elseif ply:GetRole() == ROLE_TRAITOR then
ply:SetTraitorCount(ply:GetTraitorCount() + 1)
elseif ply:GetRole() == ROLE_DETECTIVE then
ply:SetDetectiveCount(ply:GetDetectiveCount() + 1)
end
ply:SetRoundsPlayed(ply:GetRoundsPlayed() + 1)
FairSelection:UpdatePlayerChance()
end
end)
function FairSelection:SelectPlayerForTraitor(choices, prev_roles)
local total = 0
local lastChance
for _, v in pairs(choices) do
total = total + v:GetChance()
end
local r = math.random(1, total)
for _, pply in pairs(choices) do
if (r - pply:GetChance()) <= 0 then
lastChance = pply
if IsValid(pply) and ((not table.HasValue(prev_roles[ROLE_TRAITOR], pply)) or (math.random(1, 3) == 2)) then
if (not tobool(pply:GetPData("tpass", false)) and not tobool(pply:GetPData("dpass", false)) and not tobool(pply:GetPData("inno", false))) or tobool(pply:GetPData("tpassfail", false)) or tobool(pply:GetPData("dpassfail", false)) then
return pply
end
end
end
r = r - pply:GetChance()
end
return lastChance
end
function FairSelection:SelectRoles(ts, ds, traitor_count, det_count, choices, prev_roles)
local min_karma = GetConVarNumber("ttt_detective_karma_min") or 0
while ts < traitor_count do
choices = shuffleTable(choices)
selectedPlayer = self:SelectPlayerForTraitor(choices, prev_roles)
selectedPlayer:SetRole(ROLE_TRAITOR)
selectedPlayer:SetChance(FairSelection:DefaultChance())
table.RemoveByValue(choices, selectedPlayer)
ts = ts + 1
end
while(ds < det_count) and (#choices >= 1) do
if #choices <= (det_count - ds) then
for _, pply in pairs(choices) do
if IsValid(pply) then
if (not tobool(pply:GetPData("tpass", false)) and not tobool(pply:GetPData("dpass", false)) and not tobool(pply:GetPData("inno", false))) or tobool(pply:GetPData("tpassfail", false)) or tobool(pply:GetPData("dpassfail", false)) then
pply:SetRole(ROLE_DETECTIVE)
end
end
end
break
end
local pick = math.random(1, #choices)
local pply = choices[pick]
if (IsValid(pply) and ((pply:GetBaseKarma() > min_karma and table.HasValue(prev_roles[ROLE_INNOCENT], pply)) or math.random(1, 3) == 2)) then
if not pply:GetAvoidDetective() then
if (not tobool(pply:GetPData("tpass", false)) and not tobool(pply:GetPData("dpass", false)) and not tobool(pply:GetPData("inno", false))) or tobool(pply:GetPData("tpassfail", false)) or tobool(pply:GetPData("dpassfail", false)) then
pply:SetRole(ROLE_DETECTIVE)
ds = ds + 1
end
end
table.remove(choices, pick)
end
end
for _, v in pairs(choices) do
if IsValid(v) and (not v:IsSpec()) and v:GetRole() == ROLE_INNOCENT then
if FairSelection.CFG.KarmaIncreaseChance and v:GetBaseKarma() > FairSelection.CFG.KarmaIncreaseChanceThreshold then
local extra = math.random(0, 2)
v:AddChance(extra)
end
v:AddChance(math.random(6, 10))
end
end
end
function FairSelection:Standalone()
local choices = {}
local prev_roles = {
[ROLE_INNOCENT] = {},
[ROLE_TRAITOR] = {},
[ROLE_DETECTIVE] = {}
}
if not GAMEMODE.LastRole then GAMEMODE.LastRole = {} end
for _, v in pairs(player.GetAll()) do
if IsValid(v) and (not v:IsSpec()) then
local r = GAMEMODE.LastRole[v:UniqueID()] or v:GetRole() or ROLE_INNOCENT
table.insert(prev_roles[r], v)
table.insert(choices, v)
end
v:SetRole(ROLE_INNOCENT)
end
local choice_count = #choices
local traitor_count = GetTraitorCount(choice_count)
local det_count = GetDetectiveCount(choice_count)
if choice_count == 0 then return end
local ts = 0
local ds = 0
self:SelectRoles(ts, ds, traitor_count, det_count, choices, prev_roles)
GAMEMODE.LastRole = {}
for _, ply in ipairs(player.GetAll()) do
ply:SetDefaultCredits()
GAMEMODE.LastRole[ply:UniqueID()] = ply:GetRole()
end
end
hook.Add("PlayerInitialSpawn", "TTFS_PlayerInitialSpawn", function(ply)
if not ply:IsBot() then
FairSelection.DB:prepare("SELECT chance FROM prefix_chances WHERE steamid=?", {ply:SteamID64()}, function(data)
if table.Count(data) > 0 then
ply:SetChance(data[1].chance)
else
local chance = FairSelection:DefaultChance()
FairSelection.DB:prepare("INSERT INTO prefix_chances (steamid, chance, lastupdate) VALUES(?, ?, ?)", {ply:SteamID64(), chance, os.time()})
ply:SetChance(chance)
end
end)
end
end)
timer.Simple(5, function()
if FairSelection.CFG.Standalone then
SelectRoles = FairSelection:Standalone
end
end)
| mit |
taxler/radish | lua/parse/substitution/charset/alias_list.lua | 1 | 12710 |
return {
csUTF8 = 'UTF-8';
csUTF16 = 'UTF-16'; csUTF16BE = 'UTF-16BE'; csUTF16LE = 'UTF-16LE';
csUTF32 = 'UTF-32'; csUTF32BE = 'UTF-32BE'; csUTF32LE = 'UTF-32LE';
-- in a list, the first entry is the primary name
csASCII = {'US-ASCII','us',
'iso-ir-6','ANSI_X3.4-1968','ANSI_X3.4-1986','ISO_646.irv:1991','ISO646-USv','IBM367','cp367'};
csISOLatin1 = {'ISO-8859-1', 'ISO_8859-1', 'latin1', 'l1';
'iso-ir-100', 'IBM819', 'CP819'};
cswindows874 = 'windows-874';
cswindows1250 = 'windows-1250';
cswindows1251 = 'windows-1251';
cswindows1252 = 'windows-1252';
cswindows1253 = 'windows-1253';
cswindows1254 = 'windows-1254';
cswindows1255 = 'windows-1255';
cswindows1256 = 'windows-1256';
cswindows1257 = 'windows-1257';
cswindows1258 = 'windows-1258';
csISOLatin2 = {'ISO-8859-2', 'ISO_8859-2', 'latin2', 'l2'; 'iso-ir-101'};
csISOLatin3 = {'ISO-8859-3', 'ISO_8859-3', 'latin3', 'l3'; 'iso-ir-109'};
csISOLatin4 = {'ISO-8859-4', 'ISO_8859-4', 'latin4', 'l4'; 'iso-ir-110'};
csISOLatinCyrillic = {'ISO-8859-5'; 'iso-ir-144', 'ISO_8859-5', 'cyrillic'};
csISOLatinArabic = {'ISO-8859-6', 'ISO_8859-6', 'arabic'; 'iso-ir-127', 'ECMA-114', 'ASMO-708'};
csISOLatinGreek = {'ISO-8859-7', 'ISO_8859-7', 'greek', 'greek8';
'iso-ir-126', 'ELOT_928', 'ECMA-118'};
csISOLatinHebrew = {'ISO-8859-8', 'ISO_8859-8', 'hebrew', 'iso-ir-138'};
csISOLatin5 = {'ISO-8859-9'; 'ISO_8859-9', 'iso-ir-148', 'latin5', 'l5'};
csISOLatin6 = {'ISO-8859-10'; 'iso-ir-157', 'l6', 'ISO_8859-10:1992', 'latin6'};
csTIS620 = {'TIS-620', 'ISO-8859-11'};
-- there is no ISO-8859-12
csISO885913 = 'ISO-8859-13';
csISO885914 = {'ISO-8859-14', 'ISO_8859-14:1998', 'ISO_8859-14', 'latin8', 'iso-celtic', 'l8', 'iso-ir-199'};
csISO885915 = {'ISO-8859-15', 'ISO_8859-15', 'Latin-9'};
csISO885916 = {'ISO-8859-16', 'iso-ir-226', 'ISO_8859-16:2001', 'ISO_8859-16', 'latin10', 'l10'};
csISOTextComm = {'ISO_6937-2-add'; 'iso-ir-142'};
csHalfWidthKatakana = {'JIS_X0201'; 'X0201'};
csJISEncoding = 'JIS_Encoding';
csShiftJIS = {'Shift_JIS', 'MS_Kanji'};
csEUCPkdFmtJapanese = 'EUC-JP';
csEUCFixWidJapanese = 'Extended_UNIX_Code_Fixed_Width_for_Japanese';
csISO4UnitedKingdom = {'BS_4730', 'uk', 'gb', 'ISO646-GB', 'iso-ir-4'};
csISO11SwedishForNames = {'SEN_850200_C', 'se2', 'ISO646-SE2', 'iso-ir-11'};
csISO15Italian = {'IT', 'ISO646-IT', 'iso-ir-15'};
csISO17Spanish = {'ES', 'ISO646-ES', 'iso-ir-17'};
csISO21German = {'DIN_66003', 'de', 'ISO646-DE', 'iso-ir-21'};
csISO60DanishNorwegian = {'NS_4551-1', 'no', 'iso-ir-60', 'ISO646-NO', 'csISO60Norwegian1'};
csISO69French = {'NF_Z_62-010', 'fr', 'iso-ir-69', 'ISO646-FR'};
csISO10646UTF1 = 'ISO-10646-UTF-1';
csISO646basic1983 = {'ISO_646.basic:1983', 'ref'};
csINVARIANT = 'INVARIANT';
csISO2IntlRefVersion = {'ISO_646.irv:1983', 'irv', 'iso-ir-2'};
csNATSSEFI = {'NATS-SEFI', 'iso-ir-8-1'};
csNATSSEFIADD = {'NATS-SEFI-ADD', 'iso-ir-8-2'};
csNATSDANO = {'NATS-DANO', 'iso-ir-9-1'};
csNATSDANOADD = {'NATS-DANO-ADD', 'iso-ir-9-2'};
csISO10Swedish = {'SEN_850200_B', 'FI', 'se', 'ISO646-FI', 'ISO646-SE', 'iso-ir-10'};
csKSC56011987 = {'KS_C_5601-1987', 'korean', 'KS_C_5601-1989', 'KSC_5601', 'iso-ir-149'};
csISO2022KR = 'ISO-2022-KR';
csEUCKR = 'EUC-KR';
csISO2022JP = 'ISO-2022-JP';
csISO2022JP2 = 'ISO-2022-JP-2';
csISO13JISC6220jp = {'JIS_C6220-1969-jp', 'JIS_C6220-1969', 'iso-ir-13', 'katakana', 'x0201-7'};
jp = {'JIS_C6220-1969-ro', 'iso-ir-14', 'ISO646-JP'};
csISO16Portuguese = {'csISO14JISC6220ro', 'iso-ir-16', 'ISO646-PT'};
csISO18Greek7Old = {'greek7-old', 'iso-ir-18'};
csISO19LatinGreek = {'latin-greek', 'iso-ir-19'};
csISO25French = {'NF_Z_62-010_(1973)', 'iso-ir-25', 'ISO646-FR1'};
csISO27LatinGreek1 = {'Latin-greek-1', 'iso-ir-27'};
csISO5427Cyrillic = {'ISO_5427', 'iso-ir-37'};
csISO42JISC62261978 = {'JIS_C6226-1978', 'iso-ir-42'};
csISO47BSViewdata = {'BS_viewdata', 'iso-ir-47'};
csISO49INIS = {'INIS', 'iso-ir-49'};
csISO50INIS8 = {'INIS-8', 'iso-ir-50'};
csISO51INISCyrillic = {'INIS-cyrillic', 'iso-ir-51'};
csISO54271981 = {'ISO_5427:1981', 'iso-ir-54', 'ISO5427Cyrillic1981'};
csISO5428Greek = {'ISO_5428:1980', 'iso-ir-55'};
csISO57GB1988 = {'GB_1988-80', 'iso-ir-57', 'cn', 'ISO646-CN'};
csISO58GB231280 = {'GB_2312-80', 'iso-ir-58', 'chinese'};
csISO61Norwegian2 = {'NS_4551-2', 'ISO646-NO2', 'iso-ir-61', 'no2'};
csISO70VideotexSupp1 = {'videotex-suppl', 'iso-ir-70'};
csISO84Portuguese2 = {'PT2', 'iso-ir-84', 'ISO646-PT2'};
csISO85Spanish2 = {'ES2', 'iso-ir-85', 'ISO646-ES2'};
csISO86Hungarian = {'MSZ_7795.3', 'hu', 'iso-ir-86', 'ISO646-HU'};
csISO87JISX0208 = {'JIS_C6226-1983', 'iso-ir-87', 'x0208', 'JIS_X0208-1983'};
csISO88Greek7 = {'greek7', 'iso-ir-88'};
csISO89ASMO449 = {'ASMO_449', 'arabic7', 'ISO_9036', 'iso-ir-89'};
csISO90 = 'iso-ir-90';
csISO91JISC62291984a = {'JIS_C6229-1984-a', 'iso-ir-91', 'jp-ocr-a'};
csISO92JISC62991984b = {'JIS_C6229-1984-b', 'iso-ir-92', 'ISO646-JP-OCR-B', 'jp-ocr-b'};
csISO93JIS62291984badd = {'JIS_C6229-1984-b-add', 'iso-ir-93', 'jp-ocr-b-add'};
csISO94JIS62291984hand = {'JIS_C6229-1984-hand', 'iso-ir-94', 'jp-ocr-hand'};
csISO95JIS62291984handadd = {'JIS_C6229-1984-hand-add', 'iso-ir-95', 'jp-ocr-hand-add'};
csISO96JISC62291984kana = {'JIS_C6229-1984-kana', 'iso-ir-96'};
csISO2033 = {'ISO_2033-1983', 'iso-ir-98', 'e13b'};
csISO99NAPLPS = {'ANSI_X3.110-1983', 'iso-ir-99', 'CSA_T500-1983', 'NAPLPS'};
csISO102T617bit = {'T.61-7bit', 'iso-ir-102'};
csISO103T618bit = {'T.61-8bit', 'T.61', 'iso-ir-103'};
csISO111ECMACyrillic = {'ECMA-cyrillic', 'iso-ir-111', 'KOI8-E'};
csISO121Canadian1 = {'CSA_Z243.4-1985-1', 'ca', 'csa71', 'csa7-1', 'iso-ir-121', 'ISO646-CA'};
csISO122Canadian2 = {'CSA_Z243.4-1985-2', 'csa72', 'csa7-2', 'iso-ir-122', 'ISO646-CA2'};
csISO123CSAZ24341985gr = {'CSA_Z243.4-1985-gr', 'iso-ir-123'};
csISO88596E = 'ISO-8859-6-E';
csISO88596I = 'ISO-8859-6-I';
csISO128T101G2 = {'T.101-G2', 'iso-ir-128'};
csISO88598E = 'ISO-8859-8-E';
csISO88598I = 'ISO-8859-8-I';
csISO139CSN369103 = {'CSN_369103', 'iso-ir-139'};
csISO141JUSIB1002 = {'JUS_I.B1.002', 'iso-ir-141', 'ISO646-YU', 'js', 'yu'};
csISO143IECP271 = {'IEC_P27-1', 'iso-ir-143'};
csISO146Serbian = {'JUS_I.B1.003-serb', 'iso-ir-146', 'serbian'};
csISO147Macedonian = {'JUS_I.B1.003-mac', 'macedonian', 'iso-ir-147'};
csISO150GreekCCITT = {'greek-ccitt', 'iso-ir-150', 'csISO150'};
csISO151Cuba = {'NC_NC00-10:81', 'cuba', 'iso-ir-151', 'ISO646-CU'};
csISO6937Add = {'ISO_6937-2-25', 'iso-ir-152'};
csISO153GOST1976874 = {'GOST_19768-74', 'ST_SEV_358-88', 'iso-ir-153'};
csISO8859Supp = {'ISO_8859-supp', 'iso-ir-154', 'latin1-2-5'};
csISO10367Box = {'ISO_10367-box', 'iso-ir-155'};
csISO158Lap = {'latin-lap', 'lap', 'iso-ir-158'};
csISO159JISX02121990 = {'JIS_X0212-1990', 'x0212', 'iso-ir-159'};
csISO646Danish = {'DS_2089', 'DS2089', 'ISO646-DK', 'dk'};
csUSDK = 'us-dk'; csDKUS = 'dk-us';
csKSC5636 = {'KSC5636', 'ISO646-KR'};
csUnicode11UTF7 = 'UNICODE-1-1-UTF-7';
csISO2022CN = 'ISO-2022-CN';
csISO2022CNEXT = 'ISO-2022-CN-EXT';
csGBK = {'GBK', 'CP936', 'MS936', 'windows-936'};
csGB18030 = 'GB18030';
csOSDEBCDICDF0415 = 'OSD_EBCDIC_DF04_15';
csOSDEBCDICDF03IRV = 'OSD_EBCDIC_DF03_IRV';
csOSDEBCDICDF041 = 'OSD_EBCDIC_DF04_1';
csISO115481 = {'ISO-11548-1', 'ISO_11548-1', 'ISO_TR_11548-1'};
csKZ1048 = {'KZ-1048', 'STRK1048-2002', 'RK1048'};
csUnicode = 'ISO-10646-UCS-2';
csUCS4 = 'ISO-10646-UCS-4';
csUnicodeASCII = 'ISO-10646-UCS-Basic';
csUnicodeLatin1 = {'ISO-10646-Unicode-Latin1', 'ISO-10646'};
csUnicodeJapanese = 'ISO-10646-J-1';
csUnicodeIBM1261 = 'ISO-Unicode-IBM-1261';
csUnicodeIBM1268 = 'ISO-Unicode-IBM-1268';
csUnicodeIBM1276 = 'ISO-Unicode-IBM-1276';
csUnicodeIBM1264 = 'ISO-Unicode-IBM-1264';
csUnicodeIBM1265 = 'ISO-Unicode-IBM-1265';
csUnicode11 = 'UNICODE-1-1';
csSCSU = 'SCSU';
csUTF7 = 'UTF-7';
csCESU8 = {'CESU-8', 'csCESU-8'};
csBOCU1 = {'BOCU-1', 'csBOCU-1'};
csWindows30Latin1 = 'ISO-8859-1-Windows-3.0-Latin-1';
csWindows31Latin1 = 'ISO-8859-1-Windows-3.1-Latin-1';
csWindows31Latin2 = 'ISO-8859-2-Windows-Latin-2';
csWindows31Latin5 = 'ISO-8859-9-Windows-Latin-5';
csHPRoman8 = {'hp-roman8', 'roman8', 'r8'};
csAdobeStandardEncoding = 'Adobe-Standard-Encoding';
csVenturaUS = 'Ventura-US';
csVenturaInternational = 'Ventura-International';
csDECMCS = {'DEC-MCS', 'dec'};
csPC850Multilingual = {'IBM850', 'cp850', '850'};
csPC8DanishNorwegian = 'PC8-Danish-Norwegian';
csPC862LatinHebrew = {'IBM862', 'cp862', '862'};
csPC8Turkish = 'PC8-Turkish';
csIBMSymbols = 'IBM-Symbols';
csIBMThai = 'IBM-Thai';
csHPLegal = 'HP-Legal'; csHPPiFont = 'HP-Pi-font'; csHPMath8 = 'HP-Math8';
csHPPSMath = 'Adobe-Symbol-Encoding';
csHPDesktop = 'HP-DeskTop';
csVenturaMath = 'Ventura-Math';
csMicrosoftPublishing = 'Microsoft-Publishing';
csWindows31J = 'Windows-31J';
csGB2312 = 'GB2312';
csBig5 = 'Big5';
csMacintosh = {'macintosh', 'mac'};
csIBM037 = {'IBM037', 'cp037', 'ebcdic-cp-us', 'ebcdic-cp-ca', 'ebcdic-cp-wt', 'ebcdic-cp-nl'};
csIBM038 = {'IBM038', 'cp038'};
csIBM273 = {'IBM273', 'CP273'};
csIBM274 = {'IBM274', 'EBCDIC-BE', 'CP274'};
csIBM275 = {'IBM275', 'EBCDIC-BR', 'cp275'};
csIBM277 = {'IBM277', 'EBCDIC-CP-DK', 'EBCDIC-CP-NO'};
csIBM278 = {'IBM278', 'CP278', 'ebcdic-cp-fi', 'ebcdic-cp-se'};
csIBM280 = {'IBM280', 'CP280', 'ebcdic-cp-it'};
csIBM281 = {'IBM281', 'EBCDIC-JP-E', 'cp281'};
csIBM284 = {'IBM284', 'CP284', 'ebcdic-cp-es'};
csIBM285 = {'IBM285', 'CP285', 'ebcdic-cp-gb'};
csIBM290 = {'IBM290', 'cp290', 'EBCDIC-JP-kana'};
csIBM297 = {'IBM297', 'cp297', 'ebcdic-cp-fr'};
csIBM420 = {'IBM420', 'cp420', 'ebcdic-cp-ar1'};
csIBM423 = {'IBM423', 'cp423', 'ebcdic-cp-gr'};
csIBM424 = {'IBM424', 'cp424', 'ebcdic-cp-he'};
csPC8CodePage437 = {'IBM437', 'cp437', '437'};
csIBM500 = {'IBM500', 'CP500', 'ebcdic-cp-be', 'ebcdic-cp-ch'};
csIBM851 = {'IBM851', 'cp851', '851'};
csPCp852 = {'IBM852', 'cp852', '852'};
csIBM855 = {'IBM855', 'cp855', '855'};
csIBM857 = {'IBM857', 'cp857', '857'};
csIBM860 = {'IBM860', 'cp860', '860'};
csIBM861 = {'IBM861', 'cp861', '861', 'cp-is'};
csIBM863 = {'IBM863', 'cp863', '863'};
csIBM864 = {'IBM864', 'cp864'};
csIBM865 = {'IBM865', 'cp865', '865'};
csIBM868 = {'IBM868', 'CP868', 'cp-ar'};
csIBM869 = {'IBM869', 'cp869', '869', 'cp-gr'};
csIBM870 = {'IBM870', 'CP870', 'ebcdic-cp-roece', 'ebcdic-cp-yu'};
csIBM871 = {'IBM871', 'CP871', 'ebcdic-cp-is'};
csIBM880 = {'IBM880', 'cp880', 'EBCDIC-Cyrillic'};
csIBM891 = {'IBM891', 'cp891'};
csIBM903 = {'IBM903', 'cp903'};
csIBBM904 = {'IBM904', 'cp904', '904'};
csIBM905 = {'IBM905', 'CP905', 'ebcdic-cp-tr'};
csIBM918 = {'IBM918', 'CP918', 'ebcdic-cp-ar2'};
csIBM1026 = {'IBM1026', 'CP1026'};
csIBMEBCDICATDE = 'EBCDIC-AT-DE'; csEBCDICATDEA = 'EBCDIC-AT-DE-A'; csEBCDICCAFR = 'EBCDIC-CA-FR';
csEBCDICDKNO = 'EBCDIC-DK-NO'; csEBCDICDKNOA = 'EBCDIC-DK-NO-A'; csEBCDICFISE = 'EBCDIC-FI-SE';
csEBCDICFISEA = 'EBCDIC-FI-SE-A';
csEBCDICFR = 'EBCDIC-FR'; csEBCDICIT = 'EBCDIC-IT'; csEBCDICPT = 'EBCDIC-PT'; csEBCDICES = 'EBCDIC-ES';
csEBCDICESA = 'EBCDIC-ES-A'; csEBCDICESS = 'EBCDIC-ES-S';
csEBCDICUK = 'EBCDIC-UK'; csEBCDICUS = 'EBCDIC-US';
csUnknown8BiT = 'UNKNOWN-8BIT';
csMnemonic = 'MNEMONIC';
csMnem = 'MNEM';
csVISCII = 'VISCII';
csVIQR = 'VIQR';
csKOI8R = 'KOI8-R';
['HZ-GB-2312'] = 'HZ-GB-2312';
csIBM866 = {'IBM866', 'cp866', '866'};
csPC775Baltic = {'IBM775', 'cp775'};
csKOI8U = 'KOI8-U';
csIBM00858 = {'IBM00858', 'CCSID00858', 'CP00858', 'PC-Multilingual-850+euro'};
csIBM00924 = {'IBM00924', 'CCSID00924', 'CP00924', 'ebcdic-Latin9--euro'};
csIBM01140 = {'IBM01140', 'CCSID01140', 'CP01140', 'ebcdic-us-37+euro'};
csIBM01141 = {'IBM01141', 'CCSID01141', 'CP01141', 'ebcdic-de-273+euro'};
csIBM01142 = {'IBM01142', 'CCSID01142', 'CP01142', 'ebcdic-dk-277+euro', 'ebcdic-no-277+euro'};
csIBM01143 = {'IBM01143', 'CCSID01143', 'CP01143', 'ebcdic-fi-278+euro', 'ebcdic-se-278+euro'};
csIBM01144 = {'IBM01144', 'CCSID01144', 'CP01144', 'ebcdic-it-280+euro'};
csIBM01145 = {'IBM01145', 'CCSID01145', 'CP01145', 'ebcdic-es-284+euro'};
csIBM01146 = {'IBM01146', 'CCSID01146', 'CP01146', 'ebcdic-gb-285+euro'};
csIBM01147 = {'IBM01147', 'CCSID01147', 'CP01147', 'ebcdic-fr-297+euro'};
csIBM01148 = {'IBM01148', 'CCSID01148', 'CP01148', 'ebcdic-international-500+euro'};
csIBM01149 = {'IBM01149', 'CCSID01149', 'CP01149', 'ebcdic-is-871+euro'};
csBig5HKSCS = 'Big5-HKSCS';
csIBM1047 = {'IBM1047', 'IBM-1047'};
csPTCP154 = {'PTCP154', 'PT154', 'CP154', 'Cyrillic-Asian'};
csAmiga1251 = {'Amiga-1251', 'Ami1251', 'Amiga1251', 'Ami-1251'};
csKOI7switched = 'KOI7-switched';
csBRF = 'BRF';
csTSCII = 'TSCII';
csCP51932 = 'CP51932'; csCP50220 = 'CP50220';
}
| mit |
devwawi/VIP-TEAM_Wawi8 | plugins/owners.lua | 194 | 23755 | local function lock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_arabic(msg, data, target)
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic/Persian is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic/Persian has been unlocked'
end
end
local function lock_group_links(msg, data, target)
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'yes' then
return 'Link posting is already locked'
else
data[tostring(target)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
return 'Link posting has been locked'
end
end
local function unlock_group_links(msg, data, target)
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'no' then
return 'Link posting is not locked'
else
data[tostring(target)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return 'Link posting has been unlocked'
end
end
local function lock_group_spam(msg, data, target)
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'yes' then
return 'SuperGroup spam is already locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'yes'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been locked'
end
end
local function unlock_group_spam(msg, data, target)
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'no' then
return 'SuperGroup spam is not locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'no'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been unlocked'
end
end
local function lock_group_sticker(msg, data, target)
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'yes' then
return 'Sticker posting is already locked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
return 'Sticker posting has been locked'
end
end
local function unlock_group_sticker(msg, data, target)
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'no' then
return 'Sticker posting is already unlocked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'Sticker posting has been unlocked'
end
end
local function lock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'yes' then
return 'Contact posting is already locked'
else
data[tostring(target)]['settings']['lock_contacts'] = 'yes'
save_data(_config.moderation.data, data)
return 'Contact posting has been locked'
end
end
local function unlock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'no' then
return 'Contact posting is already unlocked'
else
data[tostring(target)]['settings']['lock_contacts'] = 'no'
save_data(_config.moderation.data, data)
return 'Contact posting has been unlocked'
end
end
local function enable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['strict']
if strict == 'yes' then
return 'Settings are already strictly enforced'
else
data[tostring(target)]['settings']['strict'] = 'yes'
save_data(_config.moderation.data, data)
return 'Settings will be strictly enforced'
end
end
local function disable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['strict']
if strict == 'no' then
return 'Settings will not be strictly enforced'
else
data[tostring(target)]['settings']['strict'] = 'no'
save_data(_config.moderation.data, data)
return 'Settings are not strictly enforced'
end
end
-- Show group settings
local function show_group_settingsmod(msg, data, target)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(target)]['settings']['lock_bots'] then
bots_protection = data[tostring(target)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(target)]['settings']['leave_ban'] then
leave_ban = data[tostring(target)]['settings']['leave_ban']
end
local public = "no"
if data[tostring(target)]['settings'] then
if data[tostring(target)]['settings']['public'] then
public = data[tostring(target)]['settings']['public']
end
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection.."\nPublic: "..public
return text
end
-- Show SuperGroup settings
local function show_super_group_settings(msg, data, target)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['public'] then
data[tostring(target)]['settings']['public'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_rtl'] then
data[tostring(target)]['settings']['lock_rtl'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_member'] then
data[tostring(target)]['settings']['lock_member'] = 'no'
end
end
local settings = data[tostring(target)]['settings']
local text = "SuperGroup settings for "..target..":\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict
return text
end
local function set_rules(target, rules)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function set_description(target, about)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function run(msg, matches)
if msg.to.type == 'user' then
local print_name = user_print_name(msg.from):gsub("โฎ", "")
local name = print_name:gsub("_", " ")
local chat_id = matches[1]
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
if matches[2] == 'ban' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't ban yourself"
end
ban_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3])
return 'User '..user_id..' banned'
end
if matches[2] == 'unban' then
if tonumber(matches[3]) == tonumber(our_id) then return false end
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't unban yourself"
end
local hash = 'banned:'..matches[1]
redis:srem(hash, user_id)
savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3])
return 'User '..user_id..' unbanned'
end
if matches[2] == 'kick' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't kick yourself"
end
kick_user(matches[3], chat_id)
savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3])
return 'User '..user_id..' kicked'
end
if matches[2] == 'clean' then
if matches[3] == 'modlist' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
for k,v in pairs(data[tostring(matches[1])]['moderators']) do
data[tostring(matches[1])]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist")
end
if matches[3] == 'rules' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'rules'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules")
end
if matches[3] == 'about' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'description'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned about")
channel_set_about(receiver, about_text, ok_cb, false)
return "About has been cleaned"
end
if matches[3] == 'mutelist' then
chat_id = string.match(matches[1], '^%d+$')
local hash = 'mute_user:'..chat_id
redis:del(hash)
return "Mutelist Cleaned"
end
end
if matches[2] == "setflood" then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[3]
data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]")
return 'Group flood has been set to '..matches[3]
end
if matches[2] == 'lock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
local group_type = data[tostring(matches[1])]['group_type']
if matches[3] == 'name' then
savelog(matches[1], name.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
savelog(matches[1], name.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[3] == 'arabic' then
savelog(matches[1], name.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[3] == 'links' then
savelog(matches[1], name.." ["..msg.from.id.."] locked links ")
return lock_group_links(msg, data, target)
end
if matches[3] == 'spam' then
savelog(matches[1], name.." ["..msg.from.id.."] locked spam ")
return lock_group_spam(msg, data, target)
end
if matches[3] == 'rtl' then
savelog(matches[1], name.." ["..msg.from.id.."] locked RTL chars. in names")
return unlock_group_rtl(msg, data, target)
end
if matches[3] == 'sticker' then
savelog(matches[1], name.." ["..msg.from.id.."] locked sticker")
return lock_group_sticker(msg, data, target)
end
end
if matches[2] == 'unlock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
local group_type = data[tostring(matches[1])]['group_type']
if matches[3] == 'name' then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[3] == 'arabic' then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[3] == 'links' and group_type == "SuperGroup" then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked links ")
return unlock_group_links(msg, data, target)
end
if matches[3] == 'spam' and group_type == "SuperGroup" then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked spam ")
return unlock_group_spam(msg, data, target)
end
if matches[3] == 'rtl' then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked RTL chars. in names")
return unlock_group_rtl(msg, data, target)
end
if matches[3] == 'sticker' and group_type == "SuperGroup" then
savelog(matches[1], name.." ["..msg.from.id.."] unlocked sticker")
return unlock_group_sticker(msg, data, target)
end
if matches[3] == 'contacts' and group_type == "SuperGroup" then
savelog(matches[1], name_log.." ["..msg.from.id.."] locked contact posting")
return lock_group_contacts(msg, data, target)
end
if matches[3] == 'strict' and group_type == "SuperGroup" then
savelog(matches[1], name_log.." ["..msg.from.id.."] locked enabled strict settings")
return enable_strict_rules(msg, data, target)
end
end
if matches[2] == 'new' then
if matches[3] == 'link' then
local group_type = data[tostring(matches[1])]['group_type']
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local function callback_grouplink (extra , success, result)
local receiver = 'chat#id'..matches[1]
if success == 0 then
send_large_msg(receiver, '*Error: Failed to retrieve link* \nReason: Not creator.')
end
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return
end
local function callback_superlink (extra , success, result)
vardump(result)
local receiver = 'channel#id'..matches[1]
local user = extra.user
if success == 0 then
data[tostring(matches[1])]['settings']['set_link'] = nil
save_data(_config.moderation.data, data)
return send_large_msg(user, '*Error: Failed to retrieve link* \nReason: Not creator.\n\nIf you have the link, please use /setlink to set it')
else
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return send_large_msg(user, "Created a new link")
end
end
if group_type == "Group" then
local receiver = 'chat#id'..matches[1]
savelog(matches[1], name.." ["..msg.from.id.."] created/revoked group link ")
export_chat_link(receiver, callback_grouplink, false)
return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link"
elseif group_type == "SuperGroup" then
local receiver = 'channel#id'..matches[1]
local user = 'user#id'..msg.from.id
savelog(matches[1], name.." ["..msg.from.id.."] attempted to create a new SuperGroup link")
export_channel_link(receiver, callback_superlink, {user = user})
end
end
end
if matches[2] == 'get' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local group_link = data[tostring(matches[1])]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
end
if matches[1] == 'changeabout' and matches[2] then
if not is_owner2(msg.from.id, matches[2]) then
return "You are not the owner of this group"
end
local group_type = data[tostring(matches[2])]['group_type']
if group_type == "Group" or group_type == "Realm" then
local target = matches[2]
local about = matches[3]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_description(target, about)
elseif group_type == "SuperGroup" then
local channel = 'channel#id'..matches[2]
local about_text = matches[3]
local data_cat = 'description'
local target = matches[2]
channel_set_about(channel, about_text, ok_cb, false)
data[tostring(target)][data_cat] = about_text
save_data(_config.moderation.data, data)
savelog(matches[2], name.." ["..msg.from.id.."] has changed SuperGroup description to ["..matches[3].."]")
return "Description has been set for ["..matches[2]..']'
end
end
if matches[1] == 'viewsettings' and data[tostring(matches[2])]['settings'] then
if not is_owner2(msg.from.id, matches[2]) then
return "You are not the owner of this group"
end
local target = matches[2]
local group_type = data[tostring(matches[2])]['group_type']
if group_type == "Group" or group_type == "Realm" then
savelog(matches[2], name.." ["..msg.from.id.."] requested group settings ")
return show_group_settings(msg, data, target)
elseif group_type == "SuperGroup" then
savelog(matches[2], name.." ["..msg.from.id.."] requested SuperGroup settings ")
return show_super_group_settings(msg, data, target)
end
end
if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then
local rules = matches[3]
local target = matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rules(target, rules)
end
if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
save_data(_config.moderation.data, data)
local chat_to_rename = 'chat#id'..matches[2]
local channel_to_rename = 'channel#id'..matches[2]
savelog(matches[2], "Group name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]")
rename_chat(chat_to_rename, group_name_set, ok_cb, false)
rename_channel(channel_to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then
savelog(matches[2], "log file created by owner/support/admin")
send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false)
end
end
end
return {
patterns = {
"^[#!/]owners (%d+) ([^%s]+) (.*)$",
"^[#!/]owners (%d+) ([^%s]+)$",
"^[#!/](changeabout) (%d+) (.*)$",
"^[#!/](changerules) (%d+) (.*)$",
"^[#!/](changename) (%d+) (.*)$",
"^[#!/](viewsettings) (%d+)$",
"^[#!/](loggroup) (%d+)$"
},
run = run
} | agpl-3.0 |
roboplus12/roboplus | plugins/trivia.lua | 647 | 6784 | do
-- Trivia plugin developed by Guy Spronck
-- Returns the chat hash for storing information
local function get_hash(msg)
local hash = nil
if msg.to.type == 'chat' then
hash = 'chat:'..msg.to.id..':trivia'
end
if msg.to.type == 'user' then
hash = 'user:'..msg.from.id..':trivia'
end
return hash
end
-- Sets the question variables
local function set_question(msg, question, answer)
local hash =get_hash(msg)
if hash then
redis:hset(hash, "question", question)
redis:hset(hash, "answer", answer)
redis:hset(hash, "time", os.time())
end
end
-- Returns the current question
local function get_question( msg )
local hash = get_hash(msg)
if hash then
local question = redis:hget(hash, 'question')
if question ~= "NA" then
return question
end
end
return nil
end
-- Returns the answer of the last question
local function get_answer(msg)
local hash = get_hash(msg)
if hash then
return redis:hget(hash, 'answer')
else
return nil
end
end
-- Returns the time of the last question
local function get_time(msg)
local hash = get_hash(msg)
if hash then
return redis:hget(hash, 'time')
else
return nil
end
end
-- This function generates a new question if available
local function get_newquestion(msg)
local timediff = 601
if(get_time(msg)) then
timediff = os.time() - get_time(msg)
end
if(timediff > 600 or get_question(msg) == nil)then
-- Let's show the answer if no-body guessed it right.
if(get_question(msg)) then
send_large_msg(get_receiver(msg), "The question '" .. get_question(msg) .."' has not been answered. \nThe answer was '" .. get_answer(msg) .."'")
end
local url = "http://jservice.io/api/random/"
local b,c = http.request(url)
local query = json:decode(b)
if query then
local stringQuestion = ""
if(query[1].category)then
stringQuestion = "Category: " .. query[1].category.title .. "\n"
end
if query[1].question then
stringQuestion = stringQuestion .. "Question: " .. query[1].question
set_question(msg, query[1].question, query[1].answer:lower())
return stringQuestion
end
end
return 'Something went wrong, please try again.'
else
return 'Please wait ' .. 600 - timediff .. ' seconds before requesting a new question. \nUse !triviaquestion to see the current question.'
end
end
-- This function generates a new question when forced
local function force_newquestion(msg)
-- Let's show the answer if no-body guessed it right.
if(get_question(msg)) then
send_large_msg(get_receiver(msg), "The question '" .. get_question(msg) .."' has not been answered. \nThe answer was '" .. get_answer(msg) .."'")
end
local url = "http://jservice.io/api/random/"
local b,c = http.request(url)
local query = json:decode(b)
if query then
local stringQuestion = ""
if(query[1].category)then
stringQuestion = "Category: " .. query[1].category.title .. "\n"
end
if query[1].question then
stringQuestion = stringQuestion .. "Question: " .. query[1].question
set_question(msg, query[1].question, query[1].answer:lower())
return stringQuestion
end
end
return 'Something went wrong, please try again.'
end
-- This function adds a point to the player
local function give_point(msg)
local hash = get_hash(msg)
if hash then
local score = tonumber(redis:hget(hash, msg.from.id) or 0)
redis:hset(hash, msg.from.id, score+1)
end
end
-- This function checks for a correct answer
local function check_answer(msg, answer)
if(get_answer(msg)) then -- Safety for first time use
if(get_answer(msg) == "NA")then
-- Question has not been set, give a new one
--get_newquestion(msg)
return "No question set, please use !trivia first."
elseif (get_answer(msg) == answer:lower()) then -- Question is set, lets check the answer
set_question(msg, "NA", "NA") -- Correct, clear the answer
give_point(msg) -- gives out point to player for correct answer
return msg.from.print_name .. " has answered correctly! \nUse !trivia to get a new question."
else
return "Sorry " .. msg.from.print_name .. ", but '" .. answer .. "' is not the correct answer!"
end
else
return "No question set, please use !trivia first."
end
end
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 get_user_score(msg, user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local hash = 'chat:'..msg.to.id..':trivia'
user_info.score = tonumber(redis:hget(hash, user_id) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
-- Function to print score
local function trivia_scores(msg)
if msg.to.type == 'chat' then
-- Users on chat
local hash = 'chat:'..msg.to.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_user_score(msg, user_id, msg.to.id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.score and b.score then
return a.score > b.score
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.score..'\n'
end
return text
else
return "This function is only available in group chats."
end
end
local function run(msg, matches)
if(matches[1] == "!triviascore" or matches[1] == "!triviascores") then
-- Output all scores
return trivia_scores(msg)
elseif(matches[1] == "!triviaquestion")then
return "Question: " .. get_question(msg)
elseif(matches[1] == "!triviaskip") then
if is_sudo(msg) then
return force_newquestion(msg)
end
elseif(matches[1] ~= "!trivia") then
return check_answer(msg, matches[1])
end
return get_newquestion(msg)
end
return {
description = "Trivia plugin for Telegram",
usage = {
"!trivia to obtain a new question.",
"!trivia [answer] to answer the question.",
"!triviaquestion to show the current question.",
"!triviascore to get a scoretable of all players.",
"!triviaskip to skip a question (requires sudo)"
},
patterns = {"^!trivia (.*)$",
"^!trivia$",
"^!triviaquestion$",
"^!triviascore$",
"^!triviascores$",
"^!triviaskip$"},
run = run
}
end
| gpl-2.0 |
Scavenge/darkstar | scripts/zones/Port_Bastok/npcs/Patient_Wheel.lua | 14 | 1439 | -----------------------------------
-- Area: Port Bastok
-- NPC: Patient Wheel
-- Type: Quest NPC
-- @pos -107.988 3.898 52.557 236
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatBastok = player:getVar("WildcatBastok");
if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,1) == false) then
player:startEvent(0x0162);
else
player:startEvent(0x0145);
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 == 0x0162) then
player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",1,true);
end
end;
| gpl-3.0 |
smanolache/kong | spec/plugins/ssl/fixtures.lua | 29 | 1779 | return {
cert = [[-----BEGIN CERTIFICATE-----
MIICSTCCAbICCQDZ7lxm1iUKmDANBgkqhkiG9w0BAQsFADBpMQswCQYDVQQGEwJV
UzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzEN
MAsGA1UECgwES29uZzELMAkGA1UECwwCSVQxETAPBgNVBAMMCHNzbDEuY29tMB4X
DTE1MDUxOTAwNTAzNloXDTE1MDYxODAwNTAzNlowaTELMAkGA1UEBhMCVVMxEzAR
BgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDVNhbiBGcmFuY2lzY28xDTALBgNV
BAoMBEtvbmcxCzAJBgNVBAsMAklUMREwDwYDVQQDDAhzc2wxLmNvbTCBnzANBgkq
hkiG9w0BAQEFAAOBjQAwgYkCgYEAxOixlvURWF+WfMbG4alhrd3JcavYOGxiBcOv
0qA2v2a89S5JyD43O2uC8TfE6JZc3UT5kjRKRqIA8QDTYn3XGoJwkvYd1w9oXm3R
sZXXbi05PD0oXABtIIbH+0NllXRucdeODlXLi80mCvhVIIDjHifqDRiukecZGapE
rvTsPjMCAwEAATANBgkqhkiG9w0BAQsFAAOBgQCVQdpCfTZLJk0XUu5RnenHpamp
5ZRsdKA+jwE0kwuSWXx/WbsU35GJx1QVrfnmk7qJpwwg/ZbL/KMTUpY21a4ZyITQ
WKHxfY3Klqh18Ll7oBDa9fhuhPE4G8tIum/xY3Z3mHBuXDmBxARD0bOPEJtJQw+H
LGenf2mYrZBfL47wZw==
-----END CERTIFICATE-----]],
key = [[-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDE6LGW9RFYX5Z8xsbhqWGt3clxq9g4bGIFw6/SoDa/Zrz1LknI
Pjc7a4LxN8TollzdRPmSNEpGogDxANNifdcagnCS9h3XD2hebdGxldduLTk8PShc
AG0ghsf7Q2WVdG5x144OVcuLzSYK+FUggOMeJ+oNGK6R5xkZqkSu9Ow+MwIDAQAB
AoGAcYkqPLx5j9ct0ixbKGqd475qFJzdQ0tbCa/XhT7T0nDOqyBRcqBNAHnxOlzJ
sMJiMUNAE8kKusdWe5/aQoQErkVuO9sh1U6sPr7mVD/JWmE08MRzhMwxUVP+HsXM
EZky0M6TWNyghtvyElUiHTIW8quVdjn8oXQIbR/07VXEVmECQQDj6dHJ4XxXIvE1
HQ+49EbbM9l7KFd7t2cpmng1+U4yqMGwNVk3MmEVKU8NiI/BVhznPvp0HH3QyLpV
ShPt9SltAkEA3SzAZ5/UhjycKXgLsgidwDVWOpYweWU7KDsfrr+cSJkmzw7y9WYr
vshdPYA2iSm83aY1vTzwSRV6udpZfBLiHwJBAJ1HfDie3JmdSWtn1LPEDymyDEEL
Q+PiWtTA/nfwxV/8ST16c0i+AXUC/sTOGrZG4MdMFLYP+1sbSksVRc+OwbkCQQCy
DFKfmOUnYyd7oq4XliQYFVfjNgCz2TB0RJROwuV29ANv8GLZ9nQE05tr5QkCBl2K
OUFNo/7zdp0jfIlI/pKVAkA04q30OSEBIHBj/MmapVVSRaQiYfSMLV176nA4xqhz
JkHk9MH9WKKGIchn0LvfUFHxTeBFERoREQo2A82B/WpO
-----END RSA PRIVATE KEY-----]]
}
| apache-2.0 |
Scavenge/darkstar | scripts/zones/Southern_San_dOria/npcs/Sharzalion.lua | 14 | 3803 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Sharzalion
-- Starts and Finishes Quest: The Crimson Trial
-- Involved in Quest: Peace for the Spirit
-- @zone 230
-- @pos 95 0 111
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
theCrimsonTrial = player:getQuestStatus(SANDORIA,THE_CRIMSON_TRIAL);
envelopedInDarkness = player:getQuestStatus(SANDORIA,ENVELOPED_IN_DARKNESS);
peaceForTheSpirit = player:getQuestStatus(SANDORIA,PEACE_FOR_THE_SPIRIT);
peaceForTheSpiritCS = player:getVar("peaceForTheSpiritCS");
OrcishDriedFood = player:hasKeyItem(ORCISH_DRIED_FOOD);
if (player:getMainJob() == JOBS.RDM and player:getMainLvl() >= AF1_QUEST_LEVEL and theCrimsonTrial == QUEST_AVAILABLE) then
if (player:getVar("has_seen_rdmaf1_quest_already") == 0) then
player:startEvent(0x0046);
else
player:startEvent(0x0047);
end
elseif (theCrimsonTrial == QUEST_ACCEPTED and OrcishDriedFood == false) then
player:startEvent(0x004A);
elseif (OrcishDriedFood == true) then
player:startEvent(0x004B);
elseif (theCrimsonTrial == QUEST_COMPLETED and envelopedInDarkness == QUEST_AVAILABLE) then
player:startEvent(0x0044);
elseif (envelopedInDarkness == QUEST_COMPLETED and peaceForTheSpirit == QUEST_AVAILABLE) then
player:startEvent(0x0045);
elseif (peaceForTheSpirit == QUEST_ACCEPTED and peaceForTheSpiritCS == 0) then
player:startEvent(0x0040);
elseif (peaceForTheSpirit == QUEST_ACCEPTED and peaceForTheSpiritCS == 1) then
player:startEvent(0x0041);
elseif (peaceForTheSpirit == QUEST_ACCEPTED and (peaceForTheSpiritCS == 2 or peaceForTheSpiritCS == 3)) then
player:startEvent(0x0042);
else
player:startEvent(0x000F);
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 == 0x0046 or csid == 0x0047) then
if (csid == 0x0046 and option == 0) then
player:setVar("has_seen_rdmaf1_quest_already",1);
elseif (option == 1) then
player:addQuest(SANDORIA,THE_CRIMSON_TRIAL);
player:setVar("has_seen_rdmaf1_quest_already",0);
end
elseif (csid == 0x004B) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16829); -- Fencing Degen
else
player:delKeyItem(ORCISH_DRIED_FOOD);
player:addItem(16829);
player:messageSpecial(ITEM_OBTAINED, 16829); -- Fencing Degen
player:addFame(SANDORIA,30);
player:completeQuest(SANDORIA,THE_CRIMSON_TRIAL);
end
elseif (csid == 0x0040) then
player:setVar("peaceForTheSpiritCS",1);
elseif (csid == 0x0042) then
player:setVar("peaceForTheSpiritCS",3);
end
end; | gpl-3.0 |
Zero-K-Experiments/Zero-K-Experiments | units/arm_venom.lua | 3 | 4900 | unitDef = {
unitname = [[arm_venom]],
name = [[Venom]],
description = [[Lightning Riot Spider]],
acceleration = 0.26,
brakeRate = 0.78,
buildCostEnergy = 200,
buildCostMetal = 200,
buildPic = [[arm_venom.png]],
buildTime = 200,
canAttack = true,
canGuard = true,
canMove = true,
canPatrol = true,
canstop = [[1]],
category = [[LAND]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[38 38 38]],
collisionVolumeType = [[ellipsoid]],
corpse = [[DEAD]],
customParams = {
description_fr = [[Araignรฉe ร effet de zone EMP]],
description_de = [[Unterstรผtzende EMP Spinne]],
helptext = [[The Venom is an all-terrain unit designed to paralyze enemies so other units can easily destroy them. It moves particularly fast for a riot unit and in addition to paralysis it does a small amount of damage. Works well in tandem with the Recluse to keep enemies from closing range with the fragile skirmisher.]],
helptext_fr = [[Le Venom est une araignรฉe tout terrain rapide spรฉcialement conรงue pour paralyser l'ennemi afin que d'autres unitรฉs puissent les dรฉtruire rapidement et sans risques. Sa faible portรฉe est compensรฉe par son effet de zone pouvant affecter plusieurs unitรฉs ร proximitรฉ de sa cible. Est particuliรจrement efficace en tandem avec le Recluse ou l'Hermit.]],
helptext_de = [[Venom ist eine gelรคndeunabhรคngige Einheit, welche Gegner paralysieren kann, damit andere Einheiten diese einfach zerstรถren kรถnnen. Venom besitzt eine AoE und ist nรผtzlich, um gengerische Schwรคrme in Schach zu halten.]],
aimposoffset = [[0 0 0]],
midposoffset = [[0 -6 0]],
modelradius = [[19]],
},
explodeAs = [[BIG_UNITEX]],
footprintX = 3,
footprintZ = 3,
iconType = [[spiderriotspecial]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
maxDamage = 750,
maxSlope = 72,
maxVelocity = 2.7,
maxWaterDepth = 22,
minCloakDistance = 75,
movementClass = [[TKBOT3]],
noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE SUB]],
objectName = [[venom.s3o]],
script = [[arm_venom.lua]],
seismicSignature = 4,
selfDestructAs = [[BIG_UNITEX]],
sfxtypes = {
explosiongenerators = {
[[custom:YELLOW_LIGHTNING_MUZZLE]],
[[custom:YELLOW_LIGHTNING_GROUNDFLASH]],
},
},
sightDistance = 440,
trackOffset = 0,
trackStrength = 10,
trackStretch = 1,
trackType = [[ChickenTrackPointyShort]],
trackWidth = 54,
turnRate = 1600,
weapons = {
{
def = [[spider]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER FIXEDWING GUNSHIP]],
},
},
weaponDefs = {
spider = {
name = [[Electro-Stunner]],
areaOfEffect = 160,
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
customParams = {
extra_damage = [[18]],
light_color = [[0.75 0.75 0.56]],
light_radius = 190,
},
damage = {
default = 600.5,
},
duration = 8,
explosionGenerator = [[custom:LIGHTNINGPLOSION160AoE]],
fireStarter = 0,
heightMod = 1,
impulseBoost = 0,
impulseFactor = 0,
intensity = 12,
interceptedByShieldType = 1,
noSelfDamage = true,
paralyzer = true,
paralyzeTime = 3,
range = 240,
reloadtime = 1.75,
rgbColor = [[1 1 0.7]],
soundStart = [[weapon/lightning_fire]],
soundTrigger = true,
texture1 = [[lightning]],
thickness = 10,
turret = true,
weaponType = [[LightningCannon]],
weaponVelocity = 450,
},
},
featureDefs = {
DEAD = {
blocking = false,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[venom_wreck.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2a.s3o]],
},
},
}
return lowerkeys({ arm_venom = unitDef })
| gpl-2.0 |
Scavenge/darkstar | scripts/zones/Garlaige_Citadel/npcs/qm15.lua | 14 | 1453 | -----------------------------------
-- Area: Garlaige Citadel
-- NPC: qm15 (???)
-- Involved in Quest: Hitting the Marquisate (THF AF3)
-- @pos 19.893 -5.500 325.767 200
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Garlaige_Citadel/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hittingTheMarquisateHagainCS = player:getVar("hittingTheMarquisateHagainCS");
if (hittingTheMarquisateHagainCS == 8) then
player:messageSpecial(HEAT_FROM_CEILING);
-- TODO: player must wait 10 minutes before they can spawn bomb again
SpawnMob(17596533):updateClaim(player); -- Chandelier
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 |
Zauberstuhl/gem_diaspora-prosody-config | modules/mod_diaspora_contacts.lua | 1 | 8754 | -- Prosody module to import diaspora contacts into a users roster.
-- Inspired by mod_auth_sql and mod_groups of the Prosody software.
--
-- As with mod_groups the change is not permanent and thus any changes
-- to the imported contacts will be lost.
--
-- The MIT License (MIT)
--
-- Copyright (c) <2014> <Jonne Haร <me@jhass.eu>>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
local log = require "util.logger".init("diaspora_contacts")
local DBI = require "DBI"
local jid, datamanager = require "util.jid", require "util.datamanager"
local jid_prep = jid.prep
local rostermanager = require "core.rostermanager"
local module_host = module:get_host()
local host = prosody.hosts[module_host]
local connection
local params = module:get_option("diaspora_contacts", module:get_option("auth_diaspora", module:get_option("auth_sql", module:get_option("sql"))))
local function test_connection()
if not connection then return nil; end
if connection:ping() then
return true
else
module:log("debug", "Database connection closed")
connection = nil
end
end
local function set_encoding(conn)
if params.driver ~= "MySQL" then return; end
local set_names_query = "SET NAMES '%s';"
local stmt = assert(conn:prepare("SET NAMES 'utf8mb4';"));
assert(stmt:execute());
end
local function connect()
if not test_connection() then
prosody.unlock_globals()
local dbh, err = DBI.Connect(
params.driver, params.database,
params.username, params.password,
params.host, params.port
)
prosody.lock_globals()
if not dbh then
module:log("debug", "Database connection failed: %s", tostring(err))
return nil, err
end
set_encoding(dbh);
module:log("debug", "Successfully connected to database")
dbh:autocommit(true) -- don't run in transaction
connection = dbh
return connection
end
end
do -- process options to get a db connection
assert(params.driver and params.database, "Both the SQL driver and the database need to be specified")
assert(connect())
end
local function getsql(sql, ...)
if params.driver == "PostgreSQL" then
sql = sql:gsub("`", "\"")
elseif params.driver == "MySQL" then
sql = sql:gsub(";$", " CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_unicode_ci';")
end
if not test_connection() then connect(); end
-- do prepared statement stuff
local stmt, err = connection:prepare(sql)
if not stmt and not test_connection() then error("connection failed"); end
if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end
-- run query
local ok, err = stmt:execute(...)
if not ok and not test_connection() then error("connection failed"); end
if not ok then return nil, err; end
return stmt;
end
local function get_contacts(username)
module:log("debug", "loading contacts for %s", username)
local contacts = {}
local stmt, err = getsql([[
SELECT people.diaspora_handle AS jid,
COALESCE(NULLIF(CONCAT(first_name, ' ', last_name), ' '), people.diaspora_handle) AS name,
CONCAT(aspects.name, ' (Diaspora)') AS group_name,
CASE
WHEN sharing = true AND receiving = true THEN 'both'
WHEN sharing = true AND receiving = false THEN 'to'
WHEN sharing = false AND receiving = true THEN 'from'
ELSE 'none'
END AS subscription
FROM contacts
JOIN people ON people.id = contacts.person_id
JOIN profiles ON profiles.person_id = people.id
JOIN users ON users.id = contacts.user_id
JOIN aspect_memberships ON aspect_memberships.contact_id = contacts.id
JOIN aspects ON aspects.id = aspect_memberships.aspect_id
WHERE (receiving = true OR sharing = true)
AND chat_enabled = true
AND username = ?
]], username)
if stmt then
for row in stmt:rows(true) do
if not contacts[row.jid] then
contacts[row.jid] = {}
contacts[row.jid].subscription = row.subscription
contacts[row.jid].name = row.name
contacts[row.jid].groups = {}
end
contacts[row.jid].groups[row.group_name] = true
end
return contacts
end
end
local function update_roster(roster, contacts, update_action)
if not contacts then return; end
for user_jid, contact in pairs(contacts) do
local updated = false
if not roster[user_jid] then
roster[user_jid] = {}
roster[user_jid].subscription = contact.subscription
roster[user_jid].name = contact.name
roster[user_jid].persist = false
updated = true
end
if not roster[user_jid].groups then
roster[user_jid].groups = {}
end
for group in pairs(contact.groups) do
if not roster[user_jid].groups[group] then
roster[user_jid].groups[group] = true
updated = true
end
end
for group in pairs(roster[user_jid].groups) do
if not contact.groups[group] then
roster[user_jid].groups[group] = nil
updated = true
end
end
if updated and update_action then
update_action(user_jid)
end
end
for user_jid, contact in pairs(roster) do
if contact.persist == false then
if not contacts[user_jid] then
roster[user_jid] = nil
if update_action then
update_action(user_jid)
end
end
end
end
end
function bump_roster_version(roster)
if roster[false] then
roster[false].version = (tonumber(roster[false].version) or 0) + 1
end
end
local function update_roster_contacts(username, host, roster)
update_roster(roster, get_contacts(username), function (user_jid)
module:log("debug", "pushing roster update to %s for %s", jid.join(username, host), user_jid)
bump_roster_version(roster)
rostermanager.roster_push(username, host, user_jid)
end)
end
function inject_roster_contacts(event, var2, var3)
local username = ""
local host = ""
local roster = {}
if type(event) == "table" then
module:log("debug", "Prosody 0.10 or trunk detected. Use event variable.")
username = event.username
host = event.host
roster = event.roster
else
module:log("debug", "Prosody 0.9.x detected, Use old variable style.")
username = event
host = var2
roster = var3
end
local fulljid = jid.join(username, host)
module:log("debug", "injecting contacts for %s", fulljid)
update_roster(roster, get_contacts(username))
bump_roster_version(roster)
end
function update_all_rosters()
module:log("debug", "updating all rosters")
for username, user in pairs(host.sessions) do
module:log("debug", "Updating roster for %s", jid.join(username, module_host))
update_roster_contacts(username, module_host, rostermanager.load_roster(username, module_host))
end
return 300
end
function remove_virtual_contacts(username, host, datastore, roster)
if host == module_host and datastore == "roster" then
module:log("debug", "removing injected contacts before storing roster of %s", jid.join(username, host))
local new_roster = {}
for jid, contact in pairs(roster) do
if contact.persist ~= false then
new_roster[jid] = contact
end
end
if roster[false] then
new_roster[false] = {}
new_roster[false].version = roster[false].version
end
return username, host, datastore, new_roster
end
return username, host, datastore, roster
end
function module.load()
module:hook("roster-load", inject_roster_contacts)
module:add_timer(300, update_all_rosters)
datamanager.add_callback(remove_virtual_contacts)
end
function module.unload()
datamanager.remove_callback(remove_virtual_contacts)
end
| gpl-3.0 |
mcvella/indexedRingBuffer | src/indexedRingBuffer.lua | 1 | 14403 | local indexedRingBuffer = {_TYPE='module', _NAME='indexedRingBuffer' }
local dictCache = require "dictCache"
local localCache = require "cache"
local cjson = require "cjson"
cjson.encode_sparse_array(false,0,0)
local ID_SEP = ';;'
function indexedRingBuffer.new( params )
local shared = localCache
-- if we are running in nginx, use shared dict caches
if ngx then
shared = dictCache
end
local self = {
cache = shared.new("ringBuffer"),
cacheIndex = shared.new("ringBufferIndex"),
sizeStats = shared.new("sizeStats"),
autoResize = params.autoResize or false,
desiredEjectMins = params.desiredEjectMins or 15,
autoMinSize = params.autoMinSize or 10000,
autoMaxSize = params.autoMaxSize or 10000000,
monitorPeriodMins = params.monitorPeriodMins or 10,
triggerAdjustPercent = params.triggerAdjustPercent or 20,
maxAdjustPercentUp = params.maxAdjustPercent or 25,
maxAdjustPercentDown = params.maxAdjustPercent or 10,
paramList = params.paramList,
storageMap = {},
storageInitString = '{}',
ngxEjectUpstream = params.ngxEjectUpstream or "/ejectItem_upstream",
drainParallelItems = params.drainParallelItems or 100,
ejectFunction = params.ejectFunction
}
function self.drain()
-- only one drain can occur at a given time
if not self.cache:get( "draining" ) then
self.cache:set( "draining", true )
local pos = 1
local item = self.cache:get(1)
local callList = {}
while item do
-- if ngx is present, we can leverage upstream for faster parallel drain
if ngx and self.ngxEjectUpstream then
table.insert( callList, { self.ngxEjectUpstream, { args = "pos=" .. pos } } )
if #callList >= self.drainParallelItems then
local res = ngx.location.capture_multi( callList )
callList = {}
end
else
self.ejectItem(pos)
end
pos = pos + 1
item = self.cache:get(pos)
end
if ngx and #callList > 0 then
local res = ngx.location.capture_multi( callList )
end
self.cache:flush_all()
self.cache:flush_expired()
self.cacheIndex:flush_all()
self.cacheIndex:flush_expired()
-- reinitialize position
self.cache:set( "pos", 0 )
self.cache:set( "draining", false )
end
end
function self.ejectItem( itemPos, doDel )
local item = self.cache:get(itemPos)
local splitVal = splitString(item, ID_SEP)
if self.ejectFunction then
self.ejectFunction(splitVal[1], self.makeReadableParams(cjson.decode(splitVal[2])), true)
end
if doDel then
self.cacheIndex:delete( splitVal[1] )
self.cache:delete( itemPos )
end
end
function self.resize(size)
local prevSize = self.sizeStats:get( "currentSize" )
self.sizeStats:set( "currentSize", size )
if size < prevSize then
-- if we are currently higher than new max, move to end of new size and eject the rest
if self.cache:get( "pos" ) > size then
self.cache:set( "pos", size )
end
local pos = size + 1
local item = self.cache:get(pos)
local callList = {}
while item do
-- if ngx is present, we can leverage upstream for faster parallel drain
if ngx and self.ngxEjectUpstream then
table.insert( callList, { self.ngxEjectUpstream, { args = "del=1&pos=" .. pos } } )
if #callList >= self.drainParallelItems then
local res = ngx.location.capture_multi( callList )
callList = {}
end
else
self.ejectItem(pos, true)
end
pos = pos + 1
item = self.cache:get(pos)
end
if ngx and #callList > 0 then
local res = ngx.location.capture_multi( callList )
end
end
end
function self.stats()
local serverStart = self.sizeStats:get( "serverStart" )
local totalReqCount = self.sizeStats:get( "totalReqCount" )
local totalItemCount = self.sizeStats:get( "totalItemCount" )
local stats = {
currentSize = self.sizeStats:get( "currentSize" ),
totalReqCount = totalReqCount,
avgReqsSec = totalReqCount / ( os.time() - serverStart ),
totalItemCount = totalItemCount,
avgItemsSec = totalItemCount / ( os.time() - serverStart ),
serverStart = os.date("!%Y-%m-%dT%TZ", serverStart),
lastPeriodAvgMins = self.sizeStats:get( "lastPeriodAvgMins" ),
draining = self.cache:get( "draining" ) or false
}
return stats
end
function self.set(id, params)
-- do not do anything if a drain is in process
if self.cache:get( "draining" ) then
return
end
-- first, see if this item already exists
local currentItemPos = self.cacheIndex:get( id )
local currentVal
if currentItemPos then
currentVal = self.cache:get( currentItemPos )
if not currentVal then
self.cacheIndex:delete( id )
end
end
-- if this item does not currently exist, add new item, and process evicted item, if any
if not currentVal then
currentItemPos = self.cache:incr( "pos", 1 )
--ngx.log( ngx.DEBUG, currentItemPos .. " " .. self.sizeStats:get( "currentSize" ) )
if ( currentItemPos > self.sizeStats:get( "currentSize" ) ) then
--ngx.log( ngx.DEBUG, "Reached max size of " .. self.sizeStats:get( "currentSize" ) .. ", will start at pos 1" )
self.cache:set( "pos", 1 )
currentItemPos = 1
end
local existingItem = self.cache:get( currentItemPos )
if existingItem then
local spVal = splitString( existingItem, ID_SEP )
if self.ejectFunction then
--ngx.log( ngx.DEBUG, "Will eject " .. spVal[1] )
self.ejectFunction( spVal[1], self.makeReadableParams(cjson.decode(spVal[2])), false )
end
self.cacheIndex:delete( spVal[1] )
self.cache:delete( currentItemPos )
end
self.cacheIndex:set( id, currentItemPos )
end
ngx.log( ngx.DEBUG, "Will set " .. id .. " at " .. currentItemPos )
local newVal = self.mergeValWithParams(id, currentVal, params)
local success, err = self.cache:set( currentItemPos, newVal )
-- track cache rate and resize if needed
self.checkRate(currentVal)
return
end
function self.mergeValWithParams(id, currentVal, params)
local current
if not currentVal then
currentVal = self.storageInitString
else
local spCurr = splitString(currentVal, ID_SEP)
currentVal = spCurr[2]
end
current = cjson.decode( currentVal )
for name, val in pairs(params) do
if self.storageMap[name] and val ~= '' then
if type(val) == 'string' and string.find(val, ',') then
val = '"'..val..'"'
end
current[self.storageMap[name]] = val
end
end
return id .. ID_SEP .. cjson.encode( current )
end
function self.makeReadableParams(params)
local t = {}
for name, val in pairs(self.storageMap) do
if params[val] then
t[name] = params[val]
end
end
return t
end
function self.initStorage( paramList )
local storageMap = {}
local storageInit = {}
for aIndex = 1, #paramList do
storageMap[paramList[aIndex].input] = tostring(aIndex)
end
self.storageInitString = cjson.encode(storageInit)
self.storageMap = storageMap
-- initial draining status
self.cache:set( "draining", false )
end
function self.initSizeStats( reinit )
self.sizeStats:set( "itemCount", 0 )
self.sizeStats:set( 'periodStart', os.time() )
self.sizeStats:delete( 'locked' )
if not reinit then
self.sizeStats:set( "totalReqCount", 0 )
self.sizeStats:set( "totalItemCount", 0 )
self.sizeStats:set( "serverStart", os.time() )
end
end
function self.checkRate(currentItem)
-- if this is just an update to a current item, don't track new stat or consider resizing
if not currentItem then
if self.autoResize then
local locked = self.sizeStats:get( "locked" )
if not locked then
-- is it time to determine rate?
local startSampleTime = self.sizeStats:get( 'periodStart' )
if (os.time() - startSampleTime) > ( self.monitorPeriodMins * 60 )
then
-- monitor period has passed. lock and see if we should adjust
local locked = self.sizeStats:add( "locked", true )
if locked then
local count = self.sizeStats:get( "itemCount" )
if count then
local avgEjectMins = ( self.sizeStats:get( "currentSize" ) / count ) * self.monitorPeriodMins
self.sizeStats:set( "lastPeriodAvgMins", avgEjectMins )
-- is avg eject minutes not within acceptable range of desired?
if ( math.abs( 1 - (avgEjectMins / self.desiredEjectMins) ) * 100 ) > self.triggerAdjustPercent then
--ngx.log( ngx.WARN, "Adjust cache size: YES, desired mins is " .. self.desiredEjectMins .. " and we are ejecting at " .. avgEjectMins )
local desiredCacheSize = ( count / self.monitorPeriodMins ) * self.desiredEjectMins
local newCacheSize = desiredCacheSize
-- make sure we don't change more than x% at once
local diffPercent = (desiredCacheSize - self.sizeStats:get( "currentSize" )) / self.sizeStats:get( "currentSize" )
-- we can move up at a different rate than we move down
local maxAdjustPercent = self.maxAdjustPercentUp
if diffPercent < 0 then
maxAdjustPercent = self.maxAdjustPercentDown
end
if math.abs(diffPercent) * 100 > maxAdjustPercent then
local maxChange = math.floor( self.sizeStats:get( "currentSize" ) * ( maxAdjustPercent / 100 ) )
if diffPercent > 0 then
newCacheSize = self.sizeStats:get( "currentSize" ) + maxChange
else
newCacheSize = self.sizeStats:get( "currentSize" ) - maxChange
end
end
-- make sure we don't go over or under the min/max cache sizes
if newCacheSize > self.autoMaxSize then
newCacheSize = self.autoMaxSize
end
if newCacheSize < self.autoMinSize then
newCacheSize = self.autoMinSize
end
--ngx.log( ngx.WARN, "Desired cache size: " .. desiredCacheSize .. ", new size: " .. newCacheSize )
-- resize!
self.resize(newCacheSize)
else
--ngx.log( ngx.WARN, "Adjust cache size: NO, desired mins is " .. self.desiredEjectMins .. " and we are ejecting at " .. avgEjectMins )
end
end
-- reinitialize (includes unlock)
self.initSizeStats(true)
end
else
self.sizeStats:incr( "itemCount", 1 )
end
end
end
self.sizeStats:incr( "totalItemCount", 1 )
end
self.sizeStats:incr( "totalReqCount", 1 )
end
function self.get(id)
local offset = self.cacheIndex:get(id)
if not offset then
return nil
end
local docWithKey = self.cache:get(offset)
if docWithKey then
local doc = cjson.decode(splitString(docWithKey, ID_SEP)[2])
return cjson.encode(self.makeReadableParams(doc))
end
end
-- initialize size
self.sizeStats:set( "currentSize", params.initialSize or 1000000 )
-- initialize position
self.cache:set( "pos", 0 )
-- initialize storage template
self.initStorage( self.paramList )
-- initialize size stats
self.initSizeStats()
return self
end
function splitString(s, pattern)
if not pattern then pattern = "%s+" end
local ret = {}
local pos = 1
local fstart, fend = string.find(s, pattern, pos)
while fstart do
table.insert(ret, string.sub(s, pos, fstart - 1))
pos = fend + 1
fstart, fend = string.find(s, pattern, pos)
end
table.insert(ret, string.sub(s, pos))
return ret
end
return indexedRingBuffer
| mit |
Scavenge/darkstar | scripts/globals/mobskills/Tidal_Dive.lua | 33 | 1149 | ---------------------------------------------
-- Tidal Dive
--
-- Description: Dives at nearby targets. Additional effect: Weight and/or Bind (Status Effect)
-- Type: Physical
-- Utsusemi/Blink absorb: 2-3 shadows
-- Range: Unknown radial
-- Notes: Only used over deep water.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_BIND;
local numhits = math.random(2, 3);
local accmod = 1;
local dmgmod = .8;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_NONE,info.hitslanded);
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 30);
typeEffect = EFFECT_WEIGHT;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 50, 0, 60);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
jchuang1977/openwrt | package/diy/OpenAppFilter/luci-app-oaf/luasrc/model/cbi/appfilter/appfilter.lua | 1 | 5554 |
local ds = require "luci.dispatcher"
local nxo = require "nixio"
local nfs = require "nixio.fs"
local ipc = require "luci.ip"
local sys = require "luci.sys"
local utl = require "luci.util"
local dsp = require "luci.dispatcher"
local uci = require "luci.model.uci"
local lng = require "luci.i18n"
local jsc = require "luci.jsonc"
local http = luci.http
local SYS = require "luci.sys"
local m, s
m = Map("appfilter",
translate("appfilter"),
translate(""))
s = m:section(TypedSection, "global", translate("Basic Settings"))
s:option(Flag, "enable", translate("Enable App Filter"),translate(""))
s.anonymous = true
local rule_count=0
local version=""
if nixio.fs.access("/etc/appfilter/feature.cfg") then
rule_count=tonumber(SYS.exec("cat /etc/appfilter/feature.cfg | wc -l"))
version=SYS.exec("cat /etc/appfilter/feature.cfg |grep \"#version\" | awk '{print $2}'")
end
local display_str="<strong>ๅฝๅ็ๆฌ: </strong>"..version.."<br><strong>็นๅพ็ ไธชๆฐ:</strong> "..rule_count.."<br><strong> ไธ่ฝฝๅฐๅ:</strong><a href=\"https://destan19.github.io\">https://destan19.github.io</a>"
s = m:section(TypedSection, "feature", translate("็นๅพๅบๆดๆฐ"), display_str )
fu = s:option(FileUpload, "")
fu.template = "cbi/oaf_upload"
s.anonymous = true
um = s:option(DummyValue, "rule_data")
--um.value =rule_count .. " " .. translate("Records").. " "..version
s = m:section(TypedSection, "appfilter", translate("App Filter Rules"))
s.anonymous = true
s.addremove = false
local class_fd = io.popen("find /tmp/appfilter/ -type f -name '*.class'")
if class_fd then
while true do
local apps
local class
local path = class_fd:read("*l")
if not path then
break
end
class = path:match("([^/]+)%.class$")
-- add a tab
s:tab(class, translate(class))
-- multi value option
apps = s:taboption(class, MultiValue, class.."apps", translate(""))
apps.rmempty=true
--apps.delimiter=";"
-- select
apps.widget="checkbox"
apps.size=10
local fd = io.open(path)
if fd then
local line
while true do
local cmd
local cmd_fd
line = fd:read("*l")
if not line then break end
if string.len(line) < 5 then break end
if not string.find(line,"#") then
cmd = "echo "..line.."|awk '{print $1}'"
cmd_fd = io.popen(cmd)
id = cmd_fd:read("*l");
cmd_fd:close()
cmd = "echo "..line.."|awk '{print $2}'"
cmd_fd = io.popen(cmd)
name = cmd_fd:read("*l")
cmd_fd:close()
if not id then break end
if not name then break end
apps:value(id, name)
end
end
fd:close()
end
end
class_fd:close()
end
s=m:section(TypedSection,"user",translate("Select users"))
s.anonymous = true
users = s:option(MultiValue, "users", "", translate("Select at least one user, otherwise it will take effect for all users"))
users.widget="checkbox"
function get_hostname_by_mac(dst_mac)
leasefile="/tmp/dhcp.leases"
local fd = io.open(leasefile, "r")
if not fd then return end
while true do
local ln = fd:read("*l")
if not ln then
break
end
local ts, mac, ip, name, duid = ln:match("^(%d+) (%S+) (%S+) (%S+) (%S+)")
print(ln)
if dst_mac == mac then
fd:close()
return name
end
end
fd:close()
return nil
end
function get_cmd_result(command)
local fd
local result
fd = io.popen(command);
if not fd then return "" end
result = fd:read("*l");
fd:close()
return result
end
users.widget="checkbox"
--users.widget="select"
users.size=1
local fd = io.open("/tmp/dev_list", "r")
if not fd then return m end
while true do
local line = fd:read("*l")
if not line then
break
end
if not line:match("Id*") then
local ip=get_cmd_result(string.format("echo '%s' | awk '{print $3}'", line))
local mac=get_cmd_result(string.format("echo '%s' | awk '{print $2}'", line))
if mac ~= nil then
local hostname=get_hostname_by_mac(mac)
if not hostname or hostname == "*" then
users:value(mac, mac);
else
users:value(mac, hostname);
end
end
end
end
local config_users=m.uci:get_all("appfilter.user.users")
if config_users~=nil then
local r=utl.split(config_users, "%s+", nil, true)
local max = table.getn(r)
for i=1,max,1 do
users:value(r[i], r[i]);
end
end
m:section(SimpleSection).template = "admin_network/user_status"
local dir, fd
dir = "/tmp/upload/"
nixio.fs.mkdir(dir)
http.setfilehandler(
function(meta, chunk, eof)
if not fd then
if not meta then return end
if meta and chunk then fd = nixio.open(dir .. meta.file, "w") end
if not fd then
return
end
end
if chunk and fd then
fd:write(chunk)
end
if eof and fd then
fd:close()
local fd2 = io.open("/tmp/upload/"..meta.file)
local line=fd2:read("*l");
fd2:close()
local ret=string.match(line, "#version")
if ret ~= nil then
local cmd="cp /tmp/upload/"..meta.file.." /etc/appfilter/feature.cfg";
os.execute(cmd);
os.execute("rm /tmp/appfilter -fr");
luci.sys.exec("/etc/init.d/appfilter restart &");
um.value = translate("ๆดๆฐๆๅ๏ผ่ฏทๅทๆฐ้กต้ข!")
else
um.value = translate("ๆดๆฐๅคฑ่ดฅ๏ผๆ ผๅผ้่ฏฏ!")
end
end
end
)
if luci.http.formvalue("upload") then
local f = luci.http.formvalue("ulfile")
if #f <= 0 then
--um.value = translate("No specify upload file.")
end
elseif luci.http.formvalue("download") then
Download()
end
return m
| gpl-2.0 |
raymoo/artifice | player/talent_test.lua | 1 | 2234 |
local tt = artifice.talent_tree
local tree = tt.new_tree(8, 8, "default_stone.png")
local function dumb_learn(name)
return function(p_name)
minetest.chat_send_player(p_name, "You learned " .. name)
end
end
tree:add("wood", {
description = "Wood",
icon = "default_tree.png",
x = 1.5,
y = 0.5,
parents = {},
on_learn = dumb_learn("Wood"),
})
tree:add("stone", {
description = "Stone",
icon = "default_stone.png",
x = 5.5,
y = 0.5,
parents = {},
on_learn = dumb_learn("Stone"),
})
tree:add("plank", {
description = "Plank",
icon = "default_wood.png",
x = 4.5,
y = 2.5,
parents = { wood = "straight",
},
on_learn = dumb_learn("Plank"),
})
tree:add("cobble", {
description = "Cobblestone",
icon = "default_cobble.png",
x = 6.5,
y = 2.5,
parents = { stone = "straight",
},
on_learn = dumb_learn("Cobblestone"),
})
tree:add("stonestick", {
description = "Stone on a Stick",
icon = "default_tool_stoneaxe.png",
x = 2.5,
y = 2.5,
parents = { wood = "down",
stone = "straight",
},
on_learn = dumb_learn("Stone on a Stick"),
})
tree:add("diamond", {
description = "Diamond",
icon = "default_diamond.png",
x = 3.5,
y = 4.5,
parents = { cobble = "straight",
stonestick = "straight",
plank = "straight",
},
on_learn = dumb_learn("Diamond"),
})
local maybe_string = artifice.load_data("talent_test")
local datas = (maybe_string and tree:deserialize_data(maybe_string))
or tree:new_data()
local function show_tree(p_name)
local fs = "size[9,9]"
fs = fs .. datas:build_formspec(p_name, 0.5, 0.5)
minetest.show_formspec(p_name, "artifice:test_talent", fs)
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname ~= "artifice:test_talent" then return end
local p_name = player:get_player_name()
if not fields["quit"] then
datas:handle_fields(p_name, fields)
artifice.save_data("talent_test", datas:serialize())
show_tree(p_name)
end
return true
end)
minetest.register_craftitem("artifice:test_talent", {
description = "Ultimate Talents",
groups = { not_in_creative_inventory = 1 },
inventory_image = "default_book.png",
on_use = function(itemstack, player)
show_tree(player:get_player_name())
end,
})
| gpl-3.0 |
PicoleDeLimao/Ninpou2 | game/dota_addons/ninpou2/scripts/vscripts/heroes/orochimaru/orochimaru_seneijashu.lua | 1 | 4193 | --[[
Author: PicoleDeLimao
Date: 09.17.2016
Implement Orochimaru Sen'eijashu ability
]]
function SpellStart(event)
local caster = event.caster
local ability = event.ability
local target = event.target_points[1]
local range = ability:GetCastRange()
local damagePerInt = ability:GetLevelSpecialValueFor("dmg_per_int", ability:GetLevel() - 1)
local damageType = "yin"
local duration = 0.3
local tick = 0.03
local speed = range / (duration / tick)
local radius = 150
local numsnakes = 4
local angle = 10
--caster:EmitSound("Hero_Medusa.MysticSnake.Cast")
StartAnimation(caster, {duration=duration*2,activity=ACT_DOTA_CAST_ABILITY_6, rate=1.0})
Units:Pause(caster)
-- Create dummies and animations
local caster_forward = caster:GetForwardVector()
local dummies = {}
local snakes = {}
for i = 1, numsnakes do
local rotation_angle = -angle/2 + angle/numsnakes*i + math.random(-3,3)
local forward = Vectors:rotate2DDeg(caster_forward, rotation_angle)
local dummy = CreateUnitByName("npc_dummy_unit", caster:GetAbsOrigin() + forward * 150, false, caster, caster, caster:GetTeam())
dummy:SetForwardVector(forward)
dummy.speed = speed + math.random(-4,4)
local snakefx = ParticleManager:CreateParticle("particles/heroes/orochimaru/seneijashu/shredder_timberchain.vpcf", PATTACH_CUSTOMORIGIN, caster)
ParticleManager:SetParticleAlwaysSimulate(snakefx)
ParticleManager:SetParticleControlEnt(snakefx, 0, caster, PATTACH_POINT_FOLLOW, "attach_attack1", caster:GetAbsOrigin(), true)
ParticleManager:SetParticleControlEnt(snakefx, 1, dummy, PATTACH_POINT_FOLLOW, "attach_origin", dummy:GetAbsOrigin(), true)
ParticleManager:SetParticleControl(snakefx, 2, Vector(dummy.speed * 1/tick,0,0))
dummies[i] = dummy
snakes[i] = snakefx
end
local projectile = CreateUnitByName("npc_dummy_unit", caster:GetAbsOrigin(), false, caster, caster, caster:GetTeam())
projectile:SetForwardVector(caster:GetForwardVector())
-- Chain loop
local startPulling = function(target, distanceTraveled)
Timers:CreateTimer(tick, function()
for i = 1, numsnakes do
dummies[i]:SetAbsOrigin(dummies[i]:GetAbsOrigin() - dummies[i]:GetForwardVector() * dummies[i].speed)
end
projectile:SetAbsOrigin(projectile:GetAbsOrigin() - projectile:GetForwardVector() * speed)
if target ~= nil then
local vec = (target:GetAbsOrigin() - caster:GetAbsOrigin()):Normalized()
target:SetAbsOrigin(target:GetAbsOrigin() - vec * speed)
end
distanceTraveled = distanceTraveled - speed
if distanceTraveled > 0 then
return tick
else
if target ~= nil then
FindClearSpaceForUnit(target, target:GetAbsOrigin(), true)
Units:Unpause(target)
end
EndAnimation(caster)
for i = 1, numsnakes do
dummies[i]:Destroy()
ParticleManager:DestroyParticle(snakes[i], false)
end
projectile:Destroy()
Units:Unpause(caster)
end
end)
end
local distanceTraveled = 0
Timers:CreateTimer(tick, function()
for i = 1, numsnakes do
dummies[i]:SetAbsOrigin(dummies[i]:GetAbsOrigin() + dummies[i]:GetForwardVector() * dummies[i].speed)
end
projectile:SetAbsOrigin(projectile:GetAbsOrigin() + projectile:GetForwardVector() * speed)
-- Find a enemy in range
local target = nil
Units:FindEnemiesInRange({
unit = caster,
point = projectile:GetAbsOrigin(),
radius = radius,
func = function(enemy)
if Units:IsHero(enemy) then
target = enemy
elseif target == nil and not Units:IsBuilding(enemy) then
target = enemy
end
end
})
-- Start pulling loop
if target ~= nil then
target:EmitSound("Hero_Medusa.MysticSnake.Target")
local particle = Particles:CreateTimedParticle("particles/econ/items/riki/riki_immortal_ti6/riki_immortal_ti6_blinkstrike_gold_backstab_hit_blood.vpcf", target, 2.0)
Particles:SetControl(particle, 2, Vector(800, 0, 0))
Units:Damage(caster, target, caster:GetIntellect() * damagePerInt, damageType)
Units:Pause(target)
startPulling(target, distanceTraveled)
else
distanceTraveled = distanceTraveled + speed
if distanceTraveled < range then
return tick
else
startPulling(nil, distanceTraveled)
end
end
end)
end | apache-2.0 |
Scavenge/darkstar | scripts/globals/weaponskills/fell_cleave.lua | 26 | 1424 | -----------------------------------
-- Fell Cleave
-- Great Axe weapon skill
-- Skill Level: 300
-- Delivers an area attack. Radius varies with TP.
-- Aligned with the Breeze Gorget, Thunder Gorget & Soil Gorget.
-- Aligned with the Breeze Belt, Thunder Belt & Soil Belt.
-- Element: None
-- Modifiers: STR: 60%
-- 100%TP 200%TP 300%TP
-- 2.00 2.00 2.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 1;
params.ftp100 = 2.0; params.ftp200 = 2.0; params.ftp300 = 2.0;
params.str_wsc = 0.6; 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;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 2.75; params.ftp200 = 2.75; params.ftp300 = 2.75;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
jchuang1977/openwrt | package/lean/luci-app-nps/luasrc/model/cbi/nps.lua | 4 | 1785 | m=Map("nps")
m.title=translate("Nps Setting")
m.description=translate("Nps is a fast reverse proxy to help you expose a local server behind a NAT or firewall to the internet.")
m:section(SimpleSection).template="nps/nps_status"
s=m:section(TypedSection,"nps")
s.addremove=false
s.anonymous=true
s:tab("basic",translate("Basic Setting"))
enable=s:taboption("basic",Flag,"enabled",translate("Enable"))
enable.rmempty=false
server=s:taboption("basic",Value,"server_addr",translate("Server"),translate("Must an IPv4 address"))
server.datatype="ipaddr"
server.optional=false
server.rmempty=false
port=s:taboption("basic",Value,"server_port",translate("Port"))
port.datatype="port"
port.default="8024"
port.optional=false
port.rmempty=false
protocol=s:taboption("basic",ListValue,"protocol",translate("Protocol Type"))
protocol.default="tcp"
protocol:value("tcp",translate("TCP Protocol"))
protocol:value("kcp",translate("KCP Protocol"))
vkey=s:taboption("basic",Value,"vkey",translate("vkey"))
vkey.optional=false
vkey.password=true
vkey.rmempty=false
compress=s:taboption("basic",Flag,"compress",translate("Enable Compression"),translate("The contents will be compressed to speed up the traffic forwarding speed, but this will consume some additional cpu resources."))
compress.default="1"
compress.rmempty=false
crypt=s:taboption("basic",Flag,"crypt",translate("Enable Encryption"),translate("Encrypted the communication between Npc and Nps, will effectively prevent the traffic intercepted."))
crypt.default="1"
crypt.rmempty=false
log_level=s:taboption("basic",ListValue,"log_level",translate("Log Level"))
log_level:value(0,"Emergency")
log_level:value(2,"Critical")
log_level:value(3,"Error")
log_level:value(4,"Warning")
log_level:value(7,"Debug")
log_level.default="3"
return m
| gpl-2.0 |
Zero-K-Experiments/Zero-K-Experiments | units/damagesink.lua | 3 | 1248 | unitDef = {
unitname = [[damagesink]],
name = [[Damage Sink thing]],
description = [[Does not care if you shoot at it.]],
acceleration = 0,
autoHeal = 500000,
buildCostEnergy = 10,
buildCostMetal = 10,
builder = false,
buildingGroundDecalType = [[zenith_aoplane.dds]],
buildPic = [[zenith.png]],
buildTime = 10,
canstop = [[1]],
category = [[SINK GUNSHIP]],
energyUse = 0,
footprintX = 2,
footprintZ = 2,
iconType = [[mahlazer]],
idleAutoHeal = 5,
idleTime = 1800,
maxDamage = 500000,
maxSlope = 18,
maxVelocity = 0,
maxWaterDepth = 0,
minCloakDistance = 150,
objectName = [[zenith.s3o]],
script = [[nullscript.lua]],
seismicSignature = 4,
sightDistance = 660,
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = 0,
yardMap = [[yyyy]],
}
return lowerkeys({ damagesink = unitDef })
| gpl-2.0 |
PredatorMF/Urho3D | Source/ThirdParty/toluapp/src/bin/lua/typedef.lua | 44 | 1696 | -- tolua: typedef class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id: $
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- Typedef class
-- Represents a type synonym.
-- The 'de facto' type replaces the typedef before the
-- remaining code is parsed.
-- The following fields are stored:
-- utype = typedef name
-- type = 'the facto' type
-- mod = modifiers to the 'de facto' type
classTypedef = {
utype = '',
mod = '',
type = ''
}
classTypedef.__index = classTypedef
-- Print method
function classTypedef:print (ident,close)
print(ident.."Typedef{")
print(ident.." utype = '"..self.utype.."',")
print(ident.." mod = '"..self.mod.."',")
print(ident.." type = '"..self.type.."',")
print(ident.."}"..close)
end
-- Return it's not a variable
function classTypedef:isvariable ()
return false
end
-- Internal constructor
function _Typedef (t)
setmetatable(t,classTypedef)
t.type = resolve_template_types(t.type)
appendtypedef(t)
return t
end
-- Constructor
-- Expects one string representing the type definition.
function Typedef (s)
if strfind(string.gsub(s, '%b<>', ''),'[%*&]') then
tolua_error("#invalid typedef: pointers (and references) are not supported")
end
local o = {mod = ''}
if string.find(s, "[<>]") then
_,_,o.type,o.utype = string.find(s, "^%s*([^<>]+%b<>[^%s]*)%s+(.-)$")
else
local t = split(gsub(s,"%s%s*"," ")," ")
o = {
utype = t[t.n],
type = t[t.n-1],
mod = concat(t,1,t.n-2),
}
end
return _Typedef(o)
end
| mit |
mahdib9/mahdi4 | plugins/anti_spam.lua | 923 | 3750 |
--An empty table for solving multiple kicking problem(thanks to @topkecleon )
kicktable = {}
do
local TIME_CHECK = 2 -- seconds
local data = load_data(_config.moderation.data)
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
return msg
end
if msg.from.id == our_id then
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
--Load moderation data
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
--Check if flood is one or off
if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then
return msg
end
end
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local data = load_data(_config.moderation.data)
local NUM_MSG_MAX = 5
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity
end
end
local max_msg = NUM_MSG_MAX * 1
if msgs > max_msg then
local user = msg.from.id
-- Ignore mods,owner and admins
if is_momod(msg) then
return msg
end
local chat = msg.to.id
local user = msg.from.id
-- Return end if user was kicked before
if kicktable[user] == true then
return
end
kick_user(user, chat)
local name = user_print_name(msg.from)
--save it to log file
savelog(msg.to.id, name.." ["..msg.from.id.."] spammed and kicked ! ")
-- incr it on redis
local gbanspam = 'gban:spam'..msg.from.id
redis:incr(gbanspam)
local gbanspam = 'gban:spam'..msg.from.id
local gbanspamonredis = redis:get(gbanspam)
--Check if user has spammed is group more than 4 times
if gbanspamonredis then
if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then
--Global ban that user
banall_user(msg.from.id)
local gbanspam = 'gban:spam'..msg.from.id
--reset the counter
redis:set(gbanspam, 0)
local username = " "
if msg.from.username ~= nil then
username = msg.from.username
end
local name = user_print_name(msg.from)
--Send this to that chat
send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." Globally banned (spamming)")
local log_group = 1 --set log group caht id
--send it to log group
send_large_msg("chat#id"..log_group, "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)")
end
end
kicktable[user] = true
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function cron()
--clear that table on the top of the plugins
kicktable = {}
end
return {
patterns = {},
cron = cron,
pre_process = pre_process
}
end
| gpl-2.0 |
Brenin/PJ-3100 | Working Launchers/Games/Stepmania/StepMania 5/Themes/default/Graphics/ScreenQuickSetupOverview icon/default.lua | 1 | 1379 | local gc = Var "GameCommand";
local c = {};
c.X = THEME:GetMetric( Var "LoadingScreen", "Icon" .. gc:GetName() .. "X");
c.Y = THEME:GetMetric( Var "LoadingScreen", "Icon" .. gc:GetName() .. "Y");
local t = Def.ActorFrame {};
t[#t+1] = Def.ActorFrame {
Condition=( gc:GetName() ~= "Back" );
InitCommand=cmd(x,c.X;y,c.Y);
GainFocusCommand=cmd(finishtweening;zoom,1.125;bounceend,0.125;zoom,1);
LoseFocusCommand=cmd(stoptweening;linear,0.125;zoom,0.875);
LoadActor("_base") .. {
GainFocusCommand=cmd(stoptweening;linear,0.125;diffuse,Color("Orange");diffusetopedge,Color("Yellow"));
LoseFocusCommand=cmd(stoptweening;linear,0.125;diffuse,Color("White"));
};
LoadFont("Common Normal") .. {
Text=gc:GetName();
InitCommand=cmd(strokecolor,Color("White"));
OnCommand=cmd(diffuse,Color("Black"));
};
};
t[#t+1] = Def.ActorFrame {
Condition=( gc:GetName() == "Back" );
InitCommand=cmd(x,c.X;y,c.Y);
GainFocusCommand=cmd(finishtweening;zoom,1.125;bounceend,0.125;zoom,1);
LoseFocusCommand=cmd(stoptweening;linear,0.125;zoom,0.875);
LoadActor("_base") .. {
GainFocusCommand=cmd(stoptweening;linear,0.125;diffuse,Color("Red"));
LoseFocusCommand=cmd(stoptweening;linear,0.125;diffuse,Color("White"));
};
LoadFont("Common Normal") .. {
Text=gc:GetName();
InitCommand=cmd(strokecolor,Color("White"));
OnCommand=cmd(diffuse,Color("Black"));
};
};
return t; | mit |
Scavenge/darkstar | scripts/zones/Alzadaal_Undersea_Ruins/npcs/qm4.lua | 30 | 1358 | -----------------------------------
-- Area: Alzadaal Undersea Ruins
-- NPC: ??? (Spawn Wulgaru(ZNM T2))
-- @pos -22 -4 204 72
-----------------------------------
package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs");
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local mobID = 17072179;
if (trade:hasItemQty(2597,1) and trade:getItemCount() == 1) then -- Trade Opalus Gem
if (GetMobAction(mobID) == ACTION_NONE) then
player:tradeComplete();
SpawnMob(mobID):updateClaim(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
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 |
Scavenge/darkstar | scripts/zones/Castle_Zvahl_Baileys/Zone.lua | 12 | 3391 | -----------------------------------
--
-- Zone: Castle_Zvahl_Baileys (161)
--
-----------------------------------
package.loaded["scripts/zones/Castle_Zvahl_Baileys/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/zone");
require("scripts/zones/Castle_Zvahl_Baileys/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1, -90,17,45, -84,19,51); -- map 4 NW porter
zone:registerRegion(1, 17,-90,45, -85,18,51); -- map 4 NW porter
zone:registerRegion(2, -90,17,-10, -85,18,-5); -- map 4 SW porter
zone:registerRegion(3, -34,17,-10, -30,18,-5); -- map 4 SE porter
zone:registerRegion(4, -34,17,45, -30,18,51); -- map 4 NE porter
-- Marquis Allocen
SetRespawnTime(17436913, 900, 10800);
-- Marquis Amon
SetRespawnTime(17436918, 900, 10800);
-- Duke Haborym
SetRespawnTime(17436923, 900, 10800);
-- Grand Duke Batym
SetRespawnTime(17436927, 900, 10800);
UpdateTreasureSpawnPoint(17436997);
UpdateTreasureSpawnPoint(17436998);
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(-181.969,-35.542,19.995,254);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
switch (region:GetRegionID()): caseof
{
---------------------------------
[1] = function (x) --
---------------------------------
player:startEvent(0x0003); -- ports player to NW room of map 3
end,
---------------------------------
[2] = function (x) --
---------------------------------
player:startEvent(0x0002); -- ports player to SW room of map 3
end,
---------------------------------
[3] = function (x) --
---------------------------------
player:startEvent(0x0001); -- ports player to SE room of map 3
end,
---------------------------------
[4] = function (x) --
---------------------------------
player:startEvent(0x0000); -- ports player to NE room of map 3
end,
default = function (x)
--print("default");
end,
}
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(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 |
Joker-Developer/jokersuper | plugins/wether.lua | 4 | 2180 | --[[
# For More Information ....!
# Developer : Aziz < @devss_bot > #Dev
# our channel: @help_tele
]]
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local function get_weather(location)
print("Finding weather in ", location)
local url = BASE_URL
url = url..'?q='..location..'&APPID=eedbc05ba060c787ab0614cad1f2e12b'
url = url..'&units=metric'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'ุงูุงุญูุงู ุงูุฌููุฉ ูู
ุฏููุฉ :'..city..'\n\n๐ก ุฏุฑุฌุฉ ุญุฑุงุฑุฉ ุงูููุงุก ุงูุญุงููุฉ : '..weather.main.temp..' C\n\nุงูุถุบุท ุงูุฌูู :'..weather.main.pressure..'\nุงูุฑุทูุจุฉ : '..weather.main.humidity..' %\n\n๐ปุงูุญุฏ ุงูุฃุฏูู ู
ู ุฏุฑุฌุงุช ุงูุญุฑุงุฑุฉ ุงูููู
:'..weather.main.temp_min..'\n๐บุฏุฑุฌุฉ ุงูุญุฑุงุฑุฉ ุงููุตูู ุงูููู
:'..weather.main.temp_min..'\n\n๐ฌ ุณุฑุนุฉ ุงูุฑูุงุญ : '..weather.wind.speed..'\nุงูุฑูุงุญ : '..weather.wind.deg..'\n\n๐ธุฎุท ุงูุทูู : '..weather.coord.lon..'\n๐นุฎุท ุงูุนุฑุถ : '..weather.coord.lat
local conditions = 'ุฃุญูุงู ุงูุทูุณ ุงูุญุงููุฉ:'
if weather.weather[1].main == 'Clear' then
conditions = conditions .. 'ู
ุดู
ุณ โ๐๏ธ'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. 'ุบุงุฆู
๐ฅโ
๏ธ'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. 'ู
ู
ุทุฑ โ๐ง๏ธ'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. 'ุนุงุตู ๐ช'
elseif weather.weather[1].main == 'Mist' then
conditions = conditions .. 'ู
ู ๐ซ'
end
return temp .. '\n\n' .. conditions..'\n\nุงูู
ุฒูุฏ : @help_tele'
end
local function DevPoint(msg, matches)
city = matches[1]
local wtext = get_weather(city)
if not wtext then
wtext = 'ุงูู
ููุน ุบูุฑ ุตุญูุญ'
end
return wtext
end
return {
patterns = {
"^ุงูุทูุณ (.*)$",
},
run = DevPoint
}
--[[
# For More Information ....!
# Developer : Aziz < @devss_bot > #Dev
# our channel: @help_tele
]] | gpl-2.0 |
nmacs/lm3s-uclinux | lib/liblua/lsqlite3_svn08/examples/order.lua | 8 | 2868 |
require("lsqlite3")
local db = assert( sqlite3:open_memory() )
assert( db:exec[[
CREATE TABLE customer (
id INTEGER PRIMARY KEY,
name VARCHAR(40)
);
CREATE TABLE invoice (
id INTEGER PRIMARY KEY,
customer INTEGER NOT NULL,
title VARCHAR(80) NOT NULL,
article1 VARCHAR(40) NOT NULL,
price1 REAL NOT NULL,
article2 VARCHAR(40),
price2 REAL
);
CREATE TABLE invoice_overflow (
id INTEGER PRIMARY KEY,
invoice INTEGER NOT NULL,
article VARCHAR(40) NOT NULL,
price REAL NOT NULL
);
INSERT INTO customer VALUES(
1, "Michael" );
INSERT INTO invoice VALUES(
1, 1, "Computer parts", "harddisc", 89.90, "floppy", 9.99 );
INSERT INTO customer VALUES(
2, "John" );
INSERT INTO invoice VALUES(
2, 2, "Somme food", "apples", 2.79, "pears", 5.99 );
INSERT INTO invoice_overflow VALUES(
NULL, 2, "grapes", 6.34 );
INSERT INTO invoice_overflow VALUES(
NULL, 2, "strawberries", 4.12 );
INSERT INTO invoice_overflow VALUES(
NULL, 2, "tomatoes", 6.17 );
INSERT INTO invoice VALUES(
3, 2, "A new car", "Cybercar XL-1000", 65000.00, NULL, NULL );
]] )
local function customer_name(id)
local stmt = db:prepare("SELECT name FROM customer WHERE id = ?")
stmt:bind_values(id)
stmt:step()
local r = stmt:get_uvalues()
stmt:finalize()
return r
end
local function all_invoices()
return db:nrows("SELECT id, customer, title FROM invoice")
end
local function all_articles(invoice)
local function iterator()
local stmt, row
-- Get the articles that are contained in the invoice table itself.
stmt = db:prepare("SELECT article1, price1, article2, price2 FROM invoice WHERE id = ?")
stmt:bind_values(invoice)
stmt:step()
row = stmt:get_named_values()
-- Every Invoice has at least one article.
coroutine.yield(row.article1, row.price1)
-- Maybe the Invoice has a second article?
if row.article2 then
-- Yes, there is a second article, so return it.
coroutine.yield(row.article2, row.price2)
-- When there was an second article, maybe there are even
-- more articles in the overflow table? We will see...
stmt = db:prepare("SELECT article, price FROM invoice_overflow WHERE invoice = ? ORDER BY id")
stmt:bind_values(invoice)
for row in stmt:nrows() do
coroutine.yield(row.article, row.price)
end
end
end
return coroutine.wrap(iterator)
end
for invoice in all_invoices() do
local id = invoice.id
local name = customer_name(invoice.customer)
local title = invoice.title
print()
print("Invoice #"..id..", "..name..": '"..title.."'")
print("----------------------------------------")
for article, price in all_articles(id) do
print( string.format("%20s %8.2f", article, price) )
end
print()
end
| gpl-2.0 |
Zero-K-Experiments/Zero-K-Experiments | LuaUI/Configs/zk_keys.lua | 2 | 5901 | return {
-- yyyymmdd
-- if newer than user's, overwrite ALL zir zk_keys
-- else just add any that are missing from local config
["date"] = 20130630,
-- all default ZK keybinds.
["keybinds"] = {
{ "togglecammode", "Ctrl+backspace",},
{ "togglecammode", "Shift+backspace",},
{ "edit_backspace", "Any+backspace",},
{ "toggleoverview", "Ctrl+tab",},
{ "edit_complete", "Any+tab",},
{
"chatally", {"Alt+enter", "Alt+numpad_enter"},
},
{
"chatswitchally", {"Alt+enter", "Alt+numpad_enter"},
},
{
"chatall", {"Ctrl+enter", "Ctrl+numpad_enter"},
},
{
"chatswitchall", {"Ctrl+enter", "Ctrl+numpad_enter"},
},
{ "chatspec", "None"},
{ "chatswitchspec", "None"},
{
"chat", {"Any+enter", "Any+numpad_enter"},
},
{
"edit_return", {"Any+enter", "Any+numpad_enter"},
},
{ "pause", "pause",},
{ "crudemenu", "esc",},
{ "exitwindow", "shift+esc",},
{ "quitforce", "Ctrl+Shift+esc",},
{ "edit_escape", "Any+escape",},
{ "speedup", { "Any++","Any+=","Any+numpad+"}, },
{ "prevmenu", ",",},
{ "decguiopacity", "Shift+,",},
{ "slowdown", {"Any+-","Any+numpad-",}, },
{ "nextmenu", ".",},
{ "incguiopacity", "Shift+.",},
{ "specteam 9", "0",},
{ "specteam 19", "Ctrl+0",},
{ "group0", "Any+0",},
{ "specteam 0", "1",},
{ "specteam 10", "Ctrl+1",},
{ "group1", "Any+1",},
{ "specteam 1", "2",},
{ "specteam 11", "Ctrl+2",},
{ "group2", "Any+2",},
{ "specteam 2", "3",},
{ "specteam 12", "Ctrl+3",},
{ "group3", "Any+3",},
{ "specteam 3", "4",},
{ "specteam 13", "Ctrl+4",},
{ "group4", "Any+4",},
{ "specteam 4", "5",},
{ "specteam 14", "Ctrl+5",},
{ "group5", "Any+5",},
{ "specteam 5", "6",},
{ "specteam 15", "Ctrl+6",},
{ "group6", "Any+6",},
{ "specteam 6", "7",},
{ "specteam 16", "Ctrl+7",},
{ "group7", "Any+7",},
{ "specteam 7", "8",},
{ "specteam 17", "Ctrl+8",},
{ "group8", "Any+8",},
{ "specteam 8", "9",},
{ "specteam 18", "Ctrl+9",},
{ "group9", "Any+9",},
{ "buildfacing inc", {"Any+insert", "[", "Shift+[",}, },
{ "drawinmap", {
"Any+\\",
"Any+`",
"Any+0xa7",
"Any+^",
},
},
{ "clearmapmarks", "Alt+`"},
{ "buildfacing dec", {"Any+delete", "]","Shift+]",}, },
{ "attack", "f",},
{ "areaattack", "Alt+a",},
{ "debug", "Alt+n",},
{ "debugcolvol", "Alt+b",},
{ "repeat", "ctrl+r"},
{ "priority", "ctrl+q"},
{ "selfd", "C+d",},
{ "selectcomm", "ctrl+c",},
{ "manualfire", "d",},
{ "oneclickwep", "d",},
{ "placebeacon", "d",},
{ "reclaim", "e",},
{ "fight", "a",},
{ "forcestart", "Alt+f",},
--{ "guard", "g",},
{ "areaguard", "g",},
{ "gameinfo", "Ctrl+i",},
{ "wantcloak", "k",},
{ "togglelos", "Ctrl+l",},
{ "loadunits", "l",},
{ "loadselected", "l",},
{ "move", "m",},
{ "singlestep", "Alt+o",},
{ "patrol", "p",},
{ "groupclear", "Shift+q",},
{ "repair", "r",},
{ "stop", "s",},
{ "stopproduction", "ctrl+s",},
{ "globalbuildcancel", "alt+s",},
{ "unloadunits", "u",},
{ "pastetext", "Ctrl+v",},
{ "wait", "ctrl+w",},
{ "areamex", "w",},
{ "onoff", "o",},
{ "buildspacing dec", "Any+x",},
{ "buildspacing inc", "Any+z",},
{ "edit_delete", "Any+delete",},
{ "edit_prev_line", "Any+up",},
{ "moveforward", "Any+up",},
{ "edit_next_line", "Any+down",},
{ "moveback", "Any+down",},
{ "edit_end", "Alt+right",},
{ "edit_next_word", "Ctrl+right",},
{ "edit_next_char", "Any+right",},
{ "moveright", "Any+right",},
{ "edit_home", "Alt+left",},
{ "edit_prev_word", "Ctrl+left",},
{ "edit_prev_char", "Any+left",},
{ "moveleft", "Any+left",},
{ "increaseviewradius", "home",},
{ "edit_home", "Any+home",},
{ "decreaseviewradius", "end",},
{ "edit_end", "Any+end",},
{ "moveup", "Any+pageup",},
{ "movedown", "Any+pagedown",},
{ "showelevation", "f1",},
{ "viewfps", "C+f1",},
{ "showpathtraversability", "f2",},
{ "viewta", "C+f2",},
{ "lastmsgpos", "f3",},
{ "viewtw", "C+f3",},
{ "showeco", "f4",},
{ "showmetalmap", "None"},
{ "viewrot", "C+f4",},
{ "viewfree", "C+f5",},
{ "HideInterface", "Any+f5",},
{ "NoSound", "Any+f6",},
{ "DynamicSky", "Any+f7",},
{ "savegame", "Ctrl+Shift+f8",},
{ "luaui showhealthbars", "f9",},
{ "showhealthbars", "Any+f9",},
{ "createvideo", "Ctrl+Shift+f10",},
{ "viewlobby", "f11",},
{ "luaui tweakgui", "C+f11",},
{ "epic_chili_widget_selector_widgetlist_2", "alt+f11",},
{ "screenshot png", "f12",},
{ "screenshot jpg", "ctrl+f12"},
{ "movefast", "Any+shift",},
{ "moveslow", "Any+ctrl",},
{ "track", "alt+t",},
{ "resurrect", "t",},
{ "jump", "j",},
{ "select AllMap++_ClearSelection_SelectAll+", "ctrl+a",},
{ "selectidlecon_all", "ctrl+b",},
{ "select PrevSelection+_Not_RelativeHealth_30+_ClearSelection_SelectAll+", "ctrl+e",},
{ "select AllMap+_Not_Builder_Not_Building+_ClearSelection_SelectAll+", "ctrl+f",},
{ "select AllMap+_NameContain_Hawk+_ClearSelection_SelectAll+", "ctrl+g",},
{ "select PrevSelection+_Idle+_ClearSelection_SelectAll+", "ctrl+i",},
{ "select AllMap+_Not_Builder_Not_Building_Not_Transport_Aircraft_Radar+_ClearSelection_SelectAll+", "ctrl+s",},
{ "select AllMap+_Not_Builder_Not_Building_Transport_Aircraft+_ClearSelection_SelectAll+", "ctrl+t",},
{ "selectidlecon", "z",},
{ "select Visible+_InPrevSel+_ClearSelection_SelectAll+", "ctrl+x",},
{ "select AllMap+_InPrevSel_Not_Builder+_ClearSelection_SelectAll+", "ctrl+z",},
{ "epic_chili_integral_menu_tab_economy", "x",},
{ "epic_chili_integral_menu_tab_defence", "c",},
{ "epic_chili_integral_menu_tab_special", "v",},
{ "epic_chili_integral_menu_tab_factory", "b",},
{ "epic_chili_integral_menu_tab_units", "n",},
{ "exitwindow", "s+escape",},
{ "crudesubmenu", "f10"},
{ "epic_chili_pro_console_enableconsole", "f8"},
{ "epic_chili_share_menu_v1.22_sharemenu", "tab"},
},
}
| gpl-2.0 |
Scavenge/darkstar | scripts/zones/Western_Adoulin/Zone.lua | 17 | 1708 | -----------------------------------
--
-- Zone: Western Adoulin
-- @zone 256
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil;
require("scripts/zones/Western_Adoulin/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-142, 4, -18, 4);
end
if (player:getVar("Raptor_Rapture_Status") == 2) then
-- Resuming cutscene for Quest: 'Raptor Rapture', after Pagnelle warps you to Rala Waterways mid-CS, then back here.
cs = 0x13C0;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 0x13C0) then
-- Successfully finished introduction CS event chain for Quest: 'Raptor Rapture'.
player:setVar("Raptor_Rapture_Status", 3);
if (option == 1) then
-- Starts Quest: 'Raptor Rapture'
player:addQuest(ADOULIN, RAPTOR_RAPTURE);
player:setVar("Raptor_Rapture_Status", 4);
end
end
end;
| gpl-3.0 |
Zero-K-Experiments/Zero-K-Experiments | LuaRules/Gadgets/weapon_trail_burnout.lua | 12 | 5169 | function gadget:GetInfo()
return {
name = "Trail Burnout",
desc = "Provide ability to changes weapon trail CEG after a customParam-specified time, or change specific weapon into customParam-specified weapon when underwater",
author = "Anarchid",
date = "14.01.2013",
license = "Public domain",
layer = -1, --before lups_shockwaves.lua (so that there's no shockwave after we block explosion effect)
enabled = false
}
end
------ SYNCED -------------------------------------------------------
if (gadgetHandler:IsSyncedCode()) then
local defaultCeg = ''
local burnoutWeapon = {}
local burnoutProjectile = {}
local underwaterWeapon = {}
local underwaterProjectile = {}
local noExplosionVFX = {}
local spGetGameFrame = Spring.GetGameFrame
local spSetProjectileCeg = Spring.SetProjectileCEG
local scSetWatchWeapon = Script.SetWatchWeapon
local spGetProjectilePosition = Spring.GetProjectilePosition
local spGetProjectileVelocity = Spring.GetProjectileVelocity
local spGetProjectileTarget = Spring.GetProjectileTarget
local spSetProjectileCollision = Spring.SetProjectileCollision
local spSetProjectileVelocity = Spring.SetProjectileVelocity
local spSetProjectileGravity = Spring.SetProjectileGravity
local spSpawnProjectile = Spring.SpawnProjectile
local spSetProjectileTarget = Spring.SetProjectileTarget
local spGetUnitTeam = Spring.GetUnitTeam
local spSetPieceProjectileParams = Spring.SetPieceProjectileParams
local spGetUnitTeam = Spring.GetUnitTeam
function gadget:Initialize()
for i=1,#WeaponDefs do
local wd = WeaponDefs[i]
if wd.customParams then
if wd.customParams.trail_burnout then
burnoutWeapon[wd.id] = {
burnout = wd.customParams.trail_burnout,
burnoutCeg = wd.customParams.trail_burnout_ceg or defaultCeg
}
scSetWatchWeapon(wd.id, true)
end
if wd.customParams.torp_underwater then
underwaterWeapon[wd.id] = {
torpName = wd.customParams.torp_underwater,
}
scSetWatchWeapon(wd.id, true)
end
end
end
end
function gadget:ProjectileCreated(proID, proOwnerID, weaponID)
if burnoutWeapon[weaponID] then
burnoutProjectile[proID] = {
startFrame = spGetGameFrame(),
burnout = burnoutWeapon[weaponID].burnout,
burnoutCeg = burnoutWeapon[weaponID].burnoutCeg or defaultCeg
}
end
if underwaterWeapon[weaponID] then
underwaterProjectile[proID] = {
owner = proOwnerID,
weaponID = weaponID,
torpName = underwaterWeapon[weaponID].torpName,
}
end
end
function gadget:ProjectileDestroyed(proID, proOwnerID, weaponID)
burnoutProjectile[proID] = nil
underwaterProjectile[proID] = nil
end
function gadget:Explosion(weaponDefID, px, py, pz, ownerID)
if noExplosionVFX[weaponDefID] then
px = math.modf(px+0.5)
pz = math.modf(pz+0.5)
if noExplosionVFX[weaponDefID][px..pz]==ownerID then
noExplosionVFX[weaponDefID][px..pz] = nil
return true --noVFX
end
end
end
function gadget:GameFrame(f)
StartBurnoutTrail(f)
if f % 7 == 0 then
ConvertWeaponUnderwater()
end
end
-------------------------------------------
-------------------------------------------
function StartBurnoutTrail(frame)
for id, proj in pairs(burnoutProjectile) do
if proj.startFrame+proj.burnout <= frame then
spSetProjectileCeg(id, proj.burnoutCeg)
burnoutProjectile[id] = nil
end
end
end
function ConvertWeaponUnderwater()
for id,proj in pairs(underwaterProjectile) do
if spSpawnProjectile and proj.torpName and WeaponDefNames[proj.torpName] then
local px,py,pz = Spring.GetProjectilePosition(id)
if py <= -9 then -- projectile is underwater. Set to submarine waterline (bottom = -20, top = 0) to let it hit submarine first rather than doing a conversion to torpedo
local defID = WeaponDefNames[proj.torpName].id
local ownerTeamID = spGetUnitTeam(proj.owner)
local pvx, pvy, pvz = spGetProjectileVelocity(id)
local projectileParams = {
pos = {px, py, pz},
speed = {pvx, pvy, pvz},
owner = proj.owner,
team = ownerTeamID,
}
local a, b = spGetProjectileTarget(id)
spSetPieceProjectileParams(id,0) --not sure what this do, it set piece explosion tag to 0 (disable)
px = math.modf(px+0.5) --round the number to nearest integer
pz = math.modf(pz+0.5)
noExplosionVFX[proj.weaponID] = noExplosionVFX[proj.weaponID] or {}
noExplosionVFX[proj.weaponID][px..pz] = proj.owner
spSetProjectileVelocity(id,0,0,0) --stop projectile for more accurate
spSetProjectileGravity(id,0)
spSetProjectileCollision(id) --explosion to destroy projectile. It also trigger wave in Dynamic water
local newID = spSpawnProjectile(defID, projectileParams)
if type(b)=='number' then
spSetProjectileTarget(newID,b)
elseif type(b)=='table' then
spSetProjectileTarget(newID,b[1],b[2],b[3])
elseif type(a)=='number' then
spSetProjectileTarget(newID,b,a)
end
underwaterProjectile[id]=nil
end
else
if spSpawnProjectile then
Spring.Echo("weapon_trail_burnout.lua ERROR:non existent torpedo name :".. (proj.torpName or "nil"))
end
underwaterProjectile[id]=nil
end
end
end
end
----- END SYNCED ---------------------------------------------------
| gpl-2.0 |
Zero-K-Experiments/Zero-K-Experiments | gamedata/planetwars/pw_unitdefgen.lua | 12 | 3630 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- file: pw_unitdefgen.lua
-- brief: procedural generation of unitdefs for planetwars
-- author: GoogleFrog
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Spring.Utilities = Spring.Utilities or {}
VFS.Include("LuaRules/Utilities/base64.lua")
--------------------------------------------------------------------------------
-- Produces the required planetwars structures for a given game from a generic
-- unit. The alternative is a few dozen extra unitdefs of bloat.
--------------------------------------------------------------------------------
VFS.Include("gamedata/planetwars/pw_structuredefs.lua")
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local modOptions = (Spring and Spring.GetModOptions and Spring.GetModOptions()) or {}
local pwDataRaw = modOptions.planetwarsstructures
local pwDataFunc, err, success, unitData
pwDataRaw = pwDataRaw or TEST_DEF_STRING
if not (pwDataRaw and type(pwDataRaw) == 'string') then
err = "Planetwars data entry in modoption is empty or in invalid format"
unitData = {}
else
pwDataRaw = string.gsub(pwDataRaw, '_', '=')
pwDataRaw = Spring.Utilities.Base64Decode(pwDataRaw)
pwDataFunc, err = loadstring("return "..pwDataRaw)
if pwDataFunc then
success, unitData = pcall(pwDataFunc)
if not success then -- execute Borat
err = pwData
unitData = {}
end
end
end
if err then
Spring.Log("gamedata/modularcomms/unitdefgen.lua", "warning", 'Planetwars warning: ' .. err)
end
if not unitData then
unitData = {}
end
--unitData = CopyTable(structureConfig, true)
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
structureDefs = {} --holds precedurally generated structure defs
genericStructure = UnitDefs["pw_generic"]
local function makeTechStructure(def, name)
local techName = string.sub(name,4)
techName = UnitDefs[techName]
if techName then
def.name = techName.name .. " Technology Facility"
def.description = "Gives planet owner the ability to construct " .. techName.name
end
structureConfig["generic_tech"](def)
end
--for name in pairs(unitData) do
for _, info in pairs(unitData) do
if type(info) == "table" and info.isDestroyed ~= 1 then
structureDefs[info.unitname] = CopyTable(genericStructure, true)
structureDefs[info.unitname].customparams = structureDefs[info.unitname].customparams or {}
if structureConfig[info.unitname] then
structureConfig[info.unitname](structureDefs[info.unitname])
structureDefs[info.unitname].unitname = info.unitname
else
makeTechStructure(structureDefs[info.unitname], info.unitname)
structureDefs[info.unitname].unitname = info.unitname
end
if ALLOW_SERVER_OVERRIDE_UNIT_TEXT then
structureDefs[info.unitname].name = info.name
structureDefs[info.unitname].description = info.description
end
structureDefs[info.unitname].buildcostmetal = structureDefs[info.unitname].maxdamage
structureDefs[info.unitname].buildcostenergy = structureDefs[info.unitname].maxdamage
structureDefs[info.unitname].buildtime = structureDefs[info.unitname].maxdamage
end
end
-- splice back into unitdefs
for name, data in pairs(structureDefs) do
UnitDefs[name] = data
end
| gpl-2.0 |
Escaton615/SelfCensorship | DuduTree.lua | 1 | 1655 | DuduTree = {}
function DuduTree:Filter(raw)
ret = ""
current = self.tree
matching = false
censored = ""
original = ""
for uchar in string.gfind(raw, "([%z\1-\127\194-\244][\128-\191]*)") do
if not matching then
if current[uchar] ~= nil then
matching = true
current = current[uchar]
censored = "*"
original = uchar
else
ret = ret..uchar
end
else
if current[uchar] ~= nil then
current = current[uchar]
censored = censored.."*"
original = original..uchar
else
if current['end'] then
ret = ret..censored
else
ret = ret..original
end
if self.tree[uchar] ~= nil then
current = self.tree[uchar]
censored = "*"
original = uchar
else
matching = false
original = ""
current = self.tree
ret = ret..uchar
end
end
end
end
if matching and current['end'] then
ret = ret..censored
else
ret = ret..original
end
return ret
end
function DuduTree:Build(words)
self.tree = {}
for _,word in pairs(words) do
self:AddToTree(word)
end
end
function DuduTree:AddToTree(word)
local current = self.tree
for uchar in string.gfind(word, "([%z\1-\127\194-\244][\128-\191]*)") do
if current[uchar] == nil then
current[uchar] = {}
end
current = current[uchar]
-- table.insert(uchars,uchar)
end
current['end'] = true
end
f_words = {'ๅทๆฎ','ไผไธๅก','้ปๅฅธ','ๅฅฅๅทด้ฉฌ','้ฟ่จๅพท','ๅฅฅๅทด'}
DuduTree:Build(f_words)
print(DuduTree:Filter("้ฟ้ฟ่จ้ฟ่จๅพทๅฅฅๅทดๅฅฅๅทด้ฉฌ้ป-ๅฅธๅฅฅๅทดๅทๆฎxijinping"))
return DuduTree | mit |
Zero-K-Experiments/Zero-K-Experiments | LuaUI/Widgets/unit_decloak_range.lua | 4 | 1843 | function widget:GetInfo()
return {
name = "Decloak Range",
desc = "Display decloak range around cloaked units. v2",
author = "banana_Ai, dahn",
date = "15 Jul 2016",
license = "GNU GPL v2",
layer = 0,
enabled = true,
}
end
VFS.Include("LuaRules/Utilities/glVolumes.lua")
local Chili
options_path = 'Settings/Interface/Decloak Ranges'
options_order = {
"drawranges",
"onlyforcloaked",
"onlyforselected",
"fillcolor"
}
options = {
drawranges = {
name = 'Draw decloak ranges',
type = 'bool',
value = false,
OnChange = function (self)
if self.value then
widgetHandler:UpdateCallIn("DrawWorldPreUnit")
else
widgetHandler:RemoveCallIn("DrawWorldPreUnit")
end
end
},
onlyforcloaked = {
name = 'Draw only for cloaked units',
type = 'bool',
value = true,
},
onlyforselected = {
name = 'Draw only for selected units',
type = 'bool',
value = true,
},
fillcolor = {
name = 'Fill color',
type = 'colors',
value = {0.3,0.3,1.0,0.4},
}
}
local function DrawDecloackArea(unitID,def)
local r = def.decloakDistance
local x,_,z=Spring.GetUnitPosition(unitID)
local fillcolor = options.fillcolor.value
gl.Color(fillcolor[1], fillcolor[2], fillcolor[3], fillcolor[4])
gl.Utilities.DrawGroundCircle(x,z,r)
end
function widget:DrawWorldPreUnit()
local units
if options.onlyforselected.value then
units = Spring.GetSelectedUnits()
else
units = Spring.GetTeamUnits(Spring.GetLocalTeamID())
end
for _,unitID in ipairs(units) do
local defID = Spring.GetUnitDefID(unitID)
local def = UnitDefs[defID]
if Spring.GetUnitIsCloaked(unitID) or
(def and def.canCloak and not options.onlyforcloaked.value) then
DrawDecloackArea(unitID,def)
end
end
end
function widget:Initialize()
widgetHandler:RemoveCallIn("DrawWorldPreUnit")
end
| gpl-2.0 |
GabrielGanne/vpp-flowtable | src/vpp-api/lua/bench.lua | 2 | 1998 | --[[
/*
* Copyright (c) 2016 Cisco and/or its affiliates.
* 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 vpp = require "vpp-lapi"
local ffi = require "ffi"
ffi.cdef([[
struct timespec {
long tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
int clock_gettime(int clk_id, struct timespec *tp);
]])
local time_cache = ffi.new("struct timespec[1]")
local time_cache_1 = time_cache[0]
function get_ns()
ffi.C.clock_gettime(0, time_cache)
return time_cache_1.tv_nsec + 1000000000 * time_cache_1.tv_sec
end
function do_bench()
local cycle_start = get_ns()
local n_iterations = 10000
local count = 1
for i = 1,n_iterations do
-- print(i)
vpp:api_call("show_version")
count = count + 1
-- print(i, "done")
end
cycle_end = get_ns()
local tps = n_iterations*1000000000LL/(cycle_end - cycle_start)
print (tostring(count) .. " iterations, average speed " .. tostring(tps) .. " per second")
return tps
end
root_dir = "/home/ubuntu/vpp"
pneum_path = root_dir .. "/build-root/install-vpp_lite_debug-native/vpp-api/lib64/libpneum.so"
vpp:init({ pneum_path = pneum_path })
vpp:json_api(root_dir .. "/build-root/install-vpp_lite_debug-native/vpp/vpp-api/vpe.api.json")
vpp:connect("lua-bench")
local n_tests = 10
local tps_acc = 0LL
for i=1,n_tests do
tps_acc = tps_acc + do_bench()
end
print("Average tps across the tests: " .. tostring(tps_acc/n_tests))
vpp:disconnect()
| apache-2.0 |
1yvT0s/luvit | deps/stream/init.lua | 6 | 1341 | --[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
exports.name = "luvit/stream"
exports.version = "1.1.0-4"
exports.dependencies = {
"luvit/core@1.0.5",
"luvit/utils@1.0.0",
}
exports.license = "Apache 2"
exports.homepage = "https://github.com/luvit/luvit/blob/master/deps/stream"
exports.description = "A port of node.js's stream module for luvit."
exports.tags = {"luvit", "stream"}
exports.Stream = require('./stream_core').Stream
exports.Writable = require('./stream_writable').Writable
exports.Transform = require('./stream_transform').Transform
exports.Readable = require('./stream_readable').Readable
exports.PassThrough = require('./stream_passthrough').PassThrough
exports.Observable = require('./stream_observable').Observable
exports.Duplex = require('./stream_duplex').Duplex
| apache-2.0 |
Scavenge/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/YrvaulairSCousseraux1.lua | 14 | 1204 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Yrvaulair S Cousseraux
-- @zone 80
-- @pos 0 1 -78
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, 11692); -- Not once in the four hundred years since the dawn of the Royal Knights has the kingdom found itself in such peril. Let us take up our pikes and stand our ground to ensure another four centuries of prosperity!
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 |
RuiShu/cvae | utils/evaluate.lua | 1 | 1183 | require 'hdf5'
require 'torch'
require 'nn'
require 'nngraph'
require 'cunn'
require 'cutorch'
nngraph.setDebug(false)
-- load custom modules
require 'load'
require 'Sampler'
require 'image'
-- load init data
f = hdf5.open('animate/ghost.h5', 'r')
init = f:read("init"):all():double():cuda()
-- cvae
sampler = nn.Sampler():cuda()
saved = torch.load('save/ghost_CVAE_z1.t7')
model = saved.model
prior = saved.prior
encoder = saved.encoder
decoder = saved.decoder
-- mlp
saved = torch.load('save/ghost_MLP.t7')
mlp = saved.model
-- setup
x_input = torch.Tensor(8192):cuda()
x_input[{{1,4096}}] = init[1]
x_input[{{4097,8192}}] = init[2]
N = 2000
win = nil
-- for i = 1,N do
-- pmu, plogv = unpack(prior:forward(x_input))
-- code = sampler:forward({pmu, plogv})
-- recon = decoder:forward({x_input, code})
-- x_input[{{1,4096}}] = x_input[{{4097,8192}}]
-- x_input[{{4097,8192}}] = recon
-- win = image.display({image=recon:reshape(64,64), win=win, zoom=4})
-- end
for i = 1,N do
recon = mlp:forward(x_input)
x_input[{{1,4096}}] = x_input[{{4097,8192}}]
x_input[{{4097,8192}}] = recon
win = image.display({image=recon:reshape(64,64), win=win, zoom=4})
end
| mit |
taxler/radish | packaging/extensions/platform_win32/lua/exports/mswindows/resources.lua | 1 | 9622 |
local lib = {
VS_FF_DEBUG = 0x1,
VS_FF_PRERELEASE = 0x2,
VS_FF_PATCHED = 0x4,
VS_FF_PRIVATEBUILD = 0x8,
VS_FF_INFOINFERRED = 0x10,
VS_FF_SPECIALBUILD = 0x20,
VS_FFI_SIGNATURE = 0xfeef04bd,
VS_FFI_STRUCVERSION = 0x00010000,
VOS__WINDOWS16 = 0x1,
VOS__PM16 = 0x2,
VOS__PM32 = 0x3,
VOS__WINDOWS32 = 0x4,
VOS_DOS = 0x10000,
VOS_OS216 = 0x20000,
VOS_NT = 0x40000,
VOS_OS232 = 0x30000,
VOS_NT_WINDOWS32 = 0x40004,
VOS_UNKNOWN = 0,
VFT_APP = 0x1,
VFT_DLL = 0x2,
VFT_DRV = 0x3,
VFT_FONT = 0x4,
VFT_VXD = 0x5,
VFT_STATIC_LIB = 0x7,
VFT_UNKNOWN = 0,
VFT2_DRV_COMM = 0xA,
VFT2_DRV_DISPLAY = 0x4,
VFT2_DRV_INSTALLABLE = 0x8,
VFT2_DRV_KEYBOARD = 0x2,
VFT2_DRV_LANGUAGE = 0x3,
VFT2_DRV_MOUSE = 0x5,
VFT2_DRV_NETWORK = 0x6,
VFT2_DRV_PRINTER = 0x1,
VFT2_DRV_SOUND = 0x9,
VFT2_DRV_SYSTEM = 0x7,
VFT2_DRV_VERSIONED_PRINTER = 0xC,
VFT2_UNKNOWN = 0,
VFT2_FONT_RASTER = 0x1,
VFT2_FONT_TRUETYPE = 0x3,
VFT2_FONT_VECTOR = 0x2
}
local bit = require 'bit'
local ffi = require 'ffi'
require 'exports.mswindows.handles'
require 'exports.typedef.bool32'
local winstr = require 'exports.mswindows.strings'
local winlang = require 'exports.mswindows.languages'
ffi.cdef [[
RESOURCE_UPDATE_A* BeginUpdateResourceA(const char* path, bool32 delete_existing);
RESOURCE_UPDATE_W* BeginUpdateResourceW(const wchar_t* path, bool32 delete_existing);
bool32 UpdateResourceA(
RESOURCE_UPDATE_A*,
const char* type,
const char* name,
uint16_t language,
void* data,
uint32_t data_length);
bool32 UpdateResourceW(
RESOURCE_UPDATE_W*,
const wchar_t* type,
const wchar_t* name,
uint16_t language,
void* data,
uint32_t data_length);
bool32 EndUpdateResourceA(RESOURCE_UPDATE_A*, bool32 discard_changes);
bool32 EndUpdateResourceW(RESOURCE_UPDATE_W*, bool32 discard_changes);
RESOURCE* FindResourceA(
MODULE*,
const char* name,
const char* type);
RESOURCE* FindResourceW(
MODULE*,
const wchar_t* name,
const wchar_t* type);
RESOURCE* FindResourceExA(
MODULE*,
const char* name,
const char* type,
uint16_t languageID);
RESOURCE* FindResourceExW(
MODULE*,
const wchar_t* name,
const wchar_t* type,
uint16_t languageID);
void* LoadResource(MODULE*, RESOURCE*);
void* LockResource(void*);
uint32_t SizeofResource(MODULE*, RESOURCE*);
typedef bool32 (__stdcall *EnumResTypeProcA)(
MODULE*,
char* type,
intptr_t lparam);
typedef bool32 (__stdcall *EnumResTypeProcW)(
MODULE*,
wchar_t* type,
intptr_t lparam);
bool32 EnumResourceTypesA(
MODULE*,
EnumResTypeProcA,
intptr_t lparam);
bool32 EnumResourceTypesW(
MODULE*,
EnumResTypeProcW,
intptr_t lparam);
typedef bool32 (__stdcall *EnumResNameProcA)(
MODULE*,
const char* type,
char* name,
intptr_t lparam);
typedef bool32 (__stdcall *EnumResNameProcW)(
MODULE*,
const wchar_t* type,
wchar_t* name,
intptr_t lparam);
bool32 EnumResourceNamesA(
MODULE*,
const char* type,
EnumResNameProcA,
intptr_t lparam);
bool32 EnumResourceNamesW(
MODULE*,
const wchar_t* type,
EnumResNameProcW,
intptr_t lparam);
typedef bool32 (__stdcall *EnumResLangProcA)(
MODULE*,
const char* type,
const char* name,
uint16_t languageID,
intptr_t lparam);
typedef bool32 (__stdcall *EnumResLangProcW)(
MODULE*,
const wchar_t* type,
const wchar_t* name,
uint16_t languageID,
intptr_t lparam);
bool32 EnumResourceLanguagesA(
MODULE*,
const char* type,
const char* name,
EnumResLangProcA,
intptr_t lparam);
bool32 EnumResourceLanguagesW(
MODULE*,
const wchar_t* type,
const wchar_t* name,
EnumResLangProcW,
intptr_t lparam);
typedef struct VS_FIXEDFILEINFO {
uint32_t dwSignature, dwStrucVersion, dwFileVersionMS, dwFileVersionLS;
uint32_t dwProductVersionMS, dwProductVersionLS, dwFileFlagsMask, dwFileFlags;
uint32_t dwFileOS, dwFileType, dwFileSubtype, dwFileDateMS, dwFileDateLS;
} VS_FIXEDFILEINFO;
]]
local function make_int(i)
return ffi.cast('const wchar_t*', i)
end
lib.RT_ICON = make_int(3)
lib.RT_GROUP_ICON = make_int(14)
lib.RT_VERSION = make_int(16)
lib.VS_VERSION_INFO = make_int(1)
lib.make_int = make_int
lib.VS_FIXEDFILEINFO = ffi.metatype('VS_FIXEDFILEINFO', {
__index = {
set_file_version = function(self, vstring)
local v = {}
for num in vstring:gmatch('%d+') do
v[#v+1] = tonumber(num)
end
v[1] = v[1] or 1
v[2] = v[2] or 0
v[3] = v[3] or 0
v[4] = v[4] or 0
self.dwFileVersionMS = bit.bor(bit.lshift(v[1], 16), v[2])
self.dwFileVersionLS = bit.bor(bit.lshift(v[3], 16), v[4])
end;
set_product_version = function(self, vstring)
local v = {}
for num in vstring:gmatch('%d+') do
v[#v+1] = tonumber(num)
end
v[1] = v[1] or 1
v[2] = v[2] or 0
v[3] = v[3] or 0
v[4] = v[4] or 0
self.dwFileVersionMS = bit.bor(bit.lshift(v[1], 16), v[2])
self.dwFileVersionLS = bit.bor(bit.lshift(v[3], 16), v[4])
end;
get_data = function(self)
return ffi.string(self, ffi.sizeof('VS_FIXEDFILEINFO'))
end;
};
__new = function(self_type)
local v1, v2, v3, v4 = 1, 0, 0, 0
local v = ffi.new(self_type, {
dwSignature = lib.VS_FFI_SIGNATURE;
dwStrucVersion = lib.VS_FFI_STRUCVERSION;
dwFileOS = lib.VOS__WINDOWS32;
dwFileType = lib.VFT_APP;
dwFileVersionMS = bit.bor(bit.lshift(v1, 16), v2);
dwFileVersionLS = bit.bor(bit.lshift(v3, 16), v4);
dwProductVersionMS = bit.bor(bit.lshift(v1, 16), v2);
dwProductVersionLS = bit.bor(bit.lshift(v3, 16), v4);
dwFileFlagsMask = bit.bor(
lib.VS_FF_DEBUG,
lib.VS_FF_PRERELEASE,
lib.VS_FF_PATCHED,
lib.VS_FF_PRIVATEBUILD,
lib.VS_FF_INFOINFERRED,
lib.VS_FF_SPECIALBUILD);
--dwFileFlags = bit.bor(mswin.VS_FF_PRERELEASE);
--dwFileDateMS = now.dwHighDateTime;
--dwFileDateLS = now.dwLowDateTime;
})
return v
end;
})
local kernel32 = ffi.C
local function get_resource_for_module(module, resource_type, name, language)
if type(resource_type) == 'number' then
resource_type = make_int(resource_type)
elseif type(resource_type) == 'string' then
resource_type = winstr.wide(resource_type)
end
if type(name) == 'number' then
name = make_int(name)
elseif type(name) == 'string' then
name = winstr.wide(name)
end
local res
if language then
res = kernel32.FindResourceExW(module, name, resource_type, winlang[language])
else
res = kernel32.FindResourceW(module, name, resource_type)
end
if res == nil then
return nil, 'resource not found'
end
local loaded = kernel32.LoadResource(module, res)
if loaded == nil then
return nil, 'unable to load resource'
end
local locked = kernel32.LockResource(loaded)
if locked == nil then
return nil, 'unable to lock resource'
end
return ffi.string(locked, kernel32.SizeofResource(module, res))
end
lib.get_for_module = assert(get_resource_for_module)
function lib.get(resource_type, name, language)
return get_resource_for_module(nil, resource, name, language)
end
local function encode_uint16LE(v)
return string.char(bit.band(v, 0xff), bit.rshift(v, 8))
end
local string_meta = {}
function lib.block_string(v)
return setmetatable({v}, string_meta)
end
local function encode_block(block)
local name = winstr.wide(assert(block.name, 'block must have a name'))
name = ffi.string(name, ffi.sizeof(name))
local block_type_id
local text = block.text
local data = block.bytes
if text then
if data ~= nil then
error('block cannot include both text and bytes', 2)
end
block_type_id = 1
if text == '' then
data = ''
else
data = winstr.wide(text)
data = ffi.string(data, ffi.sizeof(data))
end
elseif data == nil then
error('block must include either text or bytes', 2)
else
block_type_id = 0
end
local data_padding = string.rep('\0', (4 - (#data % 4)) % 4)
local child_data
if block[1] then
local buf = {}
for i = 1, #block do
buf[i] = encode_block(block[i])
end
child_data = table.concat(buf)
else
child_data = ''
end
local header_length = 2 + 2 + 2 + #name
local header_padding = string.rep('\0', (4 - (header_length % 4)) % 4)
local total_length = header_length + #header_padding + #data + #data_padding + #child_data
local header = encode_uint16LE(total_length)
.. encode_uint16LE(#data)
.. encode_uint16LE(block_type_id)
.. name
return header .. header_padding .. data .. data_padding .. child_data
end
lib.encode_block = encode_block
local function decode_block(encoded, i)
i = i or 1
local block = {}
local total_length = string.byte(encoded, i ) + string.byte(encoded, i+1) * 0x100
local value_length = string.byte(encoded, i+2) + string.byte(encoded, i+3) * 0x100
local is_bytes = string.sub(encoded, i+4, i+5) == '\0\0'
local j = 6
while string.sub(encoded, i+j, i+j+1) ~= '\0\0' do
j = j + 2
end
local name_ptr = ffi.cast('const char*', encoded) + (i - 1) + 6
block.name = winstr.utf8(name_ptr, (j - 6) / 2)
j = j + 2
j = j + (4 - (j % 4)) % 4
if value_length == 0 then
block[is_bytes and 'bytes' or 'text'] = ''
else
if is_bytes then
block.bytes = string.sub(encoded, i+j, i+j+value_length-1)
else
block.text = winstr.utf8(ffi.cast('const char*', encoded) + (i - 1) + j, value_length / 2)
-- remove null terminator
block.text = block.text:match('(.-)%z?$')
end
j = j + value_length
j = j + (4 - (j % 4)) % 4
end
local end_pos = i + total_length
i = i + j
while i < end_pos do
block[#block+1], i = decode_block(encoded, i)
end
return block, end_pos
end
lib.decode_block = decode_block
return lib
| mit |
Scavenge/darkstar | scripts/zones/Rabao/npcs/Dancing_Wolf.lua | 13 | 1660 | -----------------------------------
-- Area: Rabao
-- NPC: Dancing Wolf
-- Type: Standard NPC
-- @zone 247
-- @pos 7.619 7 81.209
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Rabao/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(BASTOK) == THE_SALT_OF_THE_EARTH and player:getVar("BASTOK91") == 1) then
player:startEvent(0x0066);
elseif (player:getCurrentMission(BASTOK) == THE_SALT_OF_THE_EARTH and player:getVar("BASTOK91") == 2) then
player:startEvent(0x0067);
elseif (player:getCurrentMission(BASTOK) == THE_SALT_OF_THE_EARTH and player:getVar("BASTOK91") == 3 and player:hasKeyItem(MIRACLESALT)) then
player:startEvent(0x0068);
elseif (player:getVar("BASTOK91") == 4) then
player:startEvent(0x0069);
else
player:startEvent(0x006A);
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 == 0x0066) then
player:setVar("BASTOK91",2);
elseif (csid == 0x0068) then
player:setVar("BASTOK91",4);
end
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Port_San_dOria/npcs/Altiret.lua | 13 | 3167 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Altiret
-- NPC for Quest "The Pickpocket"
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
-- "The Pickpocket" Quest status
thePickpocket = player:getQuestStatus(SANDORIA, THE_PICKPOCKET);
-- "The Pickpocket" Quest, trading for light axe
if (thePickpocket == 1) then
local count = trade:getItemCount();
local freeSlot = player:getFreeSlotsCount();
local giltGlasses = trade:hasItemQty(579, 1);
if (count == 1 and freeSlot > 0 and giltGlasses == true) then
player:tradeComplete();
player:addFame(SANDORIA,30);
player:addTitle(PICKPOCKET_PINCHER);
player:completeQuest(SANDORIA,THE_PICKPOCKET);
player:startEvent(0x0226);
elseif (giltGlasses == false) then
player:startEvent(0x0227);
else
player:messageSpecial(6402, 579); -- CANNOT_OBTAIN_ITEM
end;
-- "Flyers for Regine"
elseif (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
elseif (MagicFlyer == false) then
player:startEvent(0x0227);
end
else
player:startEvent(0x0227);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Vars for the Quest "The Pickpocket"
local thePickpocket = player:getQuestStatus(SANDORIA, THE_PICKPOCKET);
local openingCS = player:getVar("thePickpocket");
-- "The Pickpocket" Quest dialog
if (thePickpocket == 0 and openingCS == 1) then
player:startEvent(0x0223);
player:addQuest(SANDORIA,THE_PICKPOCKET);
elseif (thePickpocket == 1) then
player:startEvent(0x0223);
elseif (thePickpocket == 2) then
player:startEvent(0x0244);
else
player:startEvent(0x022f);
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);
-- "The Pickpocket" reward with light axe, done with quest
if (csid == 0x0226) then
player:addItem(16667);
player:messageSpecial(6403, 16667);
end;
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Windurst_Woods/npcs/Roberta.lua | 14 | 2324 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Roberta
-- Working 100%
-- @zone 241
-- @pos 21 -4 -157
-----------------------------------
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local BlueRibbonBlues = player:getQuestStatus(WINDURST,BLUE_RIBBON_BLUES);
if (BlueRibbonBlues == QUEST_ACCEPTED) then
local blueRibbonProg = player:getVar("BlueRibbonBluesProg");
if (blueRibbonProg >= 2 and player:hasItem(13569)) then
player:startEvent(0x017c);
elseif (player:hasItem(13569)) then
player:startEvent(0x017b);
elseif (player:hasItem(13569) == false) then
if (blueRibbonProg == 1 or blueRibbonProg == 3) then
player:startEvent(0x0179,0,13569); -- replaces ribbon if lost
elseif (blueRibbonProg < 1) then
player:startEvent(0x0178,0,13569); --gives us ribbon
end
else
player:startEvent(0x1b4);
end
else
player:startEvent(0x1b4);
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 == 0x0178 and option == 1 or csid == 0x0179 and option == 1) then
if (player:getFreeSlotsCount() >= 1) then
local blueRibbonProg = player:getVar("BlueRibbonBluesProg");
if (blueRibbonProg < 1) then
player:setVar("BlueRibbonBluesProg",1);
elseif (blueRibbonProg == 3) then
player:setVar("BlueRibbonBluesProg",4);
end
player:addItem(13569);
player:messageSpecial(ITEM_OBTAINED,13569);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13569);
end
end
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Cloister_of_Tides/Zone.lua | 30 | 1736 | -----------------------------------
--
-- Zone: Cloister_of_Tides (211)
--
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Tides/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Cloister_of_Tides/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(564.776,34.297,500.819,250);
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 |
Scavenge/darkstar | scripts/zones/Port_Bastok/npcs/Gudav.lua | 16 | 2000 | -----------------------------------
-- Area: Port Bastok
-- NPC: Gudav
-- Starts Quests: A Foreman's Best Friend
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(13096,1) and trade:getItemCount() == 1) then
if (player:getQuestStatus(BASTOK,A_FOREMAN_S_BEST_FRIEND) == QUEST_ACCEPTED) then
player:tradeComplete();
player:startEvent(0x0070);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getMainLvl() >= 7 and player:getQuestStatus(BASTOK,A_FOREMAN_S_BEST_FRIEND) == QUEST_AVAILABLE) then
player:startEvent(0x006e);
else
player:startEvent(0x001f);
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 == 0x006e) then
player:addQuest(BASTOK,A_FOREMAN_S_BEST_FRIEND);
elseif (csid == 0x0070) then
if (player:hasKeyItem(MAP_OF_THE_GUSGEN_MINES) == false) then
player:addKeyItem(MAP_OF_THE_GUSGEN_MINES);
player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_GUSGEN_MINES);
end
player:addFame(BASTOK,60);
player:completeQuest(BASTOK,A_FOREMAN_S_BEST_FRIEND);
end
end; | gpl-3.0 |
Scavenge/darkstar | scripts/zones/Kazham/npcs/Jakoh_Wahcondalo.lua | 14 | 1783 | -----------------------------------
-- Area: Kazham
-- NPC: Jakoh Wahcondalo
-- @pos 101 -16 -115 250
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(ZILART) == KAZAMS_CHIEFTAINESS) then
player:startEvent(0x0072);
elseif (player:getCurrentMission(ZILART) == THE_TEMPLE_OF_UGGALEPIH) then
player:startEvent(0x0073);
elseif (player:getCurrentMission(WINDURST) == AWAKENING_OF_THE_GODS and player:getVar("MissionStatus") == 2) then
player:startEvent(0x0109);
else
player:startEvent(0x0071);
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 == 0x0072) then
player:addKeyItem(SACRIFICIAL_CHAMBER_KEY);
player:messageSpecial(KEYITEM_OBTAINED,SACRIFICIAL_CHAMBER_KEY);
player:completeMission(ZILART,KAZAMS_CHIEFTAINESS);
player:addMission(ZILART,THE_TEMPLE_OF_UGGALEPIH);
elseif (csid == 0x0109) then
player:setVar("MissionStatus",3);
end
end;
| gpl-3.0 |
Zero-K-Experiments/Zero-K-Experiments | units/armcsa.lua | 3 | 3962 | unitDef = {
unitname = [[armcsa]],
name = [[Athena]],
description = [[Airborne SpecOps Engineer, Builds at 7.5 m/s]],
acceleration = 0.1,
airStrafe = 0,
autoHeal = 20,
brakeRate = 0.08,
buildCostEnergy = 500,
buildCostMetal = 500,
buildDistance = 180,
builder = true,
buildoptions = {
[[armnanotc]],
[[corrad]],
[[armarad]],
[[armjamt]],
[[armrectr]],
[[armflea]],
[[corak]],
[[hoverassault]],
[[spherepole]],
[[slowmort]],
[[armsptk]],
[[panther]],
[[armzeus]],
[[armsnipe]],
[[armmerl]],
[[armspy]],
[[armjeth]],
[[core_spectre]],
[[spherecloaker]],
[[amphtele]],
[[armcomdgun]],
},
buildPic = [[ARMCSA.png]],
buildRange3D = false,
buildTime = 500,
canFly = true,
canGuard = true,
canMove = true,
canPatrol = true,
canResurrect = true,
canSubmerge = false,
category = [[GUNSHIP UNARMED]],
cloakCost = 2,
cloakCostMoving = 5,
collide = true,
corpse = [[DEAD]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[30 30 30]],
collisionVolumeType = [[ellipsoid]],
cruiseAlt = 80,
customParams = {
airstrafecontrol = [[1]],
description_fr = [[ADAV de Construcion Furtif Camouflable, Construit r 7.5 m/s]],
description_de = [[Fliegender SpecOps Bauleiter, Baut mit 7.5 m/s]],
helptext = [[The Athena is the pinnacle of stealth strike capability. Equipped with a cloaking device and a radar jammer, it can slip through enemy lines to assemble squads of raiders, inflicting havoc on the opposition's logistics. The Athena can also resurrect wrecks on the battlefield, adding them to your army.]],
helptext_de = [[Athene ist die Spitze der Tarnungsschlagkraft. Ausgerรยผstet mit einem Verhรยผllungsgerรยคte und einem Radarstรยถrer kann es durch gegnerische Verteidigungslinien fliegen und Truppen aus Angreifern zusammenstellen, die dann Verwรยผstung nachsichziehen werden und die gegnerische Logistik vernichten kรยถnnen.]],
helptext_fr = [[Le Athena est un ingรยฉnieur de combat non armรยฉ. รยquipรยฉ d'un brouilleur radar et d'un camouflage optique il peut construire certaines infrastructures et des unitรยฉs nimporte ou, et ainsi surprendre l'enneme.]],
modelradius = [[15]],
},
energyMake = 0.225,
energyUse = 0,
explodeAs = [[GUNSHIPEX]],
floater = true,
footprintX = 2,
footprintZ = 2,
hoverAttack = true,
iconType = [[t3builder]],
initCloaked = false,
maxDamage = 750,
maxSlope = 36,
maxVelocity = 7,
metalMake = 0.225,
minCloakDistance = 125,
noAutoFire = false,
noChaseCategory = [[TERRAFORM SATELLITE FIXEDWING GUNSHIP HOVER SHIP SWIM SUB LAND FLOAT SINK TURRET]],
objectName = [[selene.s3o]],
radarDistance = 1200,
radarDistanceJam = 300,
script = [[armcsa.lua]],
seismicSignature = 0,
selfDestructAs = [[GUNSHIPEX]],
showNanoSpray = false,
sightDistance = 380,
sonarDistance = 600,
resurrectSpeed = 3.75,
terraformSpeed = 300,
turnRate = 148,
workerTime = 7.5,
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[selene_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2c.s3o]],
},
},
}
return lowerkeys({ armcsa = unitDef })
| gpl-2.0 |
Scavenge/darkstar | scripts/zones/Kazham/npcs/Kyun_Magopiteh.lua | 17 | 1072 | -----------------------------------
-- Area: Kazham
-- NPC: Kyun Magopiteh
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("BathedInScent") == 1) then
player:startEvent(0x00AE); -- scent from Blue Rafflesias
else
player:startEvent(0x0056);
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 |
cohadar/tanks-of-harmony-and-love | server.lua | 1 | 5474 | -------------------------------------------------------------------------------
-- embedded game server for "_tanks of Harmony and Love"
-- can NOT be run as standalone Lua app!
-- TODO: figure out how to call this in love2d console mode!
-------------------------------------------------------------------------------
require "enet"
require "love.timer"
local tank = require "tank"
local utils = require "utils"
local bullets = require "bullets"
local text = require "text"
local ticker = require "ticker"
local player = require "player"
local terrain = require "terrain"
local _tanks = {}
local _tankCommands = {}
local _players = {}
-------------------------------------------------------------------------------
local function onInit()
for i = 1, 256 do
_tanks[ i ] = tank.new()
_tankCommands[ i ] = tank.newCommand()
_players[ i ] = player.new()
end
end
-------------------------------------------------------------------------------
local function onConnect( event )
local index = event.peer:index()
text.print( "connect", index, os.time() )
_tanks[ index ] = tank.new()
_tankCommands[ index ] = tank.newCommand()
_players[ index ] = player.new()
-- TODO: let players pick side obviously
if index % 2 == 0 then
_tanks[ index ].team = "red"
_players[ index ].team = "red"
else
_tanks[ index ].team = "blue"
_players[ index ].team = "blue"
end
terrain.respawn( _tanks[ index ] )
local datagram = utils.pack{ type = "index", index = index }
event.peer:send( datagram, 0, "unsequenced" )
end
-------------------------------------------------------------------------------
local function onDisconnect( host, event )
local index = event.peer:index()
text.print( "disconnect", index )
_tanks[ index ] = nil
local gram = utils.pack{ type = "player_gone", index = index }
host:broadcast( gram )
end
-------------------------------------------------------------------------------
local function onReceive( event, server_tick )
msg = utils.unpack( event.data )
if msg.type == "tank_command" then
_tankCommands[ event.peer:index() ] = msg.tank_command
else
text.print( "ERROR: unknown msg.type", msg.type, event.data )
end
end
-------------------------------------------------------------------------------
local function onKill( tnk, index, killer_index )
_players[ index ].deaths = _players[ index ].deaths + 1
_players[ killer_index ].kills = _players[ killer_index ].kills + 1
terrain.respawn( tnk )
end
-------------------------------------------------------------------------------
local function onUpdate()
bullets.update()
for index, tnk in pairs( _tanks ) do
tank_command = _tankCommands[ index ]
tank.update( tnk, tank_command )
tank_command.client_tick = tank_command.client_tick + 1
local x, y, index = bullets.collider( tnk.x, tnk.y, tank.IMG_TANK_RADIUS )
if x and y and index then
if tank.confirmHit( tnk, x, y ) then
tnk.hit_x = x
tnk.hit_y = y
tnk.hp = tnk.hp - 10 -- TODO: make damage directional
if tnk.hp <= 0 then
local killer_index = index -- temporary bug for testing
onKill( tnk, index, index ) -- TODO: make bullets carry killer_index
end
bullets.remove( index )
end
end
end
end
-------------------------------------------------------------------------------
local function onBroadcast( host )
for index, tnk in pairs( _tanks ) do
local gram = utils.pack {
type = "broadcast",
index = index,
tank = tnk,
bullets_table = bullets.exportTable(),
client_tick = _tankCommands[ index ].client_tick - 1
}
host:broadcast( gram, 0, "unsequenced" )
tnk.hit_x = nil
tnk.hit_y = nil
end
end
-------------------------------------------------------------------------------
local function startServer( host, port )
onInit()
server_address = host .. ":" .. port
text.print( "starting server", server_address )
local host = enet.host_create( server_address )
local tick = 0
local mark = love.timer.getTime()
ticker.init( mark )
while true do
local event = host:service( 0 )
if event then
if event.type == "receive" then
onReceive( event, tick )
elseif event.type == "connect" then
onConnect( event )
elseif event.type == "disconnect" then
onDisconnect( host, event )
else
text.print( "ERROR: unknown event.type", event.type )
end
end
mark = love.timer.getTime()
while ticker.tick( mark ) do
tick = tick + 1
onUpdate()
-- we broadcast 3 times slower than we update
if tick % 3 == 0 then
onBroadcast( host )
end
end
end
end
-------------------------------------------------------------------------------
-- TODO: better start/stop control for host
-------------------------------------------------------------------------------
channel = love.thread.getChannel( "server_channel" )
value = channel:demand()
startServer( value.host, value.port )
| mit |
Scavenge/darkstar | scripts/globals/items/marinara_pizza_+1.lua | 12 | 1596 | -----------------------------------------
-- ID: 5744
-- Item: marinara_pizza +1
-- Food Effect: 4hours, All Races
-----------------------------------------
-- Health Points 25
-- Attack +21% (cap 55)
-- Accuracy +11% (cap 58)
-- Undead Killer
-----------------------------------------
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,5744);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 25);
target:addMod(MOD_FOOD_ATTP, 21);
target:addMod(MOD_FOOD_ATT_CAP, 55);
target:addMod(MOD_FOOD_ACCP, 11);
target:addMod(MOD_FOOD_ACC_CAP, 58);
target:addMod(MOD_UNDEAD_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 25);
target:delMod(MOD_FOOD_ATTP, 21);
target:delMod(MOD_FOOD_ATT_CAP, 55);
target:delMod(MOD_FOOD_ACCP, 11);
target:delMod(MOD_FOOD_ACC_CAP, 58);
target:delMod(MOD_UNDEAD_KILLER, 5);
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Mhaura/npcs/Celestina.lua | 14 | 2721 | -----------------------------------
-- Area: Mhaura
-- NPC: Celestina
-- Finish Quest: The Sand Charm
-- Involved in Quest: Riding on the Clouds
-- Guild Merchant NPC: Goldsmithing Guild
-- @pos -37.624 -16.050 75.681 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(OTHER_AREAS,THE_SAND_CHARM) == QUEST_ACCEPTED) then
if (trade:hasItemQty(13095,1) and trade:getItemCount() == 1) then
player:startEvent(0x007f); -- Finish quest "The Sand Charm"
end
end
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 5) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_3",0);
player:tradeComplete();
player:addKeyItem(SOMBER_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SOMBER_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("theSandCharmVar") == 3) then
player:startEvent(0x007e,13095); -- During quest "The Sand Charm" - 3rd dialog
elseif (player:sendGuild(528,8,23,4)) then
player:showText(npc,GOLDSMITHING_GUILD);
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 == 0x007e and option == 70) then
player:setVar("theSandCharmVar",4);
elseif (csid == 0x007f) then
player:tradeComplete();
player:setVar("theSandCharmVar",0);
player:setVar("SmallDialogByBlandine",1);
player:addKeyItem(MAP_OF_BOSTAUNIEUX_OUBLIETTE);
player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_BOSTAUNIEUX_OUBLIETTE);
player:addFame(OTHER_AREAS,30);
player:completeQuest(OTHER_AREAS,THE_SAND_CHARM);
end
end; | gpl-3.0 |
Scavenge/darkstar | scripts/zones/Bastok_Markets/npcs/Fatimah.lua | 53 | 2085 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Fatimah
-- Type: Goldsmithing Adv. Synthesis Image Support
-- @pos -193.849 -7.824 -56.372 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,6);
local SkillLevel = player:getSkillLevel(SKILL_GOLDSMITHING);
local Cost = getAdvImageSupportCost(player, SKILL_GOLDSMITHING);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_GOLDSMITHING_IMAGERY) == false) then
player:startEvent(0x012E,Cost,SkillLevel,0,0xB0001AF,player:getGil(),0,0,0); -- Event doesn't work
else
player:startEvent(0x012E,Cost,SkillLevel,0,0xB0001AF,player:getGil(),28674,0,0);
end
else
player:startEvent(0x012E);
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);
local Cost = getAdvImageSupportCost(player, SKILL_GOLDSMITHING);
if (csid == 0x012E and option == 1) then
if (player:getGil() >= Cost) then
player:messageSpecial(GOLDSMITHING_SUPPORT,0,3,0);
player:addStatusEffect(EFFECT_GOLDSMITHING_IMAGERY,3,0,480);
player:delGil(Cost);
else
player:messageSpecial(NOT_HAVE_ENOUGH_GIL);
end
end
end; | gpl-3.0 |
Zero-K-Experiments/Zero-K-Experiments | effects/warrior.lua | 25 | 3166 | -- warmuzzle
return {
["warmuzzle"] = {
bitmapmuzzleflame = {
air = true,
class = [[CBitmapMuzzleFlame]],
count = 1,
ground = true,
underwater = 1,
water = true,
properties = {
colormap = [[1 1 0.5 0.01 1 0.7 0 0.01 0 0 0 0.01]],
dir = [[dir]],
frontoffset = 0.3,
fronttexture = [[plasma0029]],
length = 1,
sidetexture = [[plasma2]],
size = 0.5,
sizegrowth = 70,
ttl = 5,
},
},
bitmapmuzzleflame2 = {
air = true,
class = [[CBitmapMuzzleFlame]],
count = 1,
ground = true,
underwater = 1,
water = true,
properties = {
colormap = [[1 1 0 0.01 1 0.5 0 0.01 0 0 0 0.01]],
dir = [[dir]],
frontoffset = -0.1,
fronttexture = [[flowerflash]],
length = 0.1,
sidetexture = [[plasma2]],
size = 20,
sizegrowth = 1,
ttl = 3,
},
},
muzzleflash = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.90,
colormap = [[1 0.7 0.2 0.01 1 0.7 0.2 0.01 0 0 0 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 10,
emitvector = [[dir]],
gravity = [[0, 0, 0]],
numparticles = 5,
particlelife = 18,
particlelifespread = 5,
particlesize = 1,
particlesizespread = 0.3,
particlespeed = 2,
particlespeedspread = 4,
pos = [[0, 0, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[plasma]],
},
},
muzzlesmoke = {
air = true,
class = [[CSimpleParticleSystem]],
count = 10,
ground = true,
water = true,
properties = {
airdrag = 0.8,
colormap = [[0 0 0 0.01 0.5 0.5 0.5 0.5 0 0 0 0.01]],
directional = false,
emitrot = 0,
emitrotspread = 10,
emitvector = [[dir]],
gravity = [[0, 0.2, 0]],
numparticles = 1,
particlelife = 5,
particlelifespread = 0,
particlesize = [[7 i-0.4]],
particlesizespread = 1,
particlespeed = [[10 i-1]],
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[smokesmall]],
},
},
},
}
| gpl-2.0 |
jchuang1977/openwrt | package/lean/mt/luci-app-mtwifi/root/usr/lib/lua/mtkwifi.lua | 2 | 37008 | #!/usr/bin/env lua
--[[
* A lua library to manipulate mtk's wifi driver. used in luci-app-mtk.
*
* Hua Shao <nossiac@163.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation
*
* 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.
]]
local mtkwifi = {}
local _, nixio = pcall(require, "nixio")
function mtkwifi.debug(...)
local ff = io.open("/tmp/mtkwifi.dbg.log", "a")
local vars = {...}
for _, v in pairs(vars) do
ff:write(v.." ")
end
ff:write("\n")
ff:close()
end
if not nixio then
nixio.syslog = mtkwifi.debug
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
function mtkwifi.__trim(s)
if s then return (s:gsub("^%s*(.-)%s*$", "%1")) end
end
function mtkwifi.__handleSpecialChars(s)
s = s:gsub("\\", "\\\\")
s = s:gsub("\"", "\\\"")
s = mtkwifi.__trim(s)
return s
end
-- if order function given, sort by it by passing the table and keys a, b,
-- otherwise just sort the keys
function mtkwifi.__spairs(t, order)
-- collect the keys
local keys = {}
for k in pairs(t) do keys[#keys+1] = k end
table.sort(keys, order)
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
function mtkwifi.__lines(str)
local t = {}
local function helper(line) table.insert(t, line) return "" end
helper((str:gsub("(.-)\r?\n", helper)))
return t
end
function mtkwifi.__get_l1dat()
if not pcall(require, "l1dat_parser") then
return
end
local parser = require("l1dat_parser")
local l1dat = parser.load_l1_profile(parser.L1_DAT_PATH)
return l1dat, parser
end
function mtkwifi.sleep(s)
local ntime = os.clock() + s
repeat until os.clock() > ntime
end
function mtkwifi.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[mtkwifi.deepcopy(orig_key)] = mtkwifi.deepcopy(orig_value)
end
setmetatable(copy, mtkwifi.deepcopy(getmetatable(orig)))
else -- number, string, boolean, etc
copy = orig
end
return copy
end
function mtkwifi.read_pipe(pipe)
local fp = io.popen(pipe)
local txt = fp:read("*a")
fp:close()
return txt
end
function mtkwifi.load_profile(path, raw)
local cfgs = {}
local content
if path then
local fd = io.open(path, "r")
if not fd then return end
content = fd:read("*all")
fd:close()
elseif raw then
content = raw
else
return
end
-- convert profile into lua table
for _,line in ipairs(mtkwifi.__lines(content)) do
line = mtkwifi.__trim(line)
if string.byte(line) ~= string.byte("#") then
local i = string.find(line, "=")
if i then
local k,v
k = string.sub(line, 1, i-1)
v = string.sub(line, i+1)
if cfgs[mtkwifi.__trim(k)] then
mtkwifi.debug("warning", "skip repeated key"..line)
end
cfgs[mtkwifi.__trim(k)] = mtkwifi.__trim(v) or ""
else
mtkwifi.debug("warning", "skip line without '=' "..line)
end
else
mtkwifi.debug("warning", "skip comment line "..line)
end
end
return cfgs
end
function mtkwifi.__profile_bak_path(profile)
local bak = "/tmp/mtk/wifi/"..string.match(profile, "([^/]+\.dat)")..".last"
os.execute("mkdir -p /tmp/mtk/wifi")
return bak
end
function mtkwifi.save_profile(cfgs, path)
if not cfgs then
mtkwifi.debug("configuration was empty, nothing saved")
return
end
local fd = io.open(path, "w")
table.sort(cfgs, function(a,b) return a<b end)
if not fd then return end
fd:write("# Generated by mtkwifi.lua\n")
fd:write("Default\n")
for k,v in mtkwifi.__spairs(cfgs, function(a,b) return string.upper(a) < string.upper(b) end) do
fd:write(k.."="..v.."\n")
end
fd:close()
if pcall(require, "mtknvram") then
local nvram = require("mtknvram")
local l1dat, l1 = mtkwifi.__get_l1dat()
local zone = l1 and l1.l1_path_to_zone(path)
if not l1dat then
mtkwifi.debug("save_profile: no l1dat", path)
nvram.nvram_save_profile(path)
else
if zone then
mtkwifi.debug("save_profile:", path, zone)
nvram.nvram_save_profile(path, zone)
else
mtkwifi.debug("save_profile:", path)
nvram.nvram_save_profile(path)
end
end
end
end
-- if path2 not give, we use path1's backup.
function mtkwifi.diff_profile(path1, path2)
assert(path1)
if not path2 then
path2 = mtkwifi.__profile_bak_path(path1)
if not mtkwifi.exists(path2) then
return {}
end
end
assert(path2)
local diff = {}
local cfg1 = mtkwifi.load_profile(path1) or {}
local cfg2 = mtkwifi.load_profile(path2) or {}
for k,v in pairs(cfg1) do
if cfg2[k] ~= cfg1[k] then
diff[k] = {cfg1[k] or "", cfg2[k] or ""}
end
end
for k,v in pairs(cfg2) do
if cfg2[k] ~= cfg1[k] then
diff[k] = {cfg1[k] or "", cfg2[k] or ""}
end
end
return diff
end
-- Mode 12 and 13 are only available for STAs.
local WirelessModeList = {
[0] = "B/G mixed",
[1] = "B only",
[2] = "A only",
-- [3] = "A/B/G mixed",
[4] = "G only",
-- [5] = "A/B/G/GN/AN mixed",
[6] = "N in 2.4G only",
[7] = "G/GN", -- i.e., no CCK mode
[8] = "A/N in 5 band",
[9] = "B/G/GN mode",
-- [10] = "A/AN/G/GN mode", --not support B mode
[11] = "only N in 5G band",
-- [12] = "B/G/GN/A/AN/AC mixed",
-- [13] = "G/GN/A/AN/AC mixed", -- no B mode
[14] = "A/AC/AN mixed",
[15] = "AC/AN mixed", --but no A mode
}
local DevicePropertyMap = {
-- 2.4G
{device="MT7603", band={"0", "1", "4", "6", "7", "9"}},
{device="MT7620", band={"0", "1", "4", "6", "7", "9"}},
{device="MT7622", band={"0", "1", "4", "9"}},
{device="MT7628", band={"0", "1", "4", "6", "7", "9"}},
-- 5G
{device="MT7610", band={"2", "8", "11", "14", "15"}},
{device="MT7612", band={"2", "8", "11", "14", "15"}},
{device="MT7662", band={"2", "8", "11", "14", "15"}},
-- Mix
{device="MT7615", band={"0", "1", "4", "9", "2", "8", "14", "15"}}
}
mtkwifi.CountryRegionList_5G_All = {
{region=0, text="0: Ch36~64, Ch149~165"},
{region=1, text="1: Ch36~64, Ch100~140"},
{region=2, text="2: Ch36~64"},
{region=3, text="3: Ch52~64, Ch149~161"},
{region=4, text="4: Ch149~165"},
{region=5, text="5: Ch149~161"},
{region=6, text="6: Ch36~48"},
{region=7, text="7: Ch36~64, Ch100~140, Ch149~165"},
{region=8, text="8: Ch52~64"},
{region=9, text="9: Ch36~64, Ch100~116, Ch132~140, Ch149~165"},
{region=10, text="10: Ch36~48, Ch149~165"},
{region=11, text="11: Ch36~64, Ch100~120, Ch149~161"},
{region=12, text="12: Ch36~64, Ch100~144"},
{region=13, text="13: Ch36~64, Ch100~144, Ch149~165"},
{region=14, text="14: Ch36~64, Ch100~116, Ch132~144, Ch149~165"},
{region=15, text="15: Ch149~173"},
{region=16, text="16: Ch52~64, Ch149~165"},
{region=17, text="17: Ch36~48, Ch149~161"},
{region=18, text="18: Ch36~64, Ch100~116, Ch132~140"},
{region=19, text="19: Ch56~64, Ch100~140, Ch149~161"},
{region=20, text="20: Ch36~64, Ch100~124, Ch149~161"},
{region=21, text="21: Ch36~64, Ch100~140, Ch149~161"},
{region=22, text="22: Ch100~140"},
{region=30, text="30: Ch36~48, Ch52~64, Ch100~140, Ch149~165"},
{region=31, text="31: Ch52~64, Ch100~140, Ch149~165"},
{region=32, text="32: Ch36~48, Ch52~64, Ch100~140, Ch149~161"},
{region=33, text="33: Ch36~48, Ch52~64, Ch100~140"},
{region=34, text="34: Ch36~48, Ch52~64, Ch149~165"},
{region=35, text="35: Ch36~48, Ch52~64"},
{region=36, text="36: Ch36~48, Ch100~140, Ch149~165"},
{region=37, text="37: Ch36~48, Ch52~64, Ch149~165, Ch173"},
}
mtkwifi.CountryRegionList_2G_All = {
{region=0, text="0: Ch1~11"},
{region=1, text="1: Ch1~13"},
{region=2, text="2: Ch10~11"},
{region=3, text="3: Ch10~13"},
{region=4, text="4: Ch14"},
{region=5, text="5: Ch1~14"},
{region=6, text="6: Ch3~9"},
{region=7, text="7: Ch5~13"},
{region=31, text="31: Ch1~11, Ch12~14"},
{region=32, text="32: Ch1~11, Ch12~13"},
{region=33, text="33: Ch1~14"},
}
mtkwifi.ChannelList_5G_All = {
{channel=0, text="Channel 0 (Auto )", region={}},
{channel= 36, text="Channel 36 (5.180 GHz)", region={[0]=1, [1]=1, [2]=1, [6]=1, [7]=1, [9]=1, [10]=1, [11]=1, [12]=1, [13]=1, [14]=1, [17]=1, [18]=1, [20]=1, [21]=1, [30]=1, [32]=1, [33]=1, [34]=1, [35]=1, [36]=1, [37]=1}},
{channel= 40, text="Channel 40 (5.200 GHz)", region={[0]=1, [1]=1, [2]=1, [6]=1, [7]=1, [9]=1, [10]=1, [11]=1, [12]=1, [13]=1, [14]=1, [17]=1, [18]=1, [20]=1, [21]=1, [30]=1, [32]=1, [33]=1, [34]=1, [35]=1, [36]=1, [37]=1}},
{channel= 44, text="Channel 44 (5.220 GHz)", region={[0]=1, [1]=1, [2]=1, [6]=1, [7]=1, [9]=1, [10]=1, [11]=1, [12]=1, [13]=1, [14]=1, [17]=1, [18]=1, [20]=1, [21]=1, [30]=1, [32]=1, [33]=1, [34]=1, [35]=1, [36]=1, [37]=1}},
{channel= 48, text="Channel 48 (5.240 GHz)", region={[0]=1, [1]=1, [2]=1, [6]=1, [7]=1, [9]=1, [10]=1, [11]=1, [12]=1, [13]=1, [14]=1, [17]=1, [18]=1, [20]=1, [21]=1, [30]=1, [32]=1, [33]=1, [34]=1, [35]=1, [36]=1, [37]=1}},
{channel= 52, text="Channel 52 (5.260 GHz)", region={[0]=1, [1]=1, [2]=1, [3]=1, [7]=1, [8]=1, [9]=1, [11]=1, [12]=1, [13]=1, [14]=1, [16]=1, [18]=1, [20]=1, [21]=1, [30]=1, [31]=1, [32]=1, [33]=1, [34]=1, [35]=1, [37]=1}},
{channel= 56, text="Channel 56 (5.280 GHz)", region={[0]=1, [1]=1, [2]=1, [3]=1, [7]=1, [8]=1, [9]=1, [11]=1, [12]=1, [13]=1, [14]=1, [16]=1, [18]=1, [19]=1, [20]=1, [21]=1, [30]=1, [31]=1, [32]=1, [33]=1, [34]=1, [35]=1, [37]=1}},
{channel= 60, text="Channel 60 (5.300 GHz)", region={[0]=1, [1]=1, [2]=1, [3]=1, [7]=1, [8]=1, [9]=1, [11]=1, [12]=1, [13]=1, [14]=1, [16]=1, [18]=1, [19]=1, [20]=1, [21]=1, [30]=1, [31]=1, [32]=1, [33]=1, [34]=1, [35]=1, [37]=1}},
{channel= 64, text="Channel 64 (5.320 GHz)", region={[0]=1, [1]=1, [2]=1, [3]=1, [7]=1, [8]=1, [9]=1, [11]=1, [12]=1, [13]=1, [14]=1, [16]=1, [18]=1, [19]=1, [20]=1, [21]=1, [30]=1, [31]=1, [32]=1, [33]=1, [34]=1, [35]=1, [37]=1}},
{channel=100, text="Channel 100 (5.500 GHz)", region={[1]=1, [7]=1, [9]=1, [11]=1, [12]=1, [13]=1, [14]=1, [18]=1, [19]=1, [20]=1, [21]=1, [22]=1, [30]=1, [31]=1, [32]=1, [33]=1, [36]=1}},
{channel=104, text="Channel 104 (5.520 GHz)", region={[1]=1, [7]=1, [9]=1, [11]=1, [12]=1, [13]=1, [14]=1, [18]=1, [19]=1, [20]=1, [21]=1, [22]=1, [30]=1, [31]=1, [32]=1, [33]=1, [36]=1}},
{channel=108, text="Channel 108 (5.540 GHz)", region={[1]=1, [7]=1, [9]=1, [11]=1, [12]=1, [13]=1, [14]=1, [18]=1, [19]=1, [20]=1, [21]=1, [22]=1, [30]=1, [31]=1, [32]=1, [33]=1, [36]=1}},
{channel=112, text="Channel 112 (5.560 GHz)", region={[1]=1, [7]=1, [9]=1, [11]=1, [12]=1, [13]=1, [14]=1, [18]=1, [19]=1, [20]=1, [21]=1, [22]=1, [30]=1, [31]=1, [32]=1, [33]=1, [36]=1}},
{channel=116, text="Channel 116 (5.580 GHz)", region={[1]=1, [7]=1, [9]=1, [11]=1, [12]=1, [13]=1, [14]=1, [18]=1, [19]=1, [20]=1, [21]=1, [22]=1, [30]=1, [31]=1, [32]=1, [33]=1, [36]=1}},
{channel=120, text="Channel 120 (5.600 GHz)", region={[1]=1, [7]=1, [11]=1, [12]=1, [13]=1, [19]=1, [20]=1, [21]=1, [22]=1, [30]=1, [31]=1, [32]=1, [33]=1, [36]=1}},
{channel=124, text="Channel 124 (5.620 GHz)", region={[1]=1, [7]=1, [12]=1, [13]=1, [19]=1, [20]=1, [21]=1, [22]=1, [30]=1, [31]=1, [32]=1, [33]=1, [36]=1}},
{channel=128, text="Channel 128 (5.640 GHz)", region={[1]=1, [7]=1, [12]=1, [13]=1, [19]=1, [21]=1, [22]=1, [30]=1, [31]=1, [32]=1, [33]=1, [36]=1}},
{channel=132, text="Channel 132 (5.660 GHz)", region={[1]=1, [7]=1, [9]=1, [12]=1, [13]=1, [14]=1, [18]=1, [19]=1, [21]=1, [22]=1, [30]=1, [31]=1, [32]=1, [33]=1, [36]=1}},
{channel=136, text="Channel 136 (5.680 GHz)", region={[1]=1, [7]=1, [9]=1, [12]=1, [13]=1, [14]=1, [18]=1, [19]=1, [21]=1, [22]=1, [30]=1, [31]=1, [32]=1, [33]=1, [36]=1}},
{channel=140, text="Channel 140 (5.700 GHz)", region={[1]=1, [7]=1, [9]=1, [12]=1, [13]=1, [14]=1, [18]=1, [19]=1, [21]=1, [22]=1, [30]=1, [31]=1, [32]=1, [33]=1, [36]=1}},
{channel=144, text="Channel 144 (5.720 GHz)", region={[12]=1, [13]=1, [14]=1}},
{channel=149, text="Channel 149 (5.745 GHz)", region={[0]=1, [3]=1, [4]=1, [5]=1, [7]=1, [9]=1, [10]=1, [11]=1, [13]=1, [14]=1, [15]=1, [16]=1, [17]=1, [19]=1, [20]=1, [21]=1, [30]=1, [31]=1, [32]=1, [34]=1, [36]=1, [37]=1}},
{channel=153, text="Channel 153 (5.765 GHz)", region={[0]=1, [3]=1, [4]=1, [5]=1, [7]=1, [9]=1, [10]=1, [11]=1, [13]=1, [14]=1, [15]=1, [16]=1, [17]=1, [19]=1, [20]=1, [21]=1, [30]=1, [31]=1, [32]=1, [34]=1, [36]=1, [37]=1}},
{channel=157, text="Channel 157 (5.785 GHz)", region={[0]=1, [3]=1, [4]=1, [5]=1, [7]=1, [9]=1, [10]=1, [11]=1, [13]=1, [14]=1, [15]=1, [16]=1, [17]=1, [19]=1, [20]=1, [21]=1, [30]=1, [31]=1, [32]=1, [34]=1, [36]=1, [37]=1}},
{channel=161, text="Channel 161 (5.805 GHz)", region={[0]=1, [3]=1, [4]=1, [5]=1, [7]=1, [9]=1, [10]=1, [11]=1, [13]=1, [14]=1, [15]=1, [16]=1, [17]=1, [19]=1, [20]=1, [21]=1, [30]=1, [31]=1, [32]=1, [34]=1, [36]=1, [37]=1}},
{channel=165, text="Channel 165 (5.825 GHz)", region={[0]=1, [4]=1, [7]=1, [9]=1, [10]=1, [13]=1, [14]=1, [15]=1, [16]=1, [30]=1, [31]=1, [34]=1, [36]=1, [37]=1}},
{channel=169, text="Channel 169 (5.845 GHz)", region={[15]=1}},
{channel=173, text="Channel 173 (5.865 GHz)", region={[15]=1, [37]=1}},
}
mtkwifi.ChannelList_2G_All = {
{channel=0, text="Channel 0 (Auto )", region={}},
{channel= 1, text="Channel 1 (2412 GHz)", region={[0]=1, [1]=1, [5]=1, [31]=1, [32]=1, [33]=1}},
{channel= 2, text="Channel 2 (2417 GHz)", region={[0]=1, [1]=1, [5]=1, [31]=1, [32]=1, [33]=1}},
{channel= 3, text="Channel 3 (2422 GHz)", region={[0]=1, [1]=1, [5]=1, [6]=1, [31]=1, [32]=1, [33]=1}},
{channel= 4, text="Channel 4 (2427 GHz)", region={[0]=1, [1]=1, [5]=1, [6]=1, [31]=1, [32]=1, [33]=1}},
{channel= 5, text="Channel 5 (2432 GHz)", region={[0]=1, [1]=1, [5]=1, [6]=1, [7]=1, [31]=1, [32]=1, [33]=1}},
{channel= 6, text="Channel 6 (2437 GHz)", region={[0]=1, [1]=1, [5]=1, [6]=1, [7]=1, [31]=1, [32]=1, [33]=1}},
{channel= 7, text="Channel 7 (2442 GHz)", region={[0]=1, [1]=1, [5]=1, [6]=1, [7]=1, [31]=1, [32]=1, [33]=1}},
{channel= 8, text="Channel 8 (2447 GHz)", region={[0]=1, [1]=1, [5]=1, [6]=1, [7]=1, [31]=1, [32]=1, [33]=1}},
{channel= 9, text="Channel 9 (2452 GHz)", region={[0]=1, [1]=1, [5]=1, [6]=1, [7]=1, [31]=1, [32]=1, [33]=1}},
{channel=10, text="Channel 10 (2457 GHz)", region={[0]=1, [1]=1, [2]=1, [3]=1, [5]=1, [7]=1, [31]=1, [32]=1, [33]=1}},
{channel=11, text="Channel 11 (2462 GHz)", region={[0]=1, [1]=1, [2]=1, [3]=1, [5]=1, [7]=1, [31]=1, [32]=1, [33]=1}},
{channel=12, text="Channel 12 (2467 GHz)", region={[1]=1, [3]=1, [5]=1, [7]=1, [31]=1, [32]=1, [33]=1}},
{channel=13, text="Channel 13 (2472 GHz)", region={[1]=1, [3]=1, [5]=1, [7]=1, [31]=1, [32]=1, [33]=1}},
{channel=14, text="Channel 14 (2477 GHz)", region={[4]=1, [5]=1, [31]=1, [33]=1}},
}
mtkwifi.ChannelList_5G_2nd_80MHZ_ALL = {
{channel=36, text="Ch36(5.180 GHz) - Ch48(5.240 GHz)", chidx=2},
{channel=52, text="Ch52(5.260 GHz) - Ch64(5.320 GHz)", chidx=6},
{channel=-1, text="Channel between 64 100", chidx=-1},
{channel=100, text="Ch100(5.500 GHz) - Ch112(5.560 GHz)", chidx=10},
{channel=112, text="Ch116(5.580 GHz) - Ch128(5.640 GHz)", chidx=14},
{channel=-1, text="Channel between 128 132", chidx=-1},
{channel=132, text="Ch132(5.660 GHz) - Ch144(5.720 GHz)", chidx=18},
{channel=-1, text="Channel between 144 149", chidx=-1},
{channel=149, text="Ch149(5.745 GHz) - Ch161(5.805 GHz)", chidx=22},
}
local AuthModeList = {
"Disable",
"OPEN",--OPENWEP
"SHARED",--SHAREDWEP
"WEPAUTO",
"WPA2",
"WPA2PSK",
"WPAPSKWPA2PSK",
"WPA1WPA2",
"IEEE8021X",
}
local WpsEnableAuthModeList = {
"Disable",
"OPEN",--OPENWEP
"WPA2PSK",
"WPAPSKWPA2PSK",
}
local ApCliAuthModeList = {
"Disable",
"OPEN",
"SHARED",
"WPAPSK",
"WPA2PSK",
"WPAPSKWPA2PSK",
-- "WPA",
-- "WPA2",
-- "WPAWPA2",
-- "8021X",
}
local WPA_Enc_List = {
"AES",
"TKIP",
"TKIPAES",
}
local WEP_Enc_List = {
"WEP",
}
local dbdc_prefix = {
{"ra", "rax"},
{"rai", "ray"},
{"rae", "raz"},
}
local dbdc_apcli_prefix = {
{"apcli", "apclix"},
{"apclii", "apcliy"},
{"apclie", "apcliz"},
}
function mtkwifi.band(mode)
local i = tonumber(mode)
if i == 0
or i == 1
or i == 4
or i == 6
or i == 7
or i == 9 then
return "2.4G"
else
return "5G"
end
end
function mtkwifi.__cfg2list(str)
-- delimeter == ";"
local i = 1
local list = {}
for k in string.gmatch(str, "([^;]+)") do
list[i] = k
i = i + 1
end
return list
end
function mtkwifi.token_set(str, n, v)
-- n start from 1
-- delimeter == ";"
if not str then return end
local tmp = mtkwifi.__cfg2list(str)
if type(v) ~= type("") and type(v) ~= type(0) then
mtkwifi.debug("err", "invalid value type in token_set, "..type(v))
return
end
if #tmp < tonumber(n) then
for i=#tmp, tonumber(n) do
if not tmp[i] then
tmp[i] = v -- pad holes with v !
end
end
else
tmp[n] = v
end
return table.concat(tmp, ";")
end
function mtkwifi.token_get(str, n, v)
-- n starts from 1
-- v is the backup in case token n is nil
if not str then return v end
local tmp = mtkwifi.__cfg2list(str)
return tmp[tonumber(n)] or v
end
function mtkwifi.search_dev_and_profile_orig()
local dir = io.popen("ls /etc/wireless/")
if not dir then return end
local result = {}
-- case 1: mt76xx.dat (best)
-- case 2: mt76xx.n.dat (multiple card of same dev)
-- case 3: mt76xx.n.nG.dat (case 2 plus dbdc and multi-profile, bloody hell....)
for line in dir:lines() do
-- mtkwifi.debug("debug", "scan "..line)
local tmp = io.popen("find /etc/wireless/"..line.." -type f -name \"*.dat\"")
for datfile in tmp:lines() do
-- mtkwifi.debug("debug", "test "..datfile)
repeat do
-- for case 1
local devname = string.match(datfile, "("..line..").dat")
if devname then
result[devname] = datfile
-- mtkwifi.debug("debug", "yes "..devname.."="..datfile)
break
end
-- for case 2
local devname = string.match(datfile, "("..line.."%.%d)%.dat")
if devname then
result[devname] = datfile
-- mtkwifi.debug("debug", "yes "..devname.."="..datfile)
break
end
-- for case 3
local devname = string.match(datfile, "("..line.."%.%d%.%dG)%.dat")
if devname then
result[devname] = datfile
-- mtkwifi.debug("debug", "yes "..devname.."="..datfile)
break
end
end until true
end
end
for k,v in pairs(result) do
mtkwifi.debug("debug", "search_dev_and_profile_orig: "..k.."="..v)
end
return result
end
function mtkwifi.search_dev_and_profile_l1()
local l1dat = mtkwifi.__get_l1dat()
if not l1dat then return end
local result = {}
local dbdc_2nd_if = ""
for k, dev in ipairs(l1dat) do
dbdc_2nd_if = mtkwifi.token_get(dev.main_ifname, 2, nil)
if dbdc_2nd_if then
result[dev["INDEX"].."."..dev["mainidx"]..".1"] = mtkwifi.token_get(dev.profile_path, 1, nil)
result[dev["INDEX"].."."..dev["mainidx"]..".2"] = mtkwifi.token_get(dev.profile_path, 2, nil)
else
result[dev["INDEX"].."."..dev["mainidx"]] = dev.profile_path
end
end
for k,v in pairs(result) do
mtkwifi.debug("debug", "search_dev_and_profile_l1: "..k.."="..v)
end
return result
end
function mtkwifi.search_dev_and_profile()
return mtkwifi.search_dev_and_profile_l1() or mtkwifi.search_dev_and_profile_orig()
end
function mtkwifi.__setup_vifs(cfgs, devname, mainidx, subidx)
local l1dat, l1 = mtkwifi.__get_l1dat()
local dridx = l1dat and l1.DEV_RINDEX
local prefix
local main_ifname
local vifs = {}
local dev_idx = ""
prefix = l1dat and l1dat[dridx][devname].ext_ifname or dbdc_prefix[mainidx][subidx]
dev_idx = string.match(devname, "(%w+)")
vifs["__prefix"] = prefix
if (cfgs.BssidNum == nil) then
mtkwifi.debug("BssidNum configuration value not found.")
mtkwifi.debug("debug","BssidNum configuration value not found.")
return
end
for j=1,tonumber(cfgs.BssidNum) do
vifs[j] = {}
vifs[j].vifidx = j -- start from 1
dev_idx = string.match(devname, "(%w+)")
main_ifname = l1dat and l1dat[dridx][devname].main_ifname or dbdc_prefix[mainidx][subidx].."0"
mtkwifi.debug("setup_vifs", prefix, dev_idx, mainidx, subidx)
vifs[j].vifname = j == 1 and main_ifname or prefix..(j-1)
if mtkwifi.exists("/sys/class/net/"..vifs[j].vifname) then
local flags = tonumber(mtkwifi.read_pipe("cat /sys/class/net/"..vifs[j].vifname.."/flags 2>/dev/null")) or 0
vifs[j].state = flags%2 == 1 and "up" or "down"
end
vifs[j].__ssid = cfgs["SSID"..j]
vifs[j].__bssid = mtkwifi.read_pipe("cat /sys/class/net/"..prefix..(j-1).."/address 2>/dev/null") or "?"
if dbdc then
vifs[j].__channel = mtkwifi.token_get(cfgs.Channel, j, 0)
vifs[j].__wirelessmode = mtkwifi.token_get(cfgs.WirelessMode, j, 0)
end
vifs[j].__authmode = mtkwifi.token_get(cfgs.AuthMode, j, "OPEN")
vifs[j].__encrypttype = mtkwifi.token_get(cfgs.EncrypType, j, "NONE")
vifs[j].__hidessid = mtkwifi.token_get(cfgs.HideSSID, j, 0)
vifs[j].__noforwarding = mtkwifi.token_get(cfgs.NoForwarding, j, 0)
vifs[j].__wmmcapable = mtkwifi.token_get(cfgs.WmmCapable, j, 0)
vifs[j].__txrate = mtkwifi.token_get(cfgs.TxRate, j, 0)
vifs[j].__ieee8021x = mtkwifi.token_get(cfgs.IEEE8021X, j, 0)
vifs[j].__preauth = mtkwifi.token_get(cfgs.PreAuth, j, 0)
vifs[j].__rekeymethod = mtkwifi.token_get(cfgs.RekeyMethod, j, 0)
vifs[j].__rekeyinterval = mtkwifi.token_get(cfgs.RekeyInterval, j, 0)
vifs[j].__pmkcacheperiod = mtkwifi.token_get(cfgs.PMKCachePeriod, j, 0)
vifs[j].__ht_extcha = mtkwifi.token_get(cfgs.HT_EXTCHA, j, 0)
vifs[j].__radius_server = mtkwifi.token_get(cfgs.RADIUS_Server, j, 0)
vifs[j].__radius_port = mtkwifi.token_get(cfgs.RADIUS_Port, j, 0)
vifs[j].__wepkey_id = mtkwifi.token_get(cfgs.DefaultKeyID, j, 0)
vifs[j].__wscconfmode = mtkwifi.token_get(cfgs.WscConfMode, j, 0)
vifs[j].__wepkeys = {
cfgs["Key"..j.."Str1"],
cfgs["Key"..j.."Str2"],
cfgs["Key"..j.."Str3"],
cfgs["Key"..j.."Str4"],
}
vifs[j].__wpapsk = cfgs["WPAPSK"..j]
-- VoW
vifs[j].__atc_tp = mtkwifi.token_get(cfgs.VOW_Rate_Ctrl_En, j, 0)
vifs[j].__atc_min_tp = mtkwifi.token_get(cfgs.VOW_Group_Min_Rate, j, "")
vifs[j].__atc_max_tp = mtkwifi.token_get(cfgs.VOW_Group_Max_Rate, j, "")
vifs[j].__atc_at = mtkwifi.token_get(cfgs.VOW_Airtime_Ctrl_En, j, 0)
vifs[j].__atc_min_at = mtkwifi.token_get(cfgs.VOW_Group_Min_Ratio, j, "")
vifs[j].__atc_max_at = mtkwifi.token_get(cfgs.VOW_Group_Max_Ratio, j, "")
-- TODO index by vifname
vifs[vifs[j].vifname] = vifs[j]
end
return vifs
end
function mtkwifi.__setup_apcli(cfgs, devname, mainidx, subidx)
local l1dat, l1 = mtkwifi.__get_l1dat()
local dridx = l1dat and l1.DEV_RINDEX
local apcli = {}
local dev_idx = string.match(devname, "(%w+)")
local apcli_prefix = l1dat and l1dat[dridx][devname].apcli_ifname or
dbdc_apcli_prefix[mainidx][subidx]
local apcli_name = apcli_prefix.."0"
if mtkwifi.exists("/sys/class/net/"..apcli_name) then
apcli.vifname = apcli_name
apcli.vifidx = "1"
local iwapcli = mtkwifi.read_pipe("iwconfig "..apcli_name.." | grep ESSID 2>/dev/null")
local _,_,ssid = string.find(iwapcli, "ESSID:\"(.*)\"")
local flags = tonumber(mtkwifi.read_pipe("cat /sys/class/net/"..apcli_name.."/flags 2>/dev/null")) or 0
apcli.state = flags%2 == 1 and "up" or "down"
if not ssid or ssid == "" then
apcli.status = "Disconnected"
else
apcli.ssid = ssid
apcli.status = "Connected"
end
apcli.devname = apcli_name
apcli.bssid = mtkwifi.read_pipe("cat /sys/class/net/"..apcli_name.."/address 2>/dev/null") or "?"
local flags = tonumber(mtkwifi.read_pipe("cat /sys/class/net/"..apcli_name.."/flags 2>/dev/null")) or 0
apcli.ifstatus = flags%2 == 1 and "up" or ""
return apcli
else
return
end
end
function mtkwifi.get_all_devs()
local devs = {}
local i = 1 -- dev idx
local profiles = mtkwifi.search_dev_and_profile()
local wpa_support = 0
local wapi_support = 0
for devname,profile in pairs(profiles) do
mtkwifi.debug("debug", "checking "..profile)
local fd = io.open(profile,"r")
if not fd then
mtkwifi.debug("debug", "cannot find "..profile)
else
fd:close()
mtkwifi.debug("debug", "load "..profile)
mtkwifi.debug("loading profile"..profile)
local cfgs = mtkwifi.load_profile(profile)
if not cfgs then
mtkwifi.debug("error loading profile"..profile)
mtkwifi.debug("err", "error loading "..profile)
return
end
devs[i] = {}
devs[i].vifs = {}
devs[i].apcli = {}
devs[i].devname = devname
devs[i].profile = profile
local tmp = ""
tmp = string.split(devname, ".")
devs[i].maindev = tmp[1]
devs[i].mainidx = tonumber(tmp[2]) or 1
devs[i].subdev = devname
devs[i].subidx = string.match(tmp[3] or "", "(%d+)")=="2" and 2 or 1
devs[i].devband = tonumber(tmp[3])
if devs[i].devband then
devs[i].multiprofile = true
devs[i].dbdc = true
end
devs[i].version = mtkwifi.read_pipe("cat /etc/wireless/"..devs[i].maindev.."/version 2>/dev/null") or "unknown"
devs[i].ApCliEnable = cfgs.ApCliEnable
devs[i].WirelessMode = cfgs.WirelessMode
devs[i].WirelessModeList = {}
for key, value in pairs(DevicePropertyMap) do
local found = string.find(string.upper(devname), string.upper(value.device))
if found then
for k=1,#value.band do
devs[i].WirelessModeList[tonumber(value.band[k])] = WirelessModeList[tonumber(value.band[k])]
end
end
end
devs[i].WscConfMode = cfgs.WscConfMode
devs[i].AuthModeList = AuthModeList
devs[i].WpsEnableAuthModeList = WpsEnableAuthModeList
if wpa_support == 1 then
table.insert(devs[i].AuthModeList,"WPAPSK")
table.insert(devs[i].AuthModeList,"WPA")
end
if wapi_support == 1 then
table.insert(devs[i].AuthModeList,"WAIPSK")
table.insert(devs[i].AuthModeList,"WAICERT")
end
devs[i].ApCliAuthModeList = ApCliAuthModeList
devs[i].WPA_Enc_List = WPA_Enc_List
devs[i].WEP_Enc_List = WEP_Enc_List
devs[i].Channel = tonumber(cfgs.Channel)
devs[i].DBDC_MODE = tonumber(cfgs.DBDC_MODE)
devs[i].band = devs[i].devband or mtkwifi.band(cfgs.WirelessMode)
if cfgs.MUTxRxEnable then
if tonumber(cfgs.ETxBfEnCond)==1
and tonumber(cfgs.MUTxRxEnable)==0
and tonumber(cfgs.ITxBfEn)==0
then devs[i].__mimo = 0
elseif tonumber(cfgs.ETxBfEnCond)==0
and tonumber(cfgs.MUTxRxEnable)==0
and tonumber(cfgs.ITxBfEn)==1
then devs[i].__mimo = 1
elseif tonumber(cfgs.ETxBfEnCond)==1
and tonumber(cfgs.MUTxRxEnable)==0
and tonumber(cfgs.ITxBfEn)==1
then devs[i].__mimo = 2
elseif tonumber(cfgs.ETxBfEnCond)==1
and tonumber(cfgs.MUTxRxEnable)>0
and tonumber(cfgs.ITxBfEn)==0
then devs[i].__mimo = 3
elseif tonumber(cfgs.ETxBfEnCond)==1
and tonumber(cfgs.MUTxRxEnable)>0
and tonumber(cfgs.ITxBfEn)==1
then devs[i].__mimo = 4
else devs[i].__mimo = 5
end
end
if cfgs.HT_BW == "0" or not cfgs.HT_BW then
devs[i].__bw = "20"
elseif cfgs.HT_BW == "1" and cfgs.VHT_BW == "0" or not cfgs.VHT_BW then
if cfgs.HT_BSSCoexistence == "0" or not cfgs.HT_BSSCoexistence then
devs[i].__bw = "40"
else
devs[i].__bw = "60" -- 20/40 coexist
end
elseif cfgs.HT_BW == "1" and cfgs.VHT_BW == "1" then
devs[i].__bw = "80"
elseif cfgs.HT_BW == "1" and cfgs.VHT_BW == "2" then
devs[i].__bw = "160"
elseif cfgs.HT_BW == "1" and cfgs.VHT_BW == "3" then
devs[i].__bw = "161"
end
devs[i].vifs = mtkwifi.__setup_vifs(cfgs, devname, devs[i].mainidx, devs[i].subidx)
devs[i].apcli = mtkwifi.__setup_apcli(cfgs, devname, devs[i].mainidx, devs[i].subidx)
-- Setup reverse indices by devname
devs[devname] = devs[i]
if devs[i].apcli then
devs[i][devs[i].apcli.devname] = devs[i].apcli
end
i = i + 1
end
end
return devs
end
function mtkwifi.exists(path)
local fp = io.open(path, "rb")
if fp then fp:close() end
return fp ~= nil
end
function mtkwifi.parse_mac(str)
local macs = {}
local pat = "^[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]$"
local function ismac(str)
if str:match(pat) then return str end
end
if not str then return macs end
local t = str:split("\n")
for _,v in pairs(t) do
local mac = ismac(mtkwifi.__trim(v))
if mac then
table.insert(macs, mac)
end
end
return macs
-- body
end
function mtkwifi.scan_ap(vifname)
os.execute("iwpriv "..vifname.." set SiteSurvey=0")
os.execute("sleep 10") -- depends on your env
local scan_result = mtkwifi.read_pipe("iwpriv "..vifname.." get_site_survey 2>/dev/null")
local aplist = {}
local xx = {}
for i, line in ipairs(mtkwifi.__lines(scan_result)) do
if #line>40 and string.match(line, " BSSID ") then
xx.Ch = {string.find(line, "Ch "),3}
xx.SSID = {string.find(line, "SSID "),32}
xx.BSSID = {string.find(line, "BSSID "),17}
xx.Security = {string.find(line, "Security "),22}
xx.Signal = {string.find(line, "Sig%a%al"),4}
xx.Mode = {string.find(line, "W-Mode"),5}
xx.ExtCh = {string.find(line, "ExtCH"),6}
xx.WPS = {string.find(line, "WPS"),3}
xx.NT = {string.find(line, "NT"),2}
end
local tmp = {}
if #line>40 and not string.match(line, " BSSID ") then
tmp = {}
tmp.channel = mtkwifi.__trim(string.sub(line, xx.Ch[1], xx.Ch[1]+xx.Ch[2]))
tmp.ssid = mtkwifi.__trim(string.sub(line, xx.SSID[1], xx.SSID[1]+xx.SSID[2]))
tmp.bssid = string.upper(mtkwifi.__trim(string.sub(line, xx.BSSID[1], xx.BSSID[1]+xx.BSSID[2])))
tmp.security = mtkwifi.__trim(string.sub(line, xx.Security[1], xx.Security[1]+xx.Security[2]))
tmp.authmode = mtkwifi.__trim(string.split(tmp.security, "/")[1])
tmp.encrypttype = mtkwifi.__trim(string.split(tmp.security, "/")[2] or "NONE")
tmp.rssi = mtkwifi.__trim(string.sub(line, xx.Signal[1], xx.Signal[1]+xx.Signal[2]))
tmp.extch = mtkwifi.__trim(string.sub(line, xx.ExtCh[1], xx.ExtCh[1]+xx.ExtCh[2]))
tmp.mode = mtkwifi.__trim(string.sub(line, xx.Mode[1], xx.Mode[1]+xx.Mode[2]))
tmp.wps = mtkwifi.__trim(string.sub(line, xx.WPS[1], xx.WPS[1]+xx.WPS[2]))
tmp.nt = mtkwifi.__trim(string.sub(line, xx.NT[1], xx.NT[1]+xx.NT[2]))
table.insert(aplist, tmp)
end
end
return aplist
end
function mtkwifi.__any_wsc_enabled(wsc_conf_mode)
if (wsc_conf_mode == "") then
return 0;
end
if (wsc_conf_mode == "7") then
return 1;
end
if (wsc_conf_mode == "4") then
return 1;
end
if (wsc_conf_mode == "2") then
return 1;
end
if (wsc_conf_mode == "1") then
return 1;
end
return 0;
end
function mtkwifi.__restart_if_wps(devname, ifname, cfgs)
local devs = mtkwifi.get_all_devs()
local ssid_index = devs[devname]["vifs"][ifname].vifidx
local wsc_conf_mode = ""
wsc_conf_mode=mtkwifi.token_get(cfgs["WscConfMode"], ssid_index, "")
os.execute("iwpriv "..ifname.." set WscConfMode=0")
mtkwifi.debug("iwpriv "..ifname.." set WscConfMode=0")
os.execute("route delete 239.255.255.250")
mtkwifi.debug("route delete 239.255.255.250")
if(mtkwifi.__any_wsc_enabled(wsc_conf_mode)) then
os.execute("iwpriv "..ifname.." set WscConfMode=7")
mtkwifi.debug("iwpriv "..ifname.." set WscConfMode=7")
os.execute("route add -host 239.255.255.250 dev br0")
mtkwifi.debug("route add -host 239.255.255.250 dev br0")
end
-- execute wps_action.lua file to send signal for current interface
os.execute("lua wps_action.lua "..ifname)
mtkwifi.debug("lua wps_action.lua "..ifname)
return cfgs
end
function mtkwifi.restart_8021x(devname, devices)
local l1dat, l1 = mtkwifi.__get_l1dat()
local dridx = l1dat and l1.DEV_RINDEX
local devs = devices or mtkwifi.get_all_devs()
local dev = devs[devname]
local main_ifname = l1dat and l1dat[dridx][devname].main_ifname or dbdc_prefix[mainidx][subidx].."0"
local prefix = l1dat and l1dat[dridx][devname].ext_ifname or dbdc_prefix[mainidx][subidx]
local ps_cmd = "ps | grep -v grep | grep rt2860apd | grep "..main_ifname.." | awk '{print $1}'"
local pid_cmd = "cat /var/run/rt2860apd_"..devs[devname].vifs[1].vifname..".pid"
local apd_pid = mtkwifi.read_pipe(pid_cmd) or mtkwifi.read_pipe(ps_cmd)
if tonumber(apd_pid) then
os.execute("kill "..apd_pid)
end
local cfgs = mtkwifi.load_profile(devs[devname].profile)
local auth_mode = cfgs['AuthMode']
local ieee8021x = cfgs['IEEE8021X']
local pat_auth_mode = {"WPA$", "WPA;", "WPA2$", "WPA2;", "WPA1WPA2$", "WPA1WPA2;"}
local pat_ieee8021x = {"1$", "1;"}
local apd_en = false
for _, pat in ipairs(pat_auth_mode) do
if string.find(auth_mode, pat) then
apd_en = true
end
end
for _, pat in ipairs(pat_ieee8021x) do
if string.find(ieee8021x, pat) then
apd_en = true
end
end
if not apd_en then
return
end
os.execute("rt2860apd -i "..main_ifname.." -p "..prefix)
end
return mtkwifi
| gpl-2.0 |
Zero-K-Experiments/Zero-K-Experiments | LuaUI/Configs/tipconfig.lua | 12 | 6628 | local THRESHOLD_EXPENSIVE = 800
--seconds
TIMER_EXPENSIVE_UNITS = 60 * 10
TIMER_ADV_FACTORY = 60 * 15
TIMER_SUPERWEAPON = 60 * 30
stringExpensiveUnits = "That <name> is particularly expensive; at this point, cheaper units offer far more flexibility. You should probably save that for later."
stringAdvFactory = "That <name> is difficult to use and inflexible early game; you should start with a more basic factory."
stringSuperweapon = "Superweapons such as that <name> are meant for resolving late-game stalemates when no other options remain. This is NOT the time to be building one!"
stringAirSpotted = "\255\255\0\0Enemy aircraft spotted.\008 Now might be a good time to invest in some anti-air."
stringNukeSpotted = "\255\255\0\0Enemy nuclear silo located.\008 Build an anti-nuke launcher while you still can."
generalTips = {
"Use the priority buttons to maximize your efficiency during stalls (expenditure outstripping income). Resources will be allocated to high priority units before low priority ones.",
"Repairing units is twice as fast as building them, but proceeds at 1/4th the normal speed if the unit has been recently damaged.",
"Different AA types are effective against different targets. The Hacksaw missile turret is lethal against bombers, while the Cobra flak cannon cuts down gunships well.",
"When fighting AoE weapons, spread out your units to minimize damage.",
"You can draw on the map with tilde (~) and left mouse. ~ + double click adds a labelled point, while ~ + middle click adds a point without label. ~ + right click erases.",
"Many commands can be issued over a whole area by keeping button the down and dragging a box or disc.",
"Heavy striders are built by the Strider Hub, buildable by any standard constructor.",
"Riot units double as improvised anti-air against most gunships.",
"Nuclear missiles are devastating, but can be intercepted by antinuke systems which provide coverage over a wide area.",
"Cloaked units can be revealed by close contact, or when damaged.",
"Slow-rays and other weapons with slowing effects will reduce the target's movement and firing rate by up to 50%.",
"Hovercraft are fast and can transverse water, but struggle on even gentle slopes.",
"Most units have a smart Unit AI, which has them automatically kite or jink enemy units as needed on a fight order or when standing still.",
"Spiders have excellent mobility including the ability to scale cliffs, although they tend to lack direct strength.",
"Space-clicking on a unit or its build button in the menu brings up the \255\255\64\0Context Menu\008, where you can view unit data or access marketplace functions.",
}
unitTips = {
corclog = {"The \255\255\64\0Dirtbag\008 leaves a mound of earth when it dies, obstructing units (especially vehicles) and weapons.", 3, 5},
capturecar = {"The \255\255\64\0Dominatrix\008 capture vehicle can capture enemy units (with a 10 second cooldown between captures), but control is lost if the capturing Dominatrix dies.", 3, 5},
armcrabe = {"The \255\255\64\0Crabe\008 outranges basic defenses. It curls up into armored form when stationary, becoming a formidable defense turret.", 3, 5},
firewalker = {"The \255\255\64\0Firewalker\008 creates large clouds of fire which can seriously harm units - friend or foe - standing in them.", 3, 5},
corsktl = {"The \255\255\64\0Skuttle\008 has a very powerful explosion with a very small blast radius. Use it to jump on enemy heavy targets and kill them in one or two blows.", 3, 5},
tawf114 = {"The \255\255\64\0Banisher\008 packs a punch against groups of small units, but can be easily rushed - make sure to screen it.", 3, 4},
armmanni = {"The \255\255\64\0Penetrator\008 can split many units apart in one shot, but has no AoE and a 20s reload time, and is itself very flimsy. Use it for pinpoint fire from a distance.", 3, 4},
}
raiderDefs = {
"armpw",
"spherepole",
"corak",
"armflash",
"corfav",
"corgator",
"corpyro",
"panther",
"logkoda",
"armsh",
"corsh",
"chicken",
"chicken_leaper",
}
assaultDefs = {
"corthud",
"corraid",
"armzeus",
--"armcrabe",
"spiderassault",
"corcan",
--"corsumo",
"armbull",
"correap",
"corgol",
"armanac",
"hoverassault",
--"armbanth",
--"armorco",
--"corkrog",
--"chickena",
--"chickenc",
--"chicken_tiamat",
}
skirmDefs = {
"armrock",
"corstorm",
"armjanus",
"armstump",
"armsptk",
"armsnipe",
"cormort",
"slowmort",
"cormortgold",
"armmanni",
"nsaclash",
"chickens",
}
riotDefs = {
"armwar",
"cormak",
"corlevlr",
"arm_venom",
"tawf003",
"tawf114",
"hoverriot",
"armraz",
"dante",
}
artyDefs = {
"armham",
"punisher",
"firewalker",
"tawf013",
"corgarp",
"armmerl",
--"armmanni",
"cormart",
"trem",
"armshock",
"armraven",
"hoverartillery",
"chickenr",
"chickenblobber",
}
bomberDefs = {
"bomberdive",
"corshad",
"corhurc2",
"armstiletto_laser",
"armcybr",
}
conDefs = {
"armrectr",
"cornecro",
"arm_weaver",
"corfast",
"corned",
"coracv",
"corch",
"armca",
"shipcon",
}
mexDefs = {"cormex"}
energyDefs = {
"armsolar",
"armwin",
"armfus",
"geo",
"cafus",
}
factoryDefs = {
"factoryship",
"striderhub",
}
advFactoryDefs = {
"factoryspider",
"factoryjump",
"factorytank",
}
airFactoryDefs = {
"factoryplane",
"factorygunship",
}
superweaponDefs = {
"armbrtha",
"corsilo",
"mahlazer",
"zenith",
"raveparty",
}
needPowerDefs = {
"armanni",
"corbhmth",
"cordoom",
}
for name in pairs(UnitDefNames) do
if string.find(name, "factory") then factoryDefs[#factoryDefs+1] = name end
end
--unitDefID-indexed versions
raider = {}
assault = {}
skirm = {}
riot = {}
arty = {}
bomber = {}
con = {}
mex = {}
energy = {}
factory = {}
commander = {}
expensive_unit = {}
adv_factory = {}
air_factory = {}
superweapon = {}
needPower = {}
for i=1,#UnitDefs do
if UnitDefs[i].customParams.commtype then commander[i]=true
elseif UnitDefs[i].metalCost > THRESHOLD_EXPENSIVE then expensive_unit[i] = true end
end
local function CreateArray(source, target)
for i=1, #source do
local def = UnitDefNames[source[i]]
if def then target[def.id] = true end
end
end
CreateArray(raiderDefs, raider)
CreateArray(assaultDefs, assault)
CreateArray(skirmDefs, skirm)
CreateArray(riotDefs, riot)
CreateArray(artyDefs, arty)
CreateArray(bomberDefs, bomber)
CreateArray(conDefs, con)
CreateArray(mexDefs, mex)
CreateArray(energyDefs, energy)
CreateArray(factoryDefs, factory)
CreateArray(advFactoryDefs, adv_factory)
CreateArray(airFactoryDefs, air_factory)
CreateArray(superweaponDefs, superweapon)
CreateArray(needPowerDefs, needPower)
| gpl-2.0 |
Youka/NyuFX | templates/Fun/border_pixels.lua | 2 | 1996 | -- Line to convert to pixels
local line = lines[1]
-- Text fill shape
local text_shape = convert.text_to_shape(line.text, line.styleref)
-- Shift text fill shape by text position subpixel offset (for correct antialiasing calculation by pixel conversion)
local x_shift, y_shift = math.floor(line.left % 1 * 8), math.floor(line.top % 1 * 8)
text_shape = shape.filter(text_shape, function(x, y)
return x+x_shift, y+y_shift
end)
-- Text outline shape
local text_outline_shape = shape.tooutline(shape.split(text_shape), line.styleref.outline * 8)
-- Text fill & outline pixels
local text_pixels = convert.shape_to_pixels(text_shape)
local text_outline_pixels = convert.shape_to_pixels(text_outline_shape)
-- Subtract fill pixels from outline pixels to get border pixels
local text_border_pixels, text_border_pixels_n = {}, 0
for _, out_pixel in ipairs(text_outline_pixels) do
local found_overlap = false
for _, in_pixel in ipairs(text_pixels) do
if out_pixel.x == in_pixel.x and out_pixel.y == in_pixel.y and in_pixel.a == 255 then -- Pixels overlap and fill pixel is opaque
found_overlap = true
break
end
end
if not found_overlap then
text_border_pixels_n = text_border_pixels_n + 1
text_border_pixels[text_border_pixels_n] = out_pixel
end
end
-- Border pixels output
for _, pixel in ipairs(text_border_pixels) do
local x, y = math.floor(line.left) + pixel.x, math.floor(line.top) + pixel.y
local alpha = pixel.a == 255 and "" or "\\1a" .. convert.a_to_ass(pixel.a)
line.text = string.format("{\\an7\\pos(%d,%d)%s\\1c%s\\bord0\\p1}m 0 0 l 1 0 1 1 0 1", x, y, alpha, line.styleref.color3)
io.write_line(line)
end
-- Fill pixels output
for _, pixel in ipairs(text_pixels) do
local x, y = math.floor(line.left) + pixel.x, math.floor(line.top) + pixel.y
local alpha = pixel.a == 255 and "" or "\\1a" .. convert.a_to_ass(pixel.a)
line.text = string.format("{\\an7\\pos(%d,%d)%s\\1c%s\\bord0\\p1}m 0 0 l 1 0 1 1 0 1", x, y, alpha, line.styleref.color1)
io.write_line(line)
end | lgpl-3.0 |
Grade-A-Software/Comcast-DASH-VLC | share/lua/playlist/joox.lua | 113 | 1637 | --[[
$Id$
Copyright ยฉ 2007 the VideoLAN 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; 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.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "joox.net" ) or
string.match( vlc.path, "/iframe.php%?video=1&" )
end
-- Parse function.
function parse()
vidtitle = ""
while true do
line = vlc.readline()
if not line then break end
if string.match( line, "iframe" ) then
-- extract the iframe
print((string.gsub( line, ".*iframe src=\"([^\"]*).*", "%1" ) ))
return { { path = (string.gsub( line, ".*iframe src=\"([^\"]*).*", "%1" )) } }
end
if string.match( line, "<param name=\"src" ) then
-- extract the video url from the iframe
print( (string.gsub( line, ".*src\" value=\"([^\"]*).*", "%1" )))
return { { path = (string.gsub( line, ".*src\" value=\"([^\"]*).*", "%1" )) } }
end
end
end
| gpl-2.0 |
Scavenge/darkstar | scripts/globals/items/bean_daifuku_+1.lua | 12 | 2204 | -----------------------------------------
-- ID: 6342
-- Item: bean_daifuku_+1
-- Food Effect: 60 Min, All Races
-----------------------------------------
-- HP +30
-- VIT +4
-- Accuracy +11% (cap 54)
-- Ranged Accuracy +11% (cap 54)
-- Pet:
-- HP +30
-- VIT +4
-- Accuracy +11% (cap 81)
-- Ranged Accuracy +11% (cap 81)
-- Haste +4%
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD)) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,6342);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 30);
target:addMod(MOD_VIT, 4);
target:addMod(MOD_FOOD_ACCP, 11);
target:addMod(MOD_FOOD_ACC_CAP, 54);
target:addMod(MOD_FOOD_RACCP, 11);
target:addMod(MOD_FOOD_RACC_CAP, 54);
target:addPetMod(MOD_HP, 30);
target:addPetMod(MOD_VIT, 4);
target:addPetMod(MOD_FOOD_ACCP, 11);
target:addPetMod(MOD_FOOD_ACC_CAP, 81);
target:addPetMod(MOD_FOOD_RACCP, 11);
target:addPetMod(MOD_FOOD_RACC_CAP, 81);
target:addPetMod(MOD_HASTE_GEAR, 41);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 30);
target:delMod(MOD_VIT, 4);
target:delMod(MOD_FOOD_ACCP, 11);
target:delMod(MOD_FOOD_ACC_CAP, 54);
target:delMod(MOD_FOOD_RACCP, 11);
target:delMod(MOD_FOOD_RACC_CAP, 54);
target:delPetMod(MOD_HP, 30);
target:delPetMod(MOD_VIT, 4);
target:delPetMod(MOD_FOOD_ACCP, 11);
target:delPetMod(MOD_FOOD_ACC_CAP, 81);
target:delPetMod(MOD_FOOD_RACCP, 11);
target:delPetMod(MOD_FOOD_RACC_CAP, 81);
target:delPetMod(MOD_HASTE_GEAR, 41);
end; | gpl-3.0 |
PicoleDeLimao/Ninpou2 | game/dota_addons/ninpou2/scripts/vscripts/addon_game_mode.lua | 1 | 5977 | -- This is the entry-point to your game mode and should be used primarily to precache models/particles/sounds/etc
require('internal/util')
require('gamemode')
-- Library containing some utilitary functions
require('mechanics/hud')
require('mechanics/players')
require('mechanics/units')
require('mechanics/particles')
require('mechanics/throwables')
require('mechanics/vectors')
require('mechanics/tables')
-- Library containing utilitary methods to check victory/defeat conditions
require('ninpou_game_rules')
-- Library containing custom commands
require('commands')
-- AI for medical ninja units in order to enable them to autocast heal ability
require('units/AI/medical_ninja_ai')
-- AI for elite anbu units
require('units/AI/elite_anbu_ai')
-- AI for elite anbu leader units
require('units/AI/elite_anbu_leader_ai')
-- AI for Juubi
require('units/AI/juubi_ai')
require('gamemode')
LinkLuaModifier("modifier_building", "libraries/modifiers/modifier_building", LUA_MODIFIER_MOTION_NONE)
function Precache( context )
--[[
This function is used to precache resources/units/items/abilities that will be needed
for sure in your game and that will not be precached by hero selection. When a hero
is selected from the hero selection screen, the game will precache that hero's assets,
any equipped cosmetics, and perform the data-driven precaching defined in that hero's
precache{} block, as well as the precache{} block for any equipped abilities.
See GameMode:PostLoadPrecache() in gamemode.lua for more information
]]
DebugPrint("[BAREBONES] Performing pre-load precache")
-- Particles can be precached individually or by folder
-- It it likely that precaching a single particle system will precache all of its children, but this may not be guaranteed
-- PrecacheResource("particle", "particles/econ/generic/generic_aoe_explosion_sphere_1/generic_aoe_explosion_sphere_1.vpcf", context)
-- PrecacheResource("particle_folder", "particles/test_particle", context)
-- Models can also be precached by folder or individually
-- PrecacheModel should generally used over PrecacheResource for individual models
-- PrecacheResource("model_folder", "particles/heroes/antimage", context)
-- PrecacheResource("model", "particles/heroes/viper/viper.vmdl", context)
-- PrecacheModel("models/heroes/viper/viper.vmdl", context)
-- Entire items can be precached by name
-- Abilities can also be precached in this way despite the name
-- PrecacheItemByNameSync("example_ability", context)
-- PrecacheItemByNameSync("item_example_item", context)
-- Entire heroes (sound effects/voice/models/particles) can be precached with PrecacheUnitByNameSync
-- Custom units from npc_units_custom.txt can also have all of their abilities and precache{} blocks precached in this way
-- PrecacheUnitByNameSync("npc_dota_hero_ancient_apparition", context)
-- PrecacheUnitByNameSync("npc_dota_hero_enigma", context)
-- Precache custom sounds
PrecacheResource("soundfile", "soundevents/game_sounds_custom.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_roshan_halloween.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_hero_pick.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_alchemist.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_batrider.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_bounty_hunter.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_brewmaster.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_clinkz.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_enigma.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_earthshaker.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_earth_spirit.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_phantom_assassin.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_medusa.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_morphling.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_kunkka.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_treant.vsndevts", context)
PrecacheResource("soundfile", "soundevents/orochimaru.vsndevts", context)
PrecacheResource("particle", "particles/base_destruction_fx/gensmoke.vpcf", context)
PrecacheResource("particle", "particles/econ/items/effigies/status_fx_effigies/base_statue_destruction_generic.vpcf", context)
PrecacheResource("particle", "particles/items/explosivekunai/explosive_kunai.vpcf", context)
PrecacheResource("particle", "particles/others/kuchiyose/kuchiyose.vpcf", context)
-- Precache units
PrecacheUnitByNameSync("npc_konoha_chunnin_unit", context)
PrecacheUnitByNameSync("npc_konoha_jounin_unit", context)
PrecacheUnitByNameSync("npc_oto_chunnin_unit", context)
PrecacheUnitByNameSync("npc_oto_jounin_unit", context)
PrecacheUnitByNameSync("npc_akatsuki_chunnin_unit", context)
PrecacheUnitByNameSync("npc_akatsuki_jounin_unit", context)
PrecacheUnitByNameSync("npc_anbu_unit", context)
PrecacheUnitByNameSync("npc_medical_ninja_unit", context)
PrecacheUnitByNameSync("npc_juubi_unit", context)
PrecacheUnitByNameSync("npc_edo_hashirama", context)
PrecacheUnitByNameSync("npc_edo_tobirama", context)
end
-- Create the game mode when we activate
function Activate()
GameRules.GameMode = GameMode()
GameRules.GameMode:InitGameMode()
end | apache-2.0 |
seblindfors/ConsolePort | ConsolePort_Config/Bindings/Combo.lua | 1 | 4726 | local _, env = ...; local db = env.db;
---------------------------------------------------------------
-- Combinations (abbrev. combos)
---------------------------------------------------------------
local Combos, Combo = CreateFromMixins(env.DynamicMixin), CreateFromMixins(CPIndexButtonMixin, env.BindingInfoMixin, {
-- true for events related to action bar, false for events related to bindings.
Events = {
ACTIONBAR_SLOT_CHANGED = true;
UPDATE_SHAPESHIFT_FORM = true;
UPDATE_BINDINGS = true;
ACTIONBAR_SHOWGRID = false;
ACTIONBAR_HIDEGRID = false;
};
}); env.CombosMixin = Combos; env.ComboMixin = Combo;
function Combo:UpdateBinding(combo)
local name, texture, actionID = self:GetBindingInfo(self:GetBinding(), nil)
self:SetText(name)
self.ActionIcon:SetAlpha(texture and 1 or 0)
self.Mask:SetAlpha(texture and 1 or 0)
self.ActionIcon:SetTexture(texture)
self:SetAttribute('action', actionID)
for event, state in pairs(self.Events) do
if not state then
if not actionID then
self:RegisterEvent(event)
else
self:UnregisterEvent(event)
end
else
self:RegisterEvent(event)
end
end
end
function Combo:GetBinding()
return GetBindingAction(self:GetAttribute('combo')), self:GetAttribute('action')
end
function Combo:HasBinding()
local binding = self:GetBinding()
return (binding and binding:len() > 0)
end
function Combo:GetAction()
return self:GetAttribute('action')
end
function Combo:OnEvent(event, ...)
-- action bar
if (event == 'ACTIONBAR_SLOT_CHANGED') then
local actionID = ...;
if (actionID == self:GetAttribute('action')) then
self:UpdateBinding()
end
elseif (event == 'UPDATE_SHAPESHIFT_FORM') then
self:UpdateBinding()
elseif (event == 'UPDATE_BINDINGS') then
self:UpdateBinding()
-- normal binding
elseif (event == 'ACTIONBAR_SHOWGRID') then
self:SetEnabled(false)
self:SetAlpha(0.5)
elseif (event == 'ACTIONBAR_HIDEGRID') then
self:SetEnabled(true)
self:SetAlpha(1)
end
end
function Combo:OnReceiveDrag()
if GetCursorInfo() and self:GetAttribute('action') then
PlaceAction(self:GetAttribute('action'))
end
end
function Combo:OnDragStart()
if self:GetAttribute('action') then
PickupAction(self:GetAttribute('action'))
end
end
function Combo:OnClick()
local isActionDrop;
if GetCursorInfo() and self:GetAttribute('action') then
PlaceAction(self:GetAttribute('action'))
self:SetChecked(false)
isActionDrop = true;
end
if not isActionDrop and self:HasBinding() then
env.Bindings:NotifyBindingFocus(self, self:GetChecked(), true)
else
self:SetChecked(false)
end
self:OnChecked(self:GetChecked())
end
function Combo:OnShow()
self:UpdateBinding()
end
function Combo:OnHide()
self:UnregisterAllEvents()
end
function Combo:OnEnter()
CPIndexButtonMixin.OnIndexButtonEnter(self)
if db('Cursor'):IsCurrentNode(self, true) then
local flexer = env.Bindings
and env.Bindings.ComboShortcuts
and env.Bindings.ComboShortcuts.Flexer;
if flexer and flexer:IsVisible() and not flexer:GetChecked() then
flexer:Click()
end
end
end
function Combo:OnLeave()
CPIndexButtonMixin.OnIndexButtonLeave(self)
end
function Combos:OnLoad()
CPFocusPoolMixin.OnLoad(self)
self:CreateFramePool('IndexButton',
'CPIndexButtonBindingComboTemplate', Combo, nil, self.Child)
end
function Combos:OnShow()
local device, map = env:GetActiveDeviceAndMap()
local mods = env:GetActiveModifiers()
if not device or not map or not mods then
return self.Child:SetSize(0, 0)
end
local id, width, height, prev = 1, self.Child:GetWidth(), 0;
for i=0, #map do
local button = map[i].Binding;
if ( device:IsButtonValidForBinding(button) ) then
for mod, keys in db.table.mpairs(mods) do
local widget, newObj = self:Acquire(mod..button)
if newObj then
local widgetWidth = widget:GetWidth()
width = widgetWidth > width and widgetWidth or width;
widget.container = self;
widget:SetSiblings(self.Registry)
widget:SetDrawOutline(true)
widget:RegisterForDrag('LeftButton')
CPAPI.Start(widget)
end
local data = env:GetHotkeyData(button, mod, 64, 32)
local modstring = '';
for i, mod in db.table.ripairs(data.modifier) do
modstring = modstring .. (db.Hotkeys:FormatIconSlug(mod, nil, '|A:%s:12:12|a') or '')
end
CPAPI.SetTextureOrAtlas(widget.Icon, data.button)
widget.Modifier:SetText(modstring)
widget:SetID(id)
widget:SetAttribute('combo', mod..button)
widget:Show()
widget:SetPoint('TOP', prev or self.Child, prev and 'BOTTOM' or 'TOP', 0, 0)
prev, height = widget, height + widget:GetHeight();
end
id = id + 1;
end
end
self:SetAttribute('numsets', id)
self.Child:SetSize(width, height)
end | artistic-2.0 |
Scavenge/darkstar | scripts/globals/items/plate_of_homemade_risotto.lua | 12 | 1869 | -----------------------------------------
-- ID: 5229
-- Item: plate_of_homemade_risotto
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Mind 1
-- Accuracy +12% (cap 80)
-- Attack +10% (cap 40)
-- Ranged Accuracy +12% (cap 80)
-- Ranged Attack +10% (cap 40)
-----------------------------------------
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,5229);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MND, 1);
target:addMod(MOD_FOOD_ACCP, 12);
target:addMod(MOD_FOOD_ACC_CAP, 80);
target:addMod(MOD_FOOD_ATTP, 10);
target:addMod(MOD_FOOD_ATT_CAP, 40);
target:addMod(MOD_FOOD_RACCP, 12);
target:addMod(MOD_FOOD_RACC_CAP, 80);
target:addMod(MOD_FOOD_RATTP, 10);
target:addMod(MOD_FOOD_RATT_CAP, 40);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MND, 1);
target:delMod(MOD_FOOD_ACCP, 12);
target:delMod(MOD_FOOD_ACC_CAP, 80);
target:delMod(MOD_FOOD_ATTP, 10);
target:delMod(MOD_FOOD_ATT_CAP, 40);
target:delMod(MOD_FOOD_RACCP, 12);
target:delMod(MOD_FOOD_RACC_CAP, 80);
target:delMod(MOD_FOOD_RATTP, 10);
target:delMod(MOD_FOOD_RATT_CAP, 40);
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/North_Gustaberg/npcs/Kuuwari-Aori_WW.lua | 14 | 3343 | -----------------------------------
-- Area: North Gustaberg
-- NPC: Kuuwari-Aori, W.W.
-- Type: Outpost Conquest Guards
-- @pos -584.687 39.107 54.281 106
-----------------------------------
package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/North_Gustaberg/TextIDs");
local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = GUSTABERG;
local csid = 0x7ff7;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %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 == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
PaulBatchelor/Soundpipe | modules/data/trand.lua | 3 | 1081 | sptbl["trand"] = {
files = {
module = "trand.c",
header = "trand.h",
example = "ex_trand.c",
},
func = {
create = "sp_trand_create",
destroy = "sp_trand_destroy",
init = "sp_trand_init",
compute = "sp_trand_compute",
},
params = {
optional = {
{
name = "min",
type = "SPFLOAT",
description ="Minimum value to use.",
default = 0
},
{
name = "max",
type = "SPFLOAT",
description ="Maximum value to use.",
default = 1
},
}
},
modtype = "module",
description = [[Triggered random number generator.
]],
ninputs = 1,
noutputs = 1,
inputs = {
{
name = "trig",
description = "When non-zero, will create a new random value."
},
},
outputs = {
{
name = "out",
description = "Signal output."
},
}
}
| mit |
Scavenge/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Enaremand.lua | 14 | 1060 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Enaremand
-- Type: Standard NPC
-- @zone 26
-- @pos 95.962 -42.003 51.613
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0219);
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 |
cyclonetm/XmakanX | libs/dkjson.lua | 3282 | 26558 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
========================================
*Version 2.4*
In the default configuration this module writes no global values, not even
the module table. Import it using
json = require ("dkjson")
In environments where `require` or a similiar function are not available
and you cannot receive the return value of the module, you can set the
option `register_global_module_table` to `true`. The module table will
then be saved in the global variable with the name given by the option
`global_module_name`.
Exported functions and values:
`json.encode (object [, state])`
--------------------------------
Create a string representing the object. `Object` can be a table,
a string, a number, a boolean, `nil`, `json.null` or any object with
a function `__tojson` in its metatable. A table can only use strings
and numbers as keys and its values have to be valid objects as
well. It raises an error for any invalid data types or reference
cycles.
`state` is an optional table with the following fields:
- `indent`
When `indent` (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.
- `keyorder`
`keyorder` is an array to specify the ordering of keys in the
encoded output. If an object has keys which are not in this array
they are written after the sorted keys.
- `level`
This is the initial level of indentation used when `indent` is
set. For each level two spaces are added. When absent it is set
to 0.
- `buffer`
`buffer` is an array to store the strings for the result so they
can be concatenated at once. When it isn't given, the encode
function will create it temporary and will return the
concatenated result.
- `bufferlen`
When `bufferlen` is set, it has to be the index of the last
element of `buffer`.
- `tables`
`tables` is a set to detect reference cycles. It is created
temporary when absent. Every table that is currently processed
is used as key, the value is `true`.
When `state.buffer` was set, the return value will be `true` on
success. Without `state.buffer` the return value will be a string.
`json.decode (string [, position [, null]])`
--------------------------------------------
Decode `string` starting at `position` or at 1 if `position` was
omitted.
`null` is an optional value to be returned for null values. The
default is `nil`, but you could set it to `json.null` or any other
value.
The return values are the object or `nil`, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.
Two metatables are created. Every array or object that is decoded gets
a metatable with the `__jsontype` field set to either `array` or
`object`. If you want to provide your own metatables use the syntax
json.decode (string, position, null, objectmeta, arraymeta)
To prevent the assigning of metatables pass `nil`:
json.decode (string, position, null, nil)
`<metatable>.__jsonorder`
-------------------------
`__jsonorder` can overwrite the `keyorder` for a specific table.
`<metatable>.__jsontype`
------------------------
`__jsontype` can be either `"array"` or `"object"`. This value is only
checked for empty tables. (The default for empty tables is `"array"`).
`<metatable>.__tojson (self, state)`
------------------------------------
You can provide your own `__tojson` function in a metatable. In this
function you can either add directly to the buffer and return true,
or you can return a string. On errors nil and a message should be
returned.
`json.null`
-----------
You can use this value for setting explicit `null` values.
`json.version`
--------------
Set to `"dkjson 2.4"`.
`json.quotestring (string)`
---------------------------
Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own `__tojson` functions.
`json.addnewline (state)`
-------------------------
When `state.indent` is set, add a newline to `state.buffer` and spaces
according to `state.level`.
LPeg support
------------
When the local configuration variable `always_try_using_lpeg` is set,
this module tries to load LPeg to replace the `decode` function. The
speed increase is significant. You can get the LPeg module at
<http://www.inf.puc-rio.br/~roberto/lpeg/>.
When LPeg couldn't be loaded, the pure Lua functions stay active.
In case you don't want this module to require LPeg on its own,
disable the option `always_try_using_lpeg` in the options section at
the top of the module.
In this case you can later load LPeg support using
### `json.use_lpeg ()`
Require the LPeg module and replace the functions `quotestring` and
and `decode` with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:
json = require "dkjson".use_lpeg()
Alternatively you can use `pcall` so the JSON module still works when
LPeg isn't found.
json = require "dkjson"
pcall (json.use_lpeg)
### `json.using_lpeg`
This variable is set to `true` when LPeg was loaded successfully.
---------------------------------------------------------------------
Contact
-------
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
---------------------------------------------------------------------
*Copyright (C) 2010-2013 David Heiko Kolf*
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<!-- This documentation can be parsed using Markdown to generate HTML.
The source code is enclosed in a HTML comment so it won't be displayed
by browsers, but it should be removed from the final HTML file as
it isn't a valid HTML comment (and wastes space).
-->
<!--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
--> | gpl-2.0 |
lingmann/dcos | packages/adminrouter/extra/src/lib/auth/common.lua | 3 | 4814 | local cjson = require "cjson"
local cookiejar = require "resty.cookie"
local jwt = require "resty.jwt"
local jwt_validators = require "resty.jwt-validators"
local util = require "util"
local errorpages_dir_path = os.getenv("AUTH_ERROR_PAGE_DIR_PATH")
if errorpages_dir_path == nil then
ngx.log(ngx.WARN, "AUTH_ERROR_PAGE_DIR_PATH not set.")
else
local p = errorpages_dir_path .. "/401.html"
ngx.log(ngx.NOTICE, "Reading 401 response from `" .. p .. "`.")
BODY_401_ERROR_RESPONSE = util.get_file_content(p)
if (BODY_401_ERROR_RESPONSE == nil or BODY_401_ERROR_RESPONSE == '') then
-- Normalize to '', for sending empty response bodies.
BODY_401_ERROR_RESPONSE = ''
ngx.log(ngx.WARN, "401 error response is empty.")
end
local p = errorpages_dir_path .. "/403.html"
ngx.log(ngx.NOTICE, "Reading 403 response from `" .. p .. "`.")
BODY_403_ERROR_RESPONSE = util.get_file_content(p)
if (BODY_403_ERROR_RESPONSE == nil or BODY_403_ERROR_RESPONSE == '') then
-- Normalize to '', for sending empty response bodies.
BODY_403_ERROR_RESPONSE = ''
ngx.log(ngx.WARN, "403 error response is empty.")
end
end
local function exit_401(authtype)
ngx.status = ngx.HTTP_UNAUTHORIZED
ngx.header["Content-Type"] = "text/html; charset=UTF-8"
ngx.header["WWW-Authenticate"] = authtype
ngx.say(BODY_401_ERROR_RESPONSE)
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
local function exit_403()
ngx.status = ngx.HTTP_FORBIDDEN
ngx.header["Content-Type"] = "text/html; charset=UTF-8"
ngx.say(BODY_403_ERROR_RESPONSE)
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
-- We need to differentiate how secret_key value is acquired so we acquire it
-- in different lua fila. This requires either passig this value as a global or
-- as a function argument. Function argument seems like a safer approach.
local function validate_jwt(secret_key)
-- Inspect Authorization header in current request. Expect JSON Web Token in
-- compliance with RFC 7519. Expect `uid` key in payload section. Extract
-- and return uid or the error code.
-- Refs:
-- https://github.com/openresty/lua-nginx-module#access_by_lua
-- https://github.com/SkyLothar/lua-resty-jwt
if secret_key == nil then
ngx.log(ngx.ERR, "Secret key not set. Cannot validate request.")
return nil, 401
end
local auth_header = ngx.var.http_Authorization
local token = nil
if auth_header ~= nil then
ngx.log(ngx.DEBUG, "Authorization header found. Attempt to extract token.")
_, _, token = string.find(auth_header, "token=(.+)")
else
ngx.log(ngx.DEBUG, "Authorization header not found.")
-- Presence of Authorization header overrides cookie method entirely.
-- Read cookie. Note: ngx.var.cookie_* cannot access a cookie with a
-- dash in its name.
local cookie, err = cookiejar:new()
token = cookie:get("dcos-acs-auth-cookie")
if token == nil then
ngx.log(ngx.DEBUG, "dcos-acs-auth-cookie not found.")
else
ngx.log(
ngx.DEBUG, "Use token from dcos-acs-auth-cookie, " ..
"set corresponding Authorization header for upstream."
)
ngx.req.set_header("Authorization", "token=" .. token)
end
end
if token == nil then
ngx.log(ngx.NOTICE, "No auth token in request.")
return nil, 401
end
-- ngx.log(ngx.DEBUG, "Token: `" .. token .. "`")
-- By default, lua-resty-jwt does not validate claims, so we build up a
-- claim validation specification:
-- * DC/OS-specific `uid` claim to be present.
-- * make `exp` claim optional as some things still require "forever tokens"
local claim_spec = {
exp = jwt_validators.opt_is_not_expired(),
__jwt = jwt_validators.require_one_of({"uid"})
}
local jwt_obj = jwt:verify(secret_key, token, claim_spec)
ngx.log(ngx.DEBUG, "JSONnized JWT table: " .. cjson.encode(jwt_obj))
-- .verified is False even for messed up tokens whereas .valid can be nil.
-- So, use .verified as reference.
if jwt_obj.verified ~= true then
ngx.log(ngx.NOTICE, "Invalid token. Reason: ".. jwt_obj.reason)
return nil, 401
end
ngx.log(ngx.DEBUG, "Valid token. Extract UID from payload.")
local uid = jwt_obj.payload.uid
if uid == nil or uid == ngx.null then
ngx.log(ngx.NOTICE, "Unexpected token payload: missing uid.")
return nil, 401
end
ngx.log(ngx.NOTICE, "UID from the valid DC/OS authentication token: `".. uid .. "`")
return uid, nil
end
-- Expose interface.
local _M = {}
_M.exit_401 = exit_401
_M.exit_403 = exit_403
_M.validate_jwt = validate_jwt
return _M
| apache-2.0 |
kankaristo/premake-core | tests/actions/vstudio/vc2010/test_config_props.lua | 9 | 8064 | --
-- tests/actions/vstudio/vc2010/test_config_props.lua
-- Validate generation of the configuration property group.
-- Copyright (c) 2011-2013 Jason Perkins and the Premake project
--
local suite = test.declare("vstudio_vs2010_config_props")
local vc2010 = premake.vstudio.vc2010
local project = premake.project
--
-- Setup
--
local wks, prj
function suite.setup()
_ACTION = "vs2010"
wks, prj = test.createWorkspace()
end
local function prepare()
cfg = test.getconfig(prj, "Debug")
vc2010.configurationProperties(cfg)
end
--
-- Check the structure with the default project values.
--
function suite.structureIsCorrect_onDefaultValues()
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
]]
end
--
-- Check the configuration type for differenet project kinds.
--
function suite.configurationType_onConsoleApp()
kind "ConsoleApp"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
]]
end
function suite.configurationType_onWindowedApp()
kind "WindowedApp"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
]]
end
function suite.configurationType_onSharedLib()
kind "SharedLib"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
]]
end
function suite.configurationType_onStaticLib()
kind "StaticLib"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
]]
end
--
-- Debug configurations (for some definition of "debug") should use the debug libraries.
--
function suite.debugLibraries_onDebugConfig()
flags "Symbols"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
]]
end
--
-- Check the support for Unicode.
--
function suite.characterSet_onUnicode()
flags "Unicode"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
]]
end
--
-- Check the support for Managed C++.
--
function suite.clrSupport_onClrOn()
clr "On"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<CLRSupport>true</CLRSupport>
]]
end
function suite.clrSupport_onClrOff()
clr "Off"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
]]
end
function suite.clrSupport_onClrUnsafe()
clr "Unsafe"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<CLRSupport>true</CLRSupport>
]]
end
function suite.clrSupport_onClrSafe()
clr "Safe"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<CLRSupport>Safe</CLRSupport>
]]
end
function suite.clrSupport_onClrPure()
clr "Pure"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<CLRSupport>Pure</CLRSupport>
]]
end
--
-- Check the support for building with MFC.
--
function suite.useOfMfc_onDynamicRuntime()
flags "MFC"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<UseOfMfc>Dynamic</UseOfMfc>
]]
end
function suite.useOfMfc_onStaticRuntime()
flags { "MFC", "StaticRuntime" }
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<UseOfMfc>Static</UseOfMfc>
]]
end
--
-- Check the support for building with ATL.
--
function suite.useOfAtl_onDynamicRuntime()
atl "Dynamic"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<UseOfATL>Dynamic</UseOfATL>
]]
end
function suite.useOfAtl_onStaticRuntime()
atl "Static"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<UseOfATL>Static</UseOfATL>
]]
end
--
-- Check handling of the ReleaseRuntime flag; should override the
-- default behavior of linking the debug runtime when symbols are
-- enabled with no optimizations.
--
function suite.releaseRuntime_onFlag()
flags { "Symbols", "ReleaseRuntime" }
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
]]
end
--
-- Check the default settings for a Makefile configuration: new
-- configuration type, no character set, output and intermediate
-- folders are moved up from their normal location in the output
-- configuration element.
--
function suite.structureIsCorrect_onMakefile()
kind "Makefile"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Makefile</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<OutDir>bin\Debug\</OutDir>
<IntDir>obj\Debug\</IntDir>
</PropertyGroup>
]]
end
function suite.structureIsCorrect_onNone()
kind "None"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Makefile</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<OutDir>bin\Debug\</OutDir>
<IntDir>obj\Debug\</IntDir>
</PropertyGroup>
]]
end
--
-- Same as above but for Utility
--
function suite.structureIsCorrect_onUtility()
kind "Utility"
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Utility</ConfigurationType>
</PropertyGroup>
]]
end
--
-- Check the LinkTimeOptimization flag
--
function suite.useOfLinkTimeOptimization()
flags { "LinkTimeOptimization" }
prepare()
test.capture [[
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
]]
end
| bsd-3-clause |
Zero-K-Experiments/Zero-K-Experiments | LuaUI/Widgets/dbg_ceg_spawner.lua | 11 | 3062 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "CEG Spawner",
desc = "v0.031 Spawn CEGs",
author = "CarRepairer",
date = "2010-11-07",
license = "GPLv2",
layer = 5,
enabled = false, -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--Set to true to sort CEGs into alphabetic submenus. This cannot be added to epicmenu options because it's used to actually change those options.
local ALPHA = true
local echo = Spring.Echo
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
options_order = { 'reload', 'xdir', 'ydir', 'zdir', 'radius', }
options_path = 'Settings/Toolbox/CEG Spawner'
options = {
reload = {
name = 'Reload CEGs',
type = 'button',
OnChange = function() Spring.SendCommands('reloadcegs') end,
},
xdir = {
name = 'X (-1,1)',
type = 'number',
min = -1, max = 1, step = 0.1,
value = 0,
},
ydir = {
name = 'Y (-1,1)',
type = 'number',
min = -1, max = 1, step = 0.1,
value = 0,
},
zdir = {
name = 'Z (-1,1)',
type = 'number',
min = -1, max = 1, step = 0.1,
value = 0,
},
radius = {
name = 'Radius (0 - 100)',
type = 'number',
min = 0, max = 100, step = 1,
value = 20,
},
}
local vsx, vsy = widgetHandler:GetViewSizes()
local cx,cy = vsx * 0.5,vsy * 0.5
function OnChangeFunc(self)
if not Spring.IsCheatingEnabled() then
echo "Cannot do this unless Cheating is enabled."
return
end
cx,cy = vsx * 0.5,vsy * 0.5
local ttype,pos = Spring.TraceScreenRay(cx, cy, true)
if ttype == 'ground' then
Spring.SendLuaRulesMsg( '*' .. self.cegname
.. '|' .. pos[1]
.. '|' .. pos[2]
.. '|' .. pos[3]
.. '|' .. options.xdir.value
.. '|' .. options.ydir.value
.. '|' .. options.zdir.value
.. '|' .. options.radius.value
)
else
echo "Cannot do this with a unit in the center of the screen."
end
end
local function AddCEGButton(cegname)
options_order[#options_order+1] = cegname
options[cegname] = {
type = 'button',
name = cegname,
cegname = cegname,
OnChange = OnChangeFunc,
}
if ALPHA then
options[cegname].path = options_path..'/' .. cegname:sub(1,1):upper()
--echo ( options[cegname].path )
end
end
local function SetupOptions()
local explosionDefs = VFS.Include("gamedata/explosions.lua")
local explosions2 = {}
for k,v in pairs(explosionDefs) do
--echo(k,v)
explosions2[#explosions2+1] = k
end
table.sort(explosions2)
for i,v in ipairs(explosions2) do
AddCEGButton(v)
end
end
function widget:ViewResize(viewSizeX, viewSizeY)
vsx = viewSizeX
vsy = viewSizeY
cx = vsx * 0.5
cy = vsy * 0.5
end
function widget:Initialize()
SetupOptions()
end
| gpl-2.0 |
Scavenge/darkstar | scripts/zones/Port_Windurst/npcs/Milma-Hapilma_WW.lua | 13 | 5582 | -----------------------------------
-- Area: Port Windurst
-- NPC: Milma-Hapilma, W.W.
-- 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/Port_Windurst/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/globals/common");
require("scripts/zones/Port_Windurst/TextIDs");
local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, JEUNO
local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border
local size = #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
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 |
rm-code/lofivi | lib/graphoon/Graphoon/init.lua | 4 | 1526 | return {
_VERSION = 'Graphoon v1.0.1',
_DESCRIPTION = 'A force directed graph algorithm written in Lua.',
_URL = 'https://github.com/rm-code/Graphoon',
_LICENSE = [[
Copyright (c) 2015 - 2016 Robert Machmer
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]],
Edge = require( (...):gsub('%.init$', '') .. '.Edge' ),
Graph = require( (...):gsub('%.init$', '') .. '.Graph' ),
Node = require( (...):gsub('%.init$', '') .. '.Node' )
};
| mit |
raymoo/artifice | spell/registration.lua | 1 | 2629 |
-- "spell_env" refers to a table holding these fields:
-- - player - casting player's name. Could be nil if not a player.
-- - owner - Creator of the spell
-- - spell_id - Unique numerical ID of the spell
-- - cast_mode - Either 1, 2, or 3
-- - quality - Build quality. A nonnegative integer.
-- "shape_inout" refers to a table with these fields:
-- - type - Either "pointed", "directional", "node", or "entity"
-- - source_pos - Where the effect is coming from
-- - pointed_thing - if type == "pointed"
-- - direction - Only if type == "directional"
-- - above - If type == "node" (Might be nil)
-- - under - If type == "node" (Not nil)
-- - entity - An ObjectRef, and only if type == "entity"
-- "local_env" is a table with these fields:
-- - modifiers - A map from modifier names to levels
-- - affinities - A map from affinity names to levels (adds up to 1)
-- A spell component definition is a table with fields:
-- - type: Either "shape", "effect", or "modifier"
-- - disp_name: Display name
-- - description: A description of the effect
-- - texture: An icon for the component
-- - affinities: A map from affinity names to nonnegative integers
-- - calc_cost: A function taking a set of modifiers as input, outputting
-- a mana cost. In the case of type == "shape", this is a
-- multiplier applied to forward effects/shapes. If this is
-- type == "effect", then it is just a straight value, which you
-- should aim to be the casting cost of a medium casting mode
-- using a touch-based shape. This field has no effect for
-- modifiers.
-- - material_costs: A list of item names to spend during spell creation
-- - executor: An executor function with env type spell_env, param type
-- local_env, and input type shape_inout. For shapes, the
-- output is also shape_inout, but for effects it is a number,
-- representing XP gain. This field has no effect for modifiers.
--
-- **NOTE**: Once registered, this is just a string registered as
-- an executor.
-- - priority: An optional field, either "first", "last", or "exclusive". Only
-- for shapes.
-- Takes a component name and definition
function artifice.register_spell_component(name, def)
local actual_def = {}
for k,v in pairs(def) do
actual_def[k] = v
end
local actual_exec = def.type .. "_" .. name
artifice.exec.register_executor(actual_exec, def.executor)
actual_def.executor = actual_exec
artifice.components[name] = actual_def
end
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Quicksand_Caves/npcs/_5sc.lua | 14 | 1273 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: Ornate Door
-- Door blocked by Weight system
-- @pos -410 0 662 208
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local difX = player:getXPos()-(-410);
local difZ = player:getZPos()-(654);
local Distance = math.sqrt( math.pow(difX,2) + math.pow(difZ,2) );
if (Distance < 3) then
return -1;
end
player:messageSpecial(DOOR_FIRMLY_SHUT);
return 1;
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 |
Scavenge/darkstar | scripts/zones/Crawlers_Nest/npcs/Grounds_Tome.lua | 26 | 1094 | -----------------------------------
-- Area: Crawlers Nest
-- NPC: Grounds Tome
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/groundsofvalor");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startGov(GOV_EVENT_CRAWLERS_NEST,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,687,688,689,690,691,692,693,694,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,687,688,689,690,691,692,693,694,0,0,GOV_MSG_CRAWLERS_NEST);
end;
| gpl-3.0 |
1yvT0s/luvit | tests/test-http-client.lua | 6 | 2125 | --[[
Copyright 2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
require('tap')(function(test)
local fs = require('fs')
local http = require('http')
test("http-client", function(expect)
http.get('http://luvit.io', expect(function (res)
assert(res.statusCode == 301)
assert(res.httpVersion == '1.1')
res:on('data', function (chunk)
p("ondata", {chunk=chunk})
end)
res:on('end', expect(function ()
p('stream ended')
end))
end))
end)
test("http-client (errors are bubbled)", function(expect)
local socket = http.get('http://luvit.io:1234', function (res)
assert(false)
end)
socket:on('error',expect(function(err)
assert(not (err == nil))
end))
end)
test("http-client stream file", function(expect)
local port = 50010
local function interceptEmit(stream, logString)
local oldEmit = stream.emit
stream.emit = function(self, type, ...)
print(logString .. type)
return oldEmit(self, type, ...)
end
end
local server
server = http.createServer(function (req, res)
local f = fs.createReadStream(module.path)
interceptEmit(f, 'readable: ')
interceptEmit(res, 'response: ')
res:on('close', function() print('response: close(r)') server:destroy() end)
f:pipe(res)
end):listen(port, function()
print('Server running ' .. port)
http.get('http://127.0.0.1:' .. port, function (res)
res:on('data', p)
assert(res.statusCode == 200, 'validate status code')
end)
end)
end)
end)
| apache-2.0 |
Scavenge/darkstar | scripts/zones/Al_Zahbi/npcs/Kahah_Hobichai.lua | 17 | 1360 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Kahah Hobichai
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
require("scripts/zones/Al_Zahbi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,KAHAHHOBICHAI_SHOP_DIALOG);
stock = {0x005A,200, -- Rusty Bucket
0x025d,200, -- Pickaxe (not available when AC is taken)
0x03FC,300, -- Sickle (not available when AC is taken)
0x03FD,500, -- Hatchet (not available when AC is taken)
0x4051,164, -- Bronze Knife
0x4052,2425} -- Knife
showShop(player, STATIC, 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 |
gmorishere/i | libs/dkjson.lua | 3282 | 26558 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
========================================
*Version 2.4*
In the default configuration this module writes no global values, not even
the module table. Import it using
json = require ("dkjson")
In environments where `require` or a similiar function are not available
and you cannot receive the return value of the module, you can set the
option `register_global_module_table` to `true`. The module table will
then be saved in the global variable with the name given by the option
`global_module_name`.
Exported functions and values:
`json.encode (object [, state])`
--------------------------------
Create a string representing the object. `Object` can be a table,
a string, a number, a boolean, `nil`, `json.null` or any object with
a function `__tojson` in its metatable. A table can only use strings
and numbers as keys and its values have to be valid objects as
well. It raises an error for any invalid data types or reference
cycles.
`state` is an optional table with the following fields:
- `indent`
When `indent` (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.
- `keyorder`
`keyorder` is an array to specify the ordering of keys in the
encoded output. If an object has keys which are not in this array
they are written after the sorted keys.
- `level`
This is the initial level of indentation used when `indent` is
set. For each level two spaces are added. When absent it is set
to 0.
- `buffer`
`buffer` is an array to store the strings for the result so they
can be concatenated at once. When it isn't given, the encode
function will create it temporary and will return the
concatenated result.
- `bufferlen`
When `bufferlen` is set, it has to be the index of the last
element of `buffer`.
- `tables`
`tables` is a set to detect reference cycles. It is created
temporary when absent. Every table that is currently processed
is used as key, the value is `true`.
When `state.buffer` was set, the return value will be `true` on
success. Without `state.buffer` the return value will be a string.
`json.decode (string [, position [, null]])`
--------------------------------------------
Decode `string` starting at `position` or at 1 if `position` was
omitted.
`null` is an optional value to be returned for null values. The
default is `nil`, but you could set it to `json.null` or any other
value.
The return values are the object or `nil`, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.
Two metatables are created. Every array or object that is decoded gets
a metatable with the `__jsontype` field set to either `array` or
`object`. If you want to provide your own metatables use the syntax
json.decode (string, position, null, objectmeta, arraymeta)
To prevent the assigning of metatables pass `nil`:
json.decode (string, position, null, nil)
`<metatable>.__jsonorder`
-------------------------
`__jsonorder` can overwrite the `keyorder` for a specific table.
`<metatable>.__jsontype`
------------------------
`__jsontype` can be either `"array"` or `"object"`. This value is only
checked for empty tables. (The default for empty tables is `"array"`).
`<metatable>.__tojson (self, state)`
------------------------------------
You can provide your own `__tojson` function in a metatable. In this
function you can either add directly to the buffer and return true,
or you can return a string. On errors nil and a message should be
returned.
`json.null`
-----------
You can use this value for setting explicit `null` values.
`json.version`
--------------
Set to `"dkjson 2.4"`.
`json.quotestring (string)`
---------------------------
Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own `__tojson` functions.
`json.addnewline (state)`
-------------------------
When `state.indent` is set, add a newline to `state.buffer` and spaces
according to `state.level`.
LPeg support
------------
When the local configuration variable `always_try_using_lpeg` is set,
this module tries to load LPeg to replace the `decode` function. The
speed increase is significant. You can get the LPeg module at
<http://www.inf.puc-rio.br/~roberto/lpeg/>.
When LPeg couldn't be loaded, the pure Lua functions stay active.
In case you don't want this module to require LPeg on its own,
disable the option `always_try_using_lpeg` in the options section at
the top of the module.
In this case you can later load LPeg support using
### `json.use_lpeg ()`
Require the LPeg module and replace the functions `quotestring` and
and `decode` with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:
json = require "dkjson".use_lpeg()
Alternatively you can use `pcall` so the JSON module still works when
LPeg isn't found.
json = require "dkjson"
pcall (json.use_lpeg)
### `json.using_lpeg`
This variable is set to `true` when LPeg was loaded successfully.
---------------------------------------------------------------------
Contact
-------
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
---------------------------------------------------------------------
*Copyright (C) 2010-2013 David Heiko Kolf*
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<!-- This documentation can be parsed using Markdown to generate HTML.
The source code is enclosed in a HTML comment so it won't be displayed
by browsers, but it should be removed from the final HTML file as
it isn't a valid HTML comment (and wastes space).
-->
<!--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
--> | gpl-2.0 |
Scavenge/darkstar | scripts/zones/Port_Windurst/npcs/Hohbiba-Mubiba.lua | 17 | 1716 | -----------------------------------
-- Area: Port Windurst
-- NPC: Hohbiba-Mubiba
-- 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,HOHBIBAMUBIBA_SHOP_DIALOG);
stock = {
0x429B, 1440,1, --Yew Wand
0x42A3, 91,1, --Bronze Rod
0x42C2, 3642,1, --Elm Staff
0x42C9, 18422,1, --Elm Pole
0x429A, 340,2, --Willow Wand
0x4282, 4945,2, --Bone Cudgel
0x42C1, 584,2, --Holly Staff
0x42C8, 4669,2, --Holly Pole
0x4299, 47,3, --Maple Wand
0x4280, 66,3, --Ash Club
0x4281, 1600,3, --Chestnut Club
0x42C0, 58,3, --Ash Staff
0x42C7, 386,3, --Ash Pole
0x4040, 143,3 --Bronze Dagger
}
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 |
Zero-K-Experiments/Zero-K-Experiments | scripts/bomberstrike.lua | 12 | 3448 | include "constants.lua"
include "bombers.lua"
local fuselage = piece 'fuselage'
local wingl = piece 'wingl'
local wingr = piece 'wingr'
local enginel = piece 'enginel'
local enginer = piece 'enginer'
local head = piece 'head'
local turretbase = piece 'turretbase'
local turret = piece 'turret'
local sleevel = piece 'sleevel'
local sleever = piece 'sleever'
local barrell = piece 'barrell'
local barrelr = piece 'barrelr'
local flarel = piece 'flarel'
local flarer = piece 'flarer'
local bombl = piece 'bombl'
local bombr = piece 'bombr'
local bFirepoint1 = false
local bFirepoint2 = false
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function script.Create()
Turn(turret, y_axis, math.pi)
StartThread(SmokeUnit, smokePiece)
Move(wingl, x_axis, -5, 7)
Move(wingr, x_axis, 5, 7)
Hide(turretbase)
Hide(turret)
Hide(sleevel)
Hide(barrell)
Hide(sleever)
Hide(barrelr)
end
function script.Activate()
Move(wingl, x_axis, 0, 7)
Move(wingr, x_axis, 0, 7)
end
function script.Deactivate()
Move(wingl, x_axis, -5, 7)
Move(wingr, x_axis, 5, 7)
end
local function RestoreAfterDelay()
Sleep(Static_Var_1)
Turn(turret, y_axis, math.rad(180), math.rad(90))
Turn(sleevel, x_axis, 0, math.rad(50))
Turn(sleever, x_axis, 0, math.rad(50))
end
function script.AimWeapon(num, heading, pitch)
return true
end
function script.QueryWeapon(num)
if num == 1 then
return bFirepoint1 and bombl or bombr
elseif num == 2 then
return bFirepoint2 and flarel or flarer
end
end
function script.AimFromWeapon(num)
if num == 1 then
return bFirepoint1 and bombl or bombr
elseif num == 2 then
return bFirepoint2 and flarel or flarer
end
end
function script.AimWeapon(num, heading, pitch)
if num == 1 then
return (Spring.GetUnitRulesParam(unitID, "noammo") ~= 1)
elseif num == 2 then
Signal(SIG_AIM_2)
SetSignalMask(SIG_AIM_2)
Turn(turret, y_axis, math.rad(heading), math.rad(390))
Turn(sleevel, x_axis, 0, math.rad(350))
Turn(sleever, x_axis, 0, math.rad(350))
WaitForTurn(turret, y_axis)
WaitForTurn(sleevel, x_axis)
WaitForTurn(sleever, x_axis)
StartThread(RestoreAfterDelay)
return true
end
end
function script.Shot(num)
if num == 1 then
bFirepoint1 = not bFirepoint1
elseif num == 2 then
EmitSfx(turret, 1025)
if bFirepoint2 then
EmitSfx(flarel, 1024)
else
EmitSfx(flarer, 1024)
end
bFirepoint2 = not bFirepoint2
end
end
function script.FireWeapon(num)
if num == 1 then
Sleep(66)
Reload()
end
end
function script.AimFromWeapon(num)
return bFirepoint2 and flarel or flarer
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity <= .5 then
Explode(fuselage, sfxNone)
Explode(head, sfxNone)
Explode(wingl, sfxNone)
Explode(wingr, sfxNone)
Explode(enginel, sfxNone)
Explode(enginer, sfxNone)
Explode(turret, sfxNone)
Explode(sleevel, sfxNone)
Explode(sleever, sfxNone)
return 1
else
Explode(fuselage, sfxFall + sfxSmoke)
Explode(head, sfxFall + sfxSmoke + sfxFire)
Explode(wingl, sfxFall + sfxSmoke)
Explode(wingr, sfxFall + sfxSmoke)
Explode(enginel, sfxFall + sfxSmoke + sfxFire + sfxExplode)
Explode(enginer, sfxFall + sfxSmoke + sfxFire + sfxExplode)
Explode(turret, sfxFall + sfxSmoke + sfxFire)
Explode(sleevel, sfxFall + sfxSmoke)
Explode(sleever, sfxFall + sfxSmoke)
return 2
end
end
| gpl-2.0 |
Zero-K-Experiments/Zero-K-Experiments | LuaUI/Widgets/gui_point_tracker.lua | 7 | 8398 | -- $Id$
local versionNumber = "v2.3"
function widget:GetInfo()
return {
name = "Point Tracker",
desc = versionNumber .. " Tracks recently placed map points.",
author = "Evil4Zerggin",
date = "29 December 2008",
license = "GNU LGPL, v2.1 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
----------------------------------------------------------------
--config
----------------------------------------------------------------
--negative to disable blinking
local blinkPeriod = -1
local ttl = 15
local highlightSize = 32
local highlightLineMin = 24
local highlightLineMax = 40
local edgeMarkerSize = 16
local lineWidth = 1
local maxAlpha = 1
local fontSize = 16
local maxLabelLength = 16
local minimapHighlightSize = 8
local minimapHighlightLineMin = 6
local minimapHighlightLineMax = 10
local useFade = true
----------------------------------------------------------------
--speedups
----------------------------------------------------------------
local ArePlayersAllied = Spring.ArePlayersAllied
local GetPlayerInfo = Spring.GetPlayerInfo
local GetTeamColor = Spring.GetTeamColor
local GetSpectatingState = Spring.GetSpectatingState
local WorldToScreenCoords = Spring.WorldToScreenCoords
local glColor = gl.Color
local glRect = gl.Rect
local glLineWidth = gl.LineWidth
local glShape = gl.Shape
local glPolygonMode = gl.PolygonMode
local glText = gl.Text
local max = math.max
local abs = math.abs
local strSub = string.sub
local GL_LINES = GL.LINES
local GL_TRIANGLES = GL.TRIANGLES
local GL_LINE = GL.LINE
local GL_FRONT_AND_BACK = GL.FRONT_AND_BACK
local GL_FILL = GL.FILL
----------------------------------------------------------------
--vars
----------------------------------------------------------------
--table; i = {r, g, b, a, px, pz, label, expiration}
local mapPoints = {}
local mapPointCount = 0
local MAP_POINT_LIMIT = 50
local myPlayerID
local timeNow, timePart
local on = false
local mapX = Game.mapX * 512
local mapY = Game.mapY * 512
local vsx, vsy, sMidX, sMidY
----------------------------------------------------------------
--local functions
----------------------------------------------------------------
local function GetPlayerColor(playerID)
local _, _, isSpec, teamID = GetPlayerInfo(playerID)
if (isSpec) then return GetTeamColor(Spring.GetGaiaTeamID()) end
if (not teamID) then return nil end
return GetTeamColor(teamID)
end
local function StartTime()
local viewSizeX, viewSizeY = widgetHandler:GetViewSizes()
widget:ViewResize(viewSizeX, viewSizeY)
timeNow = 0
timePart = 0
on = true
end
local function ClearPoints()
mapPoints = {}
end
local function SetUseFade(bool)
useFade = bool
end
----------------------------------------------------------------
--callins
----------------------------------------------------------------
function widget:Initialize()
timeNow = false
timePart = false
myPlayerID = Spring.GetMyPlayerID()
WG.PointTracker = {
ClearPoints = ClearPoints,
SetUseFade = SetUseFade
}
end
function widget:Shutdown()
WG.PointTracker = nil
end
function widget:DrawScreen()
if (not on) then return end
glLineWidth(lineWidth)
local i = 1
while i <= mapPointCount do
local curr = mapPoints[i]
local alpha = maxAlpha * (curr[6] - timeNow) / ttl
if (alpha <= 0) then
mapPoints[i] = mapPoints[mapPointCount]
mapPoints[mapPointCount] = nil
mapPointCount = mapPointCount - 1
else
local sx, sy, sz = WorldToScreenCoords(curr[2], curr[3], curr[4])
glColor(curr[1][1], curr[1][2], curr[1][3], alpha)
if (sx >= 0 and sy >= 0
and sx <= vsx and sy <= vsy) then
--in screen
local vertices = {
{v = {sx, sy - highlightLineMin, 0}},
{v = {sx, sy - highlightLineMax, 0}},
{v = {sx, sy + highlightLineMin, 0}},
{v = {sx, sy + highlightLineMax, 0}},
{v = {sx - highlightLineMin, sy, 0}},
{v = {sx - highlightLineMax, sy, 0}},
{v = {sx + highlightLineMin, sy, 0}},
{v = {sx + highlightLineMax, sy, 0}},
}
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
glRect(sx - highlightSize, sy - highlightSize, sx + highlightSize, sy + highlightSize)
glShape(GL_LINES, vertices)
else
--out of screen
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
--flip if behind screen
if (sz > 1) then
sx = sMidX - sx
sy = sMidY - sy
end
local xRatio = sMidX / abs(sx - sMidX)
local yRatio = sMidY / abs(sy - sMidY)
local edgeDist, vertices, textX, textY, textOptions
if (xRatio < yRatio) then
edgeDist = (sy - sMidY) * xRatio + sMidY
if (sx > 0) then
vertices = {
{v = {vsx, edgeDist, 0}},
{v = {vsx - edgeMarkerSize, edgeDist + edgeMarkerSize, 0}},
{v = {vsx - edgeMarkerSize, edgeDist - edgeMarkerSize, 0}},
}
textX = vsx - edgeMarkerSize
textY = edgeDist - fontSize * 0.5
textOptions = "rn"
else
vertices = {
{v = {0, edgeDist, 0}},
{v = {edgeMarkerSize, edgeDist - edgeMarkerSize, 0}},
{v = {edgeMarkerSize, edgeDist + edgeMarkerSize, 0}},
}
textX = edgeMarkerSize
textY = edgeDist - fontSize * 0.5
textOptions = "n"
end
else
edgeDist = (sx - sMidX) * yRatio + sMidX
if (sy > 0) then
vertices = {
{v = {edgeDist, vsy, 0}},
{v = {edgeDist - edgeMarkerSize, vsy - edgeMarkerSize, 0}},
{v = {edgeDist + edgeMarkerSize, vsy - edgeMarkerSize, 0}},
}
textX = edgeDist
textY = vsy - edgeMarkerSize - fontSize
textOptions = "cn"
else
vertices = {
{v = {edgeDist, 0, 0}},
{v = {edgeDist + edgeMarkerSize, edgeMarkerSize, 0}},
{v = {edgeDist - edgeMarkerSize, edgeMarkerSize, 0}},
}
textX = edgeDist
textY = edgeMarkerSize
textOptions = "cn"
end
end
glShape(GL_TRIANGLES, vertices)
glColor(1, 1, 1, alpha)
glText(curr[5], textX, textY, fontSize, textOptions)
end
i = i + 1
end
end
glColor(1, 1, 1)
glLineWidth(1)
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
end
function widget:ViewResize(viewSizeX, viewSizeY)
vsx = viewSizeX
vsy = viewSizeY
sMidX = viewSizeX * 0.5
sMidY = viewSizeY * 0.5
end
function widget:MapDrawCmd(playerID, cmdType, px, py, pz, label)
if mapPointCount >= MAP_POINT_LIMIT then
return
end
if (not timeNow) then
StartTime()
end
local spectator, fullView = GetSpectatingState()
local _, _, _, playerTeam = GetPlayerInfo(playerID)
if (label == "Start " .. playerTeam
or cmdType ~= "point"
or not (ArePlayersAllied(myPlayerID, playerID) or (spectator and fullView))) then
return
end
local r, g, b = GetPlayerColor(playerID)
local color = {r, g, b}
local expiration = timeNow + ttl
mapPointCount = mapPointCount + 1
mapPoints[mapPointCount] = {color, px, py, pz, strSub(label, 1, maxLabelLength), expiration}
end
function widget:Update(dt)
if (not timeNow) then
StartTime()
else
if useFade then
timeNow = timeNow + dt
end
timePart = timePart + dt
if (timePart > blinkPeriod and blinkPeriod > 0) then
timePart = timePart - blinkPeriod
on = not on
end
end
end
function widget:DrawInMiniMap(sx, sy)
if (not on) then return end
glLineWidth(lineWidth)
local ratioX = sx / mapX
local ratioY = sy / mapY
local i = 1
while i <= mapPointCount do
local curr = mapPoints[i]
local x = curr[2] * ratioX
local y = sy - curr[4] * ratioY
local alpha = maxAlpha * (curr[6] - timeNow) / ttl
if (alpha <= 0) then
mapPoints[i] = mapPoints[mapPointCount]
mapPoints[mapPointCount] = nil
mapPointCount = mapPointCount - 1
else
glColor(curr[1][1], curr[1][2], curr[1][3], alpha)
local vertices = {
{v = {x, y - minimapHighlightLineMin, 0}},
{v = {x, y - minimapHighlightLineMax, 0}},
{v = {x, y + minimapHighlightLineMin, 0}},
{v = {x, y + minimapHighlightLineMax, 0}},
{v = {x - minimapHighlightLineMin, y, 0}},
{v = {x - minimapHighlightLineMax, y, 0}},
{v = {x + minimapHighlightLineMin, y, 0}},
{v = {x + minimapHighlightLineMax, y, 0}},
}
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
glRect(x - minimapHighlightSize, y - minimapHighlightSize, x + minimapHighlightSize, y + minimapHighlightSize)
glShape(GL_LINES, vertices)
i = i + 1
end
end
glColor(1, 1, 1)
glLineWidth(1)
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
end
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.