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 |
|---|---|---|---|---|---|
geanux/darkstar | scripts/globals/spells/windstorm.lua | 31 | 1153 | --------------------------------------
-- Spell: Windstorm
-- Changes the weather around target party member to "windy."
--------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
target:delStatusEffectSilent(EFFECT_FIRESTORM);
target:delStatusEffectSilent(EFFECT_SANDSTORM);
target:delStatusEffectSilent(EFFECT_RAINSTORM);
target:delStatusEffectSilent(EFFECT_WINDSTORM);
target:delStatusEffectSilent(EFFECT_HAILSTORM);
target:delStatusEffectSilent(EFFECT_THUNDERSTORM);
target:delStatusEffectSilent(EFFECT_AURORASTORM);
target:delStatusEffectSilent(EFFECT_VOIDSTORM);
local merit = caster:getMerit(MERIT_STORMSURGE);
local power = 0;
if merit > 0 then
power = merit + caster:getMod(MOD_STORMSURGE_EFFECT) + 2;
end
target:addStatusEffect(EFFECT_WINDSTORM,power,0,180);
return EFFECT_WINDSTORM;
end; | gpl-3.0 |
blackops97/SAJJAD.iq | plugins/ar-onservice.lua | 1 | 1360 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY SAJJAD HUSSIEN ▀▄ ▄▀
▀▄ ▄▀ BY SAJJADHUSSIEN (@sajjad_iq98) ▀▄ ▄▀
▀▄ ▄ JUST WRITED BY SAJJAD HUSSIEN ▀▄ ▄▀
▀▄ ▄▀ KICK BOT : طرد البوت ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
local function run(msg, matches)
local bot_id = our_id
local receiver = get_receiver(msg)
if matches[1] == 'طرد البوت' and is_admin1(msg) then
chat_del_user("chat#id"..msg.to.id, 'user#id'..bot_id, ok_cb, false)
leave_channel(receiver, ok_cb, false)
elseif msg.service and msg.action.type == "chat_add_user" and msg.action.user.id == tonumber(bot_id) and not is_admin1(msg) then
send_large_msg(receiver, 'This is not one of my groups.', ok_cb, false)
chat_del_user(receiver, 'user#id'..bot_id, ok_cb, false)
leave_channel(receiver, ok_cb, false)
end
end
return {
patterns = {
"^(طرد البوت)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
geanux/darkstar | scripts/globals/abilities/scavenge.lua | 18 | 2406 | -----------------------------------
-- Ability: Scavenge
-- Searches the ground around user for items.
-- Obtained: Ranger Level 10
-- Recast Time: 3:00
-- Duration: Instant
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability,action)
return 0,0;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player, target, ability, action)
-- RNG AF2 quest check
local FireAndBrimstoneCS = player:getVar("fireAndBrimstone");
if (player:getZoneID() == 151 and FireAndBrimstoneCS == 5 and -- zone + quest match
player:getYPos() > -43 and player:getYPos() < -38 and -- Y match
player:getXPos() > -85 and player:getXPos() < -73 and -- X match
player:getZPos() > -85 and player:getZPos() < -75 and -- Z match
math.random(100) < 50) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1113);
else
player:addItem(1113);
player:messageSpecial(ITEM_OBTAINED,1113);
end
else
local bonuses = (player:getMod(MOD_SCAVENGE_EFFECT) + player:getMerit(MERIT_SCAVENGE_EFFECT) ) / 100;
local arrowsToReturn = math.floor(math.floor(player:getLocalVar("ArrowsUsed") % 10000) * (player:getMainLvl() / 200 + bonuses));
if (arrowsToReturn == 0) then
action:setMessageID(139);
else
if (arrowsToReturn > 99) then
arrowsToReturn = 99;
end
local arrowID = math.floor(player:getLocalVar("ArrowsUsed") / 10000);
player:addItem(arrowID, arrowsToReturn);
if (arrowsToReturn == 1) then
action:setParam(arrowID);
action:setMessageID(140);
else
action:setParam(arrowID);
action:setMessageID(674);
action:setAdditionalEffect(1);
action:setAddEffectParam(arrowsToReturn);
end
end
-- Reset use count
player:setLocalVar("ArrowsUsed", 0);
end
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Northern_San_dOria/npcs/Madaline.lua | 36 | 1615 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Madaline
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
Telmoda_Madaline = player:getVar("Telmoda_Madaline_Event");
if (Telmoda_Madaline ~= 1) then
player:setVar(player,"Telmoda_Madaline_Event",1);
player:startEvent(0x0213);
else
player:startEvent(0x0269);
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 |
ModusCreateOrg/libOpenMPT-ios | libopenmpt-0.2.6401/build/premake/mpt-OpenMPT-VSTi.lua | 1 | 2745 |
project "OpenMPT-VSTi"
uuid "d1ad4072-c810-4eea-95d0-27fdfa764834"
language "C++"
location ( "../../build/" .. _ACTION )
objdir "../../build/obj/OpenMPT-VSTi"
dofile "../../build/premake/premake-defaults-DLL.lua"
dofile "../../build/premake/premake-defaults.lua"
includedirs {
"../../common",
"../../soundlib",
"../../include",
"../../include/msinttypes/inttypes",
"../../include/vstsdk2.4",
"../../include/ASIOSDK2/common",
"../../include/flac/include",
"../../include/lhasa/lib/public",
"../../include/ogg/include",
"../../include/opus/include",
"../../include/opusfile/include",
"../../include/portaudio/include",
"../../include/vorbis/include",
"../../include/zlib",
"$(IntDir)/svn_version",
"../../build/svn_version",
}
files {
"../../mptrack/res/OpenMPT.manifest",
}
files {
"../../common/*.cpp",
"../../common/*.h",
"../../soundlib/*.cpp",
"../../soundlib/*.h",
"../../soundlib/plugins/*.cpp",
"../../soundlib/plugins/*.h",
"../../soundlib/plugins/dmo/*.cpp",
"../../soundlib/plugins/dmo/*.h",
"../../sounddsp/*.cpp",
"../../sounddsp/*.h",
"../../sounddev/*.cpp",
"../../sounddev/*.h",
"../../unarchiver/*.cpp",
"../../unarchiver/*.h",
"../../mptrack/*.cpp",
"../../mptrack/*.h",
"../../test/*.cpp",
"../../test/*.h",
"../../pluginBridge/BridgeCommon.h",
"../../pluginBridge/BridgeWrapper.cpp",
"../../pluginBridge/BridgeWrapper.h",
"../../plugins/MidiInOut/*.cpp",
"../../plugins/MidiInOut/*.h",
}
files {
"../../mptrack/mptrack.rc",
"../../mptrack/res/*.*", -- resource data files
}
excludes {
"../../mptrack/res/rt_manif.bin", -- the old build system manifest
}
pchheader "stdafx.h"
pchsource "../../common/stdafx.cpp"
defines { "MODPLUG_TRACKER" }
defines { "OPENMPT_VST" }
exceptionhandling "SEH"
defines { "MPT_EXCEPTIONS_SEH" }
characterset "MBCS"
flags { "MFC", "ExtraWarnings", "WinMain" }
links {
"UnRAR",
"zlib",
"minizip",
"smbPitchShift",
"lhasa",
"flac",
"ogg",
"opus",
"opusfile",
"portaudio",
"portmidi",
"r8brain",
"soundtouch",
"vorbis",
}
linkoptions {
"/DELAYLOAD:uxtheme.dll",
}
filter { "configurations:*Shared" }
filter { "not configurations:*Shared" }
linkoptions {
"/DELAYLOAD:OpenMPT_SoundTouch_f32.dll",
}
targetname "mptrack"
filter {}
filter { "not action:vs2008" }
linkoptions {
"/DELAYLOAD:mf.dll",
"/DELAYLOAD:mfplat.dll",
"/DELAYLOAD:mfreadwrite.dll",
-- "/DELAYLOAD:mfuuid.dll", -- static library
"/DELAYLOAD:propsys.dll",
}
filter {}
prebuildcommands { "..\\..\\build\\svn_version\\update_svn_version_vs_premake.cmd $(IntDir)" }
| bsd-3-clause |
geanux/darkstar | scripts/globals/items/wizard_cookie.lua | 35 | 1345 | -----------------------------------------
-- ID: 4576
-- Item: wizard_cookie
-- Food Effect: 5Min, All Races
-----------------------------------------
-- MP Recovered While Healing 7
-- Plantoid Killer 7
-- Slow Resist 7
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4576);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MPHEAL, 7);
target:addMod(MOD_PLANTOID_KILLER, 7);
target:addMod(MOD_SLOWRES, 7);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MPHEAL, 7);
target:delMod(MOD_PLANTOID_KILLER, 7);
target:delMod(MOD_SLOWRES, 7);
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Port_Windurst/npcs/Kuroido-Moido.lua | 17 | 3895 | -----------------------------------
-- Area: Port Windurst
-- NPC: Kuriodo-Moido
-- Involved In Quest: Making Amends, Wonder Wands
-- Starts and Finishes: Making Amens!
-- Working 100%
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
MakingAmends = player:getQuestStatus(WINDURST,MAKING_AMENDS); --First quest in series
MakingAmens = player:getQuestStatus(WINDURST,MAKING_AMENS); --Second quest in series
WonderWands = player:getQuestStatus(WINDURST,WONDER_WANDS); --Third and final quest in series
pfame = player:getFameLevel(WINDURST);
needToZone = player:needToZone();
BrokenWand = player:hasKeyItem(128);
if (MakingAmends == QUEST_ACCEPTED) then -- MAKING AMENDS: During Quest
player:startEvent(0x0114);
elseif (MakingAmends == QUEST_COMPLETED and MakingAmens ~= QUEST_COMPLETED and WonderWands ~= QUEST_COMPLETED and needToZone) then -- MAKING AMENDS: After Quest
player:startEvent(0x0117);
elseif (MakingAmends == QUEST_COMPLETED and MakingAmens == QUEST_AVAILABLE) then
if (pfame >=4 and not needToZone) then
player:startEvent(0x0118); -- Start Making Amens! if prerequisites are met
else
player:startEvent(0x0117); -- MAKING AMENDS: After Quest
end
elseif (MakingAmens == QUEST_ACCEPTED and not BrokenWand) then -- Reminder for Making Amens!
player:startEvent(0x011b);
elseif (MakingAmens == QUEST_ACCEPTED and BrokenWand) then -- Complete Making Amens!
player:startEvent(0x011c,GIL_RATE*6000);
elseif (MakingAmens == QUEST_COMPLETED) then
if (WonderWands == QUEST_ACCEPTED) then -- During Wonder Wands dialogue
player:startEvent(0x0105);
elseif (WonderWands == QUEST_COMPLETED) then -- Post Wonder Wands dialogue
player:startEvent(0x010a);
else
player:startEvent(0x011e,0,937); -- Post Making Amens! dialogue (before Wonder Wands)
end
elseif (player:getCurrentMission(ASA) == THAT_WHICH_CURDLES_BLOOD) 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(0x035a, item, 1134, 2778, 2778, 4099, 2778);
else
rand = math.random(1,2);
if (rand == 1) then
player:startEvent(0x00e1); -- Standard Conversation
else
player:startEvent(0x00e2); -- Standard Conversation
end
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 == 0x0118) then
player:addQuest(WINDURST,MAKING_AMENS);
elseif (csid == 0x011c) then
player:needToZone(true);
player:delKeyItem(BROKEN_WAND);
player:addTitle(HAKKURURINKURUS_BENEFACTOR);
player:addGil(GIL_RATE*6000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*6000);
player:addFame(WINDURST,WIN_FAME*150);
player:completeQuest(WINDURST,MAKING_AMENS);
end
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Sealions_Den/npcs/Jovial_Rat.lua | 38 | 1034 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Jovial Rat
-- Type: Past Event Watcher
-- @zone: 32
-- @pos
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0004);
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 |
AliNiestani/ADMIN | bot/utils.lua | 646 | 23489 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
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
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
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
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
amirh0211/shatelbot | bot/utils.lua | 646 | 23489 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
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
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
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
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
omidtarh/wizard | plugins/twitter_send.lua | 627 | 1555 | do
local OAuth = require "OAuth"
local consumer_key = ""
local consumer_secret = ""
local access_token = ""
local access_token_secret = ""
local client = OAuth.new(consumer_key, consumer_secret, {
RequestToken = "https://api.twitter.com/oauth/request_token",
AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"},
AccessToken = "https://api.twitter.com/oauth/access_token"
}, {
OAuthToken = access_token,
OAuthTokenSecret = access_token_secret
})
function run(msg, matches)
if consumer_key:isempty() then
return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua"
end
if consumer_secret:isempty() then
return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua"
end
if access_token:isempty() then
return "Twitter Access Token is empty, write it in plugins/twitter_send.lua"
end
if access_token_secret:isempty() then
return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua"
end
if not is_sudo(msg) then
return "You aren't allowed to send tweets"
end
local response_code, response_headers, response_status_line, response_body =
client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", {
status = matches[1]
})
if response_code ~= 200 then
return "Error: "..response_code
end
return "Tweet sent"
end
return {
description = "Sends a tweet",
usage = "!tw [text]: Sends the Tweet with the configured account.",
patterns = {"^!tw (.+)"},
run = run
}
end
| gpl-2.0 |
sepehrpk/bot1 | plugins/twitter_send.lua | 627 | 1555 | do
local OAuth = require "OAuth"
local consumer_key = ""
local consumer_secret = ""
local access_token = ""
local access_token_secret = ""
local client = OAuth.new(consumer_key, consumer_secret, {
RequestToken = "https://api.twitter.com/oauth/request_token",
AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"},
AccessToken = "https://api.twitter.com/oauth/access_token"
}, {
OAuthToken = access_token,
OAuthTokenSecret = access_token_secret
})
function run(msg, matches)
if consumer_key:isempty() then
return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua"
end
if consumer_secret:isempty() then
return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua"
end
if access_token:isempty() then
return "Twitter Access Token is empty, write it in plugins/twitter_send.lua"
end
if access_token_secret:isempty() then
return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua"
end
if not is_sudo(msg) then
return "You aren't allowed to send tweets"
end
local response_code, response_headers, response_status_line, response_body =
client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", {
status = matches[1]
})
if response_code ~= 200 then
return "Error: "..response_code
end
return "Tweet sent"
end
return {
description = "Sends a tweet",
usage = "!tw [text]: Sends the Tweet with the configured account.",
patterns = {"^!tw (.+)"},
run = run
}
end
| gpl-2.0 |
kaen/Zero-K | LuaUI/Widgets/unit_start_state.lua | 2 | 26450 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Unit Start State",
desc = "Configurable starting unit states for units",
author = "GoogleFrog",
date = "13 April 2011", --last update: 29 January 2014
license = "GNU GPL, v2 or later",
handler = false,
layer = 1,
enabled = true -- loaded by default?
}
end
VFS.Include("LuaRules/Configs/customcmds.h.lua")
local holdPosException = {
["factoryplane"] = true,
["factorygunship"] = true,
["armnanotc"] = true,
}
local dontFireAtRadarUnits = {
[UnitDefNames["armsnipe"].id] = true,
[UnitDefNames["armmanni"].id] = true,
[UnitDefNames["armanni"].id] = true,
[UnitDefNames["armmerl"].id] = true,
}
--local rememberToSetHoldPositionPreset = false
local function IsGround(ud)
return not ud.canFly
end
options_path = 'Game/New Unit States'
options_order = { 'presetlabel', 'holdPosition', 'disableTacticalAI', 'enableTacticalAI', 'categorieslabel', 'commander_label', 'commander_firestate0', 'commander_movestate1', 'commander_constructor_buildpriority', 'commander_misc_priority', 'commander_retreat'}
options = {
presetlabel = {name = "presetlabel", type = 'label', value = "Presets", path = options_path},
holdPosition = {
type='button',
name= "Hold Position",
desc = "Set all land units to hold position",
path = "Game/New Unit States/Presets",
OnChange = function ()
for i = 1, #options_order do
local opt = options_order[i]
local find = string.find(opt, "_movestate1")
local name = find and string.sub(opt,0,find-1)
local ud = name and UnitDefNames[name]
if ud and not holdPosException[name] and IsGround(ud) then
options[opt].value = 0
--return
end
end
end,
},
categorieslabel = {name = "presetlabel", type = 'label', value = "Categories", path = options_path},
disableTacticalAI = {
type='button',
name= "Disable Tactical AI",
desc = "Disables tactical AI (jinking and skirming) for all units.",
path = "Game/New Unit States/Presets",
OnChange = function ()
for i = 1, #options_order do
local opt = options_order[i]
local find = string.find(opt, "_tactical_ai_2")
local name = find and string.sub(opt,0,find-1)
local ud = name and UnitDefNames[name]
if ud then
options[opt].value = false
end
end
end,
},
enableTacticalAI = {
type='button',
name= "Enable Tactical AI",
desc = "Enables tactical AI (jinking and skirming) for all units.",
path = "Game/New Unit States/Presets",
OnChange = function ()
for i = 1, #options_order do
local opt = options_order[i]
local find = string.find(opt, "_tactical_ai_2")
local name = find and string.sub(opt,0,find-1)
local ud = name and UnitDefNames[name]
if ud then
options[opt].value = true
end
end
end,
},
commander_label = {
name = "label",
type = 'label',
value = "Commander",
path = "Game/New Unit States/Misc",
},
commander_firestate0 = {
name = " Firestate",
desc = "Values: hold fire, return fire, fire at will",
type = 'number',
value = 2, -- commander are fire@will by default
min = 0, -- most firestates are -1 but no factory/unit build comm (yet)
max = 2,
step = 1,
path = "Game/New Unit States/Misc",
},
commander_movestate1 = {
name = " Movestate",
desc = "Values: hold position, maneuver, roam",
type = 'number',
value = 1,
min = 0,-- no factory/unit build comm (yet)
max = 2,
step = 1,
path = "Game/New Unit States/Misc",
},
--[[
commander_buildpriority_0 = {
name = " Nanoframe Build Priority",
desc = "Values: Inherit, Low, Normal, High",
type = 'number',
value = -1,
min = -1,
max = 2,
step = 1,
path = "Game/New Unit States/Misc",
},
--]]
commander_constructor_buildpriority = {
name = " Constructor Build Priority",
desc = "Values: Low, Normal, High",
type = 'number',
value = 1,
min = 0,
max = 2,
step = 1,
path = "Game/New Unit States/Misc",
},
commander_misc_priority = {
name = " Miscellaneous Priority",
desc = "Values: Low, Normal, High",
type = 'number',
value = 1,
min = 0,
max = 2,
step = 1,
path = "Game/New Unit States/Misc",
},
commander_retreat = {
name = " Retreat at value",
desc = "Values: no retreat, 30%, 65%, 99% health remaining",
type = 'number',
value = 0,
min = 0,
max = 3,
step = 1,
path = "Game/New Unit States/Misc",
},
}
local tacticalAIDefs, behaviourDefaults = VFS.Include("LuaRules/Configs/tactical_ai_defs.lua", nil, VFS.ZIP)
local tacticalAIUnits = {}
for unitDefName, behaviourData in pairs(tacticalAIDefs) do
tacticalAIUnits[unitDefName] = {value = (behaviourData.defaultAIState or behaviourDefaults.defaultState) == 1}
end
local unitAlreadyAdded = {}
local function addLabel(text, path) -- doesn't work with order
path = (path and "Game/New Unit States/" .. path) or "Game/New Unit States"
options[text .. "_label"] = {
name = "label",
type = 'label',
value = text,
path = path,
}
options_order[#options_order+1] = text .. "_label"
end
local function addUnit(defName, path)
if unitAlreadyAdded[defName] then
return
end
unitAlreadyAdded[defName] = true
path = "Game/New Unit States/" .. path
local ud = UnitDefNames[defName]
if not ud then
Spring.Echo("Initial States invalid unit " .. defName)
return
end
options[defName .. "_label"] = {
name = "label",
type = 'label',
value = ud.humanName,
path = path,
}
options_order[#options_order+1] = defName .. "_label"
if ud.canAttack or ud.isFactory then
options[defName .. "_firestate0"] = {
name = " Firestate",
desc = "Values: inherit from factory, hold fire, return fire, fire at will",
type = 'number',
value = ud.fireState, -- most firestates are -1
min = -1,
max = 2,
step = 1,
path = path,
}
options_order[#options_order+1] = defName .. "_firestate0"
end
if (ud.canMove or ud.canPatrol) and ((not ud.isBuilding) or ud.isFactory) then
options[defName .. "_movestate1"] = {
name = " Movestate",
desc = "Values: inherit from factory, hold position, maneuver, roam",
type = 'number',
value = ud.moveState,
min = -1,
max = 2,
step = 1,
path = path,
}
options_order[#options_order+1] = defName .. "_movestate1"
end
if (ud.canFly) then
options[defName .. "_flylandstate_1"] = {
name = " Fly/Land State",
desc = "Values: inherit from factory, fly, land",
type = 'number',
value = (ud.customParams and ud.customParams.landflystate and ((ud.customParams.landflystate == "1" and 1) or 0)) or -1,
min = -1,
max = 1,
step = 1,
path = path,
}
options_order[#options_order+1] = defName .. "_flylandstate_1"
--[[
options[defName .. "_autorepairlevel1"] = {
name = " Auto Repair to airpad",
desc = "Values: inherit from factory, no autorepair, 30%, 50%, 80% health remaining",
type = 'number',
value = -1,
min = -1,
max = 3,
step = 1,
path = path,
}
options_order[#options_order+1] = defName .. "_autorepairlevel1"
--]]
elseif ud.customParams and ud.customParams.landflystate then
options[defName .. "_flylandstate_1_factory"] = {
name = " Fly/Land State for factory",
desc = "Values: fly, land",
type = 'number',
value = (ud.customParams and ud.customParams.landflystate and ud.customParams.landflystate == "1" and 1) or 0,
min = 0,
max = 1,
step = 1,
path = path,
}
options_order[#options_order+1] = defName .. "_flylandstate_1_factory"
--[[
options[defName .. "_autorepairlevel_factory"] = {
name = " Auto Repair to airpad",
desc = "Values: no autorepair, 30%, 50%, 80% health remaining",
type = 'number',
value = 0, -- auto repair is stupid
min = 0,
max = 3,
step = 1,
path = path,
}
options_order[#options_order+1] = defName .. "_autorepairlevel_factory"
--]]
end
if ud.isFactory then
options[defName .. "_repeat"] = {
name = " Repeat",
desc = "Repeat: check box to turn it on",
type = 'bool',
value = false,
path = path,
}
options_order[#options_order+1] = defName .. "_repeat"
end
if ud.customParams and ud.customParams.airstrafecontrol then
options[defName .. "_airstrafe1"] = {
name = " Air Strafe",
desc = "Air Strafe: check box to turn it on",
type = 'bool',
value = ud.customParams.airstrafecontrol == "1",
path = path,
}
options_order[#options_order+1] = defName .. "_airstrafe1"
end
if ud.customParams and ud.customParams.floattoggle then
options[defName .. "_floattoggle"] = {
name = " Float State",
desc = "Values: Never float, float to attack, float when stationary",
type = 'number',
value = (ud.customParams and ud.customParams.floattoggle) or 1,
min = 0,
max = 2,
step = 1,
path = path,
}
options_order[#options_order+1] = defName .. "_floattoggle"
end
options[defName .. "_buildpriority_0"] = {
name = " Nanoframe Build Priority",
desc = "Values: Inherit, Low, Normal, High",
type = 'number',
value = -1,
min = -1,
max = 2,
step = 1,
path = path,
}
options_order[#options_order+1] = defName .. "_buildpriority_0"
if ud.speed == 0 then
options[defName .. "_buildpriority_0"].value = 1
end
if ud.canAssist and ud.buildSpeed ~= 0 then
options[defName .. "_constructor_buildpriority"] = {
name = " Constructor Build Priority",
desc = "Values: Inherit, Low, Normal, High",
type = 'number',
value = 1,
min = -1,
max = 2,
step = 1,
path = path,
}
options_order[#options_order+1] = defName .. "_constructor_buildpriority"
end
if ud.customParams.priority_misc then
options[defName .. "_misc_priority"] = {
name = " Miscellaneous Priority",
desc = "Values: Low, Normal, High",
type = 'number',
value = ud.customParams.priority_misc,
min = 0,
max = 2,
step = 1,
path = path,
}
options_order[#options_order+1] = defName .. "_misc_priority"
end
if (ud.canMove or ud.isFactory) then
options[defName .. "_retreatpercent"] = {
name = " Retreat at value",
desc = "Values: inherit from factory, no retreat, 33%, 65%, 99% health remaining",
type = 'number',
value = -1,
min = -1,
max = 3,
step = 1,
path = path,
}
options_order[#options_order+1] = defName .. "_retreatpercent"
end
if tacticalAIUnits[defName] then
options[defName .. "_tactical_ai_2"] = {
name = " Smart AI",
desc = "Smart AI: check box to turn it on",
type = 'bool',
value = tacticalAIUnits[defName].value,
path = path,
}
options_order[#options_order+1] = defName .. "_tactical_ai_2"
end
if dontFireAtRadarUnits[ud.id] then
options[defName .. "_fire_at_radar"] = {
name = " Fire at radar",
desc = "Check box to make these units fire at radar. All other units fire at radar but these have the option not to.",
type = 'bool',
value = true,
path = path,
}
options_order[#options_order+1] = defName .. "_fire_at_radar"
end
if ud.canCloak then
options[defName .. "_personal_cloak_0"] = {
name = " Personal Cloak",
desc = "Personal Cloak: check box to turn it on",
type = 'bool',
value = ud.customParams.initcloaked,
path = path,
}
options_order[#options_order+1] = defName .. "_personal_cloak_0"
end
if ud.onOffable then
options[defName .. "_activateWhenBuilt"] = {
name = " On/Off State",
desc = "Check box to set the unit to On when built.",
type = 'bool',
value = ud.activateWhenBuilt,
path = path,
}
options_order[#options_order+1] = defName .. "_activateWhenBuilt"
end
end
local function AddFactoryOfUnits(defName)
if unitAlreadyAdded[defName] then
return
end
local ud = UnitDefNames[defName]
local name = string.gsub(ud.humanName, "/", "-")
addUnit(defName, name)
for i = 1, #ud.buildOptions do
addUnit(UnitDefs[ud.buildOptions[i]].name, name)
end
end
AddFactoryOfUnits("factoryshield")
AddFactoryOfUnits("factorycloak")
AddFactoryOfUnits("factoryveh")
AddFactoryOfUnits("factoryplane")
AddFactoryOfUnits("factorygunship")
AddFactoryOfUnits("factoryhover")
AddFactoryOfUnits("factoryamph")
AddFactoryOfUnits("factoryspider")
AddFactoryOfUnits("factoryjump")
AddFactoryOfUnits("factorytank")
AddFactoryOfUnits("factoryship")
AddFactoryOfUnits("striderhub")
AddFactoryOfUnits("missilesilo")
-- addUnit("striderhub","Mech")
-- addUnit("armcsa","Mech")
-- addUnit("armcomdgun","Mech")
-- addUnit("dante","Mech")
-- addUnit("armraven","Mech")
-- addUnit("armbanth","Mech")
-- addUnit("gorg","Mech")
-- addUnit("armorco","Mech")
local buildOpts = VFS.Include("gamedata/buildoptions.lua")
local _, _, factory_commands, econ_commands, defense_commands, special_commands, _, _, _ = include("Configs/integral_menu_commands.lua")
for i = 1, #buildOpts do
local name = buildOpts[i]
if econ_commands[-UnitDefNames[name].id] then
addUnit(name,"Economy")
elseif defense_commands[-UnitDefNames[name].id] then
addUnit(name,"Defence")
elseif special_commands[-UnitDefNames[name].id] then
addUnit(name,"Special")
else
addUnit(name,"Misc")
end
end
function widget:UnitCreated(unitID, unitDefID, unitTeam, builderID)
if unitTeam == Spring.GetMyTeamID() and unitDefID and UnitDefs[unitDefID] then
local ud = UnitDefs[unitDefID]
local orderArray = {}
if ud.customParams.commtype or ud.customParams.level then
local morphed = Spring.GetTeamRulesParam(unitTeam, "morphUnitCreating") == 1
if morphed then -- unit states are applied in unit_morph gadget
return
end
-- Spring.GiveOrderToUnit(unitID, CMD.FIRE_STATE, {options.commander_firestate0.value}, {"shift"})
-- Spring.GiveOrderToUnit(unitID, CMD.MOVE_STATE, {options.commander_movestate1.value}, {"shift"})
-- Spring.GiveOrderToUnit(unitID, CMD_RETREAT, {options.commander_retreat.value}, {"shift"})
orderArray[1] = {CMD.FIRE_STATE, {options.commander_firestate0.value}, {"shift"}}
orderArray[2] = {CMD.MOVE_STATE, {options.commander_movestate1.value}, {"shift"}}
if WG['retreat'] then
WG['retreat'].addRetreatCommand(unitID, unitDefID, options.commander_retreat.value)
end
end
local name = ud.name
if unitAlreadyAdded[name] then
if options[name .. "_firestate0"] and options[name .. "_firestate0"].value then
if options[name .. "_firestate0"].value == -1 then
if builderID then
local bdid = Spring.GetUnitDefID(builderID)
if UnitDefs[bdid] and UnitDefs[bdid].isFactory then
local firestate = Spring.GetUnitStates(builderID).firestate
if firestate then
--Spring.GiveOrderToUnit(unitID, CMD.FIRE_STATE, {firestate}, {"shift"})
orderArray[#orderArray + 1] = {CMD.FIRE_STATE, {firestate}, {"shift"}}
end
end
end
else
--Spring.GiveOrderToUnit(unitID, CMD.FIRE_STATE, {options[name .. "_firestate0"].value}, {"shift"})
orderArray[#orderArray + 1] = {CMD.FIRE_STATE, {options[name .. "_firestate0"].value}, {"shift"}}
end
end
if options[name .. "_movestate1"] and options[name .. "_movestate1"].value then
if options[name .. "_movestate1"].value == -1 then
if builderID then
local bdid = Spring.GetUnitDefID(builderID)
if UnitDefs[bdid] and UnitDefs[bdid].isFactory then
local movestate = Spring.GetUnitStates(builderID).movestate
if movestate then
--Spring.GiveOrderToUnit(unitID, CMD.MOVE_STATE, {movestate}, {"shift"})
orderArray[#orderArray + 1] = {CMD.MOVE_STATE, {movestate}, {"shift"}}
end
end
end
else
--Spring.GiveOrderToUnit(unitID, CMD.MOVE_STATE, {options[name .. "_movestate1"].value}, {"shift"})
orderArray[#orderArray + 1] = {CMD.MOVE_STATE, {options[name .. "_movestate1"].value}, {"shift"}}
end
end
if options[name .. "_flylandstate_1"] and options[name .. "_flylandstate_1"].value then
--NOTE: The unit_air_plants gadget deals with inherit
if options[name .. "_flylandstate_1"].value ~= -1 then --if not inherit
--Spring.GiveOrderToUnit(unitID, CMD.IDLEMODE, {options[name .. "_flylandstate_1"].value}, {"shift"})
orderArray[#orderArray + 1] = {CMD.IDLEMODE, {options[name .. "_flylandstate_1"].value}, {"shift"}}
end
end
if options[name .. "_flylandstate_1_factory"] and options[name .. "_flylandstate_1_factory"].value then
orderArray[#orderArray + 1] = {CMD_AP_FLY_STATE, {options[name .. "_flylandstate_1_factory"].value}, {"shift"}}
end
--[[
if options[name .. "_autorepairlevel_factory"] and options[name .. "_autorepairlevel_factory"].value then
orderArray[#orderArray + 1] = {CMD_AP_AUTOREPAIRLEVEL, {options[name .. "_autorepairlevel_factory"].value}, {"shift"}}
end
if options[name .. "_autorepairlevel1"] and options[name .. "_autorepairlevel1"].value then
--NOTE: The unit_air_plants gadget deals with inherit
if options[name .. "_autorepairlevel1"].value ~= -1 then --if not inherit
orderArray[#orderArray + 1] = {CMD.AUTOREPAIRLEVEL, {options[name .. "_autorepairlevel1"].value}, {"shift"}}
elseif not builderID then --if set to inherit but don't have parent (builder):
orderArray[#orderArray + 1] = {CMD.AUTOREPAIRLEVEL, {0}, {"shift"}}
end
end
--]]
if options[name .. "_repeat"] and options[name .. "_repeat"].value ~= nil then
-- Spring.GiveOrderToUnit(unitID, CMD.REPEAT, {options[name .. "_repeat"].value and 1 or 0}, {"shift"})
orderArray[#orderArray + 1] = {CMD.REPEAT, {options[name .. "_repeat"].value and 1 or 0}, {"shift"}}
end
if options[name .. "_airstrafe1"] and options[name .. "_airstrafe1"].value ~= nil then
-- Spring.GiveOrderToUnit(unitID, CMD_AIR_STRAFE, {options[name .. "_airstrafe1"].value and 1 or 0}, {"shift"})
orderArray[#orderArray + 1] = {CMD_AIR_STRAFE, {options[name .. "_airstrafe1"].value and 1 or 0}, {"shift"}}
end
if options[name .. "_floattoggle"] and options[name .. "_floattoggle"].value ~= nil then
-- Spring.GiveOrderToUnit(unitID, CMD_UNIT_FLOAT_STATE, {options[name .. "_floattoggle"].value}, {"shift"})
orderArray[#orderArray + 1] = {CMD_UNIT_FLOAT_STATE, {options[name .. "_floattoggle"].value}, {"shift"}}
end
if options[name .. "_retreatpercent"] and options[name .. "_retreatpercent"].value then
local retreat = options[name .. "_retreatpercent"].value
if retreat == -1 then --if inherit
if builderID then
retreat = Spring.GetUnitRulesParam(builderID,"retreatState")
else
retreat = nil
end
end
if retreat then
if retreat == 0 then
orderArray[#orderArray + 1] = {CMD_RETREAT, {0}, {"shift", "right"}} -- to set retreat to 0, "right" option must be used
else
orderArray[#orderArray + 1] = {CMD_RETREAT, {retreat}, {"shift"}}
end
end
end
if options[name .. "_buildpriority_0"] and options[name .. "_buildpriority_0"].value then
if options[name .. "_buildpriority_0"].value == -1 then
if builderID then
local priority = Spring.GetUnitRulesParam(builderID,"buildpriority")
if priority then
-- Spring.GiveOrderToUnit(unitID, CMD_PRIORITY, {priority}, {"shift"})
orderArray[#orderArray + 1] = {CMD_PRIORITY, {priority}, {"shift"}}
end
else
-- Spring.GiveOrderToUnit(unitID, CMD_PRIORITY, {1}, {"shift"})
orderArray[#orderArray + 1] = {CMD_PRIORITY, {1}, {"shift"}}
end
else
-- Spring.GiveOrderToUnit(unitID, CMD_PRIORITY, {options[name .. "_buildpriority_0"].value}, {"shift"})
orderArray[#orderArray + 1] = {CMD_PRIORITY, {options[name .. "_buildpriority_0"].value}, {"shift"}}
end
end
if options[name .. "_misc_priority"] and options[name .. "_misc_priority"].value then
if options[name .. "_misc_priority"].value ~= 1 then -- Medium is the default
orderArray[#orderArray + 1] = {CMD_MISC_PRIORITY, {options[name .. "_misc_priority"].value}, {"shift"}}
end
end
if options[name .. "_tactical_ai_2"] and options[name .. "_tactical_ai_2"].value ~= nil then
-- Spring.GiveOrderToUnit(unitID, CMD_UNIT_AI, {options[name .. "_tactical_ai_2"].value and 1 or 0}, {"shift"})
orderArray[#orderArray + 1] = {CMD_UNIT_AI, {options[name .. "_tactical_ai_2"].value and 1 or 0}, {"shift"}}
end
if options[name .. "_fire_at_radar"] and options[name .. "_fire_at_radar"].value ~= nil then
-- Spring.GiveOrderToUnit(unitID, CMD_DONT_FIRE_AT_RADAR, {options[name .. "_fire_at_radar"].value and 0 or 1}, {"shift"})
orderArray[#orderArray + 1] = {CMD_DONT_FIRE_AT_RADAR, {options[name .. "_fire_at_radar"].value and 0 or 1}, {"shift"}}
end
if options[name .. "_personal_cloak_0"] and options[name .. "_personal_cloak_0"].value ~= nil then
-- Spring.GiveOrderToUnit(unitID, CMD_WANT_CLOAK, {options[name .. "_personal_cloak_0"].value and 1 or 0}, {"shift"})
orderArray[#orderArray + 1] = {CMD_WANT_CLOAK, {options[name .. "_personal_cloak_0"].value and 1 or 0}, {"shift"}}
end
if options[name .. "_activateWhenBuilt"] and options[name .. "_activateWhenBuilt"].value ~= nil then
if options[name .. "_activateWhenBuilt"].value ~= ud.activateWhenBuilt then
orderArray[#orderArray + 1] = {CMD.ONOFF, {options[name .. "_activateWhenBuilt"].value and 1 or 0}, {"shift"}}
end
end
end
if #orderArray>0 then
Spring.GiveOrderArrayToUnitArray ({unitID,},orderArray) --give out all orders at once
end
orderArray = nil
end
end
--[[
function widget:SelectionChanged(newSelection)
for i=1,#newSelection do
local unitID = newSelection[i]
widget:UnitCreated(unitID, Spring.GetUnitDefID(unitID), Spring.GetMyTeamID())
end
end
--]]
function widget:UnitFromFactory(unitID, unitDefID, unitTeam, factID, factDefID, userOrders)
if unitTeam == Spring.GetMyTeamID() and unitDefID and UnitDefs[unitDefID] then
local name = UnitDefs[unitDefID].name
if options[name .. "_constructor_buildpriority"] and options[name .. "_constructor_buildpriority"].value then
if options[name .. "_constructor_buildpriority"].value == -1 then
local priority = Spring.GetUnitRulesParam(factID,"buildpriority")
if priority then
Spring.GiveOrderToUnit(unitID, CMD_PRIORITY, {priority}, {"shift"})
end
end
end
end
end
function widget:UnitFinished(unitID, unitDefID, unitTeam)
if unitTeam == Spring.GetMyTeamID() and unitDefID and UnitDefs[unitDefID] and (Spring.GetTeamRulesParam(unitTeam, "morphUnitCreating") ~= 1) then
local orderArray = {}
if UnitDefs[unitDefID].customParams.commtype or UnitDefs[unitDefID].customParams.level then
-- Spring.GiveOrderToUnit(unitID, CMD_PRIORITY, {options.commander_constructor_buildpriority.value}, {"shift"})
orderArray[1] = {CMD_PRIORITY, {options.commander_constructor_buildpriority.value}, {"shift"}}
orderArray[2] = {CMD_MISC_PRIORITY, {options.commander_misc_priority.value}, {"shift"}}
end
local name = UnitDefs[unitDefID].name
if options[name .. "_constructor_buildpriority"] and options[name .. "_constructor_buildpriority"].value then
if options[name .. "_constructor_buildpriority"].value ~= -1 then
-- Spring.GiveOrderToUnit(unitID, CMD_PRIORITY, {options[name .. "_constructor_buildpriority"].value}, {"shift"})
orderArray[#orderArray + 1] = {CMD_PRIORITY, {options[name .. "_constructor_buildpriority"].value}, {"shift"}}
end
end
if #orderArray>0 then
Spring.GiveOrderArrayToUnitArray ({unitID,},orderArray) --give out all orders at once
end
orderArray = nil
end
end
function widget:UnitGiven(unitID, unitDefID, newTeamID, teamID)
widget:UnitCreated(unitID, unitDefID, newTeamID)
widget:UnitFinished(unitID, unitDefID, newTeamID)
end
function widget:GameFrame(n)
if n >= 10 then
local team = Spring.GetMyTeamID()
local units = Spring.GetTeamUnits(team)
if units then
for i = 1, #units do
widget:UnitCreated(units[i], Spring.GetUnitDefID(units[i]), team, nil)
end
end
widgetHandler:RemoveCallIn("GameFrame")
end
end
--[[
function widget:Update()
if rememberToSetHoldPositionPreset then
for i = 1, #options_order do
local opt = options_order[i]
local find = string.find(opt, "_movestate1")
local name = find and string.sub(opt,0,find-1)
local ud = name and UnitDefNames[name]
if ud and not holdPosException[name] and IsGround(ud) then
options[opt].value = 0
end
end
rememberToSetHoldPositionPreset = false
end
end
--]] | gpl-2.0 |
SirFrancisBillard/lua-projects | crimeplus/lua/entities/rp_pot.lua | 1 | 4815 | AddCSLuaFile()
ENT.Type = "anim"
ENT.Base = "base_gmodentity"
ENT.PrintName = "Pot"
ENT.Category = "Crime+"
ENT.Spawnable = true
ENT.Model = "models/props_c17/metalPot001a.mdl"
function ENT:Initialize()
self:SetModel(self.Model)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
if SERVER then
self:PhysicsInit(SOLID_VPHYSICS)
self:SetUseType(SIMPLE_USE)
end
local phys = self:GetPhysicsObject()
if IsValid(phys) then
phys:Wake()
end
self:SetCookingProgress(0)
local Ang = self:GetAngles()
Ang:RotateAroundAxis(Ang:Up(), 90)
self:SetAngles(Ang)
if CLIENT then
self.EmitTime = CurTime()
self.FirePlace = ParticleEmitter(self:GetPos())
end
end
function ENT:SetupDataTables()
self:NetworkVar("Int", 0, "CookingProgress")
self:NetworkVar("Bool", 0, "HasSodium")
self:NetworkVar("Bool", 1, "HasChloride")
self:NetworkVar("Entity", 0, "Stove")
end
function ENT:IsOnStove()
for k, v in pairs(ents.FindInSphere(self:GetPos(), 12)) do
if (v:GetClass() == "rp_stove") and v:GetHasCanister() and (v:GetCanister():GetFuel() > 0) then
self:SetStove(v)
return IsValid(self)
end
end
end
function ENT:CanCook()
return (self:GetHasSodium() and self:GetHasChloride() and self:IsOnStove())
end
function ENT:DoneCooking()
return (self:GetCookingProgress() >= 100)
end
if SERVER then
function ENT:StartTouch(ent)
if IsValid(ent) then
if (ent:GetClass() == "rp_sodium") and (not self:GetHasSodium()) then
SafeRemoveEntity(ent)
self:SetHasSodium(true)
self:EmitSound(Sound("ambient/levels/canals/toxic_slime_sizzle"..math.random(2, 4)..".wav"))
self:VisualEffect()
end
if (ent:GetClass() == "rp_chloride") and (not self:GetHasChloride()) then
SafeRemoveEntity(ent)
self:SetHasChloride(true)
self:EmitSound(Sound("ambient/levels/canals/toxic_slime_sizzle"..math.random(2, 4)..".wav"))
self:VisualEffect()
end
end
end
function ENT:Think()
if self:CanCook() and (not self:DoneCooking()) then
self:SetCookingProgress(math.Clamp(self:GetCookingProgress() + 1, 0, 100))
self:GetStove():GetCanister():SetFuel(math.Clamp(self:GetStove():GetCanister():GetFuel() - 1, 0, 200))
if (math.random(1, 2) == 2) then
self:EmitSound(Sound("ambient/levels/canals/toxic_slime_gurgle"..math.random(2, 8)..".wav"))
end
end
self:NextThink(CurTime() + 1)
return true
end
function ENT:Use(activator, caller)
if IsValid(caller) and caller:IsPlayer() then
if self:DoneCooking() then
self:SetCookingProgress(0)
self:SetHasSodium(false)
self:SetHasChloride(false)
local meth = ents.Create("rp_meth")
meth:SetPos(self:GetPos() + Vector(0, 0, 30))
meth:Spawn()
self:EmitSound(Sound("ambient/levels/canals/toxic_slime_sizzle"..math.random(2, 4)..".wav"))
end
end
end
function ENT:VisualEffect()
local smoke = EffectData()
smoke:SetStart(self:GetPos())
smoke:SetOrigin(self:GetPos() + Vector(0, 0, 8))
smoke:SetScale(8)
util.Effect("GlassImpact", smoke, true, true)
end
end
// CLEITN
if CLIENT then
function ENT:Draw()
self:DrawModel()
local Pos = self:GetPos()
local Ang = self:GetAngles()
surface.SetFont("Trebuchet24")
Ang:RotateAroundAxis(Ang:Forward(), 90)
cam.Start3D2D(Pos + (Ang:Up() * 8) + (Ang:Right() * -2), Ang, 0.12)
draw.RoundedBox(2, -50, -65, 100, 30, Color(140, 0, 0, 100))
if (self:GetCookingProgress() > 0) then
draw.RoundedBox(2, -50, -65, self:GetCookingProgress(), 30, Color(0, 225, 0, 100))
end
draw.SimpleText("Progress", "Trebuchet24", -40, -63, Color(255, 255, 255, 255))
draw.WordBox(2, -55, -30, "Ingredients:", "Trebuchet24", Color(0, 225, 0, 100), Color(255, 255, 255, 255))
draw.WordBox(2, -35, 5, "Sodium", "Trebuchet24", self:GetHasSodium() and Color(0, 225, 0, 100) or Color(140, 0, 0, 100), Color(255, 255, 255, 255))
draw.WordBox(2, -40, 40, "Chloride", "Trebuchet24", self:GetHasChloride() and Color(0, 225, 0, 100) or Color(140, 0, 0, 100), Color(255, 255, 255, 255))
cam.End3D2D()
end
function ENT:Think()
if (self.EmitTime <= CurTime()) and self:CanCook() and (not self:DoneCooking()) then
local smoke = self.FirePlace:Add("particle/smokesprites_000"..math.random(1,9), self:GetPos())
smoke:SetVelocity(Vector(0, 0, 150))
smoke:SetDieTime(math.Rand(0.6, 2.3))
smoke:SetStartAlpha(math.Rand(150, 200))
smoke:SetEndAlpha(0)
smoke:SetStartSize(math.random(0, 5))
smoke:SetEndSize(math.random(33, 55))
smoke:SetRoll(math.Rand(180, 480))
smoke:SetRollDelta(math.Rand(-3, 3))
smoke:SetColor(125, 125, 125)
smoke:SetGravity(Vector(0, 0, 10))
smoke:SetAirResistance(256)
self.EmitTime = CurTime() + 0.1
end
end
end
| gpl-3.0 |
kaen/Zero-K | scripts/carrydrone.lua | 17 | 3451 | include "constants.lua"
local spGetUnitVelocity = Spring.GetUnitVelocity
--local math = math
--pieces
local fuselage = piece "fuselage"
local rotor1 = piece "rotor1"
local rotor2 = piece "rotor2"
local engineL = piece "enginel"
local engineR = piece "enginer"
local tailL = piece "taill"
local tailR = piece "tailr"
local wingL = piece "wingl"
local wingR = piece "wingr"
local podL = piece "podl"
local podR = piece "podr"
local gunpod = piece "gunpod"
local pivot = piece "pivot"
local barrel = piece "barrel"
local flare = piece "flare"
local smokePiece = {fuselage, engineL, engineR}
--constants
local tiltAngle = math.rad(10)
local tiltSpeed = math.rad(30)
local rotorSpeed = math.rad(1080)
local rotorAccel = math.rad(240)
local rotorDecel = math.rad(120)
local pivotSpeed = math.rad(180)
--variables
local tilt = 0
--signals
local SIG_Aim = 1
--cob values
----------------------------------------------------------
local function Tilt()
while true do
local vx, vy, vz = spGetUnitVelocity(unitID)
local vel = (vx^2 + vz^2)^0.5 --horizontal speed
vel = math.max(vel - 1.5, 0) --counteract jerking
--Spring.Echo(vel)
tilt = math.min(tiltAngle * vel, math.rad(20)) --cap at 20 degree tilt
Turn(fuselage, x_axis, tilt, tiltSpeed)
WaitForTurn(fuselage, x_axis)
Sleep(330)
end
end
function script.MoveRate(n)
--Turn(fuselage, x_axis, math.rad(10)*n, tiltSpeed)
end
local function RotorStart()
Spin(rotor1, y_axis, rotorSpeed, rotorAccel)
Spin(rotor2, y_axis, -rotorSpeed, rotorAccel)
end
local function RotorStop()
StopSpin(rotor1, y_axis, rotorDecel)
StopSpin(rotor2, y_axis, rotorDecel)
end
function script.Create()
StartThread(Tilt)
StartThread(RotorStart)
end
function script.StartMoving()
end
function script.StopMoving()
end
function script.QueryWeapon1() return flare end
function script.AimFromWeapon1() return gunpod end
function script.AimWeapon1(heading, pitch)
Signal(SIG_Aim)
SetSignalMask(SIG_Aim)
Turn(pivot, y_axis, heading, pivotSpeed)
Turn(pivot, x_axis, -pitch - tilt, pivotSpeed)
WaitForTurn(pivot, y_axis)
WaitForTurn(pivot, x_axis)
return true
end
function script.Shot1()
EmitSfx (gunpod, 1025)
EmitSfx (flare, 1024)
end
function script.Killed(recentDamage, maxHealth)
local severity = (recentDamage/maxHealth) * 100
if severity < 50 then
Explode(rotor1, sfxFall)
Explode(rotor2, sfxFall)
Explode(fuselage, sfxNone)
Explode(engineL, sfxSmoke)
Explode(engineR, sfxSmoke)
Explode(wingL, sfxNone)
Explode(wingR, sfxNone)
Explode(podL, sfxNone)
Explode(podR, sfxNone)
Explode(tailL, sfxNone)
Explode(tailR, sfxNone)
elseif severity < 100 then
Explode(rotor1, sfxSmoke)
Explode(rotor2, sfxSmoke)
Explode(fuselage, sfxShatter)
Explode(engineL, sfxSmoke + sfxFire + sfxExplode)
Explode(engineR, sfxSmoke + sfxFire + sfxExplode)
Explode(wingL, sfxFall)
Explode(wingR, sfxFall)
Explode(podL, sfxSmoke + sfxExplode)
Explode(podR, sfxSmoke + sfxExplode)
Explode(tailL, sfxFall)
Explode(tailR, sfxFall)
else
Explode(rotor1, sfxSmoke + sfxFire)
Explode(rotor2, sfxSmoke + sfxFire)
Explode(fuselage, sfxShatter)
Explode(engineL, sfxSmoke + sfxFire + sfxExplode)
Explode(engineR, sfxSmoke + sfxFire + sfxExplode)
Explode(wingL, sfxSmoke)
Explode(wingR, sfxSmoke)
Explode(podL, sfxSmoke + sfxFire + sfxExplode)
Explode(podR, sfxSmoke + sfxFire + sfxExplode)
Explode(tailL, sfxSmoke)
Explode(tailR, sfxSmoke)
end
end
| gpl-2.0 |
gwx/tome-elementals-race | data/libs/auto-temps-0.lua | 5 | 1697 | -- 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 3 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, see <http://www.gnu.org/licenses/>.
superload('mod.class.Actor', function(_M)
--- Apply the temporary values defined in a table.
-- The values will be recorded in source.__tmpvals to be automatically
-- discarded at the appropriate time.
-- @param source The source we're applying the values from/to.
-- @param values The table of {attribute -> increase} values we're applying. Defaults to source.temps.
function _M:autoTemporaryValues(source, values)
values = values or source.temps
for attribute, value in pairs(values) do
self:effectTemporaryValue(source, attribute, value)
end
return source
end
--- Remove the temporary values defined by autoTemporaryValues, or similar calls.
-- Removes all values in source.__tmpvals.
-- @param source The source we're applying the values of.
function _M:autoTemporaryValuesRemove(source)
values = values or source.temps
if not source.__tmpvals then return end
for _, val in pairs(source.__tmpvals) do
self:removeTemporaryValue(val[1], val[2])
end
source.__tmpvals = nil
end
end)
| gpl-3.0 |
sodzawic/tk | epan/wslua/dtd_gen.lua | 38 | 8369 | -- dtd_gen.lua
--
-- a DTD generator for wireshark
--
-- (c) 2006 Luis E. Garcia Ontanon <luis@ontanon.org>
--
-- Wireshark - Network traffic analyzer
-- By Gerald Combs <gerald@wireshark.org>
-- Copyright 1998 Gerald Combs
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
if gui_enabled() then
local xml_fld = Field.new("xml")
local function dtd_generator()
local displayed = {} -- whether or not a dtd is already displayed
local dtds = {} -- the dtds
local changed = {} -- whether or not a dtd has been modified
local dtd -- the dtd being dealt with
local dtd_name -- its name
-- we'll tap onto every frame that has xml
local ws = {} -- the windows for each dtd
local w = TextWindow.new("DTD Generator")
local function help()
local wh = TextWindow.new("DTD Generator Help")
-- XXX write help
wh:set('DTD Generator Help\n')
end
local function get_dtd_from_xml(text,d,parent)
-- obtains dtd information from xml
-- text: xml to be parsed
-- d: the current dtd (if any)
-- parent: parent entity (if any)
-- cleanup the text from useless chars
text = string.gsub(text ,"%s*<%s*","<");
text = string.gsub(text ,"%s*>%s*",">");
text = string.gsub(text ,"<%-%-(.-)%-%->"," ");
text = string.gsub(text ,"%s+"," ");
while true do
-- find the first tag
local open_tag = string.match(text,"%b<>")
if open_tag == nil then
-- no more tags, we're done
return true
end
local name = string.match(open_tag,"[%w%d_-]+")
local this_ent = nil
if d == nil then
-- there's no current dtd, this is entity is it
d = dtds[name]
if d == nil then
d = {ents = {}, attrs = {}}
dtds[name] = d
end
dtd = d
dtd_name = name
end
this_ent = d[name]
if this_ent == nil then
-- no entity by this name in this dtd, create it
this_ent = {ents = {}, attrs = {}}
d.ents[name] = this_ent
changed[dtd_name] = true
end
if parent ~= nil then
-- add this entity to its parent
parent.ents[name] = 1
changed[dtd_name] = true
end
-- add the attrs to the entity
for att in string.gmatch(open_tag, "([%w%d_-]+)%s*=") do
if not this_ent.attrs[att] then
changed[dtd_name] = true
this_ent.attrs[att] = true
end
end
if string.match(open_tag,"/>") then
-- this tag is "self closed" just remove it and continue
text = string.gsub(text,"%b<>","",1)
else
local close_tag_pat = "</%s*" .. name .. "%s*>"
if not string.match(text,close_tag_pat) then return false end
local span,left = string.match(text,"%b<>(.-)" .. close_tag_pat .. "(.*)")
if span ~= nil then
-- recurse to find child entities
if not get_dtd_from_xml(span,d,this_ent) then
return false
end
end
-- continue with what's left
text = left
end
end
return true
end
local function entity_tostring(name,entity_data)
-- name: the name of the entity
-- entity_data: a table containg the entity data
-- returns the dtd text for that entity
local text = ''
text = text .. '\t<!ELEMENT ' .. name .. ' (' --)
for e,j in pairs(entity_data.ents) do
text = text .. " " .. e .. ' |'
end
text = text .. " #PCDATA ) >\n"
text = text .. "\t<!ATTLIST " .. name
for a,j in pairs(entity_data.attrs) do
text = text .. "\n\t\t" .. a .. ' CDTATA #IMPLIED'
end
text = text .. " >\n\n"
text = string.gsub(text,"<!ATTLIST " .. name .. " >\n","")
return text
end
local function dtd_tostring(name,doctype)
local text = '<? wireshark:protocol proto_name="' .. name ..'" hierarchy="yes" ?>\n\n'
local root = doctype.ents[name]
doctype.ents[name] = nil
text = text .. entity_tostring(name,root)
for n,es in pairs(doctype.ents) do
text = text .. entity_tostring(n,es)
end
doctype.ents[name] = root
return text
end
local function element_body(name,text)
-- get the entity's children from dtd text
-- name: the name of the element
-- text: the list of children
text = string.gsub(text,"[%s%?%*%#%+%(%)]","")
text = string.gsub(text,"$","|")
text = string.gsub(text,
"^(.-)|",
function(s)
if dtd.ents[name] == nil then
dtd.ents[name] = {ents={},attrs={}}
end
dtd.ents[name].ents[s] = true
return ""
end
)
return ''
end
local function attlist_body(name,text)
-- get the entity's attributes from dtd text
-- name: the name of the element
-- text: the list of attributes
text = string.gsub(text,"([%w%d_-]+) [A-Z]+ #[A-Z]+",
function(s)
dtd.atts[s] = true
return ""
end
)
return ''
end
local function dtd_body(buff)
-- get the dtd's entities from dtd text
-- buff: the dtd text
local old_buff = buff
buff = string.gsub(buff,"<!ELEMENT ([%w%d_-]+) (%b())>%s*",element_body)
buff = string.gsub(buff,"<!ATTLIST ([%w%d_-]+) (.-)>%s*",attlist_body)
end
local function load_dtd(filename)
local dtd_filename = USER_DIR .. "/dtds/" .. filename
local buff = ''
local wireshark_info
dtd_name = nil
dtd = nil
for line in io.lines(dtd_filename) do
buff = buff .. line
end
buff = string.gsub(buff ,"%s*<%!%s*","<!");
buff = string.gsub(buff ,"%s*>%s*",">");
buff = string.gsub(buff ,"<!%-%-(.-)%-%->"," ");
buff = string.gsub(buff ,"%s+"," ");
buff = string.gsub(buff ,"^%s+","");
buff = string.gsub(buff,'(<%?%s*wireshark:protocol%s+.-%s*%?>)',
function(s)
wireshark_info = s
end
)
buff = string.gsub(buff,"^<!DOCTYPE ([%w%d_-]+) (%b[])%s*>",
function(name,body)
dtd = { ents = {}, attrs = {}}
dtd_name = name
dtds[name] = dtd
dtd_body(body)
return ""
end
)
if not dtd then
dtd_body(buff)
end
if wireshark_info then
dtd.wstag = wireshark_info
end
end
local function load_dtds()
-- loads all existing dtds in the user directory
local dirname = persconffile_path("dtds")
local status, dir = pcall(Dir.open,dirname,".dtd")
w:set('Loading DTDs from ' .. dirname .. ' \n')
if not status then
w:append("Error: could not open the directory" .. dirname .. " , make sure it exists.\n")
return
end
for dtd_filename in dir do
w:append("File:" .. dtd_filename .. "\n")
load_dtd(dtd_filename)
end
end
local function dtd_window(name)
return function()
local wd = TextWindow.new(name .. '.dtd')
wd:set(dtd_tostring(name,dtds[name]))
wd:set_editable()
local function save()
local file = io.open(persconffile_path("dtds/") .. name .. ".dtd" ,"w")
file:write(wd:get_text())
file:close()
end
wd:add_button("Save",save)
end
end
local function close()
if li ~= nil then
li:remove()
li = nil
end
end
w:set_atclose(close)
-- w:add_button("Help",help)
load_dtds()
local li = Listener.new("frame","xml")
w:append('Running')
function li.packet()
w:append('.')
local txt = xml_fld().range:string();
get_dtd_from_xml(txt)
end
function li.draw()
for name,j in pairs(changed) do
w:append("\n" .. name .. " has changed\n")
if not displayed[name] then
w:add_button(name,dtd_window(name))
displayed[name] = true
end
end
end
retap_packets()
w:append(t2s(dtds))
w:append('\n')
end
register_menu("DTD Generator",dtd_generator,MENU_TOOLS_UNSORTED)
end
| gpl-2.0 |
geanux/darkstar | scripts/globals/items/plate_of_sole_sushi.lua | 14 | 1743 | -----------------------------------------
-- ID: 5149
-- Item: plate_of_sole_sushi
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP 20
-- Strength 5
-- Dexterity 6
-- Accuracy % 15
-- Ranged ACC % 15
-- Sleep Resist 5
-----------------------------------------
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,5149);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_STR, 5);
target:addMod(MOD_DEX, 6);
target:addMod(MOD_ACCP, 15);
target:addMod(MOD_FOOD_ACC_CAP, 72);
target:addMod(MOD_RACCP, 15);
target:addMod(MOD_FOOD_RACC_CAP, 72);
target:addMod(MOD_SLEEPRES, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_STR, 5);
target:delMod(MOD_DEX, 6);
target:delMod(MOD_ACCP, 15);
target:delMod(MOD_FOOD_ACC_CAP, 72);
target:delMod(MOD_RACCP, 15);
target:delMod(MOD_FOOD_RACC_CAP, 72);
target:delMod(MOD_SLEEPRES, 5);
end;
| gpl-3.0 |
forward619/luci | applications/luci-app-asterisk/luasrc/model/cbi/asterisk/trunk_sip.lua | 68 | 2351 | -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local ast = require("luci.asterisk")
--
-- SIP trunk info
--
if arg[2] == "info" then
form = SimpleForm("asterisk", "SIP Trunk Information")
form.reset = false
form.submit = "Back to overview"
local info, keys = ast.sip.peer(arg[1])
local data = { }
for _, key in ipairs(keys) do
data[#data+1] = {
key = key,
val = type(info[key]) == "boolean"
and ( info[key] and "yes" or "no" )
or ( info[key] == nil or #info[key] == 0 )
and "(none)"
or tostring(info[key])
}
end
itbl = form:section(Table, data, "SIP Trunk %q" % arg[1])
itbl:option(DummyValue, "key", "Key")
itbl:option(DummyValue, "val", "Value")
function itbl.parse(...)
luci.http.redirect(
luci.dispatcher.build_url("admin", "asterisk", "trunks")
)
end
return form
--
-- SIP trunk config
--
elseif arg[1] then
cbimap = Map("asterisk", "Edit SIP Trunk")
peer = cbimap:section(NamedSection, arg[1])
peer.hidden = {
type = "peer",
qualify = "yes",
}
back = peer:option(DummyValue, "_overview", "Back to trunk overview")
back.value = ""
back.titleref = luci.dispatcher.build_url("admin", "asterisk", "trunks")
sipdomain = peer:option(Value, "host", "SIP Domain")
sipport = peer:option(Value, "port", "SIP Port")
function sipport.cfgvalue(...)
return AbstractValue.cfgvalue(...) or "5060"
end
username = peer:option(Value, "username", "Authorization ID")
password = peer:option(Value, "secret", "Authorization Password")
password.password = true
outboundproxy = peer:option(Value, "outboundproxy", "Outbound Proxy")
outboundport = peer:option(Value, "outboundproxyport", "Outbound Proxy Port")
register = peer:option(Flag, "register", "Register with peer")
register.enabled = "yes"
register.disabled = "no"
regext = peer:option(Value, "registerextension", "Extension to register (optional)")
regext:depends({register="1"})
didval = peer:option(ListValue, "_did", "Number of assigned DID numbers")
didval:value("", "(none)")
for i=1,24 do didval:value(i) end
dialplan = peer:option(ListValue, "context", "Dialplan Context")
dialplan:value(arg[1] .. "_inbound", "(default)")
cbimap.uci:foreach("asterisk", "dialplan",
function(s) dialplan:value(s['.name']) end)
return cbimap
end
| apache-2.0 |
geanux/darkstar | scripts/zones/Mhaura/npcs/Nomad_Moogle.lua | 34 | 1116 | -----------------------------------
-- Area: Mhaura
-- NPC: Nomad Moogle
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mhaura/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,NOMAD_MOOGLE_DIALOG);
player:sendMenu(1);
end;
-----------------------------------
-- onEventUpdate Action
-----------------------------------
function onEventUpdate(player,csid,option)
--print("onEventUpdate");
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--print("onEventFinish");
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Lufaise_Meadows/mobs/Leshy.lua | 29 | 1618 | -----------------------------------
-- Area: Lufaise Meadows
-- MOB: Leshy
-----------------------------------
function onMobRoam(mob)
local Colorful_Leshy = 16875762;
local Colorful_Leshy_PH = 0;
local Colorful_Leshy_PH_Table =
{
16875754,
16875755,
16875756,
16875757,
16875758,
16875759,
16875760,
16875761
};
local Colorful_Leshy_ToD = GetMobByID(Colorful_Leshy):getLocalVar("1");
if (Colorful_Leshy_ToD <= os.time()) then
Colorful_Leshy_PH = math.random((0), (table.getn(Colorful_Leshy_PH_Table)));
if (Colorful_Leshy_PH_Table[Colorful_Leshy_PH] ~= nil) then
if (GetMobAction(Colorful_Leshy) == 0) then
SetServerVariable("Colorful_Leshy_PH", Colorful_Leshy_PH_Table[Colorful_Leshy_PH]);
DeterMob(Colorful_Leshy_PH_Table[Colorful_Leshy_PH], true);
DeterMob(Colorful_Leshy, false);
DespawnMob(Colorful_Leshy_PH_Table[Colorful_Leshy_PH]);
SpawnMob(Colorful_Leshy, "", 0);
end
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
local Leshy = mob:getID();
local Colorful_Leshy = 16875762;
local Colorful_Leshy_PH_Table =
{
16875754,
16875755,
16875756,
16875757,
16875758,
16875759,
16875760,
16875761
};
for i = 1, table.getn(Colorful_Leshy_PH_Table), 1 do
if (Colorful_Leshy_PH_Table[i] ~= nil) then
if (Leshy == Colorful_Leshy_PH_Table[i]) then
GetMobByID(Colorful_Leshy):setLocalVar("1",os.time() + math.random((43200), (86400)));
end
end
end
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Bastok_Mines/npcs/Crying_Wind_IM.lua | 28 | 4888 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Crying Wind, I.M.
-- 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/Bastok_Mines/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/globals/common");
require("scripts/zones/Bastok_Mines/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, JEUNO
local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border
local size = table.getn(BastInv);
local inventory = BastInv;
-----------------------------------
-- 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(0x7ff9,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdateCSID: %u",csid);
-- printf("onUpdateOPTION: %u",option);
if (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
CPVerify = 1;
if (player:getCP() >= inventory[Item + 1]) then
CPVerify = 0;
end;
player:updateEvent(2,CPVerify,inventory[Item + 2]);
break;
end;
end;
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
if (player:getFreeSlotsCount() >= 1) then
-- Logic to impose limits on exp bands
if (option >= 32933 and option <= 32935) then
if (checkConquestRing(player) > 0) then
player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]);
break;
else
player:setVar("CONQUEST_RING_TIMER",getConquestTally());
end
end
if (player:getNation() == guardnation) then
itemCP = inventory[Item + 1];
else
if (inventory[Item + 1] <= 8000) then
itemCP = inventory[Item + 1] * 2;
else
itemCP = inventory[Item + 1] + 8000;
end;
end;
if (player:hasItem(inventory[Item + 2]) == false) then
player:delCP(itemCP);
player:addItem(inventory[Item + 2],1);
player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
break;
end;
end;
elseif (option >= 65541 and option <= 65565) then -- player chose supply quest.
local region = option - 65541;
player:addKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region));
player:setVar("supplyQuest_started",vanaDay());
player:setVar("supplyQuest_region",region);
player:setVar("supplyQuest_fresh",getConquestTally());
end;
end; | gpl-3.0 |
evilexecutable/ResourceKeeper | install/Lua/lib/luarocks/rocks/luasocket/3.0rc1-2/test/smtptest.lua | 44 | 5376 | local sent = {}
local from = "diego@localhost"
local server = "localhost"
local rcpt = "luasocket@localhost"
local files = {
"/var/spool/mail/luasocket",
"/var/spool/mail/luasock1",
"/var/spool/mail/luasock2",
"/var/spool/mail/luasock3",
}
local t = socket.time()
local err
dofile("mbox.lua")
local parse = mbox.parse
dofile("testsupport.lua")
local total = function()
local t = 0
for i = 1, #sent do
t = t + sent[i].count
end
return t
end
local similar = function(s1, s2)
return
string.lower(string.gsub(s1, "%s", "")) ==
string.lower(string.gsub(s2, "%s", ""))
end
local fail = function(s)
s = s or "failed!"
print(s)
os.exit()
end
local readfile = function(name)
local f = io.open(name, "r")
if not f then
fail("unable to open file!")
return nil
end
local s = f:read("*a")
f:close()
return s
end
local empty = function()
for i,v in ipairs(files) do
local f = io.open(v, "w")
if not f then
fail("unable to open file!")
end
f:close()
end
end
local get = function()
local s = ""
for i,v in ipairs(files) do
s = s .. "\n" .. readfile(v)
end
return s
end
local check_headers = function(sent, got)
sent = sent or {}
got = got or {}
for i,v in pairs(sent) do
if not similar(v, got[i]) then fail("header " .. v .. "failed!") end
end
end
local check_body = function(sent, got)
sent = sent or ""
got = got or ""
if not similar(sent, got) then fail("bodies differ!") end
end
local check = function(sent, m)
io.write("checking ", m.headers.title, ": ")
for i = 1, #sent do
local s = sent[i]
if s.title == m.headers.title and s.count > 0 then
check_headers(s.headers, m.headers)
check_body(s.body, m.body)
s.count = s.count - 1
print("ok")
return
end
end
fail("not found")
end
local insert = function(sent, message)
if type(message.rcpt) == "table" then
message.count = #message.rcpt
else message.count = 1 end
message.headers = message.headers or {}
message.headers.title = message.title
table.insert(sent, message)
end
local mark = function()
local time = socket.time()
return { time = time }
end
local wait = function(sentinel, n)
local to
io.write("waiting for ", n, " messages: ")
while 1 do
local mbox = parse(get())
if n == #mbox then break end
if socket.time() - sentinel.time > 50 then
to = 1
break
end
socket.sleep(1)
io.write(".")
io.stdout:flush()
end
if to then fail("timeout")
else print("ok") end
end
local stuffed_body = [[
This message body needs to be
stuffed because it has a dot
.
by itself on a line.
Otherwise the mailer would
think that the dot
.
is the end of the message
and the remaining text would cause
a lot of trouble.
]]
insert(sent, {
from = from,
rcpt = {
"luasocket@localhost",
"luasock3@dell-diego.cs.princeton.edu",
"luasock1@dell-diego.cs.princeton.edu"
},
body = "multiple rcpt body",
title = "multiple rcpt",
})
insert(sent, {
from = from,
rcpt = {
"luasock2@localhost",
"luasock3",
"luasock1"
},
headers = {
header1 = "header 1",
header2 = "header 2",
header3 = "header 3",
header4 = "header 4",
header5 = "header 5",
header6 = "header 6",
},
body = stuffed_body,
title = "complex message",
})
insert(sent, {
from = from,
rcpt = rcpt,
server = server,
body = "simple message body",
title = "simple message"
})
insert(sent, {
from = from,
rcpt = rcpt,
server = server,
body = stuffed_body,
title = "stuffed message body"
})
insert(sent, {
from = from,
rcpt = rcpt,
headers = {
header1 = "header 1",
header2 = "header 2",
header3 = "header 3",
header4 = "header 4",
header5 = "header 5",
header6 = "header 6",
},
title = "multiple headers"
})
insert(sent, {
from = from,
rcpt = rcpt,
title = "minimum message"
})
io.write("testing host not found: ")
local c, e = socket.connect("wrong.host", 25)
local ret, err = socket.smtp.mail{
from = from,
rcpt = rcpt,
server = "wrong.host"
}
if ret or e ~= err then fail("wrong error message")
else print("ok") end
io.write("testing invalid from: ")
local ret, err = socket.smtp.mail{
from = ' " " (( _ * ',
rcpt = rcpt,
}
if ret or not err then fail("wrong error message")
else print(err) end
io.write("testing no rcpt: ")
local ret, err = socket.smtp.mail{
from = from,
}
if ret or not err then fail("wrong error message")
else print(err) end
io.write("clearing mailbox: ")
empty()
print("ok")
io.write("sending messages: ")
for i = 1, #sent do
ret, err = socket.smtp.mail(sent[i])
if not ret then fail(err) end
io.write("+")
io.stdout:flush()
end
print("ok")
wait(mark(), total())
io.write("parsing mailbox: ")
local mbox = parse(get())
print(#mbox .. " messages found!")
for i = 1, #mbox do
check(sent, mbox[i])
end
print("passed all tests")
print(string.format("done in %.2fs", socket.time() - t))
| gpl-2.0 |
kaen/Zero-K | units/destroyer.lua | 2 | 6543 | unitDef = {
unitname = [[destroyer]],
name = [[Daimyo]],
description = [[Destroyer (Riot/Antisub)]],
acceleration = 0.0417,
activateWhenBuilt = true,
brakeRate = 0.142,
buildAngle = 16384,
buildCostEnergy = 700,
buildCostMetal = 700,
builder = false,
buildPic = [[destroyer.png]],
buildTime = 700,
canAttack = true,
canGuard = true,
canMove = true,
canPatrol = true,
category = [[SHIP]],
collisionVolumeOffsets = [[0 0 3]],
collisionVolumeScales = [[32 46 102]],
collisionVolumeTest = 1,
collisionVolumeType = [[box]],
corpse = [[DEAD]],
customParams = {
description_fr = [[Destroyer]],
description_pl = [[Niszczyciel]],
description_de = [[Zerstörer]],
helptext = [[The Daimyo class destroyer packs a wallop with its main gun, a powerful riot cannon. It also features missiles that can hit submarines and surface targets alike. The Daimyo is best attacked from afar, using surface ships or hovercraft with long-range weapons.]],
helptext_pl = [[Glowna bronia Daimyo jest mocne dzialo; jest takze wyposazony w rakiety, ktore moga zanurzyc sie i uderzac w cele podwodne. Walczac przeciwko Daimyo, najlepiej atakowac z bezpiecznej odleglosci.]],
extradrawrange = 420,
},
explodeAs = [[BIG_UNITEX]],
floater = true,
footprintX = 4,
footprintZ = 4,
iconType = [[destroyer]],
idleAutoHeal = 5,
idleTime = 1800,
mass = 320,
maxDamage = 3300,
maxVelocity = 2.9,
minCloakDistance = 75,
minWaterDepth = 10,
movementClass = [[BOAT4]],
noAutoFire = false,
noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE]],
objectName = [[destroyer.s3o]],
script = [[destroyer.lua]],
seismicSignature = 4,
selfDestructAs = [[BIG_UNITEX]],
side = [[ARM]],
sightDistance = 500,
sfxtypes = {
explosiongenerators = {
[[custom:LARGE_MUZZLE_FLASH_FX]],
[[custom:PULVMUZZLE]],
},
},
smoothAnim = true,
sonarDistance = 700,
turninplace = 0,
turnRate = 311,
waterline = 0,
workerTime = 0,
weapons = {
{
def = [[PLASMA]],
badTargetCategory = [[GUNSHIP]],
onlyTargetCategory = [[SWIM LAND SHIP SINK TURRET FLOAT GUNSHIP HOVER]],
},
{
def = [[MISSILE]],
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[SWIM FIXEDWING LAND SUB SINK TURRET FLOAT SHIP GUNSHIP HOVER]],
},
},
weaponDefs = {
PLASMA = {
name = [[Medium Plasma Cannon]],
accuracy = 200,
areaOfEffect = 160,
craterBoost = 1,
craterMult = 2,
damage = {
default = 350,
planes = 350,
subs = 17.5,
},
explosionGenerator = [[custom:bigbulletimpact]],
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
noSelfDamage = true,
range = 350,
reloadtime = 2,
soundHit = [[weapon/cannon/cannon_hit2]],
soundStart = [[weapon/cannon/heavy_cannon]],
startsmoke = [[1]],
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 330,
},
MISSILE = {
name = [[Destroyer Missiles]],
areaOfEffect = 48,
cegTag = [[missiletrailyellow]],
craterBoost = 1,
craterMult = 2,
damage = {
default = 160,
subs = 160,
},
edgeEffectiveness = 0.5,
fireStarter = 100,
fixedLauncher = true,
flightTime = 4,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 2,
model = [[wep_m_hailstorm.s3o]],
noSelfDamage = true,
range = 420,
reloadtime = 2,
smokeTrail = true,
soundHit = [[weapon/missile/missile_fire12]],
soundStart = [[weapon/missile/missile_fire10]],
startVelocity = 100,
tolerance = 4000,
tracks = true,
turnrate = 30000,
turret = true,
waterWeapon = true,
weaponAcceleration = 300,
weaponTimer = 1,
weaponType = [[StarburstLauncher]],
weaponVelocity = 1800,
},
},
featureDefs = {
DEAD = {
description = [[Wreckage - Daimyo]],
blocking = false,
category = [[corpses]],
collisionVolumeOffsets = [[0 0 3]],
collisionVolumeScales = [[32 46 102]],
collisionVolumeTest = 1,
collisionVolumeType = [[box]],
damage = 3300,
energy = 0,
featureDead = [[HEAP]],
footprintX = 5,
footprintZ = 5,
height = [[4]],
hitdensity = [[100]],
metal = 280,
object = [[destroyer_dead.s3o]],
reclaimable = true,
reclaimTime = 280,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
HEAP = {
description = [[Debris - Daimyo]],
blocking = false,
category = [[heaps]],
damage = 3300,
energy = 0,
featurereclamate = [[SMUDGE01]],
footprintX = 4,
footprintZ = 4,
hitdensity = [[100]],
metal = 140,
object = [[debris4x4b.s3o]],
reclaimable = true,
reclaimTime = 140,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
},
}
return lowerkeys({ destroyer = unitDef })
| gpl-2.0 |
geanux/darkstar | scripts/zones/Al_Zahbi/npcs/Zazarg.lua | 38 | 1028 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Zazarg
-- Type: Stoneserpent General
-- @zone: 48
-- @pos -41.675 -8 104.452
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x010c);
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 |
geanux/darkstar | scripts/globals/items/silken_squeeze.lua | 36 | 1215 | -----------------------------------------
-- ID: 5630
-- Item: Silken Squeeze
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP Recovered while healing +4
-- MP Recovered while healing +5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5630);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HPHEAL, 4);
target:addMod(MOD_MPHEAL, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HPHEAL, 4);
target:delMod(MOD_MPHEAL, 5);
end;
| gpl-3.0 |
EinBaum/server | dep/recastnavigation/RecastDemo/premake4.lua | 82 | 3551 | --
-- premake4 file to build RecastDemo
-- http://industriousone.com/premake
--
local action = _ACTION or ""
local todir = "Build/" .. action
solution "recastnavigation"
configurations {
"Debug",
"Release"
}
location (todir)
-- extra warnings, no exceptions or rtti
flags {
"ExtraWarnings",
"FloatFast",
"NoExceptions",
"NoRTTI",
"Symbols"
}
-- debug configs
configuration "Debug*"
defines { "DEBUG" }
targetdir ( todir .. "/lib/Debug" )
-- release configs
configuration "Release*"
defines { "NDEBUG" }
flags { "Optimize" }
targetdir ( todir .. "/lib/Release" )
-- windows specific
configuration "windows"
defines { "WIN32", "_WINDOWS", "_CRT_SECURE_NO_WARNINGS" }
project "DebugUtils"
language "C++"
kind "StaticLib"
includedirs {
"../DebugUtils/Include",
"../Detour/Include",
"../DetourTileCache/Include",
"../Recast/Include"
}
files {
"../DebugUtils/Include/*.h",
"../DebugUtils/Source/*.cpp"
}
project "Detour"
language "C++"
kind "StaticLib"
includedirs {
"../Detour/Include"
}
files {
"../Detour/Include/*.h",
"../Detour/Source/*.cpp"
}
project "DetourCrowd"
language "C++"
kind "StaticLib"
includedirs {
"../DetourCrowd/Include",
"../Detour/Include",
"../Recast/Include"
}
files {
"../DetourCrowd/Include/*.h",
"../DetourCrowd/Source/*.cpp"
}
project "DetourTileCache"
language "C++"
kind "StaticLib"
includedirs {
"../DetourTileCache/Include",
"../Detour/Include",
"../Recast/Include"
}
files {
"../DetourTileCache/Include/*.h",
"../DetourTileCache/Source/*.cpp"
}
project "Recast"
language "C++"
kind "StaticLib"
includedirs {
"../Recast/Include"
}
files {
"../Recast/Include/*.h",
"../Recast/Source/*.cpp"
}
project "RecastDemo"
language "C++"
kind "WindowedApp"
includedirs {
"../RecastDemo/Include",
"../RecastDemo/Contrib",
"../RecastDemo/Contrib/fastlz",
"../DebugUtils/Include",
"../Detour/Include",
"../DetourCrowd/Include",
"../DetourTileCache/Include",
"../Recast/Include"
}
files {
"../RecastDemo/Include/*.h",
"../RecastDemo/Source/*.cpp",
"../RecastDemo/Contrib/fastlz/*.h",
"../RecastDemo/Contrib/fastlz/*.c"
}
-- project dependencies
links {
"DebugUtils",
"Detour",
"DetourCrowd",
"DetourTileCache",
"Recast"
}
-- distribute executable in RecastDemo/Bin directory
targetdir "Bin"
-- linux library cflags and libs
configuration { "linux", "gmake" }
buildoptions {
"`pkg-config --cflags sdl`",
"`pkg-config --cflags gl`",
"`pkg-config --cflags glu`"
}
linkoptions {
"`pkg-config --libs sdl`",
"`pkg-config --libs gl`",
"`pkg-config --libs glu`"
}
-- windows library cflags and libs
configuration { "windows" }
includedirs { "../RecastDemo/Contrib/SDL/include" }
libdirs { "../RecastDemo/Contrib/SDL/lib/x86" }
links {
"opengl32",
"glu32",
"sdlmain",
"sdl"
}
-- mac includes and libs
configuration { "macosx" }
kind "ConsoleApp" -- xcode4 failes to run the project if using WindowedApp
includedirs { "/Library/Frameworks/SDL.framework/Headers" }
buildoptions { "-Wunused-value -Wshadow -Wreorder -Wsign-compare -Wall" }
links {
"OpenGL.framework",
"/Library/Frameworks/SDL.framework",
"Cocoa.framework",
}
files {
"../RecastDemo/Include/SDLMain.h",
"../RecastDemo/Source/SDLMain.m",
-- These don't seem to work in xcode4 target yet.
-- "Info.plist",
-- "Icon.icns",
-- "English.lproj/InfoPlist.strings",
-- "English.lproj/MainMenu.xib",
}
| gpl-2.0 |
Aarhus-BSS/Aarhus-Research-Rebuilt | lib/luaj-3.0.1/test/lua/errors.lua | 7 | 6006 | -- tostring replacement that assigns ids
local ts,id,nid,types = tostring,{},0,{table='tbl',thread='thr',userdata='uda',['function']='func'}
tostring = function(x)
if not x or not types[type(x)] then return ts(x) end
if not id[x] then nid=nid+1; id[x]=types[type(x)]..'.'..nid end
return id[x]
end
-- test of common types of errors
-- local function c(f,...) return f(...) end
-- local function b(...) return c(...) end
--local function a(...) return (pcall(b,...)) end
local function a(...) local s,e=pcall(...) if s then return s,e else return false,type(e) end end
s = 'some string'
local t = {}
-- error message tests
print( 'a(error)', a(error) )
print( 'a(error,"msg")', a(error,"msg") )
print( 'a(error,"msg",0)', a(error,"msg",0) )
print( 'a(error,"msg",1)', a(error,"msg",1) )
print( 'a(error,"msg",2)', a(error,"msg",2) )
print( 'a(error,"msg",3)', a(error,"msg",3) )
print( 'a(error,"msg",4)', a(error,"msg",4) )
print( 'a(error,"msg",5)', a(error,"msg",5) )
print( 'a(error,"msg",6)', a(error,"msg",6) )
-- call errors
print( 'a(nil())', a(function() return n() end) )
print( 'a(t()) ', a(function() return t() end) )
print( 'a(s()) ', a(function() return s() end) )
print( 'a(true())', a(function() local b = true; return b() end) )
-- arithmetic errors
print( 'a(nil+1)', a(function() return nil+1 end) )
print( 'a(a+1) ', a(function() return a+1 end) )
print( 'a(s+1) ', a(function() return s+1 end) )
print( 'a(true+1)', a(function() local b = true; return b+1 end) )
-- table errors
print( 'a(nil.x)', a(function() return n.x end) )
print( 'a(a.x) ', a(function() return a.x end) )
print( 'a(s.x) ', a(function() return s.x end) )
print( 'a(true.x)', a(function() local b = true; return b.x end) )
print( 'a(nil.x=5)', a(function() n.x=5 end) )
print( 'a(a.x=5) ', a(function() a.x=5 end) )
print( 'a(s.x=5) ', a(function() s.x=5 end) )
print( 'a(true.x=5)', a(function() local b = true; b.x=5 end) )
-- len operator
print( 'a(#nil) ', a(function() return #n end) )
print( 'a(#t) ', a(function() return #t end) )
print( 'a(#s) ', a(function() return #s end) )
print( 'a(#a) ', a(function() return #a end) )
print( 'a(#true)', a(function() local b = true; return #b end) )
-- comparison errors
print( 'a(nil>1)', a(function() return nil>1 end) )
print( 'a(a>1) ', a(function() return a>1 end) )
print( 'a(s>1) ', a(function() return s>1 end) )
print( 'a(true>1)', a(function() local b = true; return b>1 end) )
-- unary minus errors
print( 'a(-nil)', a(function() return -n end) )
print( 'a(-a) ', a(function() return -a end) )
print( 'a(-s) ', a(function() return -s end) )
print( 'a(-true)', a(function() local b = true; return -b end) )
-- string concatenation
local function concatsuite(comparefunc)
print( '"a".."b"', comparefunc("a","b") )
print( '"a"..nil', comparefunc("a",nil) )
print( 'nil.."b"', comparefunc(nil,"b") )
print( '"a"..{}', comparefunc("a",{}) )
print( '{}.."b"', comparefunc({},"b") )
print( '"a"..2', comparefunc("a",2) )
print( '2.."b"', comparefunc(2,"b") )
print( '"a"..print', comparefunc("a",print) )
print( 'print.."b"', comparefunc(print,"b") )
print( '"a"..true', comparefunc("a",true) )
print( 'true.."b"', comparefunc(true,"b") )
print( 'nil..true', comparefunc(nil,true) )
print( '"a"..3.5', comparefunc("a",3.5) )
print( '3.5.."b"', comparefunc(3.5,"b") )
end
local function strconcat(a,b)
return (pcall( function() return a..b end) )
end
local function tblconcat(a,b)
local t={a,b}
return (pcall( function() return table.concat(t,'-',1,2) end ))
end
print( '-------- string concatenation' )
concatsuite(strconcat)
print( '-------- table concatenation' )
concatsuite(tblconcat)
-- pairs
print( '-------- pairs tests' )
print( 'a(pairs(nil))', a(function() return pairs(nil,{}) end) )
print( 'a(pairs(a)) ', a(function() return pairs(a,{}) end) )
print( 'a(pairs(s)) ', a(function() return pairs(s,{}) end) )
print( 'a(pairs(t)) ', a(function() return pairs(t,{}) end) )
print( 'a(pairs(true))', a(function() local b = true; return pairs(b,{}) end) )
-- setmetatable
print( '-------- setmetatable tests' )
function sm(...)
return tostring(setmetatable(...))
end
print( 'a(setmetatable(nil))', a(function() return sm(nil,{}) end) )
print( 'a(setmetatable(a)) ', a(function() return sm(a,{}) end) )
print( 'a(setmetatable(s)) ', a(function() return sm(s,{}) end) )
print( 'a(setmetatable(true))', a(function() local b = true; return sm(b,{}) end) )
print( 'a(setmetatable(t)) ', a(function() return sm(t,{}) end) )
print( 'a(getmetatable(t)) ', a(function() return getmetatable(t),type(getmetatable(t)) end) )
print( 'a(setmetatable(t*)) ', a(function() return sm(t,{__metatable={}}) end) )
print( 'a(getmetatable(t)) ', a(function() return getmetatable(t),type(getmetatable(t)) end) )
print( 'a(setmetatable(t)) ', a(function() return sm(t,{}) end) )
print( 'a(getmetatable(t)) ', a(function() return getmetatable(t),type(getmetatable(t)) end) )
t = {}
print( 'a(setmetatable(t)) ', a(function() return sm(t,{}) end) )
print( 'a(getmetatable(t)) ', a(function() return getmetatable(t),type(getmetatable(t)) end) )
print( 'a(setmetatable(t*)) ', a(function() return sm(t,{__metatable='some string'}) end) )
print( 'a(getmetatable(t)) ', a(function() return getmetatable(t),type(getmetatable(t)) end) )
print( 'a(setmetatable(t)) ', a(function() return sm(t,{}) end) )
print( 'a(getmetatable(t)) ', a(function() return getmetatable(t),type(getmetatable(t)) end) )
print( 'a(setmetatable(t,nil)) ', a(function() return sm(t,nil) end) )
print( 'a(setmetatable(t)) ', a(function() return sm(t) end) )
print( 'a(setmetatable({},"abc")) ', a(function() return sm({},'abc') end) )
-- bad args to error!
print( 'error("msg","arg")', a(function() error('some message', 'some bad arg') end) )
-- loadfile, dofile on missing files
print( 'loadfile("bogus.txt")', a(function() return loadfile("bogus.txt") end) )
print( 'dofile("bogus.txt")', a(function() return dofile("bogus.txt") end) )
| apache-2.0 |
geanux/darkstar | scripts/zones/Southern_San_dOria/npcs/Hinaree.lua | 19 | 1923 | -----------------------------------
-- Area: Southern San d'Oria@
-- NPC: Hinaree
-- Type: Standard NPC
-- @zone: 230
-- @pos -301.535 -10.199 97.698
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local currentday = tonumber(os.date("%j"));
if (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("EMERALD_WATERS_Status")==6 ) then
player:startEvent(0x0017);
elseif (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path")== 0 ) then
player:startEvent(0x0016);
elseif (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==3 and player:getVar("Promathia_kill_day") ~= currentday and player:getVar("COP_louverance_story")== 0 ) then
player:startEvent(0x02F5);
else
player:startEvent(0x0244);
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 == 0x0017) then
player:setVar("EMERALD_WATERS_Status",7); --end 3-3A: San d'Oria Route: "Emerald Waters"
elseif (csid == 0x0016) then
player:setVar("COP_Ulmia_s_Path",1);
elseif (csid == 0x02F5) then
player:setVar("COP_louverance_story",1);
end
end;
| gpl-3.0 |
geanux/darkstar | scripts/globals/items/purple_polypore.lua | 36 | 1156 | -----------------------------------------
-- ID: 5682
-- Item: Purple Polypore
-- Food Effect: 5 Min, All Races
-----------------------------------------
-- Strength -6
-- Mind +4
-----------------------------------------
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,5156);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, -6);
target:addMod(MOD_MND, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, -6);
target:delMod(MOD_MND, 4);
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Jugner_Forest/npcs/Alexius.lua | 17 | 1617 | -----------------------------------
-- Area: Jugner Forest
-- NPC: Alexius
-- Involved in Quest: A purchase of Arms & Sin Hunting
-- @pos 105 1 382 104
-----------------------------------
package.loaded["scripts/zones/Jugner_Forest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Jugner_Forest/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local SinHunting = player:getVar("sinHunting"); -- RNG AF1
if (player:hasKeyItem(WEAPONS_ORDER) == true) then
player:startEvent(0x0005);
elseif (SinHunting == 3) then
player:startEvent(0x000a);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0005) then
player:delKeyItem(WEAPONS_ORDER);
player:addKeyItem(WEAPONS_RECEIPT);
player:messageSpecial(KEYITEM_OBTAINED,WEAPONS_RECEIPT);
elseif (csid == 0x000a) then
player:setVar("sinHunting",4);
end
end; | gpl-3.0 |
geanux/darkstar | scripts/zones/Xarcabard/npcs/Pelogrant.lua | 17 | 1856 | -----------------------------------
-- Area: Xarcabard
-- NPC: Pelogrant
-- Type: Outpost Vendor
-- @pos 210 -22 -201 112
-----------------------------------
package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
require("scripts/zones/Xarcabard/TextIDs");
local region = VALDEAUNIA;
local csid = 0x7ff4;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local owner = GetRegionOwner(region);
local arg1 = getArg1(owner,player);
if (owner == player:getNation()) then
nation = 1;
elseif (arg1 < 1792) then
nation = 2;
else
nation = 0;
end
player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
player:updateEvent(player:getGil(),OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP());
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
if (option == 1) then
ShowOPVendorShop(player);
elseif (option == 2) then
if (player:delGil(OP_TeleFee(player,region))) then
toHomeNation(player);
end
elseif (option == 6) then
player:delCP(OP_TeleFee(player,region));
toHomeNation(player);
end
end; | gpl-3.0 |
vvtam/vlc | share/lua/playlist/mpora.lua | 97 | 2565 | --[[
$Id$
Copyright © 2009 the VideoLAN team
Authors: Konstantin Pavlov (thresh@videolan.org)
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, "video%.mpora%.com/watch/" )
end
-- Parse function.
function parse()
p = {}
while true do
-- Try to find the video's title
line = vlc.readline()
if not line then break end
if string.match( line, "meta name=\"title\"" ) then
_,_,name = string.find( line, "content=\"(.*)\" />" )
end
if string.match( line, "image_src" ) then
_,_,arturl = string.find( line, "image_src\" href=\"(.*)\" />" )
end
if string.match( line, "video_src" ) then
_,_,video = string.find( line, 'href="http://video%.mpora%.com/ep/(.*)%.swf" />' )
end
end
if not name or not arturl or not video then return nil end
-- Try and get URL for SD video.
sd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/")
if not sd then return nil end
page = sd:read( 65653 )
sdurl = string.match( page, "url=\"(.*)\" />")
page = nil
table.insert( p, { path = sdurl; name = name; arturl = arturl; } )
-- Try and check if HD video is available.
checkhd = vlc.stream("http://api.mpora.com/tv/player/load/vid/"..video.."/platform/video/domain/video.mpora.com/" )
if not checkhd then return nil end
page = checkhd:read( 65653 )
hashd = tonumber( string.match( page, "<has_hd>(%d)</has_hd>" ) )
page = nil
if hashd then
hd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/hd/true/")
page = hd:read( 65653 )
hdurl = string.match( page, "url=\"(.*)\" />")
table.insert( p, { path = hdurl; name = name.." (HD)"; arturl = arturl; } )
end
return p
end
| gpl-2.0 |
geanux/darkstar | scripts/zones/Southern_San_dOria/npcs/Foletta.lua | 36 | 1433 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Foletta
-- General Info NPC
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x29a);
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 |
tonyshow/UniLua | Assets/StreamingAssets/LuaRoot/test/events.lua | 9 | 9663 | print('testing metatables')
X = 20; B = 30
_ENV = setmetatable({}, {__index=_G})
collectgarbage()
X = X+10
assert(X == 30 and _G.X == 20)
B = false
assert(B == false)
B = nil
assert(B == 30)
assert(getmetatable{} == nil)
assert(getmetatable(4) == nil)
assert(getmetatable(nil) == nil)
a={}; setmetatable(a, {__metatable = "xuxu",
__tostring=function(x) return x.name end})
assert(getmetatable(a) == "xuxu")
assert(tostring(a) == nil)
-- cannot change a protected metatable
assert(pcall(setmetatable, a, {}) == false)
a.name = "gororoba"
assert(tostring(a) == "gororoba")
local a, t = {10,20,30; x="10", y="20"}, {}
assert(setmetatable(a,t) == a)
assert(getmetatable(a) == t)
assert(setmetatable(a,nil) == a)
assert(getmetatable(a) == nil)
assert(setmetatable(a,t) == a)
function f (t, i, e)
assert(not e)
local p = rawget(t, "parent")
return (p and p[i]+3), "dummy return"
end
t.__index = f
a.parent = {z=25, x=12, [4] = 24}
assert(a[1] == 10 and a.z == 28 and a[4] == 27 and a.x == "10")
collectgarbage()
a = setmetatable({}, t)
function f(t, i, v) rawset(t, i, v-3) end
setmetatable(t, t) -- causes a bug in 5.1 !
t.__newindex = f
a[1] = 30; a.x = "101"; a[5] = 200
assert(a[1] == 27 and a.x == 98 and a[5] == 197)
local c = {}
a = setmetatable({}, t)
t.__newindex = c
a[1] = 10; a[2] = 20; a[3] = 90
assert(c[1] == 10 and c[2] == 20 and c[3] == 90)
do
local a;
a = setmetatable({}, {__index = setmetatable({},
{__index = setmetatable({},
{__index = function (_,n) return a[n-3]+4, "lixo" end})})})
a[0] = 20
for i=0,10 do
assert(a[i*3] == 20 + i*4)
end
end
do -- newindex
local foi
local a = {}
for i=1,10 do a[i] = 0; a['a'..i] = 0; end
setmetatable(a, {__newindex = function (t,k,v) foi=true; rawset(t,k,v) end})
foi = false; a[1]=0; assert(not foi)
foi = false; a['a1']=0; assert(not foi)
foi = false; a['a11']=0; assert(foi)
foi = false; a[11]=0; assert(foi)
foi = false; a[1]=nil; assert(not foi)
foi = false; a[1]=nil; assert(foi)
end
setmetatable(t, nil)
function f (t, ...) return t, {...} end
t.__call = f
do
local x,y = a(table.unpack{'a', 1})
assert(x==a and y[1]=='a' and y[2]==1 and y[3]==nil)
x,y = a()
assert(x==a and y[1]==nil)
end
local b = setmetatable({}, t)
setmetatable(b,t)
function f(op)
return function (...) cap = {[0] = op, ...} ; return (...) end
end
t.__add = f("add")
t.__sub = f("sub")
t.__mul = f("mul")
t.__div = f("div")
t.__mod = f("mod")
t.__unm = f("unm")
t.__pow = f("pow")
t.__len = f("len")
assert(b+5 == b)
assert(cap[0] == "add" and cap[1] == b and cap[2] == 5 and cap[3]==nil)
assert(b+'5' == b)
assert(cap[0] == "add" and cap[1] == b and cap[2] == '5' and cap[3]==nil)
assert(5+b == 5)
assert(cap[0] == "add" and cap[1] == 5 and cap[2] == b and cap[3]==nil)
assert('5'+b == '5')
assert(cap[0] == "add" and cap[1] == '5' and cap[2] == b and cap[3]==nil)
b=b-3; assert(getmetatable(b) == t)
assert(5-a == 5)
assert(cap[0] == "sub" and cap[1] == 5 and cap[2] == a and cap[3]==nil)
assert('5'-a == '5')
assert(cap[0] == "sub" and cap[1] == '5' and cap[2] == a and cap[3]==nil)
assert(a*a == a)
assert(cap[0] == "mul" and cap[1] == a and cap[2] == a and cap[3]==nil)
assert(a/0 == a)
assert(cap[0] == "div" and cap[1] == a and cap[2] == 0 and cap[3]==nil)
assert(a%2 == a)
assert(cap[0] == "mod" and cap[1] == a and cap[2] == 2 and cap[3]==nil)
assert(-a == a)
assert(cap[0] == "unm" and cap[1] == a)
assert(a^4 == a)
assert(cap[0] == "pow" and cap[1] == a and cap[2] == 4 and cap[3]==nil)
assert(a^'4' == a)
assert(cap[0] == "pow" and cap[1] == a and cap[2] == '4' and cap[3]==nil)
assert(4^a == 4)
assert(cap[0] == "pow" and cap[1] == 4 and cap[2] == a and cap[3]==nil)
assert('4'^a == '4')
assert(cap[0] == "pow" and cap[1] == '4' and cap[2] == a and cap[3]==nil)
assert(#a == a)
assert(cap[0] == "len" and cap[1] == a)
-- test for rawlen
t = setmetatable({1,2,3}, {__len = function () return 10 end})
assert(#t == 10 and rawlen(t) == 3)
assert(rawlen"abc" == 3)
assert(not pcall(rawlen, io.stdin))
assert(not pcall(rawlen, 34))
assert(not pcall(rawlen))
t = {}
t.__lt = function (a,b,c)
collectgarbage()
assert(c == nil)
if type(a) == 'table' then a = a.x end
if type(b) == 'table' then b = b.x end
return a<b, "dummy"
end
function Op(x) return setmetatable({x=x}, t) end
local function test ()
assert(not(Op(1)<Op(1)) and (Op(1)<Op(2)) and not(Op(2)<Op(1)))
assert(not(1 < Op(1)) and (Op(1) < 2) and not(2 < Op(1)))
assert(not(Op('a')<Op('a')) and (Op('a')<Op('b')) and not(Op('b')<Op('a')))
assert(not('a' < Op('a')) and (Op('a') < 'b') and not(Op('b') < Op('a')))
assert((Op(1)<=Op(1)) and (Op(1)<=Op(2)) and not(Op(2)<=Op(1)))
assert((Op('a')<=Op('a')) and (Op('a')<=Op('b')) and not(Op('b')<=Op('a')))
assert(not(Op(1)>Op(1)) and not(Op(1)>Op(2)) and (Op(2)>Op(1)))
assert(not(Op('a')>Op('a')) and not(Op('a')>Op('b')) and (Op('b')>Op('a')))
assert((Op(1)>=Op(1)) and not(Op(1)>=Op(2)) and (Op(2)>=Op(1)))
assert((1 >= Op(1)) and not(1 >= Op(2)) and (Op(2) >= 1))
assert((Op('a')>=Op('a')) and not(Op('a')>=Op('b')) and (Op('b')>=Op('a')))
assert(('a' >= Op('a')) and not(Op('a') >= 'b') and (Op('b') >= Op('a')))
end
test()
t.__le = function (a,b,c)
assert(c == nil)
if type(a) == 'table' then a = a.x end
if type(b) == 'table' then b = b.x end
return a<=b, "dummy"
end
test() -- retest comparisons, now using both `lt' and `le'
-- test `partial order'
local function Set(x)
local y = {}
for _,k in pairs(x) do y[k] = 1 end
return setmetatable(y, t)
end
t.__lt = function (a,b)
for k in pairs(a) do
if not b[k] then return false end
b[k] = nil
end
return next(b) ~= nil
end
t.__le = nil
assert(Set{1,2,3} < Set{1,2,3,4})
assert(not(Set{1,2,3,4} < Set{1,2,3,4}))
assert((Set{1,2,3,4} <= Set{1,2,3,4}))
assert((Set{1,2,3,4} >= Set{1,2,3,4}))
assert((Set{1,3} <= Set{3,5})) -- wrong!! model needs a `le' method ;-)
t.__le = function (a,b)
for k in pairs(a) do
if not b[k] then return false end
end
return true
end
assert(not (Set{1,3} <= Set{3,5})) -- now its OK!
assert(not(Set{1,3} <= Set{3,5}))
assert(not(Set{1,3} >= Set{3,5}))
t.__eq = function (a,b)
for k in pairs(a) do
if not b[k] then return false end
b[k] = nil
end
return next(b) == nil
end
local s = Set{1,3,5}
assert(s == Set{3,5,1})
assert(not rawequal(s, Set{3,5,1}))
assert(rawequal(s, s))
assert(Set{1,3,5,1} == Set{3,5,1})
assert(Set{1,3,5} ~= Set{3,5,1,6})
t[Set{1,3,5}] = 1
assert(t[Set{1,3,5}] == nil) -- `__eq' is not valid for table accesses
t.__concat = function (a,b,c)
assert(c == nil)
if type(a) == 'table' then a = a.val end
if type(b) == 'table' then b = b.val end
if A then return a..b
else
return setmetatable({val=a..b}, t)
end
end
c = {val="c"}; setmetatable(c, t)
d = {val="d"}; setmetatable(d, t)
A = true
assert(c..d == 'cd')
assert(0 .."a".."b"..c..d.."e".."f"..(5+3).."g" == "0abcdef8g")
A = false
assert((c..d..c..d).val == 'cdcd')
x = c..d
assert(getmetatable(x) == t and x.val == 'cd')
x = 0 .."a".."b"..c..d.."e".."f".."g"
assert(x.val == "0abcdefg")
-- concat metamethod x numbers (bug in 5.1.1)
c = {}
local x
setmetatable(c, {__concat = function (a,b)
assert(type(a) == "number" and b == c or type(b) == "number" and a == c)
return c
end})
assert(c..5 == c and 5 .. c == c)
assert(4 .. c .. 5 == c and 4 .. 5 .. 6 .. 7 .. c == c)
-- test comparison compatibilities
local t1, t2, c, d
t1 = {}; c = {}; setmetatable(c, t1)
d = {}
t1.__eq = function () return true end
t1.__lt = function () return true end
setmetatable(d, t1)
assert(c == d and c < d and not(d <= c))
t2 = {}
t2.__eq = t1.__eq
t2.__lt = t1.__lt
setmetatable(d, t2)
assert(c == d and c < d and not(d <= c))
-- test for several levels of calls
local i
local tt = {
__call = function (t, ...)
i = i+1
if t.f then return t.f(...)
else return {...}
end
end
}
local a = setmetatable({}, tt)
local b = setmetatable({f=a}, tt)
local c = setmetatable({f=b}, tt)
i = 0
x = c(3,4,5)
assert(i == 3 and x[1] == 3 and x[3] == 5)
assert(_G.X == 20)
print'+'
local _g = _G
_ENV = setmetatable({}, {__index=function (_,k) return _g[k] end})
a = {}
rawset(a, "x", 1, 2, 3)
assert(a.x == 1 and rawget(a, "x", 3) == 1)
print '+'
-- testing metatables for basic types
local debug = require'debug'
mt = {}
debug.setmetatable(10, mt)
assert(getmetatable(-2) == mt)
mt.__index = function (a,b) return a+b end
assert((10)[3] == 13)
assert((10)["3"] == 13)
debug.setmetatable(23, nil)
assert(getmetatable(-2) == nil)
debug.setmetatable(true, mt)
assert(getmetatable(false) == mt)
mt.__index = function (a,b) return a or b end
assert((true)[false] == true)
assert((false)[false] == false)
debug.setmetatable(false, nil)
assert(getmetatable(true) == nil)
debug.setmetatable(nil, mt)
assert(getmetatable(nil) == mt)
mt.__add = function (a,b) return (a or 0) + (b or 0) end
assert(10 + nil == 10)
assert(nil + 23 == 23)
assert(nil + nil == 0)
debug.setmetatable(nil, nil)
assert(getmetatable(nil) == nil)
debug.setmetatable(nil, {})
-- loops in delegation
a = {}; setmetatable(a, a); a.__index = a; a.__newindex = a
assert(not pcall(function (a,b) return a[b] end, a, 10))
assert(not pcall(function (a,b,c) a[b] = c end, a, 10, true))
-- bug in 5.1
T, K, V = nil
grandparent = {}
grandparent.__newindex = function(t,k,v) T=t; K=k; V=v end
parent = {}
parent.__newindex = parent
setmetatable(parent, grandparent)
child = setmetatable({}, parent)
child.foo = 10 --> CRASH (on some machines)
assert(T == parent and K == "foo" and V == 10)
print 'OK'
return 12
| mit |
geanux/darkstar | scripts/zones/West_Ronfaure/npcs/Colmaie.lua | 19 | 1122 | -----------------------------------
-- Area: West Ronfaure
-- NPC: Colmaie
-- Type: Standard NPC
-- @pos -133.627 -61.999 272.373 100
-----------------------------------
package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local thePickpocket = player:getQuestStatus(SANDORIA, THE_PICKPOCKET);
if (thePickpocket > 0) then
player:showText(npc, 7263);
else
player:showText(npc, COLMAIE_DIALOG);
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 |
legend18/dragonbone_cocos2dx-3.x | demos/cocos2d-x-3.x/DragonBonesCppDemos/cocos2d/cocos/scripting/lua-bindings/auto/api/ControlColourPicker.lua | 6 | 2337 |
--------------------------------
-- @module ControlColourPicker
-- @extend Control
-- @parent_module cc
--------------------------------
-- @function [parent=#ControlColourPicker] setEnabled
-- @param self
-- @param #bool bool
--------------------------------
-- @function [parent=#ControlColourPicker] getHuePicker
-- @param self
-- @return ControlHuePicker#ControlHuePicker ret (return value: cc.ControlHuePicker)
--------------------------------
-- @function [parent=#ControlColourPicker] setColor
-- @param self
-- @param #color3b_table color3b
--------------------------------
-- @function [parent=#ControlColourPicker] hueSliderValueChanged
-- @param self
-- @param #cc.Ref ref
-- @param #int eventtype
--------------------------------
-- @function [parent=#ControlColourPicker] getcolourPicker
-- @param self
-- @return ControlSaturationBrightnessPicker#ControlSaturationBrightnessPicker ret (return value: cc.ControlSaturationBrightnessPicker)
--------------------------------
-- @function [parent=#ControlColourPicker] setBackground
-- @param self
-- @param #cc.Sprite sprite
--------------------------------
-- @function [parent=#ControlColourPicker] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#ControlColourPicker] setcolourPicker
-- @param self
-- @param #cc.ControlSaturationBrightnessPicker controlsaturationbrightnesspicker
--------------------------------
-- @function [parent=#ControlColourPicker] colourSliderValueChanged
-- @param self
-- @param #cc.Ref ref
-- @param #int eventtype
--------------------------------
-- @function [parent=#ControlColourPicker] setHuePicker
-- @param self
-- @param #cc.ControlHuePicker controlhuepicker
--------------------------------
-- @function [parent=#ControlColourPicker] getBackground
-- @param self
-- @return Sprite#Sprite ret (return value: cc.Sprite)
--------------------------------
-- @function [parent=#ControlColourPicker] create
-- @param self
-- @return ControlColourPicker#ControlColourPicker ret (return value: cc.ControlColourPicker)
--------------------------------
-- @function [parent=#ControlColourPicker] ControlColourPicker
-- @param self
return nil
| mit |
kaen/Zero-K | effects/gundam_prettypop.lua | 26 | 1976 | -- prettypop
return {
["prettypop"] = {
groundflash = {
air = true,
alwaysvisible = true,
circlealpha = 0.0,
circlegrowth = 8,
flashalpha = 0.9,
flashsize = 20,
ground = true,
ttl = 17,
water = true,
color = {
[1] = 1,
[2] = 0,
[3] = 0.5,
},
},
poof01 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 0.2,
alwaysvisible = true,
colormap = [[1.0 1.0 1.0 0.04 1.0 0.0 0.5 0.01 0.1 0.1 0.1 0.01]],
directional = false,
emitrot = 45,
emitrotspread = 32,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.005, 0]],
numparticles = 16,
particlelife = 5,
particlelifespread = 16,
particlesize = 20,
particlesizespread = 0,
particlespeed = 16,
particlespeedspread = 1,
pos = [[0, 2, 0]],
sizegrowth = 0.8,
sizemod = 1.0,
texture = [[randdots]],
useairlos = false,
},
},
pop1 = {
air = true,
class = [[heatcloud]],
count = 1,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 0.8,
maxheat = 10,
pos = [[r-2 r2, 5, r-2 r2]],
size = 1,
sizegrowth = 16,
speed = [[0, 0, 0]],
texture = [[bluenovaexplo]],
},
},
},
}
| gpl-2.0 |
geanux/darkstar | scripts/zones/Northern_San_dOria/npcs/Cauzeriste.lua | 17 | 1263 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Cauzeriste
-- Guild Merchant NPC: Woodworking Guild
-- @pos -175.946 3.999 280.301 231
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(513,6,21,0)) then
player:showText(npc,CAUZERISTE_SHOP_DIALOG);
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 |
geanux/darkstar | scripts/zones/Bastok_Mines/npcs/Odoba.lua | 19 | 1145 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Odoba
-- Guild Merchant NPC: Alchemy Guild
-- @pos 108.473 5.017 1.089 234
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(526,8,23,6)) then
player:showText(npc, ODOBA_SHOP_DIALOG);
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 |
Schwertspize/cuberite | Server/Plugins/APIDump/Hooks/OnPlayerBreakingBlock.lua | 44 | 1596 | return
{
HOOK_PLAYER_BREAKING_BLOCK =
{
CalledWhen = "Just before a player breaks a block. Plugin may override / refuse. ",
DefaultFnName = "OnPlayerBreakingBlock", -- also used as pagename
Desc = [[
This hook is called when a {{cPlayer|player}} breaks a block, before the block is actually broken in
the {{cWorld|World}}. Plugins may refuse the breaking.</p>
<p>
See also the {{OnPlayerBrokenBlock|HOOK_PLAYER_BROKEN_BLOCK}} hook for a similar hook called after
the block is broken.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is digging the block" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
{ Name = "BlockFace", Type = "number", Notes = "Face of the block upon which the player is acting. One of the BLOCK_FACE_ constants" },
{ Name = "BlockType", Type = "BLOCKTYPE", Notes = "The block type of the block being broken" },
{ Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "The block meta of the block being broken " },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called, and then the block
is broken. If the function returns true, no other plugin's callback is called and the block breaking
is cancelled. The server re-sends the block back to the player to replace it (the player's client
already thinks the block was broken).
]],
}, -- HOOK_PLAYER_BREAKING_BLOCK
}
| apache-2.0 |
kaen/Zero-K | LuaUI/Widgets/camera_recorder.lua | 17 | 8831 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "CameraRecorder",
desc = "v0.011 Record positions of the camera to a file and repath those positions when loading the replay.",
author = "CarRepairer",
date = "2011-07-04",
license = "GNU GPL, v2 or later",
layer = 1002,
enabled = false,
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--[[
HOW TO USE:
Start a game (such as a replay).
Type /luaui reload
Push Settings > Camera > Recording > Record
Move your camera around.
Push Record again to stop.
End game.
Start a replay of that game you just recorded the camera in.
Type /luaui reload
Push Settings > Camera > Recording > Play
The camera will follow the path you recorded.
Notes:
For some reason the Game.gameID constant doesn't work until you type /luaui reload
The camera positions are saved to a file based on the gameID. If you don't
reload luaui it will save to (or read from) the file camrec_AAAAAAAAAAAAAAAAAAAAAA==.txt
--]]
options_path = 'Settings/Camera/Recording'
--options_order = { }
local OverviewAction = function() end
options = {
record = {
name = "Record",
desc = "Record now",
type = 'button',
-- OnChange defined later
},
play = {
name = "Play",
desc = "Play now",
type = 'button',
-- OnChange defined later
},
help = {
name = 'Help',
type = 'text',
value = [[
* Start a game (such as a replay).
* Type /luaui reload
* Push Settings > Camera > Recording > Record
* Move your camera around.
* Push Record again to stop.
* End game.
* Start a replay of that game you just recorded the camera in.
* Type /luaui reload
* Push Settings > Camera > Recording > Play
* The camera will follow the path you recorded.
]],
}
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--config
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spGetCameraState = Spring.GetCameraState
local spGetCameraVectors = Spring.GetCameraVectors
local spGetModKeyState = Spring.GetModKeyState
local spGetMouseState = Spring.GetMouseState
local spIsAboveMiniMap = Spring.IsAboveMiniMap
local spSendCommands = Spring.SendCommands
local spSetCameraState = Spring.SetCameraState
local spSetMouseCursor = Spring.SetMouseCursor
local spTraceScreenRay = Spring.TraceScreenRay
local spWarpMouse = Spring.WarpMouse
local spGetCameraDirection = Spring.GetCameraDirection
local abs = math.abs
local min = math.min
local max = math.max
local sqrt = math.sqrt
local sin = math.sin
local cos = math.cos
local echo = Spring.Echo
local KF_FRAMES = 1
local recording = false
local recData = {}
local filename
local ranInit = false
Spring.Utilities = Spring.Utilities or {}
VFS.Include("LuaRules/Utilities/base64.lua")
options.record.OnChange = function()
recording = not recording
echo (recording and '<Camera Recording> Recording begun.' or '<Camera Recording> Recording stopped.')
end
options.play.OnChange = function()
playing = not playing
echo (playing and '<Camera Recording> Playback begun.' or '<Camera Recording> Playback stopped.')
end
local CAMERA_STATE_FORMATS = {
fps = {
"px", "py", "pz",
"dx", "dy", "dz",
"rx", "ry", "rz",
"oldHeight",
},
free = {
"px", "py", "pz",
"dx", "dy", "dz",
"rx", "ry", "rz",
"fov",
"gndOffset",
"gravity",
"slide",
"scrollSpeed",
"velTime",
"avelTime",
"autoTilt",
"goForward",
"invertAlt",
"gndLock",
"vx", "vy", "vz",
"avx", "avy", "avz",
},
OrbitController = {
"px", "py", "pz",
"tx", "ty", "tz",
},
ta = {
"px", "py", "pz",
"dx", "dy", "dz",
"height",
"zscale",
"flipped",
},
ov = {
"px", "py", "pz",
},
rot = {
"px", "py", "pz",
"dx", "dy", "dz",
"rx", "ry", "rz",
"oldHeight",
},
sm = {
"px", "py", "pz",
"dx", "dy", "dz",
"height",
"zscale",
"flipped",
},
tw = {
"px", "py", "pz",
"rx", "ry", "rz",
},
}
local CAMERA_NAMES = {
"fps",
"free",
"OrbitController",
"ta",
"ov",
"rot",
"sm",
"tw",
}
local CAMERA_IDS = {}
for i=1, #CAMERA_NAMES do
CAMERA_IDS[CAMERA_NAMES[i]] = i
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function explode(div,str)
if (div=='') then return false end
local pos,arr = 0,{}
-- for each divider found
for st,sp in function() return string.find(str,div,pos,true) end do
table.insert(arr,string.sub(str,pos,st-1)) -- Attach chars left of current divider
pos = sp + 1 -- Jump past current divider
end
table.insert(arr,string.sub(str,pos)) -- Attach chars right of last divider
return arr
end
local function CameraStateToString(frame, cs)
local name = cs.name
local stateFormat = CAMERA_STATE_FORMATS[name]
local cameraID = CAMERA_IDS[name]
if not stateFormat or not cameraID then return nil end
local result = frame .. '|' .. cameraID .. '|' .. cs.mode
for i=1, #stateFormat do
local num = cs[stateFormat[i]]
if not num then return nil end
result = result .. '|' .. num
end
return result
end
local function StringToCameraState(str)
local s_arr = explode('|', str)
local frame = s_arr[1]
local cameraID = s_arr[2]
local mode = s_arr[3]
local name = CAMERA_NAMES[cameraID+0]
local stateFormat = CAMERA_STATE_FORMATS[name]
if not (cameraID and mode and name and stateFormat) then
--echo ('ISSUE', cameraID , mode , name , stateFormat)
return nil
end
local result = {
frame = frame,
name = name,
mode = mode,
}
for i=1, #stateFormat do
local num = s_arr[i+3]
if not num then return nil end
result[stateFormat[i]] = num
end
return result
end
local function IsKeyframe(frame)
return frame % KF_FRAMES == 0
end
local function RecordFrame(frame)
--echo ('<camrec> recording frame', frame)
local str = CameraStateToString( frame, spGetCameraState() )
local out = assert(io.open(filename, "a+"), "Unable to save camera recording file to "..filename)
out:write(str .. "\n")
assert(out:close())
end
local function FileToData(filename)
--local file = assert(io.open(filename,'r'), "Unable to load camera recording file from "..filename)
local file = io.open(filename,'r')
if not file then
echo('<Camrec> No such file ' .. filename )
return {}
end
local recData = {}
local prevkey = 0
while true do
line = file:read()
if not line then
break
end
--echo ('<camrec> opening line ', line)
local data = StringToCameraState( line )
--recData[ data.frame ] = data
if prevkey ~= 0 then
--echo('<camrec> adding data', prevkey )
recData[ prevkey+0 ] = data
end
prevkey = data.frame
end
return recData
end
local function RunInit()
if ranInit then
return true
end
local gameID = Game.gameID
--echo ('gameid=', gameID)
if not gameID or gameID == '' then
return false
end
ranInit = true
local gameID_enc = Spring.Utilities.Base64Encode( gameID )
--echo( '<camrec>', gameID, gameID_enc )
local gameID_dec = Spring.Utilities.Base64Decode( gameID_enc )
--echo( '<camrec>','equal?', gameID_dec == gameID )
filename = 'camrec_' .. gameID_enc .. '.txt'
--echo ('<camrec>',filename)
recData = FileToData( filename )
return true
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GameFrame()
local frame = Spring.GetGameFrame()
if frame < 1 then return end
if not RunInit() then return end
if recording then
if IsKeyframe(frame) then
RecordFrame(frame)
end
end
if playing then
if recData[frame] then
--echo ('playing frame', frame)
spSetCameraState(recData[frame], KF_FRAMES / 32)
end
end
end
function widget:Initialize()
end
--------------------------------------------------------------------------------
| gpl-2.0 |
sami2448/a | plugins/inpm.lua | 7 | 3011 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '馃懃 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n馃懃"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
kaen/Zero-K | LuaUI/Widgets/map_edge_barrier.lua | 7 | 7418 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Map Edge Barrier",
version = "v0.22",
desc = "Draws a vertical grid along map edge",
author = "Pako",
date = "2012.02.19 - 2012.02.21", --YYYY.MM.DD, created - updated
license = "GPL",
layer = -1, --higher layer is loaded last
enabled = false,
--detailsDefault = 2
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if VFS.FileExists("nomapedgewidget.txt") then
return
end
local spGetGroundHeight = Spring.GetGroundHeight
local spTraceScreenRay = Spring.TraceScreenRay
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local wallTex = "bitmaps/PD/hexbig.png"
--local wallTex = "bitmaps/PD/shield2.png"
--local wallTex = "LuaUI/Images/vr_grid.png"
local height = 2048
local minHeight = -height/4
local maxHeight = height*3/4
local texScale = 0.01
local colorFloor = { 0.1, 0.88, 1, 1}
local colorCeiling = { 0.1, 0.88, 1, 0}
local dListWall
local island = false
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
options_path = 'Settings/Graphics/Map/Edge Barrier'
options = {
drawForIslands = {
name = "Draw for islands",
type = 'bool',
value = true,
desc = "Draws boundary wall when map is an island",
},
wallFromOutside = {
name = "Visible walls from outside",
type = 'bool',
value = false,
desc = "Map wall is visible from the outside (e.g. when it's between camera and main map)",
OnChange = function(self)
if dListWall then
gl.DeleteList(dListWall)
widget:Initialize()
end
end
},
northSouthText = {
name = "North, East, South, & West text",
type = 'bool',
value = false,
desc = 'Help you identify map direction under rotation by placing a "North/South/East/West" text on the map edges',
OnChange = function(self)
if dListWall then
gl.DeleteList(dListWall)
widget:Initialize()
end
end,
},
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function GetGroundHeight(x, z)
return spGetGroundHeight(x,z)
end
local function IsIsland()
local sampleDist = 512
for i=1,Game.mapSizeX,sampleDist do
-- top edge
if GetGroundHeight(i, 0) > 0 then
return false
end
-- bottom edge
if GetGroundHeight(i, Game.mapSizeZ) > 0 then
return false
end
end
for i=1,Game.mapSizeZ,sampleDist do
-- left edge
if GetGroundHeight(0, i) > 0 then
return false
end
-- right edge
if GetGroundHeight(Game.mapSizeX, i) > 0 then
return false
end
end
return true
end
local function TextOutside()
if (options.northSouthText.value) then
local mapSizeX = Game.mapSizeX
local mapSizeZ = Game.mapSizeZ
local average = (GetGroundHeight(mapSizeX/2,0) + GetGroundHeight(0,mapSizeZ/2) + GetGroundHeight(mapSizeX/2,mapSizeZ) +GetGroundHeight(mapSizeX,mapSizeZ/2))/4
gl.Rotate(-90,1,0,0)
gl.Translate (0,0,average)
gl.Text("North", mapSizeX/2, 200, 200, "co")
gl.Rotate(-90,0,0,1)
gl.Text("East", mapSizeZ/2, mapSizeX+200, 200, "co")
gl.Rotate(-90,0,0,1)
gl.Text("South", -mapSizeX/2, mapSizeZ +200, 200, "co")
gl.Rotate(-90,0,0,1)
gl.Text("West", -mapSizeZ/2,200, 200, "co")
-- gl.Text("North", mapSizeX/2, 100, 200, "on")
-- gl.Text("South", mapSizeX/2,-mapSizeZ, 200, "on")
-- gl.Text("East", mapSizeX,-(mapSizeZ/2), 200, "on")
-- gl.Text("West", 0,-(mapSizeZ/2), 200, "on")
end
end
local function DrawMapWall()
gl.Texture(wallTex)
if not options.wallFromOutside.value then
gl.Culling(GL.FRONT) --'cuts' the outside faces --remove this if you want it to draw over map too
end
gl.Shape( GL.TRIANGLE_STRIP,
{
{ v = { 0, minHeight, 0}, --top left down
texcoord = { 0, 0 },
c = colorFloor
},
{ v = { 0, maxHeight, 0},
texcoord = { 0, height*texScale }, --top left up
c = colorCeiling
},
{ v = { Game.mapSizeX, minHeight, 0},
texcoord = { Game.mapSizeX*texScale, 0 }, --top right
c = colorFloor
},
{ v = { Game.mapSizeX, maxHeight, 0},
texcoord = { Game.mapSizeX*texScale, height*texScale },
c = colorCeiling
},
{ v = { Game.mapSizeX, minHeight, Game.mapSizeZ}, -- bottom right
texcoord = { Game.mapSizeX*texScale+Game.mapSizeZ*texScale, 0 },
c = colorFloor
},
{ v = { Game.mapSizeX, maxHeight, Game.mapSizeZ},
texcoord = { Game.mapSizeX*texScale+Game.mapSizeZ*texScale, height*texScale },
c = colorCeiling
},
{ v = { 0, minHeight, Game.mapSizeZ}, --bottom left
texcoord = { Game.mapSizeZ*texScale, 0 },
c = colorFloor
},
{ v = { 0, maxHeight, Game.mapSizeZ},
texcoord = { Game.mapSizeZ*texScale, height*texScale },
c = colorCeiling
},
{ v = { 0, minHeight, 0}, --back to top right
texcoord = { 0, 0 },
c = colorFloor
},
{ v = { 0, maxHeight, 0},
texcoord = { 0, height*texScale },
c = colorCeiling
},
}
)
gl.Culling(false)
----draw map compass text
gl.PushAttrib(GL.ALL_ATTRIB_BITS)
gl.Texture(false)
gl.DepthMask(false)
gl.DepthTest(false)
gl.Color(1,1,1,1)
TextOutside()
gl.PopAttrib()
----
end
function widget:Initialize()
island = IsIsland()
dListWall = gl.CreateList(DrawMapWall)
end
function widget:Shutdown()
gl.DeleteList(dListWall)
end
local function DrawWorldFunc()
if (not island) or options.drawForIslands.value then
gl.DepthTest(GL.LEQUAL)
gl.CallList(dListWall)
gl.DepthTest(false)
end
end
function widget:DrawWorldPreUnit()
DrawWorldFunc()
end
function widget:DrawWorldRefraction()
DrawWorldFunc()
end
function widget:MousePress(x, y, button)
local _, mpos = spTraceScreenRay(x, y, true) --//convert UI coordinate into ground coordinate.
if mpos==nil then --//activate epic menu if mouse position is outside the map
local _, _, meta, _ = Spring.GetModKeyState()
if meta then --//show epicMenu when user also press the Spacebar
WG.crude.OpenPath(options_path) --click + space will shortcut to option-menu
WG.crude.ShowMenu() --make epic Chili menu appear.
return false
end
end
end
| gpl-2.0 |
evilexecutable/ResourceKeeper | install/Lua/lib/lua/luarocks/tools/zip.lua | 2 | 8340 |
--- A Lua implementation of .zip file archiving (used for creating .rock files),
-- using only lua-zlib.
module("luarocks.tools.zip", package.seeall)
local zlib = require("zlib")
local fs = require("luarocks.fs")
local dir = require("luarocks.dir")
local function number_to_bytestring(number, nbytes)
local out = {}
for i = 1, nbytes do
local byte = number % 256
table.insert(out, string.char(byte))
number = (number - byte) / 256
end
return table.concat(out)
end
--- Begin a new file to be stored inside the zipfile.
-- @param self handle of the zipfile being written.
-- @param filename filenome of the file to be added to the zipfile.
-- @return true if succeeded, nil in case of failure.
local function zipwriter_open_new_file_in_zip(self, filename)
if self.in_open_file then
self:close_file_in_zip()
return nil
end
local lfh = {}
self.local_file_header = lfh
lfh.last_mod_file_time = 0 -- TODO
lfh.last_mod_file_date = 0 -- TODO
lfh.crc32 = 0 -- initial value
lfh.compressed_size = 0 -- unknown yet
lfh.uncompressed_size = 0 -- unknown yet
lfh.file_name_length = #filename
lfh.extra_field_length = 0
lfh.file_name = filename:gsub("\\", "/")
lfh.external_attr = 0 -- TODO properly store permissions
self.in_open_file = true
self.data = {}
return true
end
--- Write data to the file currently being stored in the zipfile.
-- @param self handle of the zipfile being written.
-- @param buf string containing data to be written.
-- @return true if succeeded, nil in case of failure.
local function zipwriter_write_file_in_zip(self, buf)
if not self.in_open_file then
return nil
end
local lfh = self.local_file_header
local cbuf = zlib.compress(buf):sub(3, -5)
lfh.crc32 = zlib.crc32(lfh.crc32, buf)
lfh.compressed_size = lfh.compressed_size + #cbuf
lfh.uncompressed_size = lfh.uncompressed_size + #buf
table.insert(self.data, cbuf)
return true
end
--- Complete the writing of a file stored in the zipfile.
-- @param self handle of the zipfile being written.
-- @return true if succeeded, nil in case of failure.
local function zipwriter_close_file_in_zip(self)
local zh = self.ziphandle
if not self.in_open_file then
return nil
end
-- Local file header
local lfh = self.local_file_header
lfh.offset = zh:seek()
zh:write(number_to_bytestring(0x04034b50, 4)) -- signature
zh:write(number_to_bytestring(20, 2)) -- version needed to extract: 2.0
zh:write(number_to_bytestring(0, 2)) -- general purpose bit flag
zh:write(number_to_bytestring(8, 2)) -- compression method: deflate
zh:write(number_to_bytestring(lfh.last_mod_file_time, 2))
zh:write(number_to_bytestring(lfh.last_mod_file_date, 2))
zh:write(number_to_bytestring(lfh.crc32, 4))
zh:write(number_to_bytestring(lfh.compressed_size, 4))
zh:write(number_to_bytestring(lfh.uncompressed_size, 4))
zh:write(number_to_bytestring(lfh.file_name_length, 2))
zh:write(number_to_bytestring(lfh.extra_field_length, 2))
zh:write(lfh.file_name)
-- File data
for _, cbuf in ipairs(self.data) do
zh:write(cbuf)
end
-- Data descriptor
zh:write(number_to_bytestring(lfh.crc32, 4))
zh:write(number_to_bytestring(lfh.compressed_size, 4))
zh:write(number_to_bytestring(lfh.uncompressed_size, 4))
table.insert(self.files, lfh)
self.in_open_file = false
return true
end
-- @return boolean or (boolean, string): true on success,
-- false and an error message on failure.
local function zipwriter_add(self, file)
local fin
local ok, err = self:open_new_file_in_zip(file)
if not ok then
err = "error in opening "..file.." in zipfile"
else
fin = io.open(fs.absolute_name(file), "rb")
if not fin then
ok = false
err = "error opening "..file.." for reading"
end
end
if ok then
local buf = fin:read("*a")
if not buf then
err = "error reading "..file
ok = false
else
ok = self:write_file_in_zip(buf)
if not ok then
err = "error in writing "..file.." in the zipfile"
end
end
end
if fin then
fin:close()
end
if ok then
ok = self:close_file_in_zip()
if not ok then
err = "error in writing "..file.." in the zipfile"
end
end
return ok == true, err
end
--- Complete the writing of the zipfile.
-- @param self handle of the zipfile being written.
-- @return true if succeeded, nil in case of failure.
local function zipwriter_close(self)
local zh = self.ziphandle
local central_directory_offset = zh:seek()
local size_of_central_directory = 0
-- Central directory structure
for _, lfh in ipairs(self.files) do
zh:write(number_to_bytestring(0x02014b50, 4)) -- signature
zh:write(number_to_bytestring(3, 2)) -- version made by: UNIX
zh:write(number_to_bytestring(20, 2)) -- version needed to extract: 2.0
zh:write(number_to_bytestring(0, 2)) -- general purpose bit flag
zh:write(number_to_bytestring(8, 2)) -- compression method: deflate
zh:write(number_to_bytestring(lfh.last_mod_file_time, 2))
zh:write(number_to_bytestring(lfh.last_mod_file_date, 2))
zh:write(number_to_bytestring(lfh.crc32, 4))
zh:write(number_to_bytestring(lfh.compressed_size, 4))
zh:write(number_to_bytestring(lfh.uncompressed_size, 4))
zh:write(number_to_bytestring(lfh.file_name_length, 2))
zh:write(number_to_bytestring(lfh.extra_field_length, 2))
zh:write(number_to_bytestring(0, 2)) -- file comment length
zh:write(number_to_bytestring(0, 2)) -- disk number start
zh:write(number_to_bytestring(0, 2)) -- internal file attributes
zh:write(number_to_bytestring(lfh.external_attr, 4)) -- external file attributes
zh:write(number_to_bytestring(lfh.offset, 4)) -- relative offset of local header
zh:write(lfh.file_name)
size_of_central_directory = size_of_central_directory + 46 + lfh.file_name_length
end
-- End of central directory record
zh:write(number_to_bytestring(0x06054b50, 4)) -- signature
zh:write(number_to_bytestring(0, 2)) -- number of this disk
zh:write(number_to_bytestring(0, 2)) -- number of disk with start of central directory
zh:write(number_to_bytestring(#self.files, 2)) -- total number of entries in the central dir on this disk
zh:write(number_to_bytestring(#self.files, 2)) -- total number of entries in the central dir
zh:write(number_to_bytestring(size_of_central_directory, 4))
zh:write(number_to_bytestring(central_directory_offset, 4))
zh:write(number_to_bytestring(0, 2)) -- zip file comment length
zh:close()
return true
end
--- Return a zip handle open for writing.
-- @param name filename of the zipfile to be created.
-- @return a zip handle, or nil in case of error.
function new_zipwriter(name)
local zw = {}
zw.ziphandle = io.open(fs.absolute_name(name), "wb")
if not zw.ziphandle then
return nil
end
zw.files = {}
zw.in_open_file = false
zw.add = zipwriter_add
zw.close = zipwriter_close
zw.open_new_file_in_zip = zipwriter_open_new_file_in_zip
zw.write_file_in_zip = zipwriter_write_file_in_zip
zw.close_file_in_zip = zipwriter_close_file_in_zip
return zw
end
--- Compress files in a .zip archive.
-- @param zipfile string: pathname of .zip archive to be created.
-- @param ... Filenames to be stored in the archive are given as
-- additional arguments.
-- @return boolean or (boolean, string): true on success,
-- false and an error message on failure.
function zip(zipfile, ...)
local zw = new_zipwriter(zipfile)
if not zw then
return nil, "error opening "..zipfile
end
local ok, err
for _, file in pairs({...}) do
if fs.is_dir(file) then
for _, entry in pairs(fs.find(file)) do
local fullname = dir.path(file, entry)
if fs.is_file(fullname) then
ok, err = zw:add(fullname)
if not ok then break end
end
end
else
ok, err = zw:add(file)
if not ok then break end
end
end
local ok = zw:close()
if not ok then
return false, "error closing "..zipfile
end
return ok, err
end
| gpl-2.0 |
mohammadclashclash/elll2014 | plugins/danbooru.lua | 616 | 1750 | do
local URL = "http://danbooru.donmai.us"
local URL_NEW = "/posts.json"
local URL_POP = "/explore/posts/popular.json"
local scale_day = "?scale=day"
local scale_week = "?scale=week"
local scale_month = "?scale=month"
local function get_post(url)
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local posts = json:decode(b)
return posts[math.random(#posts)]
end
local function run(msg, matches)
local url = URL
if matches[1] == "!danbooru" then
url = url .. URL_NEW
else
url = url .. URL_POP
if matches[1] == "d" then
url = url .. scale_day
elseif matches[1] == "w" then
url = url .. scale_week
elseif matches[1] == "m" then
url = url .. scale_month
end
end
local post = get_post(url)
if post then
vardump(post)
local img = URL .. post.large_file_url
send_photo_from_url(get_receiver(msg), img)
local txt = ''
if post.tag_string_artist ~= '' then
txt = 'Artist: ' .. post.tag_string_artist .. '\n'
end
if post.tag_string_character ~= '' then
txt = txt .. 'Character: ' .. post.tag_string_character .. '\n'
end
if post.file_size ~= '' then
txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url
end
return txt
end
end
return {
description = "Gets a random fresh or popular image from Danbooru",
usage = {
"!danbooru - gets a random fresh image from Danbooru 🔞",
"!danboorud - random daily popular image 🔞",
"!danbooruw - random weekly popular image 🔞",
"!danboorum - random monthly popular image 🔞"
},
patterns = {
"^!danbooru$",
"^!danbooru ?(d)$",
"^!danbooru ?(w)$",
"^!danbooru ?(m)$"
},
run = run
}
end | gpl-2.0 |
esn3s/3S_LUA | vrac/_esnFbaScreenshot/sfiii3-hitboxes_mame.lua | 1 | 13622 | --MAME-rrêphitbox.luaB
--ù¶Ìhitbox.luaðAȺÌlÉÏXB
--EPt[ãÌ»èð\¦µÄ¢½ ¨ »Ìt[Å̽è»èð\¦·éæ¤ÉÏX
--EÊíÌH碻èU»è¾¯\¦µÄ¢½ ¨ Uðoµ½ÌH碻èà\¦·éæ¤ÉÏX
--ELÌcÀWªOȺÉÈ鯻èª\¦³êÈ©Á½¨ \¦·éæ¤ÉÏX
local SCREEN_WIDTH = 384
local SCREEN_HEIGHT = 224
local GROUND_OFFSET = 40
local MAX_GAME_OBJECTS = 30
local AXIS_COLOUR = 0xFFFFFFFF
local AXIS_SIZE = 25
local HITBOX_PASSIVE = 0
local HITBOX_ACTIVE = 1
local HITBOX_PASSIVE2 = 2
local HITBOX_PASSIVE_COLOUR = 0x00008040
local HITBOX_ACTIVE_COLOUR = 0x00FF0040
local HITBOX_PASSIVE2_COLOUR = 0x0000FF40
local GAME_PHASE_PLAYING = 2
timeInLua = 0
timeInGame = 0
local address = {
player1 = 0x02068C6C,
player2 = 0x02069104,
screen_center_x = 0x02026CC0,
screen_center_y = 0x0206A121,
}
local globals = {
screen_center_x = 0,
screen_center_y = 0,
num_misc_objs = 0
}
local globals2 = {
screen_center_x = 0,
screen_center_y = 0,
num_misc_objs = 0
}
local player1 = {}
local player2 = {}
local player1_2 = {}
local player2_2 = {}
local misc_objs = {}
local misc_objs_2 = {}
--XN[ÌÀWÆQ[tFCYðXV
function update_globals()
globals2.screen_center_x = globals.screen_center_x
globals2.screen_center_y = globals.screen_center_y
globals2.num_misc_objs = globals.num_misc_objs
globals.screen_center_x = memory.readword(address.screen_center_x)
globals.screen_center_y = memory.readbyte(address.screen_center_y)
end
--à©ç½è»èf[^ðÇÝÞ
function hitbox_load(obj, i, type, facing_dir, offset_x, offset_y, addr)
local left = memory.readwordsigned(addr)
local right = memory.readwordsigned(addr + 2)
local bottom = memory.readwordsigned(addr + 4)
local top = memory.readwordsigned(addr + 6)
if facing_dir == 1 then
left = -left
right = -right
end
left = left + offset_x
right = right + left
bottom = bottom + offset_y
top = top + bottom
if type == HITBOX_PASSIVE then
obj.p_hboxes[i] = {
left = left,
right = right,
bottom = bottom,
top = top,
type = type
}
else
if type == HITBOX_ACTIVE then
obj.a_hboxes[i] = {
left = left,
right = right,
bottom = bottom,
top = top,
type = type
}
else
obj.p2_hboxes[i] = {
left = left,
right = right,
bottom = bottom,
top = top,
type = type
}
end
end
end
function update_game_object(obj, base)
obj.p_hboxes = {}
obj.a_hboxes = {}
obj.p2_hboxes = {}
obj.facing_dir = memory.readbyte(base + 0xA)
obj.opponent_dir = memory.readbyte(base + 0xB)
obj.pos_x = memory.readword(base + 0x64)
obj.pos_y = num2signed(memory.readword(base + 0x68),2)
obj.anim_frame = memory.readword(base + 0x21A)
-- Load the passive hitboxes
local p_hb_addr = memory.readdword(base + 0x2A0)
for i = 1, 4 do
hitbox_load(obj, i, HITBOX_PASSIVE, obj.facing_dir, obj.pos_x, obj.pos_y, p_hb_addr)
p_hb_addr = p_hb_addr + 8
end
-- Load the active hitboxes
local a_hb_addr = memory.readdword(base + 0x2C8)
for i = 1, 4 do
hitbox_load(obj, i, HITBOX_ACTIVE, obj.facing_dir, obj.pos_x, obj.pos_y, a_hb_addr)
a_hb_addr = a_hb_addr + 8
end
-- Load the passive2 hitboxes
local a_hb_addr = memory.readdword(base + 0x2A8)
for i = 1, 4 do
hitbox_load(obj, i, HITBOX_PASSIVE2, obj.facing_dir, obj.pos_x, obj.pos_y, a_hb_addr)
a_hb_addr = a_hb_addr + 8
end
end
function read_misc_objects(table)
local obj_index
local obj_addr
local p_hb_addr
local a_hb_addr
-- This function reads all game objects other than the two player characters.
-- This includes all projectiles and even Yang's Seiei-Enbu shadows.
-- The game uses the same structure all over the place and groups them
-- into lists with each element containing an index to the next element
-- in that list. An index of -1 signals the end of the list.
-- I believe there are at least 7 lists (0-6) but it seems everything we need
-- (and lots we don't) is in list 3.
local list = 3
num_misc_objs = 1
obj_index = memory.readwordsigned(0x02068A96 + (list * 2))
while num_misc_objs <= MAX_GAME_OBJECTS and obj_index ~= -1 do
obj_addr = 0x02028990 + (obj_index * 0x800)
-- I don't really know how to tell different game objects types apart yet so
-- just read everything that has non-zero hitbox addresses. Seems to
-- work fine...
p_hb_addr = memory.readdword(obj_addr + 0x2A0)
a_hb_addr = memory.readdword(obj_addr + 0x2C8)
p2_hb_addr = memory.readdword(obj_addr + 0x2A8)
if p_hb_addr ~= 0 and a_hb_addr ~= 0 and p2_hb_addr ~= 0 then
table[num_misc_objs] = {}
update_game_object(table[num_misc_objs], obj_addr)
num_misc_objs = num_misc_objs + 1
end
-- Get the index to the next object in this list.
obj_index = memory.readwordsigned(obj_addr + 0x1C)
end
end
function game_x_to_mame(x)
local left_edge = globals2.screen_center_x - (SCREEN_WIDTH / 2)
return (x - left_edge)
end
function game_y_to_mame(y)
-- Why subtract 17? No idea, the game driver does the same thing.
return (SCREEN_HEIGHT - (y + GROUND_OFFSET - 17) + num2signed(globals2.screen_center_y,1))
end
function draw_hitbox(hb)
local left = game_x_to_mame(hb.left)
local bottom = game_y_to_mame(hb.bottom)
local right = game_x_to_mame(hb.right)
local top = game_y_to_mame(hb.top)
if(hb.type == HITBOX_PASSIVE) then
colour = HITBOX_PASSIVE_COLOUR
else
if(hb.type == HITBOX_ACTIVE) then
colour = HITBOX_ACTIVE_COLOUR
else
colour = HITBOX_PASSIVE2_COLOUR
end
end
gui.box(left, top, right, bottom, colour)
end
function draw_game_object(obj)
local x = game_x_to_mame(obj.pos_x)
local y = game_y_to_mame(obj.pos_y)
for i = 1, 4 do
draw_hitbox(obj.p_hboxes[i])
end
for i = 1, 4 do
draw_hitbox(obj.p2_hboxes[i])
end
for i = 1, 4 do
draw_hitbox(obj.a_hboxes[i])
end
gui.drawline(x, y-AXIS_SIZE, x, y+AXIS_SIZE, AXIS_COLOUR)
gui.drawline(x-AXIS_SIZE, y, x+AXIS_SIZE, y, AXIS_COLOUR)
end
function render_sfiii_hitboxes()
--ÎíÅȯêÎI¹
if memory.readword(0x020154A6) ~= GAME_PHASE_PLAYING then
gui.clearuncommitted()
return
end
--luaðN®µÄÅÌt[ÍA
--Pt[OÌf[^ªe[uÉi[³êĢȢÌÅ`æÅ«È¢
if timeInLua > 1 then
--Q[àoßÔªôÌÍAï¾Á½Ì½è»èð\¦
if memory.readbyte(0x02068AB7) % 2 == 0 then
draw_game_object(player1)
draw_game_object(player2)
for i = 1, num_misc_objs-1 do
if #misc_objs > 0 then
draw_game_object(misc_objs[i])
end
end
else--Q[àoßÔªïÌÍAô¾Á½Ì½è»èð\¦
draw_game_object(player1_2)
draw_game_object(player2_2)
for i = 1, num_misc_objs-1 do
if #misc_objs_2 > 0 then
draw_game_object(misc_objs_2[i])
end
end
end
end
--Q[àÌÔªoߵ̽çLuaàÌÔàißéB
--ÂÜèALuaðJnµÄÌt[©çªÌ`æªÀs³êé
if timeInGame ~= memory.readbyte(0x02068AB7) then
update_globals()
timeInLua = timeInLua + 1
end
--Q[àoßÔªôÌÍA½è»èf[^ð±Á¿Éi[
if memory.readbyte(0x02068AB7) % 2 == 0 then
update_game_object(player1_2, address.player1)
update_game_object(player2_2, address.player2)
read_misc_objects(misc_objs_2)
else--Q[àoßÔªïÌÍA½è»èf[^ð±Á¿Éi[
update_game_object(player1, address.player1)
update_game_object(player2, address.player2)
read_misc_objects(misc_objs)
end
timeInGame = memory.readbyte(0x02068AB7)
end
--- Returns HEX representation of num
function num2hex(num)
local hexstr = '0123456789ABCDEF'
local s = ''
while num > 0 do
local mod = math.fmod(num, 16)
s = string.sub(hexstr, mod+1, mod+1) .. s
num = math.floor(num / 16)
end
if s == '' then s = '0' end
return s
end
----±±©çºÍÕç·ªìÁ½ÖQB±ÌluaÅÍwÇgÁÄÈ¢----
--********lvalueÌAbitnumÔÚÌrbgðÔ·Ö********
--@param value ²×½¢Ï
--@param bitnum ½ÔÚð²×½¢©iźÊ
Í0j
function bitReturn(value,bitnum)
re = value
--bitnumæèãÊ
ðØèÌÄé
re = SHIFT(re,bitnum-31)
--bitnumæèºÊ
ðØèÌÄé
re = SHIFT(re,31)
return re
end
--D«ÈoCgª«±ñÅêéÖ
function write(addr,value,byte)
for i=1,byte,1 do
memory.writebyte(addr,value)
addr = addr + 1
value = ((value-(value%0x100)) / 0x100)
end
end
--D«ÈoCgªtü«É«ñÅêéÖ
function writeReverse(addr,value,byte)
for i=1,byte,1 do
memory.writebyte(addr,(value % 0x100))
addr = addr - 1
value = ((value-(value%0x100)) / 0x100)
end
end
--D«ÈoCgªÇݱñÅêéÖ
function read(addr,byte)
value = 0
for i=1,byte,1 do
value = (value + memory.readbyte(addr+i-1)) * 0x100
end
return value / 0x100
end
--D«ÈoCgªtü«ÉÇÝñÅêéÖ
function readReverse(addr,byte)
value = 0
for i=1,byte,1 do
value = value + (memory.readbyte(addr-(i-1)) * (0x100^(i-1)))
end
return value
end
--àÌlðA^CÅ©½¢Æ«Ég¤B
--AhXªÉA©½¢AhXÌlðüÍ·éÆA»ÌüÓÌlª©¦éB
function viewMemory(addr)
for i=0,20,1 do
gui.text(10,14+i*8,num2hex(addr+(i*0x10)))
for j=0,15,1 do
gui.text(48+j*16,4,num2hex(j))
gui.text(48+j*16,14+i*8,num2hex(memory.readbyte((addr)+j+(i*0x10))))
end
end
end
--àÌlðAt@CÉ«¾µÄêéB
--startÍJnAhXAlastÍÅIAhXB
function writeFileMemory(start,last)
out = io.open("memoryOut.txt","w")
for i=start,last,1 do
out:write(memory.readbyte(i).."\n")
end
end
--ÊuÀWðlÅ\¦µÄêéB
function viewPosition()
--1PÌÀWð16iÅ\¦
offsetX1 = 52
offsetY1 = 32
if readReverse(0x02068CD1,2) < 0x100 then
gui.text(offsetX1,offsetY1,"X: "..num2hex(readReverse(0x02068CD1,2)))
else
gui.text(offsetX1,offsetY1,"X:"..num2hex(readReverse(0x02068CD1,2)))
end
if (readReverse(0x02068CD2,1)) == 0 then
gui.text(offsetX1+20,offsetY1,".00")
else
gui.text(offsetX1+20,offsetY1,"."..num2hex(readReverse(0x02068CD2,1)))
end
gui.text(offsetX1,offsetY1+8,"Y:")
gui.text(offsetX1+20-string.len(readReverse(0x02068CD5,2))*4,offsetY1+8,readReverse(0x02068CD5,2))
if (readReverse(0x02068CD6,1)) == 0 then
gui.text(offsetX1+20,offsetY1+8,".00")
else
gui.text(offsetX1+20,offsetY1+8,"."..num2hex(readReverse(0x02068CD6,1)))
end
--2PÌÀWð16iÅ\¦
offsetX2 = 256
offsetY2 = 32
if readReverse(0x02069169,2) < 0x100 then
gui.text(offsetX2,offsetY2,"X: "..num2hex(readReverse(0x02069169,2)))
else
gui.text(offsetX2,offsetY2,"X:"..num2hex(readReverse(0x02069169,2)))
end
if (readReverse(0x0206916A,1)) == 0 then
gui.text(offsetX2+20,offsetY2,".00")
else
gui.text(offsetX2+20,offsetY2,"."..num2hex(readReverse(0x0206916A,1)))
end
gui.text(offsetX2,offsetY2+8,"Y:")
gui.text(offsetX2+20-string.len(readReverse(0x0206916D,2))*4,offsetY2+8,readReverse(0x0206916D,2))
if (readReverse(0x0206916E,1)) == 0 then
gui.text(offsetX2+20,offsetY2+8,".00")
else
gui.text(offsetX2+20,offsetY2+8,"."..num2hex(readReverse(0x0206916E,1)))
end
--·ªÌxÀWð16iÅ\¦
offsetX3 = 180
offsetY3 = 38
x1P = readReverse(0x02068CD1,2)
x2P = readReverse(0x02069169,2)
if x2P > x1P then
if x2P < 0x100 then
gui.text(offsetX3,offsetY3,"2P: "..num2hex(x2P))
else
gui.text(offsetX3,offsetY3,"2P: "..num2hex(x2P))
end
if x1P < 0x100 then
gui.text(offsetX3,offsetY3+8,"1P: "..num2hex(x1P))
else
gui.text(offsetX3,offsetY3+8,"1P: "..num2hex(x1P))
end
gui.drawbox(offsetX3-10,offsetY3+15,offsetX3+28,offsetY3+17,0xFFFFFFFF,0x000000FF)
if x2P-x1P < 0x100 then
gui.text(offsetX3-8,offsetY3+19,"DIFF: "..num2hex(x2P-x1P))
else
gui.text(offsetX3-8,offsetY3+19,"DIFF: "..num2hex(x2P-x1P))
end
else
if x1P < 0x100 then
gui.text(offsetX3,offsetY3,"1P: "..num2hex(x1P))
else
gui.text(offsetX3,offsetY3,"1P: "..num2hex(x1P))
end
if x2P < 0x100 then
gui.text(offsetX3,offsetY3+8,"2P: "..num2hex(x2P))
else
gui.text(offsetX3,offsetY3+8,"2P: "..num2hex(x2P))
end
gui.drawbox(offsetX3-10,offsetY3+15,offsetX3+28,offsetY3+17,0xFFFFFFFF,0x000000FF)
if x1P-x2P < 0x100 then
gui.text(offsetX3-8,offsetY3+19,"DIFF: "..num2hex(x1P-x2P))
else
gui.text(offsetX3-8,offsetY3+19,"DIFF: "..num2hex(x1P-x2P))
end
end
end
--lÆoCgðøÉüêéÆAt«ÌlÉÏ·µÄÔµÄêéB
function num2signed(value,byte)
local subValue = 1
for i=1,byte,1 do
subValue = subValue * 0x100
end
if value >= (subValue/2) then
value = value - subValue
end
return value
end
gui.register( function()
--±±È~ÉAU»èÌf[^ª°ÁÄ¢éÁÛ¢B
--©½¢êͱ±ÌRgðO·
viewMemory(0x02068F30)
--ÊuÀWðlÅ©½¢êͱ±ÌRgðO·
--viewPosition()
render_sfiii_hitboxes()
end) | mit |
geanux/darkstar | scripts/zones/Mount_Zhayolm/TextIDs.lua | 7 | 1063 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6383; -- Obtained: <item>
GIL_OBTAINED = 6384; -- Obtained <number> gil
KEYITEM_OBTAINED = 6386; -- Obtained key item: <keyitem>
FISHING_MESSAGE_OFFSET = 7040; -- You can't fish here
HOMEPOINT_SET = 8709; -- Home point set!
-- Mining
MINING_IS_POSSIBLE_HERE = 7404; -- Mining is possible here if you have
-- Assault
CANNOT_ENTER = 7463; -- You cannot enter at this time. Please wait a while before trying again.
AREA_FULL = 7464; -- This area is fully occupied. You were unable to enter.
MEMBER_NO_REQS = 7468; -- Not all of your party members meet the requirements for this objective. Unable to enter area.
MEMBER_TOO_FAR = 7472; -- One or more party members are too far away from the entrance. Unable to enter area.
-- Other Texts
NOTHING_HAPPENS = 7449; -- Nothing happens...
RESPONSE = 7315; -- There is no response...
| gpl-3.0 |
evilexecutable/ResourceKeeper | install/LuaRocks/lua/luarocks/repos.lua | 20 | 11978 |
--- Functions for managing the repository on disk.
--module("luarocks.repos", package.seeall)
local repos = {}
package.loaded["luarocks.repos"] = repos
local fs = require("luarocks.fs")
local path = require("luarocks.path")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local dir = require("luarocks.dir")
local manif = require("luarocks.manif")
local deps = require("luarocks.deps")
--- Get all installed versions of a package.
-- @param name string: a package name.
-- @return table or nil: An array of strings listing installed
-- versions of a package, or nil if none is available.
local function get_installed_versions(name)
assert(type(name) == "string")
local dirs = fs.list_dir(path.versions_dir(name))
return (dirs and #dirs > 0) and dirs or nil
end
--- Check if a package exists in a local repository.
-- Version numbers are compared as exact string comparison.
-- @param name string: name of package
-- @param version string: package version in string format
-- @return boolean: true if a package is installed,
-- false otherwise.
function repos.is_installed(name, version)
assert(type(name) == "string")
assert(type(version) == "string")
return fs.is_dir(path.install_dir(name, version))
end
local function recurse_rock_manifest_tree(file_tree, action)
assert(type(file_tree) == "table")
assert(type(action) == "function")
local function do_recurse_rock_manifest_tree(tree, parent_path, parent_module)
for file, sub in pairs(tree) do
if type(sub) == "table" then
local ok, err = do_recurse_rock_manifest_tree(sub, parent_path..file.."/", parent_module..file..".")
if not ok then return nil, err end
else
local ok, err = action(parent_path, parent_module, file)
if not ok then return nil, err end
end
end
return true
end
return do_recurse_rock_manifest_tree(file_tree, "", "")
end
local function store_package_data(result, name, file_tree)
if not file_tree then return end
return recurse_rock_manifest_tree(file_tree,
function(parent_path, parent_module, file)
local pathname = parent_path..file
result[path.path_to_module(pathname)] = pathname
return true
end
)
end
--- Obtain a list of modules within an installed package.
-- @param package string: The package name; for example "luasocket"
-- @param version string: The exact version number including revision;
-- for example "2.0.1-1".
-- @return table: A table of modules where keys are module identifiers
-- in "foo.bar" format and values are pathnames in architecture-dependent
-- "foo/bar.so" format. If no modules are found or if package or version
-- are invalid, an empty table is returned.
function repos.package_modules(package, version)
assert(type(package) == "string")
assert(type(version) == "string")
local result = {}
local rock_manifest = manif.load_rock_manifest(package, version)
store_package_data(result, package, rock_manifest.lib)
store_package_data(result, package, rock_manifest.lua)
return result
end
--- Obtain a list of command-line scripts within an installed package.
-- @param package string: The package name; for example "luasocket"
-- @param version string: The exact version number including revision;
-- for example "2.0.1-1".
-- @return table: A table of items where keys are command names
-- as strings and values are pathnames in architecture-dependent
-- ".../bin/foo" format. If no modules are found or if package or version
-- are invalid, an empty table is returned.
function repos.package_commands(package, version)
assert(type(package) == "string")
assert(type(version) == "string")
local result = {}
local rock_manifest = manif.load_rock_manifest(package, version)
store_package_data(result, package, rock_manifest.bin)
return result
end
--- Check if a rock contains binary executables.
-- @param name string: name of an installed rock
-- @param version string: version of an installed rock
-- @return boolean: returns true if rock contains platform-specific
-- binary executables, or false if it is a pure-Lua rock.
function repos.has_binaries(name, version)
assert(type(name) == "string")
assert(type(version) == "string")
local rock_manifest = manif.load_rock_manifest(name, version)
if rock_manifest.bin then
for name, md5 in pairs(rock_manifest.bin) do
-- TODO verify that it is the same file. If it isn't, find the actual command.
if fs.is_actual_binary(dir.path(cfg.deploy_bin_dir, name)) then
return true
end
end
end
return false
end
function repos.run_hook(rockspec, hook_name)
assert(type(rockspec) == "table")
assert(type(hook_name) == "string")
local hooks = rockspec.hooks
if not hooks then
return true
end
if cfg.hooks_enabled == false then
return nil, "This rockspec contains hooks, which are blocked by the 'hooks_enabled' setting in your LuaRocks configuration."
end
if not hooks.substituted_variables then
util.variable_substitutions(hooks, rockspec.variables)
hooks.substituted_variables = true
end
local hook = hooks[hook_name]
if hook then
util.printout(hook)
if not fs.execute(hook) then
return nil, "Failed running "..hook_name.." hook."
end
end
return true
end
local function install_binary(source, target, name, version)
assert(type(source) == "string")
assert(type(target) == "string")
if fs.is_lua(source) then
repos.ok, repos.err = fs.wrap_script(source, target, name, version)
else
repos.ok, repos.err = fs.copy_binary(source, target)
end
return repos.ok, repos.err
end
local function resolve_conflict(target, deploy_dir, name, version)
local cname, cversion = manif.find_current_provider(target)
if not cname then
return nil, cversion
end
if name ~= cname or deps.compare_versions(version, cversion) then
local versioned = path.versioned_name(target, deploy_dir, cname, cversion)
local ok, err = fs.make_dir(dir.dir_name(versioned))
if not ok then return nil, err end
fs.move(target, versioned)
return target
else
return path.versioned_name(target, deploy_dir, name, version)
end
end
function repos.should_wrap_bin_scripts(rockspec)
assert(type(rockspec) == "table")
if cfg.wrap_bin_scripts ~= nil then
return cfg.wrap_bin_scripts
end
if rockspec.deploy and rockspec.deploy.wrap_bin_scripts == false then
return false
end
return true
end
function repos.deploy_files(name, version, wrap_bin_scripts)
assert(type(name) == "string")
assert(type(version) == "string")
assert(type(wrap_bin_scripts) == "boolean")
local function deploy_file_tree(file_tree, path_fn, deploy_dir, move_fn)
local source_dir = path_fn(name, version)
if not move_fn then
move_fn = fs.move
end
return recurse_rock_manifest_tree(file_tree,
function(parent_path, parent_module, file)
local source = dir.path(source_dir, parent_path, file)
local target = dir.path(deploy_dir, parent_path, file)
local ok, err
if fs.exists(target) then
local new_target, err = resolve_conflict(target, deploy_dir, name, version)
if err == "untracked" then
local backup = target
repeat
backup = backup.."~"
until not fs.exists(backup) -- slight race condition here, but shouldn't be a problem.
util.printerr("Warning: "..target.." is not tracked by this installation of LuaRocks. Moving it to "..backup)
fs.move(target, backup)
elseif err then
return nil, err.." Cannot install new version."
else
target = new_target
end
end
ok, err = fs.make_dir(dir.dir_name(target))
if not ok then return nil, err end
ok, err = move_fn(source, target, name, version)
fs.remove_dir_tree_if_empty(dir.dir_name(source))
if not ok then return nil, err end
return true
end
)
end
local rock_manifest = manif.load_rock_manifest(name, version)
local ok, err = true
if rock_manifest.bin then
local move_bin_fn = wrap_bin_scripts and install_binary or fs.copy_binary
ok, err = deploy_file_tree(rock_manifest.bin, path.bin_dir, cfg.deploy_bin_dir, move_bin_fn)
end
if ok and rock_manifest.lua then
ok, err = deploy_file_tree(rock_manifest.lua, path.lua_dir, cfg.deploy_lua_dir)
end
if ok and rock_manifest.lib then
ok, err = deploy_file_tree(rock_manifest.lib, path.lib_dir, cfg.deploy_lib_dir)
end
return ok, err
end
local function delete_suffixed(filename, suffix)
local filenames = { filename }
if suffix and suffix ~= "" then filenames = { filename..suffix, filename } end
for _, name in ipairs(filenames) do
if fs.exists(name) then
fs.delete(name)
if fs.exists(name) then
return nil, "Failed deleting "..name, "fail"
end
return true, name
end
end
return false, "File not found", "not found"
end
--- Delete a package from the local repository.
-- Version numbers are compared as exact string comparison.
-- @param name string: name of package
-- @param version string: package version in string format
-- @param quick boolean: do not try to fix the versioned name
-- of another version that provides the same module that
-- was deleted. This is used during 'purge', as every module
-- will be eventually deleted.
function repos.delete_version(name, version, quick)
assert(type(name) == "string")
assert(type(version) == "string")
local function delete_deployed_file_tree(file_tree, deploy_dir, suffix)
return recurse_rock_manifest_tree(file_tree,
function(parent_path, parent_module, file)
local target = dir.path(deploy_dir, parent_path, file)
local versioned = path.versioned_name(target, deploy_dir, name, version)
local ok, name, err = delete_suffixed(versioned, suffix)
if ok then
fs.remove_dir_tree_if_empty(dir.dir_name(versioned))
return true
end
if err == "fail" then return nil, name end
ok, name, err = delete_suffixed(target, suffix)
if err == "fail" then return nil, name end
if not quick then
local next_name, next_version = manif.find_next_provider(target)
if next_name then
local versioned = path.versioned_name(name, deploy_dir, next_name, next_version)
fs.move(versioned, name)
fs.remove_dir_tree_if_empty(dir.dir_name(versioned))
end
end
fs.remove_dir_tree_if_empty(dir.dir_name(target))
return true
end
)
end
local rock_manifest = manif.load_rock_manifest(name, version)
if not rock_manifest then
return nil, "rock_manifest file not found for "..name.." "..version.." - not a LuaRocks 2 tree?"
end
local ok, err = true
if rock_manifest.bin then
ok, err = delete_deployed_file_tree(rock_manifest.bin, cfg.deploy_bin_dir, cfg.wrapper_suffix)
end
if ok and rock_manifest.lua then
ok, err = delete_deployed_file_tree(rock_manifest.lua, cfg.deploy_lua_dir)
end
if ok and rock_manifest.lib then
ok, err = delete_deployed_file_tree(rock_manifest.lib, cfg.deploy_lib_dir)
end
if err then return nil, err end
fs.delete(path.install_dir(name, version))
if not get_installed_versions(name) then
fs.delete(dir.path(cfg.rocks_dir, name))
end
return true
end
return repos
| gpl-2.0 |
kaen/Zero-K | LuaUI/Widgets/chili_new/themes/theme.lua | 18 | 1465 | --//=============================================================================
--// Theme
theme = {}
theme.name = "default"
--//=============================================================================
--// Define default skins
local defaultSkin = "Carbon"
--local defaultSkin = "DarkGlass"
theme.skin = {
general = {
skinName = defaultSkin,
},
imagelistview = {
-- imageFolder = "luaui/images/folder.png",
-- imageFolderUp = "luaui/images/folder_up.png",
},
icons = {
-- imageplaceholder = "luaui/images/placeholder.png",
},
}
--//=============================================================================
--// Theme
function theme.GetDefaultSkin(class)
local skinName
repeat
skinName = theme.skin[class.classname].skinName
class = class.inherited
--FIXME check if the skin contains the current control class! if not use inherit the theme table before doing so in the skin
until ((skinName)and(SkinHandler.IsValidSkin(skinName)))or(not class);
if (not skinName)or(not SkinHandler.IsValidSkin(skinName)) then
skinName = theme.skin.general.skinName
end
if (not skinName)or(not SkinHandler.IsValidSkin(skinName)) then
skinName = "default"
end
return skinName
end
function theme.LoadThemeDefaults(control)
if (theme.skin[control.classname])
then table.merge(control,theme.skin[control.classname]) end -- per-class defaults
table.merge(control,theme.skin.general)
end
| gpl-2.0 |
geanux/darkstar | scripts/globals/items/porcupine_pie.lua | 35 | 1945 | -----------------------------------------
-- ID: 5156
-- Item: porcupine_pie
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP 55
-- Strength 6
-- Vitality 2
-- Intelligence -3
-- Mind 3
-- MP recovered while healing 2
-- Accuracy 5
-- Attack % 18 (cap 95)
-- Ranged Attack % 18 (cap 95)
-----------------------------------------
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,5156);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 55);
target:addMod(MOD_STR, 6);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_INT, -3);
target:addMod(MOD_MND, 3);
target:addMod(MOD_MPHEAL, 2);
target:addMod(MOD_ACC, 5);
target:addMod(MOD_FOOD_ATTP, 18);
target:addMod(MOD_FOOD_ATT_CAP, 95);
target:addMod(MOD_FOOD_RATTP, 18);
target:addMod(MOD_FOOD_RATT_CAP, 95);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 55);
target:delMod(MOD_STR, 6);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_INT, -3);
target:delMod(MOD_MND, 3);
target:delMod(MOD_MPHEAL, 2);
target:delMod(MOD_ACC, 5);
target:delMod(MOD_FOOD_ATTP, 18);
target:delMod(MOD_FOOD_ATT_CAP, 95);
target:delMod(MOD_FOOD_RATTP, 18);
target:delMod(MOD_FOOD_RATT_CAP, 95);
end;
| gpl-3.0 |
kaen/Zero-K | LuaUI/Widgets/gui_epicmenu.lua | 2 | 86017 | function widget:GetInfo()
return {
name = "EPIC Menu",
desc = "v1.438 Extremely Powerful Ingame Chili Menu.",
author = "CarRepairer",
date = "2009-06-02", --2014-05-3
license = "GNU GPL, v2 or later",
layer = -100001,
handler = true,
experimental = false,
enabled = true,
alwaysStart = true,
}
end
include("utility_two.lua") --contain file backup function
--CRUDE EXPLAINATION (third party comment) on how things work: (by Msafwan)
--1) first... a container called "OPTION" is shipped into epicMenuFactory from various sources (from widgets or epicmenu_conf.lua)
--Note: "OPTION" contain a smaller container called "OnChange" (which is the most important content).
--2) "OPTION" is then brought into epicMenuFactory\AddOption() which then attach a tracker which calls "SETTINGS" whenever "OnChange" is called.
--Note: "SETTINGS" is container which come and go from epicMenuFactory. Its destination is at CAWidgetFactory which save into "Zk_data.lua".
--4) "OPTION" are then brought into epicMenuFactory\MakeSubWindow() which then wrap the content(s) into regular buttons/checkboxes. This include the modified "OnChange"
--5) then Hotkey buttons is created in epicMenuFactory\MakeHotkeyedControl() and attached to regular buttons horizontally (thru 'StackPanel') which then sent back to epicMenuFactory\MakeSubWindow()
--6) then epicMenuFactory\MakeSubWindow() attaches all created button(s) to main "Windows" and finished the job. (now waiting for ChiliFactory to render them all).
--Note: hotkey button press is handled by Spring, but its registration & attachment with "OnChange" is handled by epicMenuFactory
--Note: all button rendering & clicking is handled by ChiliFactory (which receive button settings & call "OnChange" if button is pressed)
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if not WG.lang then
local lang
WG.lang=function(l)
if not l then
return lang
else
lang=l
end
end
end
local spGetConfigInt = Spring.GetConfigInt
local spSendCommands = Spring.SendCommands
local min = math.min
local max = math.max
local echo = Spring.Echo
--------------------------------------------------------------------------------
local isMission = Game.modDesc:find("Mission Mutator")
-- Config file data
local keybind_file, defaultkeybinds, defaultkeybind_date, confdata
do
--load config file:
local file = LUAUI_DIRNAME .. "Configs/epicmenu_conf.lua"
confdata = VFS.Include(file, nil, VFS.RAW_FIRST)
--assign keybind file:
keybind_file = LUAUI_DIRNAME .. 'Configs/' .. Game.modShortName:lower() .. '_keys.lua' --example: zk_keys.lua
if isMission then
--FIXME: find modname instead of using hardcoded mission_keybinds_file name
keybind_file = (confdata.mission_keybinds_file and LUAUI_DIRNAME .. 'Configs/' .. confdata.mission_keybinds_file) or keybind_file --example: singleplayer_keys.lua
end
--check for validity, backup or delete
CheckLUAFileAndBackup(keybind_file,'') --this utility create backup file in user's Spring folder OR delete them if they are not LUA content (such as corrupted or wrong syntax). included in "utility_two.lua"
--load default keybinds:
--FIXME: make it automatically use same name for mission, multiplayer, and default keybinding file
local default_keybind_file = LUAUI_DIRNAME .. 'Configs/' .. confdata.default_source_file
local file_return = VFS.FileExists(default_keybind_file, VFS.ZIP) and VFS.Include(default_keybind_file, nil, VFS.ZIP) or {keybinds={},date=0}
defaultkeybinds = file_return.keybinds
defaultkeybind_date = file_return.date
end
local epic_options = confdata.eopt
local color = confdata.color
local title_text = confdata.title
local title_image = confdata.title_image
local subMenuIcons = confdata.subMenuIcons
local useUiKeys = false
--file_return = nil
local custom_cmd_actions = select(9, include("Configs/integral_menu_commands.lua"))
--------------------------------------------------------------------------------
-- Chili control classes
local Chili
local Button
local Label
local Colorbars
local Checkbox
local Window
local Panel
local ScrollPanel
local StackPanel
local LayoutPanel
local Grid
local Trackbar
local TextBox
local Image
local Progressbar
local Colorbars
local screen0
--------------------------------------------------------------------------------
-- Global chili controls
local window_crude
local window_exit
local window_exit_confirm
local window_flags
local window_help
local window_getkey
local lbl_gtime, lbl_fps, lbl_clock, img_flag
local cmsettings_index = -1
local window_sub_cur
local filterUserInsertedTerm = "" --the term used to search the button list
local explodeSearchTerm = {text="", terms={}} -- store exploded "filterUserInsertedTerm" (brokendown into sub terms)
--------------------------------------------------------------------------------
-- Misc
local B_HEIGHT = 26
local B_WIDTH_TOMAINMENU = 80
local C_HEIGHT = 16
local scrH, scrW = 0,0
local cycle = 1
local curSubKey = ''
local curPath = ''
local init = false
local myCountry = 'wut'
local pathoptions = {}
local actionToOption = {}
local exitWindowVisible = false
--------------------------------------------------------------------------------
-- Key bindings
-- KEY BINDINGS AND YOU:
-- First, Epic Menu checks for a keybind bound to the action in LuaUI/Configs/zk_keys.lua.
-- If the local copy has a lower date value than the one in the mod,
-- it overwrites ALL conflicting keybinds in the local config.
-- Else it just adds any action-key pairs that are missing from the local config.
-- zk_keys.lua is written to at the end of loading LuaUI and on LuaUI shutdown.
-- Next, if it's a widget command, it checks if the widget specified a default keybind.
-- If so, it uses that command.
-- Lastly, it checks uikeys.txt (read-only).
include("keysym.h.lua")
local keysyms = {}
for k,v in pairs(KEYSYMS) do
keysyms['' .. v] = k
end
--[[
for k,v in pairs(KEYSYMS) do
keysyms['' .. k] = v
end
--]]
local get_key = false
local kb_path
local kb_action
local transkey = include("Configs/transkey.lua")
local wantToReapplyBinding = false
--------------------------------------------------------------------------------
-- Widget globals
WG.crude = {}
if not WG.Layout then
WG.Layout = {}
end
--------------------------------------------------------------------------------
-- Luaui config settings
local keybounditems = {}
local keybind_date = 0
local settings = {
versionmin = 50,
lang = 'en',
widgets = {},
show_crudemenu = true,
music_volume = 0.5,
showAdvanced = false,
}
----------------------------------------------------------------
-- Helper Functions
-- [[
local function to_string(data, indent)
local str = ""
if(indent == nil) then
indent = 0
end
local indenter = " "
-- Check the type
if(type(data) == "string") then
str = str .. (indenter):rep(indent) .. data .. "\n"
elseif(type(data) == "number") then
str = str .. (indenter):rep(indent) .. data .. "\n"
elseif(type(data) == "boolean") then
if(data == true) then
str = str .. "true"
else
str = str .. "false"
end
elseif(type(data) == "table") then
local i, v
for i, v in pairs(data) do
-- Check for a table in a table
if(type(v) == "table") then
str = str .. (indenter):rep(indent) .. i .. ":\n"
str = str .. to_string(v, indent + 2)
else
str = str .. (indenter):rep(indent) .. i .. ": " ..
to_string(v, 0)
end
end
elseif(type(data) == "function") then
str = str .. (indenter):rep(indent) .. 'function' .. "\n"
else
echo(1, "Error: unknown data type: %s", type(data))
end
return str
end
--]]
local function CapCase(str)
local str = str:lower()
str = str:gsub( '_', ' ' )
str = str:sub(1,1):upper() .. str:sub(2)
str = str:gsub( ' (.)',
function(x) return (' ' .. x):upper(); end
)
return str
end
local function explode(div,str)
if (div=='') then return false end
local pos,arr = 0,{}
-- for each divider found
for st,sp in function() return string.find(str,div,pos,true) end do
table.insert(arr,string.sub(str,pos,st-1)) -- Attach chars left of current divider
pos = sp + 1 -- Jump past current divider
end
table.insert(arr,string.sub(str,pos)) -- Attach chars right of last divider
return arr
end
local function GetIndex(t,v) local idx = 1; while (t[idx]<v)and(t[idx+1]) do idx=idx+1; end return idx end
local function CopyTable(tableToCopy, deep)
local copy = {}
for key, value in pairs(tableToCopy) do
if (deep and type(value) == "table") then
copy[key] = Spring.Utilities.CopyTable(value, true)
else
copy[key] = value
end
end
return copy
end
--[[
local function tableMerge(t1, t2, appendIndex)
for k,v in pairs(t2) do
if type(v) == "table" then
if type(t1[k] or false) == "table" then
tableMerge(t1[k] or {}, t2[k] or {}, appendIndex)
else
if type(k) == 'number' and appendIndex then
t1[#t1+1] = v
else
t1[k] = v
end
end
else
if type(k) == 'number' and appendIndex then
t1[#t1+1] = v
else
t1[k] = v
end
end
end
return t1
end
--]]
local function tableremove(table1, item)
local table2 = {}
for i=1, #table1 do
local v = table1[i]
if v ~= item then
table2[#table2+1] = v
end
end
return table2
end
-- function GetTimeString() taken from trepan's clock widget
local function GetTimeString()
local secs = math.floor(Spring.GetGameSeconds())
if (timeSecs ~= secs) then
timeSecs = secs
local h = math.floor(secs / 3600)
local m = math.floor((secs % 3600) / 60)
local s = math.floor(secs % 60)
if (h > 0) then
timeString = string.format('%02i:%02i:%02i', h, m, s)
else
timeString = string.format('%02i:%02i', m, s)
end
end
return timeString
end
local function BoolToInt(bool)
return bool and 1 or 0
end
local function IntToBool(int)
return int ~= 0
end
-- cool new framework for ordered table that has keys
local function otget(t,key)
for i=1,#t do
if not t[i] then
return
end
if t[i][1] == key then --key stored in index 1, while value at index 2
return t[i][2]
end
end
return nil
end
local function otset(t, key, val)
for i=1,#t do
if t[i][1] == key then --key stored in index 1, while value at index 2
if val == nil then
table.remove( t, i )
else
t[i][2] = val
end
return
end
end
if val ~= nil then
t[#t+1] = {key, val}
end
end
local function otvalidate(t)
for i=1,#t do
if not t[i] then
return false
end
end
return true
end
--end cool new framework
--------------------------------------------------------------------------------
WG.crude.SetSkin = function(Skin)
if Chili then
Chili.theme.skin.general.skinName = Skin
end
end
--Reset custom widget settings, defined in Initialize
WG.crude.ResetSettings = function() end
--Reset hotkeys, defined in Initialized
WG.crude.ResetKeys = function() end
--Get hotkey by actionname, defined in Initialize()
WG.crude.GetHotkey = function() end
WG.crude.GetHotkeys = function() end
--Set hotkey by actionname, defined in Initialize(). Is defined in Initialize() because trying to iterate pathoptions table here (at least if running epicmenu.lua in local copy) will return empty pathoptions table.
WG.crude.SetHotkey = function() end
--Callin often used for space+click shortcut, defined in Initialize(). Is defined in Initialize() because it help with testing epicmenu.lua in local copy
WG.crude.OpenPath = function() end
--Allow other widget to toggle-up/show Epic-Menu remotely, defined in Initialize()
WG.crude.ShowMenu = function() end --// allow other widget to toggle-up Epic-Menu which allow access to game settings' Menu via click on other GUI elements.
WG.crude.GetActionOption = function(actionName)
return actionToOption[actionName]
end
local function SaveKeybinds()
local keybindfile_table = { keybinds = keybounditems, date=keybind_date }
--table.save( keybindfile_table, keybind_file )
WG.SaveTable(keybindfile_table, keybind_file, nil, {concise = true, prefixReturn = true, endOfFile = true})
end
local function LoadKeybinds()
local loaded = false
if VFS.FileExists(keybind_file, VFS.RAW) then
local file_return = VFS.Include(keybind_file, nil, VFS.RAW)
if file_return then
keybounditems, keybind_date = file_return.keybinds, file_return.date
if keybounditems and keybind_date then
if not otvalidate(keybounditems) then
keybounditems = {}
end
loaded = true
keybind_date = keybind_date or defaultkeybind_date -- reverse compat
if not keybind_date or keybind_date == 0 or (keybind_date+0) < defaultkeybind_date then
-- forcibly assign default keybind to actions it finds
-- note that it won't do anything to keybinds if the action is not defined in default keybinds
-- to overwrite such keys, assign the action's keybind to "None"
keybind_date = defaultkeybind_date
for _,elem in ipairs(defaultkeybinds) do
local action = elem[1]
local keybind = elem[2]
otset( keybounditems, action, keybind)
end
else
for _, elem in ipairs(defaultkeybinds) do
local action = elem[1]
local keybind = elem[2]
otset( keybounditems, action, otget( keybounditems, action ) or keybind )
end
end
end
end
end
if not loaded then
keybounditems = CopyTable(defaultkeybinds, true)
keybind_date = defaultkeybind_date
end
if not otvalidate(keybounditems) then
keybounditems = {}
end
end
----------------------------------------------------------------
--May not be needed with new chili functionality
local function AdjustWindow(window)
local nx
if (0 > window.x) then
nx = 0
elseif (window.x + window.width > screen0.width) then
nx = screen0.width - window.width
end
local ny
if (0 > window.y) then
ny = 0
elseif (window.y + window.height > screen0.height) then
ny = screen0.height - window.height
end
if (nx or ny) then
window:SetPos(nx,ny)
end
end
-- Adding functions because of "handler=true"
local function AddAction(cmd, func, data, types)
return widgetHandler.actionHandler:AddAction(widget, cmd, func, data, types)
end
local function RemoveAction(cmd, types)
return widgetHandler.actionHandler:RemoveAction(widget, cmd, types)
end
local function GetFullKey(path, option)
--local curkey = path .. '_' .. option.key
local fullkey = ('epic_'.. option.wname .. '_' .. option.key)
fullkey = fullkey:gsub(' ', '_')
return fullkey
end
local function GetActionName(path, option)
local fullkey = GetFullKey(path, option):lower()
return option.action or fullkey
end
WG.crude.GetActionName = GetActionName
WG.crude.GetOptionHotkey = function(path, option)
return WG.crude.GetHotkey(GetActionName(path,option))
end
-- returns whether widget is enabled
local function WidgetEnabled(wname)
local order = widgetHandler.orderList[wname]
return order and (order > 0)
end
-- by default it allows if player is not spectating and there are no other players
local function AllowPauseOnMenuChange()
if Spring.GetSpectatingState() then
return false
end
if settings.config['epic_Settings/Misc_Menu_pauses_in_SP'] == false then
return false
end
local playerlist = Spring.GetPlayerList() or {}
local myPlayerID = Spring.GetMyPlayerID()
for i=1, #playerlist do
local playerID = playerlist[i]
if myPlayerID ~= playerID then
local _,active,spectator = Spring.GetPlayerInfo(playerID)
if active and not spectator then
return false
end
end
end
return true
end
local function PlayingButNoTeammate() --I am playing and playing alone with no teammate
if Spring.GetSpectatingState() then
return false
end
local myAllyTeamID = Spring.GetMyAllyTeamID() -- get my alliance ID
local teams = Spring.GetTeamList(myAllyTeamID) -- get list of teams in my alliance
if #teams == 1 then -- if I'm alone and playing (no ally)
return true
end
return false
end
-- Kill submenu window
local function KillSubWindow(makingNew)
if window_sub_cur then
settings.sub_pos_x = window_sub_cur.x
settings.sub_pos_y = window_sub_cur.y
window_sub_cur:Dispose()
window_sub_cur = nil
curPath = ''
if not makingNew and AllowPauseOnMenuChange() then
local paused = select(3, Spring.GetGameSpeed())
if paused then
spSendCommands("pause")
end
end
end
end
-- Update colors for labels of widget checkboxes in widgetlist window
local function checkWidget(widget)
if WG.cws_checkWidget then
WG.cws_checkWidget(widget)
end
end
VFS.Include("LuaUI/Utilities/json.lua");
local function UTF8SupportCheck()
local version=Game.version
local first_dot=string.find(version,"%.")
local major_version = (first_dot and string.sub(version,0,first_dot-1)) or version
local major_version_number = tonumber(major_version)
return major_version_number>=98
end
local UTF8SUPPORT = UTF8SupportCheck()
local function SetLangFontConf()
if UTF8SUPPORT and VFS.FileExists("Luaui/Configs/nonlatin/"..WG.lang()..".json", VFS.ZIP) then
WG.langData = Spring.Utilities.json.decode(VFS.LoadFile("Luaui/Configs/nonlatin/"..WG.lang()..".json", VFS.ZIP))
WG.langFont = nil
WG.langFontConf = nil
else
WG.langData = nil
WG.langFont = nil
WG.langFontConf = nil
end
end
local function SetCountry(self)
echo('Setting country: "' .. self.country .. '" ')
WG.country = self.country
settings.country = self.country
if WG.lang then
WG.lang(self.countryLang)
end
SetLangFontConf()
settings.lang = self.countryLang
if img_flag then
img_flag.file = ":cn:".. LUAUI_DIRNAME .. "Images/flags/".. settings.country ..'.png'
img_flag:Invalidate()
end
end
--Make country chooser window
local function MakeFlags()
if window_flags then return end
local countries = {}
local flagdir = 'LuaUI/Images/flags/'
local files = VFS.DirList(flagdir)
for i=1,#files do
local file = files[i]
local country = file:sub( #flagdir+1, -5 )
countries[#countries+1] = country
end
local country_langs = {
br='bp',
de='de',
es='es',
fi='fi',
fr='fr',
it='it',
my='my',
pl='pl',
pt='pt',
pr='es',
ru='ru',
}
local flagChildren = {}
flagChildren[#flagChildren + 1] = Label:New{ caption='Flag', align='center' }
flagChildren[#flagChildren + 1] = Button:New{
name = 'flagButton';
caption = 'Auto',
country = myCountry,
countryLang = country_langs[myCountry] or 'en',
width='50%',
textColor = color.sub_button_fg,
backgroundColor = color.sub_button_bg,
OnClick = { SetCountry }
}
local flagCount = 0
for i=1, #countries do
local country = countries[i]
local countryLang = country_langs[country] or 'en'
flagCount = flagCount + 1
flagChildren[#flagChildren + 1] = Image:New{ file=":cn:".. LUAUI_DIRNAME .. "Images/flags/".. country ..'.png', }
flagChildren[#flagChildren + 1] = Button:New{ caption = country:upper(),
name = 'countryButton' .. country;
width='50%',
textColor = color.sub_button_fg,
backgroundColor = color.sub_button_bg,
country = country,
countryLang = countryLang,
OnClick = { SetCountry }
}
end
local window_height = 300
local window_width = 170
window_flags = Window:New{
caption = 'Choose Your Location...',
x = settings.sub_pos_x,
y = settings.sub_pos_y,
clientWidth = window_width,
clientHeight = window_height,
maxWidth = 200,
parent = screen0,
backgroundColor = color.sub_bg,
children = {
ScrollPanel:New{
x=0,y=15,
right=5,bottom=0+B_HEIGHT,
children = {
Grid:New{
columns=2,
x=0,y=0,
width='100%',
height=#flagChildren/2*B_HEIGHT*1,
children = flagChildren,
}
}
},
--close button
Button:New{ caption = 'Close', x=10, y=0-B_HEIGHT, bottom=5, right=5,
name = 'makeFlagCloseButton';
OnClick = { function(self) window_flags:Dispose(); window_flags = nil; end },
width=window_width-20, backgroundColor = color.sub_close_bg, textColor = color.sub_close_fg,
},
}
}
end
--Make help text window
local function MakeHelp(caption, text)
local window_height = 400
local window_width = 400
window_help = Window:New{
caption = caption or 'Help?',
x = settings.sub_pos_x,
y = settings.sub_pos_y,
clientWidth = window_width,
clientHeight = window_height,
parent = screen0,
backgroundColor = color.sub_bg,
children = {
ScrollPanel:New{
x=0,y=15,
right=5,
bottom=B_HEIGHT,
height = window_height - B_HEIGHT*3 ,
children = {
TextBox:New{ x=0,y=10, text = text, textColor = color.sub_fg, width = window_width - 40, }
}
},
--Close button
Button:New{ caption = 'Close', OnClick = { function(self) self.parent:Dispose() end }, x=10, bottom=1, right=50, height=B_HEIGHT,
name = 'makeHelpCloseButton';
backgroundColor = color.sub_close_bg, textColor = color.sub_close_fg, },
}
}
end
local function MakeSubWindow(key)
end
local function GetReadableHotkeyMod(mod)
local modlowercase = mod:lower()
return (modlowercase:find('a%+') and 'Alt+' or '') ..
(modlowercase:find('c%+') and 'Ctrl+' or '') ..
(modlowercase:find('m%+') and 'Meta+' or '') ..
(modlowercase:find('s%+') and 'Shift+' or '') ..
''
end
local function HotKeyBreakdown(hotkey) --convert hotkey string into a standardized hotkey string
hotkey = hotkey:gsub('numpad%+', 'numpadplus')
local hotkey_table = explode('+', hotkey)
local alt, ctrl, meta, shift
for i=1, #hotkey_table-1 do
local str2 = hotkey_table[i]:lower()
if str2 == 'a' or str2 == 'alt' then alt = true
elseif str2 == 'c' or str2 == 'ctrl' then ctrl = true
elseif str2 == 's' or str2 == 'shift' then shift = true
elseif str2 == 'm' or str2 == 'meta' then meta = true
end
end
local mod = '' ..
(alt and 'A+' or '') ..
(ctrl and 'C+' or '') ..
(meta and 'M+' or '') ..
(shift and 'S+' or '')
local key = hotkey_table[#hotkey_table]
key = key:gsub( 'numpadplus', 'numpad+')
return mod, key
end
local function GetReadableHotkey(hotkey)
local mod, key = HotKeyBreakdown(hotkey)
return GetReadableHotkeyMod(mod) .. CapCase(key)
end
local function GetActionHotkeys(action)
return Spring.GetActionHotKeys(action)
end
local function GetActionHotkey(action)
local actionHotkeys = Spring.GetActionHotKeys(action)
if actionHotkeys and actionHotkeys[1] then
return (actionHotkeys[1])
end
return nil
end
local function AssignKeyBindAction(hotkey, actionName, verbose)
if verbose then
--local actions = Spring.GetKeyBindings(hotkey.mod .. hotkey.key)
local actions = Spring.GetKeyBindings(hotkey)
if (actions and #actions > 0) then
echo( 'Warning: There are other actions bound to this hotkey combo (' .. GetReadableHotkey(hotkey) .. '):' )
for i=1, #actions do
for actionCmd, actionExtra in pairs(actions[i]) do
echo (' - ' .. actionCmd .. ' ' .. actionExtra)
end
end
end
echo( 'Hotkey (' .. GetReadableHotkey(hotkey) .. ') bound to action: ' .. actionName )
end
--actionName = actionName:lower()
if type(hotkey) == 'string' then
--otset( keybounditems, actionName, hotkey )
--echo("bind " .. hotkey .. " " .. actionName)
spSendCommands("bind " .. hotkey .. " " .. actionName)
local buildCommand = actionName:find('buildunit_')
local isUnitCommand
local isUnitStateCommand
local isUnitInstantCommand
if custom_cmd_actions[actionName] then
local number = custom_cmd_actions[actionName]
isUnitCommand = number == 1
isUnitStateCommand = number == 2
isUnitInstantCommand = number == 3
end
if custom_cmd_actions[actionName] or buildCommand then
-- bind shift+hotkey as well if needed for unit commands
local alreadyShift = hotkey:lower():find("s%+") or hotkey:lower():find("shift%+")
if not alreadyShift then
if isUnitCommand or buildCommand then
spSendCommands("bind S+" .. hotkey .. " " .. actionName)
elseif isUnitStateCommand or isUnitInstantCommand then
spSendCommands("bind S+" .. hotkey .. " " .. actionName .. " queued")
end
end
end
end
end
--create spring action for this option. Note: this is used by AddOption()
local function CreateOptionAction(path, option)
local kbfunc = option.OnChange
if option.type == 'bool' then
kbfunc = function()
local wname = option.wname
-- [[ Note: following code between -- [[ and --]] is just to catch an exception. Is not part of code's logic.
if not pathoptions[path] or not otget( pathoptions[path], wname..option.key ) then
Spring.Echo("Warning, detected keybind mishap. Please report this info and help us fix it:")
Spring.Echo("Option path is "..path)
Spring.Echo("Option name is "..option.wname..option.key)
if pathoptions[path] then --pathoptions[path] table still intact, but option table missing
Spring.Echo("case: option table was missing")
otset( pathoptions[path], option.wname..option.key, option ) --re-add option table
else --both option table & pathoptions[path] was missing, probably was never initialized
Spring.Echo("case: whole path was never initialized")
pathoptions[path] = {}
otset( pathoptions[path], option.wname..option.key, option )
end
-- [f=0088425] Error: LuaUI::RunCallIn: error = 2, ConfigureLayout, [string "LuaUI/Widgets/gui_epicmenu.lua"]:583: attempt to index field '?' (a nil value)
end
--]]
local pathoption = otget( pathoptions[path], wname..option.key )
newval = not pathoption.value
pathoption.value = newval
otset( pathoptions[path], wname..option.key, pathoption )
option.OnChange({checked=newval})
if path == curPath then
MakeSubWindow(path, false)
end
end
end
local actionName = GetActionName(path, option)
AddAction(actionName, kbfunc, nil, "t")
actionToOption[actionName] = option
if option.hotkey then
local existingRegister = otget( keybounditems, actionName) --check whether existing actionname is already bound with a custom hotkey in zkkey
if existingRegister == nil then
Spring.Echo("Epicmenu: " .. option.hotkey .. " (" .. option.key .. ", " .. option.wname..")") --tell user (in infolog.txt) that a widget is adding hotkey
otset(keybounditems, actionName, option.hotkey ) --save new hotkey if no existing key found (not yet applied. Will be applied in IntegrateWidget())
end
end
end
--remove spring action for this option
local function RemoveOptionAction(path, option)
local actionName = GetActionName(path, option)
RemoveAction(actionName)
end
-- Unassign a keybinding from settings and other tables that keep track of related info
local function UnassignKeyBind(actionName, verbose)
local actionHotkeys = GetActionHotkeys(actionName)
if actionHotkeys then
for _,actionHotkey in ipairs(actionHotkeys) do
--[[
unbind and unbindaction don't work on a command+params, only on the command itself
--]]
local actionName_split = explode(' ', actionName)
local actionName_cmd = actionName_split[1]
--echo("unbind " .. actionHotkey .. ' ' .. actionName_cmd:lower())
spSendCommands("unbind " .. actionHotkey .. ' ' .. actionName_cmd:lower()) -- must be lowercase when calling unbind
--spSendCommands("unbindaction " .. actionName ) --don't do this, unbinding one select would unbind all.
if verbose then
echo( 'Unbound hotkeys from action: ' .. actionName )
end
end
end
--otset( keybounditems, actionName, nil )
end
--unassign and reassign keybinds
local function ReApplyKeybinds()
--[[
To migrate from uikeys:
Find/Replace:
bind\s*(\S*)\s*(.*)
{ "\2", "\1" },
]]
--echo 'ReApplyKeybinds'
if useUiKeys then
return
end
for _,elem in ipairs(keybounditems) do
local actionName = elem[1]
local hotkey = elem[2]
--actionName = actionName:lower()
UnassignKeyBind(actionName, false)
local hotkeyTable = type(hotkey) == 'table' and hotkey or {hotkey}
for _,hotkey2 in ipairs(hotkeyTable) do
if hotkey2 ~= 'None' then
AssignKeyBindAction(hotkey2, actionName, false)
end
end
--echo("unbindaction(1) ", actionName)
--echo("bind(1) ", hotkey, actionName)
end
end
local function AddOption(path, option, wname ) --Note: this is used when loading widgets and in Initialize()
--echo(path, wname, option)
if not wname then
wname = path
end
local path2 = path
if not option then
if not pathoptions[path] then
pathoptions[path] = {}
end
-- must be before path var is changed
local icon = subMenuIcons[path]
local pathexploded = explode('/',path)
local pathend = pathexploded[#pathexploded]
pathexploded[#pathexploded] = nil
path = table.concat(pathexploded, '/')--Example = if path2 is "Game", then current path became ""
option = {
type='button',
name=pathend .. '...',
icon = icon,
OnChange = function(self)
MakeSubWindow(path2, false) --this made this button open another menu
end,
desc=path2,
isDirectoryButton = true,
}
if path == '' and path2 == '' then --prevent adding '...' button on '' (Main Menu)
return
end
end
if not pathoptions[path] then
AddOption( path )
end
if not option.key then
option.key = option.name
end
option.wname = wname
local curkey = path .. '_' .. option.key
--local fullkey = ('epic_'.. curkey)
local fullkey = GetFullKey(path, option)
fullkey = fullkey:gsub(' ', '_')
--get spring config setting
local valuechanged = false
local newval
if option.springsetting ~= nil then --nil check as it can be false but maybe not if springconfig only assumes numbers
newval = Spring.GetConfigInt( option.springsetting, 0 )
if option.type == 'bool' then
newval = IntToBool(newval)
end
else
--load option from widget settings (LuaUI/Config/ZK_data.lua).
--Read/write is handled by widgethandler; see widget:SetConfigData and widget:GetConfigData
if settings.config[fullkey] ~= nil then --nil check as it can be false
newval = settings.config[fullkey]
end
end
if option.type ~= 'button' and option.type ~= 'label' and option.default == nil then
if option.value ~= nil then
option.default = option.value
else
option.default = newval
end
end
if newval ~= nil and option.value ~= newval then --must nilcheck newval
valuechanged = true
option.value = newval
end
local origOnChange = option.OnChange
local controlfunc = function() end
if option.type == 'button' and (option.action) and (not option.noAutoControlFunc) then
controlfunc =
function(self)
spSendCommands{option.action}
end
elseif option.type == 'bool' then
controlfunc =
function(self)
if self then
option.value = self.checked
end
if option.springsetting then --if widget supplies option for springsettings
Spring.SetConfigInt( option.springsetting, BoolToInt(option.value) )
end
settings.config[fullkey] = option.value
end
elseif option.type == 'number' then
if option.valuelist then
option.min = 1
option.max = #(option.valuelist)
option.step = 1
end
--option.desc_orig = option.desc or ''
controlfunc =
function(self)
if self then
if option.valuelist then
option.value = option.valuelist[self.value]
else
option.value = self.value
end
--self.tooltip = option.desc_orig .. ' - Current: ' .. option.value
end
if option.springsetting then
if not option.value then
echo ('<EPIC Menu> Error #444', fullkey)
else
Spring.SetConfigInt( option.springsetting, option.value )
end
end
settings.config[fullkey] = option.value
end
elseif option.type == 'colors' then
controlfunc =
function(self)
if self then
option.value = self.color
end
settings.config[fullkey] = option.value
end
elseif option.type == 'list' then
controlfunc =
function(item)
option.value = item.value
settings.config[fullkey] = option.value
end
elseif option.type == 'radioButton' then
controlfunc =
function(item)
option.value = item.value
settings.config[fullkey] = option.value
if (path == curPath) or filterUserInsertedTerm~='' then --we need to refresh the window to show changes, and current path is irrelevant if we are doing search
MakeSubWindow(curPath, false) --remake window to update the buttons' visuals when pressed
end
end
end
origOnChange = origOnChange or function() end
option.OnChange = function(self)
controlfunc(self) --note: 'self' in this context will be refer to the button/checkbox/slider state provided by Chili UI
origOnChange(option)
end
--call onchange once
if valuechanged and option.type ~= 'button' and (origOnChange ~= nil)
--and not option.springsetting --need a different solution
then
origOnChange(option)
end
--Keybindings
if (option.type == 'button' and not option.isDirectoryButton) or option.type == 'bool' then
if (not option.dontRegisterAction) then
local actionName = GetActionName(path, option)
--migrate from old logic, make sure this is done before setting orig_key
if option.hotkey and type(option.hotkey) == 'table' then
option.hotkey = option.hotkey.mod .. option.hotkey.key --change hotkey table into string
end
if option.hotkey then
local orig_hotkey = ''
orig_hotkey = option.hotkey
option.orig_hotkey = orig_hotkey
end
CreateOptionAction(path, option)
end
--Keybinds for radiobuttons
elseif option.type == 'radioButton' then --if its a list of checkboxes:
for i=1, #option.items do --prepare keybinds for each of radioButton's checkbox
local item = option.items[i] --note: referring by memory
item.wname = wname.."radioButton" -- unique wname for Hotkey
item.value = option.items[i].key --value of this item is this item's key
item.OnChange = function() option.OnChange(item) end --OnChange() is an 'option.OnChange()' that feed on an input of 'item'(instead of 'self'). So that it always execute the 'value' of 'item' regardless of current 'value' of 'option'
local actionName = GetActionName(path, item)
if item.hotkey then
local orig_hotkey = ''
orig_hotkey = item.hotkey
item.orig_hotkey = orig_hotkey
end
CreateOptionAction(path,item)
end
end
otset( pathoptions[path], wname..option.key, option )--is used for remake epicMenu's button(s)
end
local function RemOption(path, option, wname )
if not pathoptions[path] then
--this occurs when a widget unloads itself inside :init
--echo ('<epic menu> error #333 ', wname, path)
--echo ('<epic menu> ...error #333 ', (option and option.key) )
return
end
RemoveOptionAction(path, option)
otset( pathoptions[path], wname..option.key, nil )
end
-- sets key and wname for each option so that GetOptionHotkey can work before widget initialization completes
local function PreIntegrateWidget(w)
local options = w.options
if type(options) ~= 'table' then
return
end
local wname = w.whInfo.name
local defaultpath = w.options_path or ('Settings/Misc/' .. wname)
if w.options.order then
echo ("<EPIC Menu> " .. wname .. ", don't index an option with the word 'order' please, it's too soon and I'm not ready.")
w.options.order = nil
end
--Generate order table if it doesn't exist
if not w.options_order then
w.options_order = {}
for k,v in pairs(options) do
w.options_order[#(w.options_order) + 1] = k
end
end
for i=1, #w.options_order do
local k = w.options_order[i]
local option = options[k]
if not option then
Spring.Log(widget:GetInfo().name, LOG.ERROR, '<EPIC Menu> Error in loading custom widget settings in ' .. wname .. ', order table incorrect.' )
return
end
option.key = k
option.wname = wname
end
end
--(Un)Store custom widget settings for a widget
local function IntegrateWidget(w, addoptions, index)
local options = w.options
if type(options) ~= 'table' then
return
end
local wname = w.whInfo.name
local defaultpath = w.options_path or ('Settings/Misc/' .. wname)
--[[
--If a widget disables itself in widget:Initialize it will run the removewidget before the insertwidget is complete. this fix doesn't work
if not WidgetEnabled(wname) then
return
end
--]]
if w.options.order then
echo ("<EPIC Menu> " .. wname .. ", don't index an option with the word 'order' please, it's too soon and I'm not ready.")
w.options.order = nil
end
--Generate order table if it doesn't exist
if not w.options_order then
w.options_order = {}
for k,v in pairs(options) do
w.options_order[#(w.options_order) + 1] = k
end
end
for i=1, #w.options_order do
local k = w.options_order[i]
local option = options[k]
if not option then
Spring.Log(widget:GetInfo().name, LOG.ERROR, '<EPIC Menu> Error in loading custom widget settings in ' .. wname .. ', order table incorrect.' )
return
end
--Add empty onchange function if doesn't exist
if not option.OnChange or type(option.OnChange) ~= 'function' then
w.options[k].OnChange = function(self) end
end
--store default
w.options[k].default = w.options[k].value
option.key = k
option.wname = wname
local origOnChange = w.options[k].OnChange
if option.type ~= 'button' then
option.OnChange =
function(self)
if self then
w.options[k].value = self.value
end
origOnChange(self)
end
else
option.OnChange = origOnChange
end
local path = option.path or defaultpath
-- [[
local value = w.options[k].value
w.options[k].value = nil
w.options[k].priv_value = value
--setmetatable( w.options[k], temp )
--local temp = w.options[k]
--w.options[k] = {}
w.options[k].__index = function(t, key)
if key == 'value' then
--[[
if( not wname:find('Chili Chat') ) then
echo ('get val', wname, k, key, t.priv_value)
end
--]]
--return t.priv_value
return t.priv_value
end
end
w.options[k].__newindex = function(t, key, val)
-- For some reason this is called twice per click with the same parameters for most options
-- a few rare options have val = nil for their second call which resets the option.
if key == 'value' then
if val ~= nil then -- maybe this isn't needed
--echo ('set val', wname, k, key, val)
t.priv_value = val
local fullkey = GetFullKey(path, option)
fullkey = fullkey:gsub(' ', '_')
settings.config[fullkey] = option.value
end
else
rawset(t,key,val)
end
end
setmetatable( w.options[k], w.options[k] )
--]]
if addoptions then
AddOption(path, option, wname )
else
RemOption(path, option, wname )
end
end
if window_sub_cur then
MakeSubWindow(curPath, false)
end
wantToReapplyBinding = true --request ReApplyKeybind() in widget:Update(). IntegrateWidget() will be called many time during LUA loading but ReApplyKeybind() will be done only once in widget:Update()
end
--Store custom widget settings for all active widgets
local function AddAllCustSettings()
local cust_tree = {}
for i=1,#widgetHandler.widgets do
IntegrateWidget(widgetHandler.widgets[i], true, i)
end
end
local function RemakeEpicMenu()
end
-- Spring's widget list
local function ShowWidgetList(self)
spSendCommands{"luaui selector"}
end
-- Crudemenu's widget list
WG.crude.ShowWidgetList2 = function(self)
MakeWidgetList()
end
WG.crude.ShowFlags = function()
MakeFlags()
end
--Make little window to indicate user needs to hit a keycombo to save a keybinding
local function MakeKeybindWindow( path, option, hotkey )
local window_height = 80
local window_width = 300
get_key = true
kb_path = path
kb_action = GetActionName(path, option)
UnassignKeyBind(kb_action, true) -- 2nd param = verbose
--otset( keybounditems, kb_action, nil )
otset( keybounditems, kb_action, 'None' )
window_getkey = Window:New{
caption = 'Set a HotKey',
x = (scrW-window_width)/2,
y = (scrH-window_height)/2,
clientWidth = window_width,
clientHeight = window_height,
parent = screen0,
backgroundColor = color.sub_bg,
resizable=false,
draggable=false,
children = {
Label:New{ y=10, caption = 'Press a key combo', textColor = color.sub_fg, },
Label:New{ y=30, caption = '(Hit "Escape" to clear keybinding)', textColor = color.sub_fg, },
}
}
end
--Get hotkey action and readable hotkey string. Note: this is used in MakeHotkeyedControl() which make hotkey handled by Chili.
local function GetHotkeyData(path, option)
local actionName = GetActionName(path, option)
local hotkey = otget( keybounditems, actionName )
if type(hotkey) == 'table' then
hotkey = hotkey[1]
end
if hotkey and hotkey ~= 'None' then --if ZKkey contain definitive hotkey: return zkkey's hotkey
if hotkey:find('%+%+') then
hotkey = hotkey:gsub( '%+%+', '+plus' )
end
return GetReadableHotkey(hotkey)
end
if (not hotkey ) and option.hotkey then --if widget supplied default hotkey: return widget's hotkey (this only effect hotkey on Chili menu)
return option.hotkey
end
return 'None' --show "none" on epicmenu's menu
end
--Make a stack with control and its hotkey button
local function MakeHotkeyedControl(control, path, option, icon, noHotkey)
local children = {}
if noHotkey then
control.x = 0
if icon then
control.x = 20
end
control.right = 2
control:DetectRelativeBounds()
if icon then
local iconImage = Image:New{ file= icon, width = 16,height = 16, }
children = { iconImage, }
end
children[#children+1] = control
else
local hotkeystring = GetHotkeyData(path, option)
local kbfunc = function()
if not get_key then
MakeKeybindWindow( path, option )
end
end
local hklength = math.max( hotkeystring:len() * 10, 20)
local control2 = control
control.x = 0
if icon then
control.x = 20
end
control.right = hklength+2 --room for hotkey button on right side
control:DetectRelativeBounds()
local hkbutton = Button:New{
name = option.wname .. ' hotKeyButton';
minHeight = 30,
right=0,
width = hklength,
caption = hotkeystring,
OnClick = { kbfunc },
backgroundColor = color.sub_button_bg,
textColor = color.sub_button_fg,
tooltip = 'Hotkey: ' .. hotkeystring,
}
--local children = {}
if icon then
local iconImage = Image:New{ file= icon, width = 16,height = 16, }
children = { iconImage, }
end
children[#children+1] = control
children[#children+1] = hkbutton
end
return Panel:New{
width = "100%",
orientation='horizontal',
resizeItems = false,
centerItems = false,
autosize = true,
backgroundColor = {0, 0, 0, 0},
itemMargin = {0,0,0,0},
margin = {0,0,0,0},
itemPadding = {0,0,0,0},
padding = {0,0,0,0},
children=children,
}
end
local function ResetWinSettings(path)
for _,elem in ipairs(pathoptions[path]) do
local option = elem[2]
if not ({button=1, label=1, menu=1})[option.type] then
if option.default ~= nil then --fixme : need default
if option.type == 'bool' or option.type == 'number' then
option.value = option.valuelist and GetIndex(option.valuelist, option.default) or option.default
option.checked = option.value
option.OnChange(option)
elseif option.type == 'list' or option.type == 'radioButton' then
option.value = option.default
option.OnChange(option)
elseif option.type == 'colors' then
option.color = option.default
option.OnChange(option)
end
else
Spring.Log(widget:GetInfo().name, LOG.ERROR, '<EPIC Menu> Error #627', option.name, option.type)
end
end
end
end
--[[ WIP
WG.crude.MakeHotkey = function(path, optionkey)
local option = pathoptions[path][optionkey]
local hotkey, hotkeystring = GetHotkeyData(path, option)
if not get_key then
MakeKeybindWindow( path, option, hotkey )
end
end
--]]
local function SearchElement(termToSearch,path)
local filtered_pathOptions = {}
local tree_children = {} --used for displaying buttons
local maximumResult = 23 --maximum result to display. Any more it will just say "too many"
local DiggDeeper = function() end --must declare itself first before callin self within self
DiggDeeper = function(currentPath)
local virtualCategoryHit = false --category deduced from the text label preceding the option(s)
for _,elem in ipairs(pathoptions[currentPath]) do
local option = elem[2]
local lowercase_name = option.name:lower()
local lowercase_text = option.text and option.text:lower() or ''
local lowercase_desc = option.desc and option.desc:lower() or ''
local found_name = SearchInText(lowercase_name,termToSearch) or SearchInText(lowercase_text,termToSearch) or SearchInText(lowercase_desc,termToSearch) or virtualCategoryHit
--if option.advanced and not settings.config['epic_Settings_Show_Advanced_Settings'] then
if option.advanced and not settings.showAdvanced then
--do nothing
elseif option.type == 'button' then
local hide = false
if option.desc and option.desc:find(currentPath) and option.name:find("...") then --this type of button is defined in AddOption(path,option,wname) (a link into submenu)
local menupath = option.desc
if pathoptions[menupath] then
if #pathoptions[menupath] >= 1 then
DiggDeeper(menupath) --travel into & search into this branch
else --dead end
hide = true
end
end
end
if not hide then
local hotkeystring = GetHotkeyData(currentPath, option)
local lowercase_hotkey = hotkeystring:lower()
if found_name or lowercase_hotkey:find(termToSearch) then
filtered_pathOptions[#filtered_pathOptions+1] = {currentPath,option}--remember this option and where it is found
end
end
elseif option.type == 'label' then
local virtualCategory = option.value or option.name
virtualCategory = virtualCategory:lower()
virtualCategoryHit = SearchInText(virtualCategory,termToSearch)
if virtualCategoryHit then
filtered_pathOptions[#filtered_pathOptions+1] = {currentPath,option}
end
elseif option.type == 'text' then
if found_name then
filtered_pathOptions[#filtered_pathOptions+1] = {currentPath,option}
end
elseif option.type == 'bool' then
local hotkeystring = GetHotkeyData(currentPath, option)
local lowercase_hotkey = hotkeystring:lower()
if found_name or lowercase_hotkey:find(termToSearch) then
filtered_pathOptions[#filtered_pathOptions+1] = {currentPath,option}
end
elseif option.type == 'number' then
if found_name then
filtered_pathOptions[#filtered_pathOptions+1] = {currentPath,option}
end
elseif option.type == 'list' then
if found_name then
filtered_pathOptions[#filtered_pathOptions+1] = {currentPath,option}
else
for i=1, #option.items do
local item = option.items[i]
lowercase_name = item.name:lower()
lowercase_desc = item.desc and item.desc:lower() or ''
local found = SearchInText(lowercase_name,termToSearch) or SearchInText(lowercase_desc,termToSearch)
if found then
filtered_pathOptions[#filtered_pathOptions+1] = {currentPath,option}
break;
end
end
end
elseif option.type == 'radioButton' then
if found_name then
filtered_pathOptions[#filtered_pathOptions+1] = {currentPath,option}
else
for i=1, #option.items do
local item = option.items[i]
lowercase_name = item.name and item.name:lower() or ''
lowercase_desc = item.desc and item.desc:lower() or ''
local hotkeystring = GetHotkeyData(currentPath, item)
local lowercase_hotkey = hotkeystring:lower()
local found = SearchInText(lowercase_name,termToSearch) or SearchInText(lowercase_desc,termToSearch) or lowercase_hotkey:find(termToSearch)
if found then
filtered_pathOptions[#filtered_pathOptions+1] = {currentPath,option}
break
end
end
end
elseif option.type == 'colors' then
if found_name then
filtered_pathOptions[#filtered_pathOptions+1] = {currentPath,option}
end
end
end
end
DiggDeeper(path)
local roughNumberOfHit = #filtered_pathOptions
if roughNumberOfHit == 0 then
tree_children[1] = Label:New{ caption = "- no match for \"" .. filterUserInsertedTerm .."\" -", textColor = color.sub_header, textColor = color.postit, }
elseif roughNumberOfHit > maximumResult then
tree_children[1] = Label:New{ caption = "- the term \"" .. filterUserInsertedTerm .."\" had too many match -", textColor = color.postit,}
tree_children[2] = Label:New{ caption = "- please navigate the menu to see all options -", textColor = color.postit, }
tree_children[3] = Label:New{ caption = "- (" .. roughNumberOfHit .. " match in total) -", textColor = color.postit, }
filtered_pathOptions = {}
end
return filtered_pathOptions,tree_children
end
-- Make submenu window based on index from flat window list
MakeSubWindow = function(path, pause)
if pause == nil then
pause = true
end
if not pathoptions[path] then
return
end
local explodedpath = explode('/', path)
explodedpath[#explodedpath] = nil
local parent_path = table.concat(explodedpath,'/')
local settings_height = #(pathoptions[path]) * B_HEIGHT
local settings_width = 270
local tree_children = {}
local hotkeybuttons = {}
local root = path == ''
local searchedElement
if filterUserInsertedTerm ~= "" then --this check whether window is a remake for Searching or not.
--if Search term is being used then remake the Search window instead of normal window
parent_path = path --User go "back" (back button) to HERE if we go "back" after searching
searchedElement,tree_children = SearchElement(filterUserInsertedTerm,path)
end
local listOfElements = searchedElement or pathoptions[path] --show search result or show all
local pathLabeling = searchedElement and ""
for _,elem in ipairs(listOfElements) do
local option = elem[2]
local currentPath
if pathLabeling then
currentPath = elem[1] --note: during search mode the first entry in "listOfElements[index]" table will contain search result's path, in normal mode the first entry in "pathoptions[path]" table will contain indexes.
if pathLabeling ~= currentPath then --add label which shows where this option is found
local sub_path = currentPath:gsub(path,"") --remove root
-- tree_children[#tree_children+1] = Label:New{ caption = "- Location: " .. sub_path, textColor = color.tooltip_bg, }
tree_children[#tree_children+1] = Button:New{
name = sub_path .. #tree_children; --note: name must not be same as existing button or crash.
x=0,
width = settings_width,
minHeight = 20,
fontsize = 11,
caption = "- Location: " .. currentPath,
OnClick = {function() filterUserInsertedTerm = ''; end,function(self)
MakeSubWindow(currentPath, false) --this made this "label" open another path when clicked
end,},
backgroundColor = color.transGray,
textColor = color.postit,
tooltip = currentPath,
padding={2,2,2,2},
}
pathLabeling = currentPath
end
end
local optionkey = option.key
--fixme: shouldn't be needed (?)
if not option.OnChange then
option.OnChange = function(self) end
end
if not option.desc then
option.desc = ''
end
--if option.advanced and not settings.config['epic_Settings_Show_Advanced_Settings'] then
if option.advanced and not settings.showAdvanced then
--do nothing
elseif option.type == 'button' then
local hide = false
if option.wname == 'epic' then --menu
local menupath = option.desc
if pathoptions[menupath] and #(pathoptions[menupath]) == 0 then
hide = true
settings_height = settings_height - B_HEIGHT
end
end
if not hide then
local escapeSearch = searchedElement and option.desc and option.desc:find(currentPath) and option.isDirectoryButton --this type of button will open sub-level when pressed (defined in "AddOption(path, option, wname )")
local disabled = option.DisableFunc and option.DisableFunc()
local icon = option.icon
local button = Button:New{
name = option.wname .. " " .. option.name;
x=0,
minHeight = root and 36 or 30,
caption = option.name,
OnClick = escapeSearch and {function() filterUserInsertedTerm = ''; end,option.OnChange} or {option.OnChange},
backgroundColor = disabled and color.disabled_bg or {1, 1, 1, 1},
textColor = disabled and color.disabled_fg or color.sub_button_fg,
tooltip = option.desc,
padding={2,2,2,2},
}
if icon then
local width = root and 24 or 16
Image:New{ file= icon, width = width, height = width, parent = button, x=4,y=4, }
end
tree_children[#tree_children+1] = MakeHotkeyedControl(button, path, option,nil,option.isDirectoryButton )
end
elseif option.type == 'label' then
tree_children[#tree_children+1] = Label:New{ caption = option.value or option.name, textColor = color.sub_header, }
elseif option.type == 'text' then
tree_children[#tree_children+1] =
Button:New{
name = option.wname .. " " .. option.name;
width = "100%",
minHeight = 30,
caption = option.name,
OnClick = { function() MakeHelp(option.name, option.value) end },
backgroundColor = color.sub_button_bg,
textColor = color.sub_button_fg,
tooltip=option.desc
}
elseif option.type == 'bool' then
local chbox = Checkbox:New{
x=0,
right = 35,
caption = option.name,
checked = option.value or false,
OnClick = { option.OnChange, },
textColor = color.sub_fg,
tooltip = option.desc,
}
tree_children[#tree_children+1] = MakeHotkeyedControl(chbox, path, option)
elseif option.type == 'number' then
settings_height = settings_height + B_HEIGHT
local icon = option.icon
if icon then
tree_children[#tree_children+1] = Panel:New{
backgroundColor = {0,0,0,0},
padding = {0,0,0,0},
margin = {0,0,0,0},
--itemMargin = {2,2,2,2},
autosize = true,
children = {
Image:New{ file= icon, width = 16,height = 16, x=4,y=0, },
Label:New{ caption = option.name, textColor = color.sub_fg, x=20,y=0, },
}
}
else
tree_children[#tree_children+1] = Label:New{ caption = option.name, textColor = color.sub_fg, }
end
if option.valuelist then
option.value = GetIndex(option.valuelist, option.value)
end
tree_children[#tree_children+1] =
Trackbar:New{
width = "100%",
caption = option.name,
value = option.value,
trackColor = color.sub_fg,
min=option.min or 0,
max=option.max or 100,
step=option.step or 1,
OnMouseup = { option.OnChange }, --using onchange triggers repeatedly during slide
tooltip=option.desc,
--useValueTooltip=true,
}
elseif option.type == 'list' then
tree_children[#tree_children+1] = Label:New{ caption = option.name, textColor = color.sub_header, }
local items = {};
for i=1, #option.items do
local item = option.items[i]
item.value = item.key --for 'OnClick'
settings_height = settings_height + B_HEIGHT
tree_children[#tree_children+1] = Button:New{
name = option.wname .. " " .. item.name;
width = "100%",
caption = item.name,
OnClick = { function(self) option.OnChange(item) end },
backgroundColor = color.sub_button_bg,
textColor = color.sub_button_fg,
tooltip=item.desc,
}
end
--[[
tree_children[#tree_children+1] = ComboBox:New {
items = items;
}
]]--
elseif option.type == 'radioButton' then
tree_children[#tree_children+1] = Label:New{ caption = option.name, textColor = color.sub_header, }
for i=1, #option.items do
local item = option.items[i]
settings_height = settings_height + B_HEIGHT
local cb = Checkbox:New{
--x=0,
right = 35,
caption = ' ' .. item.name, --caption
checked = (option.value == item.value), --status
OnClick = {function(self) option.OnChange(item) end},
textColor = color.sub_fg,
tooltip = item.desc, --tooltip
}
local icon = option.items[i].icon
tree_children[#tree_children+1] = MakeHotkeyedControl( cb, path, item, icon)
end
tree_children[#tree_children+1] = Label:New{ caption = '', }
elseif option.type == 'colors' then
settings_height = settings_height + B_HEIGHT*2.5
tree_children[#tree_children+1] = Label:New{ caption = option.name, textColor = color.sub_fg, }
tree_children[#tree_children+1] =
Colorbars:New{
width = "100%",
height = B_HEIGHT*2,
tooltip=option.desc,
color = option.value or {1,1,1,1},
OnClick = { option.OnChange, },
}
end
end
local window_height = min(400, scrH - B_HEIGHT*6)
if settings_height < window_height then
window_height = settings_height+10
end
local window_width = 300
local window_children = {}
window_children[#window_children+1] =
ScrollPanel:New{
x=0,y=15,
bottom=B_HEIGHT+20,
width = '100%',
children = {
StackPanel:New{
x=0,
y=0,
right=0,
orientation = "vertical",
--width = "100%",
height = "100%",
backgroundColor = color.sub_bg,
children = tree_children,
itemMargin = {2,2,2,2},
resizeItems = false,
centerItems = false,
autosize = true,
},
}
}
window_height = window_height + B_HEIGHT
local buttonBar = Grid:New{
x=0;bottom=0;
right=10,height=B_HEIGHT,
columns = 4,
padding = {0, 0, 0, 0},
itemMargin = {0, 0, 0, 0}, --{1, 1, 1, 1},
autosize = true,
resizeItems = true,
centerItems = false,
}
window_children[#window_children+1] = Checkbox:New{
--x=0,
width=180;
right = 5,
bottom=B_HEIGHT;
caption = 'Show Advanced Settings',
checked = settings.showAdvanced,
OnChange = { function(self)
settings.showAdvanced = not self.checked
RemakeEpicMenu()
end },
textColor = color.sub_fg,
tooltip = 'For experienced users only.',
}
window_children[#window_children+1] = buttonBar
--back button
if parent_path then
Button:New{ name= 'backButton', caption = '', OnClick = { KillSubWindow, function() filterUserInsertedTerm = ''; MakeSubWindow(parent_path, false) end, },
backgroundColor = color.sub_back_bg,textColor = color.sub_back_fg, height=B_HEIGHT,
padding= {2,2,2,2},
parent = buttonBar;
children = {
Image:New{ file= LUAUI_DIRNAME .. 'images/epicmenu/arrow_left.png', width = 16,height = 16, parent = button, x=4,y=2, },
Label:New{ caption = 'Back',x=24,y=4, }
}
}
end
--search button
Button:New{ name= 'searchButton', caption = '',
OnClick = { function() spSendCommands("chat","PasteText /search:" ) end },
textColor = color.sub_close_fg, backgroundColor = color.sub_close_bg, height=B_HEIGHT,
padding= {2,2,2,2},parent = buttonBar;
children = {
Image:New{ file= LUAUI_DIRNAME .. 'images/epicmenu/find.png', width = 16,height = 16, parent = button, x=4,y=2, },
Label:New{ caption = 'Search',x=24,y=4, }
}
}
if not searchedElement then --do not display reset setting button when search is a bunch of mixed options
--reset button
Button:New{ name= 'resetButton', caption = '',
OnClick = { function() ResetWinSettings(path); RemakeEpicMenu(); end },
textColor = color.sub_close_fg, backgroundColor = color.sub_close_bg, height=B_HEIGHT,
padding= {2,2,2,2}, parent = buttonBar;
children = {
Image:New{ file= LUAUI_DIRNAME .. 'images/epicmenu/undo.png', width = 16,height = 16, parent = button, x=4,y=2, },
Label:New{ caption = 'Reset',x=24,y=4, }
}
}
end
--close button
Button:New{ name= 'menuCloseButton', caption = '',
OnClick = { function() KillSubWindow(); filterUserInsertedTerm = ''; end },
textColor = color.sub_close_fg, backgroundColor = color.sub_close_bg, height=B_HEIGHT,
padding= {2,2,2,2}, parent = buttonBar;
children = {
Image:New{ file= LUAUI_DIRNAME .. 'images/epicmenu/close.png', width = 16,height = 16, parent = button, x=4,y=2, },
Label:New{ caption = 'Close',x=24,y=4, }
}
}
KillSubWindow(true)
curPath = path -- must be done after KillSubWindow
window_sub_cur = Window:New{
caption= (searchedElement and "Searching in: \"" .. path .. "...\"") or ((not root) and (path) or "MAIN MENU"),
x = settings.sub_pos_x,
y = settings.sub_pos_y,
clientWidth = window_width,
clientHeight = window_height+B_HEIGHT*4,
minWidth = 250,
minHeight = 350,
--resizable = false,
parent = settings.show_crudemenu and screen0 or nil,
backgroundColor = color.sub_bg,
children = window_children,
}
AdjustWindow(window_sub_cur)
if pause and AllowPauseOnMenuChange() then
local paused = select(3, Spring.GetGameSpeed())
if not paused then
spSendCommands("pause")
end
end
end
-- Show or hide menubar
local function ShowHideCrudeMenu(dontChangePause)
--WG.crude.visible = settings.show_crudemenu -- HACK set it to wg to signal to player list
if settings.show_crudemenu then
if window_crude then
screen0:AddChild(window_crude)
--WG.chat.showConsole()
--window_crude:UpdateClientArea()
end
if window_sub_cur then
screen0:AddChild(window_sub_cur)
if (not dontChangePause) and AllowPauseOnMenuChange() then
local paused = select(3, Spring.GetGameSpeed())
if (not paused) and (not window_exit_confirm) then
spSendCommands("pause")
end
end
end
else
if window_crude then
screen0:RemoveChild(window_crude)
--WG.chat.hideConsole()
end
if window_sub_cur then
screen0:RemoveChild(window_sub_cur)
if (not dontChangePause) and AllowPauseOnMenuChange() then
local paused = select(3, Spring.GetGameSpeed())
if paused and (not window_exit_confirm) then
spSendCommands("pause")
end
end
end
end
if window_sub_cur then
AdjustWindow(window_sub_cur)
end
end
local function DisposeExitConfirmWindow()
if window_exit_confirm then
window_exit_confirm:Dispose()
window_exit_confirm = nil
end
end
local function LeaveExitConfirmWindow()
settings.show_crudemenu = not settings.show_crudemenu
DisposeExitConfirmWindow()
ShowHideCrudeMenu(true)
end
local function MakeExitConfirmWindow(text, action)
local screen_width,screen_height = Spring.GetWindowGeometry()
local menu_width = 320
local menu_height = 64
LeaveExitConfirmWindow()
window_exit_confirm = Window:New{
name='exitwindow_confirm',
parent = screen0,
x = screen_width/2 - menu_width/2,
y = screen_height/2 - menu_height/2,
dockable = false,
clientWidth = menu_width,
clientHeight = menu_height,
draggable = false,
tweakDraggable = false,
resizable = false,
tweakResizable = false,
minimizable = false,
}
Label:New{
parent = window_exit_confirm,
caption = text,
width = "100%",
--x = "50%",
y = 4,
align="center",
textColor = color.main_fg
}
Button:New{
name = 'confirmExitYesButton';
parent = window_exit_confirm,
caption = "Yes",
OnClick = { function()
action()
DisposeExitConfirmWindow()
end
},
height=32,
x = 4,
right = "55%",
bottom = 4,
}
Button:New{
name = 'confirmExitNoButton';
parent = window_exit_confirm,
caption = "No",
OnClick = { function()
LeaveExitConfirmWindow()
end
},
height=32,
x = "55%",
right = 4,
bottom = 4,
}
end
local function MakeMenuBar()
local btn_padding = {4,3,2,2}
local btn_margin = {0,0,0,0}
local exit_menu_width = 210
local exit_menu_height = 280
local exit_menu_btn_width = 7*exit_menu_width/8
local exit_menu_btn_height = max(exit_menu_height/8, 30)
local exit_menu_cancel_width = exit_menu_btn_width/2
local exit_menu_cancel_height = 2*exit_menu_btn_height/3
local crude_width = 400
local crude_height = B_HEIGHT+10
lbl_fps = Label:New{ name='lbl_fps', caption = 'FPS:', textColor = color.sub_header, margin={0,5,0,0}, }
lbl_gtime = Label:New{ name='lbl_gtime', caption = 'Time:', width = 55, height=5, textColor = color.sub_header, }
lbl_clock = Label:New{ name='lbl_clock', caption = 'Clock:', width = 45, height=5, textColor = color.main_fg, } -- autosize=false, }
img_flag = Image:New{ tooltip='Choose Your Location', file=":cn:".. LUAUI_DIRNAME .. "Images/flags/".. settings.country ..'.png', width = 16,height = 11, OnClick = { MakeFlags }, margin={4,4,4,6} }
local screen_width,screen_height = Spring.GetWindowGeometry()
window_crude = Window:New{
name='epicmenubar',
right = 0,
y = 0,
dockable = true,
clientWidth = crude_width,
clientHeight = crude_height,
draggable = false,
tweakDraggable = true,
resizable = false,
minimizable = false,
backgroundColor = color.main_bg,
color = color.main_bg,
margin = {0,0,0,0},
padding = {0,0,0,0},
parent = screen0,
children = {
StackPanel:New{
name='stack_main',
orientation = 'horizontal',
width = '100%',
height = '100%',
resizeItems = false,
padding = {0,0,0,0},
itemPadding = {1,1,1,1},
itemMargin = {1,1,1,1},
autoArrangeV = false,
autoArrangeH = false,
children = {
--GAME LOGO GOES HERE
Image:New{ tooltip = title_text, file = title_image, height=B_HEIGHT, width=B_HEIGHT, },
Button:New{
name= 'tweakGuiButton',
caption = "", OnClick = { function() spSendCommands{"luaui tweakgui"} end, }, textColor=color.menu_fg, height=B_HEIGHT+4, width=B_HEIGHT+5,
padding = btn_padding, margin = btn_margin, tooltip = "Move and resize parts of the user interface (\255\0\255\0Ctrl+F11\008) (Hit ESC to exit)",
children = {
Image:New{ file=LUAUI_DIRNAME .. 'Images/epicmenu/move.png', height=B_HEIGHT-2,width=B_HEIGHT-2, },
},
},
--MAIN MENU BUTTON
Button:New{
name= 'subMenuButton',
OnClick = { function() ActionSubmenu(nil,'') end, },
textColor=color.game_fg,
height=B_HEIGHT+12,
width=B_WIDTH_TOMAINMENU + 1,
caption = "Menu (\255\0\255\0"..WG.crude.GetHotkey("crudesubmenu").."\008)",
padding = btn_padding,
margin = btn_margin,
tooltip = '',
children = {
--Image:New{file = title_image, height=B_HEIGHT-2,width=B_HEIGHT-2, x=2, y = 4},
--Label:New{ caption = "Menu (\255\0\255\0"..WG.crude.GetHotkey("crudesubmenu").."\008)", valign = "center"}
},
},
--VOLUME SLIDERS
Grid:New{
height = '100%',
width = 100,
columns = 2,
rows = 2,
resizeItems = false,
margin = {0,0,0,0},
padding = {0,0,0,0},
itemPadding = {1,1,1,1},
itemMargin = {1,1,1,1},
children = {
--Label:New{ caption = 'Vol', width = 20, textColor = color.main_fg },
Image:New{ tooltip = 'Volume', file=LUAUI_DIRNAME .. 'Images/epicmenu/vol.png', width= 18,height= 18, },
Trackbar:New{
tooltip = 'Volume',
height=15,
width=70,
trackColor = color.main_fg,
value = spGetConfigInt("snd_volmaster", 50),
OnChange = { function(self) spSendCommands{"set snd_volmaster " .. self.value} end },
},
Image:New{ tooltip = 'Music', file=LUAUI_DIRNAME .. 'Images/epicmenu/vol_music.png', width= 18,height= 18, },
Trackbar:New{
tooltip = 'Music',
height=15,
width=70,
min = 0,
max = 1,
step = 0.01,
trackColor = color.main_fg,
value = settings.music_volume or 0.5,
prevValue = settings.music_volume or 0.5,
OnChange = {
function(self)
if (WG.music_start_volume or 0 > 0) then
Spring.SetSoundStreamVolume(self.value / WG.music_start_volume)
else
Spring.SetSoundStreamVolume(self.value)
end
settings.music_volume = self.value
WG.music_volume = self.value
if (self.prevValue > 0 and self.value <=0) then widgetHandler:DisableWidget("Music Player") end
if (self.prevValue <=0 and self.value > 0) then widgetHandler:EnableWidget("Music Player") end
self.prevValue = self.value
end
},
},
},
},
--FPS & FLAG
Grid:New{
orientation = 'horizontal',
columns = 1,
rows = 2,
width = 60,
height = '100%',
--height = 40,
resizeItems = true,
autoArrangeV = true,
autoArrangeH = true,
padding = {0,0,0,0},
itemPadding = {0,0,0,0},
itemMargin = {0,0,0,0},
children = {
lbl_fps,
img_flag,
},
},
--GAME CLOCK AND REAL-LIFE CLOCK
Grid:New{
orientation = 'horizontal',
columns = 1,
rows = 2,
width = 80,
height = '100%',
--height = 40,
resizeItems = true,
autoArrangeV = true,
autoArrangeH = true,
padding = {0,0,0,0},
itemPadding = {0,0,0,0},
itemMargin = {0,0,0,0},
children = {
StackPanel:New{
orientation = 'horizontal',
width = 70,
height = '100%',
resizeItems = false,
autoArrangeV = false,
autoArrangeH = false,
padding = {0,0,0,0},
itemMargin = {2,0,0,0},
children = {
Image:New{ file= LUAUI_DIRNAME .. 'Images/epicmenu/game.png', width = 20,height = 20, },
lbl_gtime,
},
},
StackPanel:New{
orientation = 'horizontal',
width = 80,
height = '100%',
resizeItems = false,
autoArrangeV = false,
autoArrangeH = false,
padding = {0,0,0,0},
itemMargin = {2,0,0,0},
children = {
Image:New{ file= LUAUI_DIRNAME .. 'Images/clock.png', width = 20,height = 20, },
lbl_clock,
},
},
},
},
}
}
}
}
settings.show_crudemenu = true
--ShowHideCrudeMenu()
end
local function MakeQuitButtons()
AddOption('',{
type='label',
name='Quit game',
value = 'Quit game',
key='Quit game',
})
AddOption('',{
type='button',
name='Vote Resign',
desc = "Ask teammates to resign",
OnChange = function()
if not (Spring.GetSpectatingState() or PlayingButNoTeammate() or isMission) then
spSendCommands("say !voteresign")
ActionMenu()
end
end,
key='Vote Resign',
DisableFunc = function()
return (Spring.GetSpectatingState() or PlayingButNoTeammate() or isMission)
end, --function that trigger grey colour on buttons (not actually disable their functions)
})
AddOption('',{
type='button',
name='Resign',
desc = "Abandon team and become spectator",
OnChange = function()
if not (isMission or Spring.GetSpectatingState()) then
MakeExitConfirmWindow("Are you sure you want to resign?", function()
local paused = select(3, Spring.GetGameSpeed())
if (paused) and AllowPauseOnMenuChange() then
spSendCommands("pause")
end
spSendCommands{"spectator"}
end)
end
end,
key='Resign',
DisableFunc = function()
return (Spring.GetSpectatingState() or isMission)
end, --function that trigger grey colour on buttons (not actually disable their functions)
})
AddOption('',{
type='button',
name='Exit to Desktop',
desc = "Exit game completely",
OnChange = function()
MakeExitConfirmWindow("Are you sure you want to quit the game?", function()
local paused = select(3, Spring.GetGameSpeed())
if (paused) and AllowPauseOnMenuChange() then
spSendCommands("pause")
end
spSendCommands{"spectator","quit","quitforce"}
end)
end,
key='Exit to Desktop',
})
end
--Remakes crudemenu and remembers last submenu open
RemakeEpicMenu = function()
local lastPath = curPath
local subwindowOpen = window_sub_cur ~= nil
KillSubWindow(subwindowOpen)
if subwindowOpen then
MakeSubWindow(lastPath, true)
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:ViewResize(vsx, vsy)
scrW = vsx
scrH = vsy
end
function widget:Initialize()
if (not WG.Chili) then
widgetHandler:RemoveWidget(widget)
return
end
init = true
spSendCommands("unbindaction hotbind")
spSendCommands("unbindaction hotunbind")
-- setup Chili
Chili = WG.Chili
Button = Chili.Button
Label = Chili.Label
Colorbars = Chili.Colorbars
Checkbox = Chili.Checkbox
Window = Chili.Window
Panel = Chili.Panel
ScrollPanel = Chili.ScrollPanel
StackPanel = Chili.StackPanel
LayoutPanel = Chili.LayoutPanel
Grid = Chili.Grid
Trackbar = Chili.Trackbar
TextBox = Chili.TextBox
Image = Chili.Image
Progressbar = Chili.Progressbar
Colorbars = Chili.Colorbars
screen0 = Chili.Screen0
widget:ViewResize(Spring.GetViewGeometry())
-- Set default positions of windows on first run
local screenWidth, screenHeight = Spring.GetWindowGeometry()
if not settings.sub_pos_x then
settings.sub_pos_x = screenWidth/2 - 150
settings.sub_pos_y = screenHeight/2 - 200
end
if not keybounditems then
keybounditems = {}
end
if not settings.config then
settings.config = {}
end
if not settings.country or settings.country == 'wut' then
myCountry = select(8, Spring.GetPlayerInfo( Spring.GetLocalPlayerID() ) )
if not myCountry or myCountry == '' then
myCountry = 'wut'
end
settings.country = myCountry
end
WG.country = settings.country
WG.lang(settings.lang)
SetLangFontConf()
-- add custom widget settings to crudemenu
AddAllCustSettings()
--this is done to establish order the correct button order
local imgPath = LUAUI_DIRNAME .. 'images/'
AddOption('Game')
AddOption('Settings/Reset Settings')
AddOption('Settings/Audio')
AddOption('Settings/Camera')
AddOption('Settings/Graphics')
AddOption('Settings/HUD Panels')
AddOption('Settings/HUD Presets')
AddOption('Settings/Interface')
AddOption('Settings/Misc')
-- Add pre-configured button/options found in epicmenu config file
local options_temp = CopyTable(epic_options, true)
for i=1, #options_temp do
local option = options_temp[i]
AddOption(option.path, option)
end
MakeQuitButtons()
-- Clears all saved settings of custom widgets stored in crudemenu's config
WG.crude.ResetSettings = function()
for path, _ in pairs(pathoptions) do
ResetWinSettings(path)
end
RemakeEpicMenu()
echo 'Cleared all settings.'
end
-- clear all keybindings
WG.crude.ResetKeys = function()
keybounditems = {}
keybounditems = CopyTable(defaultkeybinds, true) --restore with mods zkkey's default value
--restore with widget's default value:
for path, subtable in pairs ( pathoptions) do
for _,element in ipairs(subtable) do
local option = element[2]
local defaultHotkey = option.orig_hotkey
if defaultHotkey then
option.hotkey = defaultHotkey --make chili menu display the default hotkey
local actionName = GetActionName(path, option)
otset( keybounditems, actionName, defaultHotkey) --save default hotkey to zkkey
end
end
end
ReApplyKeybinds() --unbind all hotkey and re-attach with stuff in keybounditems table
echo 'Reset all hotkeys to default.'
end
-- get hotkey
WG.crude.GetHotkey = function(actionName, all) --Note: declared here because keybounditems must not be empty
local actionHotkey = GetActionHotkey(actionName)
--local hotkey = keybounditems[actionName] or actionHotkey
local hotkey = otget( keybounditems, actionName ) or actionHotkey
if not hotkey or hotkey == 'None' then
return all and {} or ''
end
if not all then
if type(hotkey) == 'table' then
hotkey = hotkey[1]
end
return GetReadableHotkey(hotkey)
else
local ret = {}
if type(hotkey) == 'table' then
for k, v in pairs( hotkey ) do
ret[#ret+1] = GetReadableHotkey(v)
end
else
ret[#ret+1] = GetReadableHotkey(hotkey)
end
return ret
end
end
WG.crude.GetHotkeys = function(actionName)
return WG.crude.GetHotkey(actionName, true)
end
-- set hotkey
WG.crude.SetHotkey = function(actionName, hotkey, func) --Note: declared here because pathoptions must not be empty
if hotkey then
hotkey = GetReadableHotkey(hotkey) --standardize hotkey (just in case stuff happen)
end
if hotkey == '' then
hotkey = nil --convert '' into NIL.
end
if func then
if hotkey then
AddAction(actionName, func, nil, "t") --attach function to action
else
RemoveAction(actionName) --detach function from action
end
end
if hotkey then
AssignKeyBindAction(hotkey, actionName, false) --attach action to keybinds
else
UnassignKeyBind(actionName,false) --detach action from keybinds
end
otset(keybounditems, actionName, hotkey) --update epicmenu's hotkey table
for path, subtable in pairs (pathoptions) do
for _,element in ipairs(subtable) do
local option = element[2]
local indirectActionName = GetActionName(path, option)
local directActionName = option.action
if indirectActionName==actionName or directActionName == actionName then
option.hotkey = hotkey or "None" --update pathoption hotkey for Chili menu display & prevent conflict with hotkey registerd by Chili . Note: LUA is referencing table, so we don't need to change same table elsewhere.
end
end
end
end
-- Add custom actions for the following keybinds
AddAction("crudemenu", ActionMenu, nil, "t")
AddAction("crudesubmenu", ActionSubmenu, nil, "t")
AddAction("exitwindow", ActionExitWindow, nil, "t")
MakeMenuBar()
useUiKeys = settings.config['epic_Settings/Misc_Use_uikeys.txt']
if not useUiKeys then
spSendCommands("unbindall")
else
echo('You have opted to use the engine\'s uikeys.txt. The menu keybind system will not be used.')
end
LoadKeybinds()
ReApplyKeybinds()
-- Override widgethandler functions for the purposes of alerting crudemenu
-- when widgets are loaded, unloaded or toggled
widgetHandler.OriginalInsertWidget = widgetHandler.InsertWidget
widgetHandler.InsertWidget = function(self, widget)
PreIntegrateWidget(widget)
local ret = self:OriginalInsertWidget(widget)
if type(widget) == 'table' and type(widget.options) == 'table' then
IntegrateWidget(widget, true)
if not (init) then
RemakeEpicMenu()
end
end
checkWidget(widget)
return ret
end
widgetHandler.OriginalRemoveWidget = widgetHandler.RemoveWidget
widgetHandler.RemoveWidget = function(self, widget)
local ret = self:OriginalRemoveWidget(widget)
if type(widget) == 'table' and type(widget.options) == 'table' then
IntegrateWidget(widget, false)
if not (init) then
RemakeEpicMenu()
end
end
checkWidget(widget)
return ret
end
widgetHandler.OriginalToggleWidget = widgetHandler.ToggleWidget
widgetHandler.ToggleWidget = function(self, name)
local ret = self:OriginalToggleWidget(name)
local w = widgetHandler:FindWidget(name)
if w then
checkWidget(w)
else
checkWidget(name)
end
return ret
end
init = false
--intialize remote menu trigger
WG.crude.OpenPath = function(path, pause) --Note: declared here so that it work in local copy
MakeSubWindow(path, pause) -- FIXME should pause the game
end
--intialize remote menu trigger 2
WG.crude.ShowMenu = function() --// allow other widget to toggle-up Epic-Menu. This'll enable access to game settings' Menu via click on other GUI elements.
if not settings.show_crudemenu then
settings.show_crudemenu = true
ShowHideCrudeMenu()
end
end
--intialize remote option fetcher
WG.GetWidgetOption = function(wname, path, key) -- still fails if path and key are un-concatenatable
return (pathoptions and path and key and wname and pathoptions[path] and otget( pathoptions[path], wname..key ) ) or {}
end
--intialize remote option setter
WG.SetWidgetOption = function(wname, path, key, value)
if (pathoptions and path and key and wname and pathoptions[path] and otget( pathoptions[path], wname..key ) ) then
local option = otget( pathoptions[path], wname..key )
option.OnChange({checked=value, value=value, color=value})
end
end
end
function widget:Shutdown()
-- Restore widgethandler functions to original states
if widgetHandler.OriginalRemoveWidget then
widgetHandler.InsertWidget = widgetHandler.OriginalInsertWidget
widgetHandler.OriginalInsertWidget = nil
widgetHandler.RemoveWidget = widgetHandler.OriginalRemoveWidget
widgetHandler.OriginalRemoveWidget = nil
widgetHandler.ToggleWidget = widgetHandler.OriginalToggleWidget
widgetHandler.OriginalToggleWidget = nil
end
if window_crude then
screen0:RemoveChild(window_crude)
end
if window_sub_cur then
screen0:RemoveChild(window_sub_cur)
end
RemoveAction("crudemenu")
RemoveAction("crudesubmenu")
spSendCommands("unbind esc crudemenu")
end
function widget:GetConfigData()
SaveKeybinds()
return settings
end
function widget:SetConfigData(data)
if (data and type(data) == 'table') then
if data.versionmin and data.versionmin >= 50 then
settings = data
end
end
WG.music_volume = settings.music_volume or 0.5
LoadKeybinds()
end
function widget:Update()
cycle = cycle%32+1
if cycle == 1 then
--Update clock, game timer and fps meter that show on menubar
if lbl_fps then
lbl_fps:SetCaption( 'FPS: ' .. Spring.GetFPS() )
end
if lbl_gtime then
lbl_gtime:SetCaption( GetTimeString() )
end
if lbl_clock then
--local displaySeconds = true
--local format = displaySeconds and "%H:%M:%S" or "%H:%M"
local format = "%H:%M" --fixme: running game for over an hour pushes time label down
--lbl_clock:SetCaption( 'Clock\n ' .. os.date(format) )
lbl_clock:SetCaption( os.date(format) )
end
end
if wantToReapplyBinding then --widget integration request ReApplyKeybinds()?
ReApplyKeybinds() --unbind all action/key, rebind action/key
wantToReapplyBinding = false
end
end
function widget:KeyPress(key, modifier, isRepeat)
if key == KEYSYMS.LCTRL
or key == KEYSYMS.RCTRL
or key == KEYSYMS.LALT
or key == KEYSYMS.RALT
or key == KEYSYMS.LSHIFT
or key == KEYSYMS.RSHIFT
or key == KEYSYMS.LMETA
or key == KEYSYMS.RMETA
or key == KEYSYMS.SPACE
then
return
end
local modstring =
(modifier.alt and 'A+' or '') ..
(modifier.ctrl and 'C+' or '') ..
(modifier.meta and 'M+' or '') ..
(modifier.shift and 'S+' or '')
--Set a keybinding
if get_key then
get_key = false
window_getkey:Dispose()
translatedkey = transkey[ keysyms[''..key]:lower() ] or keysyms[''..key]:lower()
--local hotkey = { key = translatedkey, mod = modstring, }
local hotkey = modstring .. translatedkey
if key ~= KEYSYMS.ESCAPE then
--otset( keybounditems, kb_action, hotkey )
AssignKeyBindAction(hotkey, kb_action, true) -- param4 = verbose
otset( keybounditems, kb_action, hotkey )
end
ReApplyKeybinds()
if kb_path == curPath then
MakeSubWindow(kb_path, false)
end
return true
end
end
function ActionExitWindow()
WG.crude.ShowMenu()
MakeSubWindow(submenu or '')
end
function ActionSubmenu(_, submenu)
if window_sub_cur then
KillSubWindow()
else
WG.crude.ShowMenu()
MakeSubWindow(submenu or '')
end
end
function ActionMenu()
settings.show_crudemenu = not settings.show_crudemenu
DisposeExitConfirmWindow()
ShowHideCrudeMenu()
end
do --Set our prefered camera mode when first screen frame is drawn. The engine always go to default TA at first screen frame, so we need to re-apply our camera settings.
if Spring.GetGameFrame() == 0 then --we check if this code is run at midgame (due to /reload). In that case we don't need to re-apply settings (the camera mode is already set at gui_epicmenu.lua\AddOption()).
local screenFrame = 0
function widget:DrawScreen() --game event: Draw Screen
if screenFrame >= 1 then --detect frame no.2
local option = otget( pathoptions['Settings/Camera'], 'Settings/Camera'..'Camera Type' ) --get camera option we saved earlier in gui_epicmenu.lua\AddOption()
option.OnChange(option) --re-apply our settings
Spring.Echo("Epicmenu: Switching to " .. option.value .. " camera mode") --notify in log what happen.
widgetHandler:RemoveWidgetCallIn("DrawScreen", self) --stop updating "widget:DrawScreen()" event. Note: this is a special "widgetHandler:RemoveCallin" for widget that use "handler=true".
end
screenFrame = screenFrame+1
end
end
end
--]]
-------------------------------------------------------
-------------------------------------------------------
-- detect when user press ENTER to insert search term for searching option in epicmenu
function widget:TextCommand(command)
if window_sub_cur and command:sub(1,7) == "search:" then
filterUserInsertedTerm = command:sub(8)
filterUserInsertedTerm = filterUserInsertedTerm:lower() --Reference: http://lua-users.org/wiki/StringLibraryTutorial
Spring.Echo("EPIC Menu: searching \"" .. filterUserInsertedTerm.."\"")
MakeSubWindow(curPath,true) --remake the menu window. If search term is not "" the MakeSubWindowSearch(curPath) will be called instead
WG.crude.ShowMenu()
return true
end
return false
end
function SearchInText(randomTexts,searchText) --this allow search term to be unordered (eg: "sel view" == "view sel")
local explodedTerms = explode(' ',searchText)
explodeSearchTerm.terms = explodedTerms
explodeSearchTerm.text = searchText
local found = true --this return true if all term match (eg: found("sel") && found("view"))
local explodedTerms = explodeSearchTerm.terms
for i=1, #explodedTerms do
local subSearchTerm = explodedTerms[i]
local findings = randomTexts:find(subSearchTerm)
if not findings then
found = false
break
end
end
return found
end
| gpl-2.0 |
geanux/darkstar | scripts/globals/abilities/pets/stone_iv.lua | 20 | 1151 | ---------------------------------------------------
-- Stone 4
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/globals/magic");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill)
local spell = getSpell(162);
--calculate raw damage
local dmg = calculateMagicDamage(381,2,pet,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false);
--get resist multiplier (1x if no resist)
local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, 2);
--get the resisted damage
dmg = dmg*resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = mobAddBonuses(pet,spell,target,dmg, 2);
--add on TP bonuses
local tp = skill:getTP();
if tp < 100 then
tp = 100;
end
dmg = dmg * tp / 100;
--add in final adjustments
dmg = finalMagicAdjustments(pet,target,spell,dmg);
return dmg;
end | gpl-3.0 |
xXDarkBoyXx/Cloud_Tm | plugins/Anti-spam.lua | 30 | 4161 |
do
local NUM_MSG_MAX = 4
local TIME_CHECK = 4 -- seconds
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
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
print('Service message')
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)
-- Check flood
local kick = chat_del_user(chat_id , user_id, ok_cb, true)
vardump(kick)
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false)
print('User '..msg.from.id..'is flooding '..msgs)
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nChats: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == "stats" then
if not matches[2] then
if msg.to.type == 'chat' then
local chat_id = msg.to.id
return chat_stats(chat_id)
else
return 'Stats works only on chats'
end
end
if matches[2] == "bot" then
if not is_sudo(msg) then
return "Bot stats requires privileged user"
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return "This command requires privileged user"
else
return chat_stats(matches[3])
end
end
end
end
return {
description = "Plugin to update user stats.",
usage = {
"!stats: Returns a list of Username [telegram_id]: msg_num",
"!stats chat <chat_id>: Show stats for chat_id",
"!stats bot: Shows bot stats (sudo users)"
},
patterns = {
"^!([Ss]tats)$",
"^!([Ss]tats) (chat) (%d+)",
"^!([Ss]tats) (bot)"
},
run = run,
pre_process = pre_process
}
end
| gpl-2.0 |
mullikine/vlc | share/lua/intf/dumpmeta.lua | 98 | 2125 | --[==========================================================================[
dumpmeta.lua: dump a file's meta data on stdout/stderr
--[==========================================================================[
Copyright (C) 2010 the VideoLAN team
$Id$
Authors: Antoine Cellerier <dionoea at videolan dot org>
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.
--]==========================================================================]
--[[ to dump meta data information in the debug output, run:
vlc -I luaintf --lua-intf dumpmeta coolmusic.mp3
Additional options can improve performance and output readability:
-V dummy -A dummy --no-video-title --no-media-library -q
--]]
local item
repeat
item = vlc.input.item()
until (item and item:is_preparsed())
-- preparsing doesn't always provide all the information we want (like duration)
repeat
until item:stats()["demux_read_bytes"] > 0
vlc.msg.info("name: "..item:name())
vlc.msg.info("uri: "..vlc.strings.decode_uri(item:uri()))
vlc.msg.info("duration: "..tostring(item:duration()))
vlc.msg.info("meta data:")
local meta = item:metas()
if meta then
for key, value in pairs(meta) do
vlc.msg.info(" "..key..": "..value)
end
else
vlc.msg.info(" no meta data available")
end
vlc.msg.info("info:")
for cat, data in pairs(item:info()) do
vlc.msg.info(" "..cat)
for key, value in pairs(data) do
vlc.msg.info(" "..key..": "..value)
end
end
vlc.misc.quit()
| gpl-2.0 |
tonylauCN/tutorials | lua/debugger/lualibs/lexers/yaml.lua | 4 | 3921 | -- Copyright 2006-2016 Mitchell mitchell.att.foicica.com. See LICENSE.
-- YAML LPeg lexer.
-- It does not keep track of indentation perfectly.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'yaml'}
-- Whitespace.
local indent = #l.starts_line(S(' \t')) *
(token(l.WHITESPACE, ' ') + token('indent_error', '\t'))^1
local ws = token(l.WHITESPACE, S(' \t')^1 + l.newline^1)
-- Comments.
local comment = token(l.COMMENT, '#' * l.nonnewline^0)
-- Strings.
local string = token(l.STRING, l.delimited_range("'") + l.delimited_range('"'))
-- Numbers.
local integer = l.dec_num + l.hex_num + '0' * S('oO') * R('07')^1
local special_num = '.' * word_match({'inf', 'nan'}, nil, true)
local number = token(l.NUMBER, special_num + l.float + integer)
-- Timestamps.
local ts = token('timestamp', l.digit * l.digit * l.digit * l.digit * -- year
'-' * l.digit * l.digit^-1 * -- month
'-' * l.digit * l.digit^-1 * -- day
((S(' \t')^1 + S('tT'))^-1 * -- separator
l.digit * l.digit^-1 * -- hour
':' * l.digit * l.digit * -- minute
':' * l.digit * l.digit * -- second
('.' * l.digit^0)^-1 * -- fraction
('Z' + -- timezone
S(' \t')^0 * S('-+') * l.digit * l.digit^-1 *
(':' * l.digit * l.digit)^-1)^-1)^-1)
-- Constants.
local constant = token(l.CONSTANT,
word_match({'null', 'true', 'false'}, nil, true))
-- Types.
local type = token(l.TYPE, '!!' * word_match({
-- Collection types.
'map', 'omap', 'pairs', 'set', 'seq',
-- Scalar types.
'binary', 'bool', 'float', 'int', 'merge', 'null', 'str', 'timestamp',
'value', 'yaml'
}, nil, true) + '!' * l.delimited_range('<>'))
-- Document boundaries.
local doc_bounds = token('document', l.starts_line(P('---') + '...'))
-- Directives
local directive = token('directive', l.starts_line('%') * l.nonnewline^1)
local word = (l.alpha + '-' * -l.space) * (l.alnum + '-')^0
-- Keys and literals.
local colon = S(' \t')^0 * ':' * (l.space + -1)
local key = token(l.KEYWORD,
#word * (l.nonnewline - colon)^1 * #colon *
P(function(input, index)
local line = input:sub(1, index - 1):match('[^\r\n]+$')
return not line:find('[%w-]+:') and index
end))
local value = #word * (l.nonnewline - l.space^0 * S(',]}'))^1
local block = S('|>') * S('+-')^-1 * (l.newline + -1) * function(input, index)
local rest = input:sub(index)
local level = #rest:match('^( *)')
for pos, indent, line in rest:gmatch('() *()([^\r\n]+)') do
if indent - pos < level and line ~= ' ' or level == 0 and pos > 1 then
return index + pos - 1
end
end
return #input + 1
end
local literal = token('literal', value + block)
-- Indicators.
local anchor = token(l.LABEL, '&' * word)
local alias = token(l.VARIABLE, '*' * word)
local tag = token('tag', '!' * word * P('!')^-1)
local reserved = token(l.ERROR, S('@`') * word)
local indicator_chars = token(l.OPERATOR, S('-?:,[]{}!'))
M._rules = {
{'indent', indent},
{'whitespace', ws},
{'comment', comment},
{'doc_bounds', doc_bounds},
{'key', key},
{'literal', literal},
{'timestamp', ts},
{'number', number},
{'constant', constant},
{'type', type},
{'indicator', tag + indicator_chars + alias + anchor + reserved},
{'directive', directive},
}
M._tokenstyles = {
indent_error = 'back:%(color.red)',
document = l.STYLE_CONSTANT,
literal = l.STYLE_DEFAULT,
timestamp = l.STYLE_NUMBER,
tag = l.STYLE_CLASS,
directive = l.STYLE_PREPROCESSOR,
}
M._FOLDBYINDENTATION = true
return M
| apache-2.0 |
semyon422/lua-mania | src/lmfw/ui/classes/QuadTextButton.lua | 1 | 2112 | local init = function(classes, ui)
--------------------------------
local QuadTextButton = classes.UiObject:new()
QuadTextButton.layer = 2
QuadTextButton.textXAlign = "center"
QuadTextButton.textYAlign = "center"
QuadTextButton.textXPadding = 0
QuadTextButton.textYPadding = 0
QuadTextButton.textColor = {255, 255, 255, 255}
QuadTextButton.quadXAlign = "center"
QuadTextButton.quadYAlign = "center"
QuadTextButton.quadXPadding = 0
QuadTextButton.quadYPadding = 0
QuadTextButton.quadColor = {255, 255, 255, 255}
QuadTextButton.locate = "in"
QuadTextButton.load = function(self)
self.fontBaseResolution = self.fontBaseResolution or {self.pos:x2X(1), self.pos:y2Y(1)}
self.drawable = self.drawable or love.graphics.newImage(self.imagePath)
self.quad = self.quad or love.graphics.newQuad(self.quadX, self.quadY, self.quadWidth, self.quadHeight, self.drawable:getWidth(), self.drawable:getHeight())
self.quadObject = loveio.output.classes.QuadBox:new({
x = self.x + self.quadXPadding, y = self.y + self.quadYPadding,
w = self.w - 2*self.quadXPadding, h = self.h - 2*self.quadYPadding,
drawable = self.drawable, quad = self.quad,
xAlign = self.quadXAlign, yAlign = self.quadYAlign,
quadWidth = self.quadWidth,
quadHeight = self.quadHeight,
layer = self.layer,
locate = self.locate,
pos = self.pos
}):insert(loveio.output.objects)
loveio.input.callbacks.mousepressed[tostring(self)] = function(mx, my)
local x = self:getAbs("x", true)
local y = self:getAbs("y", true)
local w = self:getAbs("w")
local h = self:getAbs("h")
if isInBox(mx, my, x, y, w, h) then
self:activate()
end
end
loveio.input.callbacks.resize[tostring(self)] = function()
self:valueChanged()
end
self:valueChanged()
end
QuadTextButton.unload = function(self)
if self.loaded then
self.quadObject:remove()
self["text-1"]:remove()
loveio.input.callbacks.mousepressed[tostring(self)] = nil
loveio.input.callbacks.resize[tostring(self)] = nil
end
end
QuadTextButton.valueChanged = classes.DrawableTextButton.valueChanged
return QuadTextButton
--------------------------------
end
return init
| gpl-3.0 |
johanburati/pushover | themes/aztec.lua | 1 | 1828 |
-- the 22 foreground tiles
foreground = {
1, 0, -- FgElementPlatformStart
2, 0, -- FgElementPlatformMiddle
3, 0, -- FgElementPlatformEnd
4, 0, -- FgElementPlatformLadderDown
5, 0, -- FgElementLadder
6, 0, -- FgElementPlatformLadderUp
7, 0, -- FgElementPlatformStep1
8, 0, -- FgElementPlatformStep2
9, 0, -- FgElementPlatformStep3
10, 0, -- FgElementPlatformStep4
11, 0, -- FgElementPlatformStep5
12, 0, -- FgElementPlatformStep6
13, 0, -- FgElementPlatformStep7
14, 0, -- FgElementPlatformStep8
17, 0, -- FgElementLadderMiddle
18, 0, -- FgElementPlatformStrip
5, 0, -- FgElementLadder2 -- identical with FgElementLadder
20, 0, -- FgElementDoor0
21, 0, -- FgElementDoor1
22, 0, -- FgElementDoor2
23, 0, -- FgElementDoor3
}
-- as many background tiles as you want.
background = {
24, 0,
25, 0,
26, 0,
27, 0,
28, 0,
29, 0,
30, 0,
31, 0,
0, 1,
1, 1,
2, 1,
3, 1,
4, 1,
5, 1,
6, 1,
7, 1,
8, 1,
9, 1,
10, 1,
11, 1,
12, 1,
13, 1,
14, 1,
15, 1,
16, 1,
17, 1,
18, 1,
19, 1,
20, 1,
21, 1,
22, 1,
23, 1,
24, 1,
25, 1,
26, 1,
27, 1,
28, 1,
29, 1,
30, 1,
31, 1,
0, 2,
1, 2,
2, 2,
3, 2,
4, 2,
5, 2,
6, 2,
7, 2,
8, 2,
9, 2,
10, 2,
11, 2,
12, 2,
13, 2,
14, 2,
15, 2,
16, 2,
17, 2,
18, 2,
19, 2,
20, 2,
21, 2,
22, 2,
23, 2,
24, 2,
25, 2,
26, 2,
27, 2,
28, 2,
31, 2,
0, 3,
1, 3,
2, 3,
3, 3,
4, 3,
5, 3,
6, 3,
7, 3,
8, 3,
9, 3,
10, 3,
11, 3,
12, 3,
13, 3,
14, 3,
15, 3,
16, 3,
17, 3,
18, 3,
19, 3,
20, 3,
21, 3,
22, 3,
23, 3,
24, 3,
25, 3,
26, 3,
27, 3,
28, 3,
29, 3,
30, 3,
31, 3,
0, 4,
1, 4,
2, 4,
3, 4,
4, 4,
5, 4,
6, 4,
7, 4,
8, 4,
9, 4,
16, 4,
17, 4,
18, 4,
19, 4,
20, 4,
21, 4,
22, 4,
23, 4,
24, 4,
25, 4,
26, 4,
27, 4,
}
| gpl-3.0 |
esn3s/3S_LUA | vrac/_c_cube/3rd_training_20120212_esn_mod.lua | 1 | 73390 | -- 3rd_training.lua
-- auther c_cube
TIME = 0
--[[
XVð
2012/02/12(Sun) JvXQL[fBXvCðüÇBQPÎÔoßÅÁ¦éæ¤ÉB
2012/02/09(Thu) 02/07ÌL[fBXvCðíB02/08ÌdlÉí¹ÄìèȨ·\èB
2012/02/08(Wed) JvXQÁÛ¢L[fBXvCðÀBªòªÊ|LÄâÁÏèPP¤¾¯B
2012/02/07(Tue) L[fBXvCQðÀAÆè ¦¸PP¤¾¯BüÍóµð©ÈèÚ×ÜÅ\¦B
2011/05/16(Mon) BGM̹Êðº°çêé`[gÇÁBgíÈ¢êÍRgAEgB
2011/05/15(Sun) 2P¤ÌL[fBXvCªALÌü«ÉæÁÄÍtÉÈÁÄ¢½ÌÅC³B
2011/04/23 Yêܵ½
2011/03/06(Sun) àÌlª©¦é@\ðÄÚBiÍRgAEgB
2011/02/19(Sat) oK`ûK[hðüÇB
2011/02/14(Mon) oK`ûK[hðÀBܾÈÕÅÆ¾Á½Æ±ëBRgâ·\èB
2010/10/04(Mon) X^[g{^QñÅQPX^lª^ÉÈé`[gðÇÁB
2010/10/03(Sun) qbgXgbvª[ÉÈé`[gðC³B
OqbgXgbvÆ[qbgXgbvð¼ûg¦éæ¤ÉC³B
g[jO[hðÇÁBX^[g{^QñÅQPÌÍ^ÉB
2010/10/02(Sat) qbgXgbvª[ÉÈé`[gðÇÁB
2010/10/01(Fli) qbgXgbvÌ·Èé`[gðÇÁB
`[g[hAÆè ¦¸LÌ®«¾¯Í~Ü鿤ÉC³iqbgXgbvðpjB
2010/09/26(Mon) óÇÔ³ÀÌ`[gðÇÁB
2010/09/25(Sat) drawOriginNumÖÌgðC³
`[g[hÚBX^[g{^·µÅN®I¹µA`[gðIðµÄIItÅ«éB
PPÌQ[WðMAXÉ·é`[gðÇÁB
2010/09/24(Fri) lð©ìtHgÅ\¦Å«éÖdrawOriginNumðÀB
²Ìdng®ÌßQ[Wð»B
2010/09/21(Tue) ¯¶æ¤Èª½©Á½ÌÅAÖðg¢ñ·æ¤ÉµÄsðí¸µ½B
QP¤ÉàL[fBXvC@\ðÇÁB
2010/09/19(Sun) AAQA~[AIÌßZÌßñßQ[Wð»B
ÇÂ\ÔÌQ[WÉÚ·èðÇÁB
2010/09/18(Sat) q
[S[ÌA[TgvXÆ~[gXJbV[yÑMKXu[J[Ì
L[üÍÆñ]^C}[ð»BMKXÍIðÌÝ\¦·éB
AbNXÌnCp[{ÌL[üÍÆñ]^C}[à»B±¿çàIðÌÝB
ÇÂ\ÔÌQ[WtßÉlà\¦·éæ¤Éµ½B
2010/09/17(Fli) tíÌASôrÌAÅñÆAÅ^C}[AXsoÌßñßQ[Wð»B
í¸lÆAÇÂ\Ôð»B
2010/09/15(Wed) AbNXÌAXbV
G{[ÆGAX^s[gÌßñßQ[Wð»B
L[fBXvC@\ðÇÁBXgSâJvGXÌzÆÍá¤B
]]
--æ\¦Ì×ÉKvÈLqÁÛ¢
require "gd"
--æðÇÝñŨ
blank = gd.createFromPng("resources/waza/blank.png"):gdStr()
blank2 = gd.createFromPng("resources/waza/blank2.png"):gdStr()
blank3 = gd.createFromPng("resources/waza/blank3.png"):gdStr()
alex_1 = gd.createFromPng("resources/waza/alex_1.png"):gdStr()
alex_2 = gd.createFromPng("resources/waza/alex_2.png"):gdStr()
alex_3 = gd.createFromPng("resources/waza/alex_3.png"):gdStr()
ryu_1 = gd.createFromPng("resources/waza/ryu_1.png"):gdStr()
chun_1 = gd.createFromPng("resources/waza/chun_1.png"):gdStr()
chun_2 = gd.createFromPng("resources/waza/chun_2.png"):gdStr()
chun_3 = gd.createFromPng("resources/waza/chun_3.png"):gdStr()
chun_4 = gd.createFromPng("resources/waza/chun_4.png"):gdStr()
hugo_1 = gd.createFromPng("resources/waza/hugo_1.png"):gdStr()
hugo_2 = gd.createFromPng("resources/waza/hugo_2.png"):gdStr()
hugo_3 = gd.createFromPng("resources/waza/hugo_3.png"):gdStr()
remy_1 = gd.createFromPng("resources/waza/remy_1.png"):gdStr()
remy_2 = gd.createFromPng("resources/waza/remy_2.png"):gdStr()
remy_3 = gd.createFromPng("resources/waza/remy_3.png"):gdStr()
q_1 = gd.createFromPng("resources/waza/q_1.png"):gdStr()
q_2 = gd.createFromPng("resources/waza/q_2.png"):gdStr()
oro_1 = gd.createFromPng("resources/waza/oro_1.png"):gdStr()
oro_2 = gd.createFromPng("resources/waza/oro_2.png"):gdStr()
urien_1 = gd.createFromPng("resources/waza/urien_1.png"):gdStr()
urien_2 = gd.createFromPng("resources/waza/urien_2.png"):gdStr()
urien_3 = gd.createFromPng("resources/waza/urien_3.png"):gdStr()
punch_1 = gd.createFromPng("resources/command/punch_1.png"):gdStr()
punch_2 = gd.createFromPng("resources/command/punch_2.png"):gdStr()
punch_3 = gd.createFromPng("resources/command/punch_3.png"):gdStr()
punch_1_2 = gd.createFromPng("resources/command/punch_1_2.png"):gdStr()
punch_2_2 = gd.createFromPng("resources/command/punch_2_2.png"):gdStr()
punch_3_2 = gd.createFromPng("resources/command/punch_3_2.png"):gdStr()
kick_1 = gd.createFromPng("resources/command/kick_1.png"):gdStr()
kick_2 = gd.createFromPng("resources/command/kick_2.png"):gdStr()
kick_3 = gd.createFromPng("resources/command/kick_3.png"):gdStr()
kick_1_2 = gd.createFromPng("resources/command/kick_1_2.png"):gdStr()
kick_2_2 = gd.createFromPng("resources/command/kick_2_2.png"):gdStr()
kick_3_2 = gd.createFromPng("resources/command/kick_3_2.png"):gdStr()
keyDisp2_dir0 = gd.createFromPng("resources/command/keyDisp2_dir0.png"):gdStr()
keyDisp2_dir1 = gd.createFromPng("resources/command/keyDisp2_dir1.png"):gdStr()
keyDisp2_dir0_real = gd.createFromPng("resources/command/keyDisp2_dir0_real.png"):gdStr()
keyDisp2_dir1_real = gd.createFromPng("resources/command/keyDisp2_dir1_real.png"):gdStr()
keyDisp2_lp1 = gd.createFromPng("resources/command/keyDisp2_lp1.png"):gdStr()
keyDisp2_lk1 = gd.createFromPng("resources/command/keyDisp2_lk1.png"):gdStr()
keyDisp2_l2 = gd.createFromPng("resources/command/keyDisp2_l2.png"):gdStr()
keyDisp2_mp1 = gd.createFromPng("resources/command/keyDisp2_mp1.png"):gdStr()
keyDisp2_mk1 = gd.createFromPng("resources/command/keyDisp2_mk1.png"):gdStr()
keyDisp2_m2 = gd.createFromPng("resources/command/keyDisp2_m2.png"):gdStr()
keyDisp2_hp1 = gd.createFromPng("resources/command/keyDisp2_hp1.png"):gdStr()
keyDisp2_hk1 = gd.createFromPng("resources/command/keyDisp2_hk1.png"):gdStr()
keyDisp2_h2 = gd.createFromPng("resources/command/keyDisp2_h2.png"):gdStr()
keyDisp2_hold1 = gd.createFromPng("resources/command/keyDisp2_hold1.png"):gdStr()
keyDisp2_hold2 = gd.createFromPng("resources/command/keyDisp2_hold2.png"):gdStr()
arrow_up1 = gd.createFromPng("resources/command/arrow_up1.png"):gdStr()
arrow_up2 = gd.createFromPng("resources/command/arrow_up2.png"):gdStr()
arrow_up3 = gd.createFromPng("resources/command/arrow_up3.png"):gdStr()
arrow_right1 = gd.createFromPng("resources/command/arrow_right1.png"):gdStr()
arrow_right2 = gd.createFromPng("resources/command/arrow_right2.png"):gdStr()
arrow_right3 = gd.createFromPng("resources/command/arrow_right3.png"):gdStr()
arrow_down1 = gd.createFromPng("resources/command/arrow_down1.png"):gdStr()
arrow_down2 = gd.createFromPng("resources/command/arrow_down2.png"):gdStr()
arrow_down3 = gd.createFromPng("resources/command/arrow_down3.png"):gdStr()
arrow_left1 = gd.createFromPng("resources/command/arrow_left1.png"):gdStr()
arrow_left2 = gd.createFromPng("resources/command/arrow_left2.png"):gdStr()
arrow_left3 = gd.createFromPng("resources/command/arrow_left3.png"):gdStr()
button_l1 = gd.createFromPng("resources/command/button_l1.png"):gdStr()
button_l2 = gd.createFromPng("resources/command/button_l2.png"):gdStr()
button_m1 = gd.createFromPng("resources/command/button_m1.png"):gdStr()
button_m2 = gd.createFromPng("resources/command/button_m2.png"):gdStr()
button_h1 = gd.createFromPng("resources/command/button_h1.png"):gdStr()
button_h2 = gd.createFromPng("resources/command/button_h2.png"):gdStr()
button_s1 = gd.createFromPng("resources/command/button_s1.png"):gdStr()
button_s2 = gd.createFromPng("resources/command/button_s2.png"):gdStr()
inputView_on = gd.createFromPng("resources/cheat/inputView_on.png"):gdStr()
inputView_off = gd.createFromPng("resources/cheat/inputView_off.png"):gdStr()
inputView_text = gd.createFromPng("resources/cheat/inputView_text.png"):gdStr()
tameView_on = gd.createFromPng("resources/cheat/tameView_on.png"):gdStr()
tameView_off = gd.createFromPng("resources/cheat/tameView_off.png"):gdStr()
tameView_text = gd.createFromPng("resources/cheat/tameView_text.png"):gdStr()
rendaView_on = gd.createFromPng("resources/cheat/rendaView_on.png"):gdStr()
rendaView_off = gd.createFromPng("resources/cheat/rendaView_off.png"):gdStr()
rendaView_text = gd.createFromPng("resources/cheat/rendaView_text.png"):gdStr()
kaitenView_on = gd.createFromPng("resources/cheat/kaitenView_on.png"):gdStr()
kaitenView_off = gd.createFromPng("resources/cheat/kaitenView_off.png"):gdStr()
kaitenView_text = gd.createFromPng("resources/cheat/kaitenView_text.png"):gdStr()
denjinView_on = gd.createFromPng("resources/cheat/denjinView_on.png"):gdStr()
denjinView_off = gd.createFromPng("resources/cheat/denjinView_off.png"):gdStr()
denjinView_text = gd.createFromPng("resources/cheat/denjinView_text.png"):gdStr()
BLView_on = gd.createFromPng("resources/cheat/BLView_on.png"):gdStr()
BLView_off = gd.createFromPng("resources/cheat/BLView_off.png"):gdStr()
BLView_text = gd.createFromPng("resources/cheat/BLView_text.png"):gdStr()
airTimerView_on = gd.createFromPng("resources/cheat/airTimerView_on.png"):gdStr()
airTimerView_off = gd.createFromPng("resources/cheat/airTimerView_off.png"):gdStr()
airTimerView_text = gd.createFromPng("resources/cheat/airTimerView_text.png"):gdStr()
longHitStop_on = gd.createFromPng("resources/cheat/longHitStop_on.png"):gdStr()
longHitStop_off = gd.createFromPng("resources/cheat/longHitStop_off.png"):gdStr()
longHitStop_text = gd.createFromPng("resources/cheat/longHitStop_text.png"):gdStr()
zeroHitStop_on = gd.createFromPng("resources/cheat/zeroHitStop_on.png"):gdStr()
zeroHitStop_off = gd.createFromPng("resources/cheat/zeroHitStop_off.png"):gdStr()
zeroHitStop_text = gd.createFromPng("resources/cheat/zeroHitStop_text.png"):gdStr()
trainingMode_on = gd.createFromPng("resources/cheat/trainingMode_on.png"):gdStr()
trainingMode_off = gd.createFromPng("resources/cheat/trainingMode_off.png"):gdStr()
trainingMode_text = gd.createFromPng("resources/cheat/trainingMode_text.png"):gdStr()
stunMax_on = gd.createFromPng("resources/cheat/stunMax_on.png"):gdStr()
stunMax_off = gd.createFromPng("resources/cheat/stunMax_off.png"):gdStr()
stunMax_text = gd.createFromPng("resources/cheat/stunMax_text.png"):gdStr()
combo = gd.createFromPng("resources/moji/combo.png"):gdStr()
maxCombo = gd.createFromPng("resources/moji/maxCombo.png"):gdStr()
maxDamage = gd.createFromPng("resources/moji/maxDamage.png"):gdStr()
totalDamage = gd.createFromPng("resources/moji/totalDamage.png"):gdStr()
cheat_on = gd.createFromPng("resources/cheat/cheat_on.png"):gdStr()
gaugeMax_on = gd.createFromPng("resources/cheat/gaugeMax_on.png"):gdStr()
gaugeMax_off = gd.createFromPng("resources/cheat/gaugeMax_off.png"):gdStr()
gaugeMax_text = gd.createFromPng("resources/cheat/gaugeMax_text.png"):gdStr()
airComboInf_on = gd.createFromPng("resources/cheat/airComboInf_on.png"):gdStr()
airComboInf_off = gd.createFromPng("resources/cheat/airComboInf_off.png"):gdStr()
airComboInf_text = gd.createFromPng("resources/cheat/airComboInf_text.png"):gdStr()
--tHg»ÌO
nums0 = {
gd.createFromPng("resources/num/num0_0.png"):gdStr(),
gd.createFromPng("resources/num/num0_1.png"):gdStr(),
gd.createFromPng("resources/num/num0_2.png"):gdStr(),
gd.createFromPng("resources/num/num0_3.png"):gdStr(),
gd.createFromPng("resources/num/num0_4.png"):gdStr(),
gd.createFromPng("resources/num/num0_5.png"):gdStr(),
gd.createFromPng("resources/num/num0_6.png"):gdStr(),
gd.createFromPng("resources/num/num0_7.png"):gdStr(),
gd.createFromPng("resources/num/num0_8.png"):gdStr(),
gd.createFromPng("resources/num/num0_9.png"):gdStr()
}
--L[fBXvCQÌo[
keyDisp2Reba = {
gd.createFromPng("resources/command/keyDisp2_reba1_1.png"):gdStr(),
gd.createFromPng("resources/command/keyDisp2_reba1_2.png"):gdStr(),
gd.createFromPng("resources/command/keyDisp2_reba1_3.png"):gdStr(),
gd.createFromPng("resources/command/keyDisp2_reba1_4.png"):gdStr(),
gd.createFromPng("resources/command/keyDisp2_reba1_5.png"):gdStr(),
gd.createFromPng("resources/command/keyDisp2_reba1_6.png"):gdStr(),
gd.createFromPng("resources/command/keyDisp2_reba1_7.png"):gdStr(),
gd.createFromPng("resources/command/keyDisp2_reba1_8.png"):gdStr(),
gd.createFromPng("resources/command/keyDisp2_reba1_9.png"):gdStr()
}
--üÍÌü«ð\·Ï
local input_dir
--OÌüÍ©çoßµ½t[ð\·Ï
local reba_flame_from_before_input1P = 0
local button_flame_from_before_input1P = 0
local reba_flame_from_before_input2P = 0
local button_flame_from_before_input2P = 0
--
before_time_in_game1P = 1234
before_time_in_game2P = 1234
time_in_game1P = 5678
time_in_game2P = 5678
--o[ÌüÍóÔð\·Ï
local input_up, input_down, input_right, input_left
--{^ÌüÍóÔð\·Ï
local input_lp, input_mp, input_hp, input_lk, input_mk, input_hk
--1t[OÌüÍðÛ¶µÄ¨Ï
local before_reba1P = 0
local before_input_lp1P = 0
local before_input_mp1P = 0
local before_input_hp1P = 0
local before_input_lk1P = 0
local before_input_mk1P = 0
local before_input_hk1P = 0
local before_reba2P = 0
local before_input_lp2P = 0
local before_input_mp2P = 0
local before_input_hp2P = 0
local before_input_lk2P = 0
local before_input_mk2P = 0
local before_input_hk2P = 0
--o[Ìæt@C¼Ég¤Ï
local reba_num
--X^[g{^ª½b³ê½©
startButton = 0
--`[gZNgæÊ©Ç¤©
cheatModeNum = 0
--eXÌ`[gtOBúÌIItͱ±ÅØè֦ܵå¤
inputView = 0
tameView = 0
rendaView = 0
kaitenView = 0
denjinView = 1
BLView = 0
airTimerView = 1
trainingMode = 0
stunMax = 0
gaugeMax = 0
airComboInf = 0
longHitStop = 0
zeroHitStop = 0
--`[gj
[Ú
menu = {
{inputView_off, trainingMode_off, 0},
{tameView_off, stunMax_off, gaugeMax_off},
{rendaView_off, 0, airComboInf_off},
{kaitenView_off, 0, longHitStop_off},
{denjinView_off, 0, zeroHitStop_off},
{BLView_off, 0, 0},
{airTimerView_off, 0, 0}
}
--`[gÌà¾
cheatText = {
{inputView_text, trainingMode_text, 0},
{tameView_text, stunMax_text, gaugeMax_text},
{rendaView_text, 0, airComboInf_text},
{kaitenView_text, 0, longHitStop_text},
{denjinView_text, 0, zeroHitStop_text},
{BLView_text, 0, 0},
{airTimerView_text, 0, 0}
}
--`[g[hÌJ[\
cursorX = 1
cursorY = 1
--e{^ðµÄ¢éÔÌ·³
up_count = 0
down_count = 0
right_count = 0
left_count = 0
button_count = 0
lp_count = 0
mp_count = 0
hp_count = 0
lk_count = 0
mk_count = 0
hk_count = 0
--»Ìt[ÅÌoK`li³üÍÌÆ«Ét[P¸é×AúlðPɵĢéj
gachaValue1 = 1
gachaValue2 = 1
gachaValue3 = 1
gachaValue4 = 1
--ß31t[ÌoK`lB
--PF ½è̽ÏoK`lðÆé×Ég¤
previousGachaValue1s = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
previousGachaValue2s = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
previousGachaValue3s = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
previousGachaValue4s = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
--g[jO[hÌ`[gÉg¤JE^[Æ©
trainingModeCount = 0
maxDamagevalue = 0
maxCombovalue = 0
--qbgXgbvÌ`[gÉg¤JE^[
hitStopCount = 0
zeroStopCount = 0
--L[fBXvCQÌüÍðüê
keyDisplay2_box1P = {
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
}
keyDisplay2_box2P = {
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
{"","","0000000"},
}
--L[fBXvCQ̳üÍÔ
no_input_time1P = 0
no_input_time2P = 0
no_input_limit = 300
--»Ì{^ª³êÄ¢éÆAJEgðPâµÄÔ·¾¯ÌÖ
function buttonCount(button, count)
if button == 1 then
count = count + 1
else
count = 0
end
return count
end
--J[\ÌÊuɶÄ`[gðIItµÂÂ`[góÔðÔ·Ö
function cursorToCheat(x,y,cheat,onImage,offImage)
if cursorX == x and cursorY == y then
cheat = (cheat - 1)^2
if cheat == 1 then
menu[y][x] = onImage
else
menu[y][x] = offImage
end
end
return cheat
end
--oK`ûKÌð·éÖ
function gachaTrainingMode()
--Ôݽ¢Èæð\¦
gui.image(0,0,blank3)
--»ÝÌüÍóÔðA1Â1ÂÌÏɪ¯é
input_up = bitReturn(memory.readbyte(0x0202564B),0)
input_down = bitReturn(memory.readbyte(0x0202564B),1)
input_left = bitReturn(memory.readbyte(0x0202564B),2)
input_right = bitReturn(memory.readbyte(0x0202564B),3)
input_lp = bitReturn(memory.readbyte(0x0202564B),4)
input_mp = bitReturn(memory.readbyte(0x0202564B),5)
input_hp = bitReturn(memory.readbyte(0x0202564B),6)
input_lk = bitReturn(memory.readbyte(0x0202564B-1),0)
input_mk = bitReturn(memory.readbyte(0x0202564B-1),1)
input_hk = bitReturn(memory.readbyte(0x0202564B-1),2)
--æð\¦·éƫƩÌîÀWðZbg
offsetX = 40
offsetY = 80
--e{^ÌJE^[Bµ±¯Ä¢éƦA£·ÆOÉÈéB
--ÂÜèAJE^[ªP̪{^ðµ½Æ¢¤ÉÈéB
up_count = buttonCount(input_up, up_count)
down_count = buttonCount(input_down, down_count)
right_count = buttonCount(input_right, right_count)
left_count = buttonCount(input_left, left_count)
lp_count = buttonCount(input_lp, lp_count)
mp_count = buttonCount(input_mp, mp_count)
hp_count = buttonCount(input_hp, hp_count)
lk_count = buttonCount(input_lk, lk_count)
mk_count = buttonCount(input_mk, mk_count)
hk_count = buttonCount(input_hk, hk_count)
--»Ìt[ÅÌoK`lB
--àÆàÆsè^C}[âdn^C}[Ít[P¸ÁÄ¢éÌÅAftHÅPɵĢéB
gachaValue1 = 1
gachaValue2 = 0
gachaValue3 = 1
gachaValue4 = 1
--ßRPt[ÌoK`lvB
--½Ïlðo·½ßÉg¤B
sumGachaValue1 = 0
sumGachaValue2 = 0
sumGachaValue3 = 0
sumGachaValue4 = 0
--o[㪳ê½çAoK`lðâ·
--dnÌÝA¯ûüüÍÌðs¤B
if up_count == 1 then
gachaValue1 = gachaValue1 + 2
gachaValue2 = gachaValue2 + 4
--¡ûüà¯Éü͵½Æ«ÍÁÊRAPÌÌÆ«ÍQB
if right_count == 1 or left_count == 1 then
gachaValue3 = gachaValue3 + 3
else
gachaValue3 = gachaValue3 + 2
end
end
if down_count == 1 then
gachaValue1 = gachaValue1 + 2
gachaValue2 = gachaValue2 + 4
if right_count == 1 or left_count == 1 then
gachaValue3 = gachaValue3 + 3
else
gachaValue3 = gachaValue3 + 2
end
end
if right_count == 1 then
gachaValue1 = gachaValue1 + 2
gachaValue2 = gachaValue2 + 4
--PÌÅüÍ³ê½Æ«ÌÝÁÊQB
--¯üÍÌÍãÌûÅâÁÄ¢éÌÅAà¤âçÈ¢
if up_count ~=1 and down_count ~= 1 then
gachaValue3 = gachaValue3 + 2
end
end
if left_count == 1 then
gachaValue1 = gachaValue1 + 2
gachaValue2 = gachaValue2 + 4
if up_count ~=1 and down_count ~= 1 then
gachaValue3 = gachaValue3 + 2
end
end
--p`{^ª³ê½çAoK`lðâ·
if lp_count == 1 then
gachaValue1 = gachaValue1 + 1
gachaValue2 = gachaValue2 + 2
gachaValue3 = gachaValue3 + 1
end
if mp_count == 1 then
gachaValue1 = gachaValue1 + 1
gachaValue2 = gachaValue2 + 2
gachaValue3 = gachaValue3 + 1
end
if hp_count == 1 then
gachaValue1 = gachaValue1 + 1
gachaValue2 = gachaValue2 + 2
gachaValue3 = gachaValue3 + 1
end
--¬LbNªPÌÅ³ê½Æ«
if lk_count == 1 then
--¼ÌLbNÆ¯É³ê½Æ«
if mk_count == 1 or hk_count == 1 then
gachaValue1 = gachaValue1 + 1
gachaValue3 = gachaValue3 + 1
end
gachaValue2 = gachaValue2 + 1
else
--¬LbNª³êĨç¸A¼ÌLbNªQÂ¯É³ê½Æ«
if mk_count == 1 and hk_count == 1 then
gachaValue1 = gachaValue1 + 1
gachaValue3 = gachaValue3 + 1
end
end
--LbNªPÌÅ³ê½Æ«
if mk_count == 1 then
if lk_count ~=1 and hk_count ~= 1 then
gachaValue2 = gachaValue2 + 1
end
end
--LbNªPÌÅ³ê½Æ«
if hk_count == 1 then
if lk_count ~=1 and mk_count ~= 1 then
gachaValue2 = gachaValue2 + 1
end
end
--ßÌoK`lÌaðo·B
for i=1,31,1 do
sumGachaValue1 = sumGachaValue1 + previousGachaValue1s[i]
sumGachaValue2 = sumGachaValue2 + previousGachaValue2s[i]
sumGachaValue3 = sumGachaValue3 + previousGachaValue3s[i]
end
--ÅãÉA»ÝÌoK`lð«·B
sumGachaValue1 = sumGachaValue1 + gachaValue1
sumGachaValue2 = sumGachaValue2 + gachaValue2
sumGachaValue3 = sumGachaValue3 + gachaValue3
--p`{^ªPÂàµÁÏȵÅÈ©Á½çAdnͳø
if lp_count <= 1 and mp_count <= 1 and hp_count <= 1 then
sumGachaValue3 = 32
for i=1,31,1 do
previousGachaValue3s[i] = 1
end
gachaValue3 = 1
end
--oK`lɶÄQ[Wð\¦·éB
tateGauge(alex_1,80,160,16,120,(sumGachaValue1/32)-1,2,1,0xFFFF00FF)
tateGauge(alex_1,160,160,16,120,(sumGachaValue2/32),4,0,0xFF4444FF)
tateGauge(alex_1,240,160,16,120,(sumGachaValue3/32)-1,2,1,0x00FFFFFF)
--oK`lPªPæèå«¢i³üÍÅÈ¢jÆ«ÍAoK`lð\¦
if gachaValue1 > 1 then
drawOriginNum(nums0, 80-4, 20, gachaValue1, 2, 10)
end
if gachaValue2 > 0 then
drawOriginNum(nums0, 160-4, 20, gachaValue2, 2, 10)
end
if gachaValue3 > 1 then
drawOriginNum(nums0, 240-4, 20, gachaValue3, 2, 10)
end
--ßÌoK`lði[µÄ¢ézñÌgðãëÉP¸çµA
--»ÝÌoK`lðæªÉi[·éB
for i=31,2,-1 do
previousGachaValue1s[i] = previousGachaValue1s[i-1]
previousGachaValue2s[i] = previousGachaValue2s[i-1]
previousGachaValue3s[i] = previousGachaValue3s[i-1]
end
previousGachaValue1s[1] = gachaValue1
previousGachaValue2s[1] = gachaValue2
previousGachaValue3s[1] = gachaValue3
end
--`[g[hÌð·éÖ
function cheatMode()
gui.image(0,0,blank3)
input_up = bitReturn(memory.readbyte(0x0202564B),0)
input_down = bitReturn(memory.readbyte(0x0202564B),1)
input_left = bitReturn(memory.readbyte(0x0202564B),2)
input_right = bitReturn(memory.readbyte(0x0202564B),3)
input_lp = bitReturn(memory.readbyte(0x0202564B),4)
input_mp = bitReturn(memory.readbyte(0x0202564B),5)
input_hp = bitReturn(memory.readbyte(0x0202564B),6)
input_lk = bitReturn(memory.readbyte(0x0202564B-1),0)
input_mk = bitReturn(memory.readbyte(0x0202564B-1),1)
input_hk = bitReturn(memory.readbyte(0x0202564B-1),2)
offsetX = 20
offsetY = 20
--J[\ÌÊuɶÄA`[gÚðÔÅÍÞ
gui.drawbox(offsetX-2+108*(cursorX-1),offsetY-2+24*(cursorY-1),offsetX+100+1+108*(cursorX-1),offsetY+20+1+24*(cursorY-1),0xFF0000FF,0xFF0000FF)
--`[gÚæð·×Ä\¦·é
--zñ¼ÌOÉ#ªÂÆAzñÌvfÆ¢¤Ó¡ÉÈéB
for i=1,#menu,1 do
for j=1,#menu[i],1 do
if menu[i][j] ~= 0 then
gui.image(offsetX, offsetY, menu[i][j])
end
offsetX = offsetX + 108
end
offsetX = 20
offsetY = offsetY + 24
end
gui.image(20,194,cheatText[cursorY][cursorX])
--Cvbg`FbN
up_count = buttonCount(input_up, up_count)
down_count = buttonCount(input_down, down_count)
right_count = buttonCount(input_right, right_count)
left_count = buttonCount(input_left, left_count)
if input_lp == 1 or input_mp == 1 or input_hp == 1 or input_lk == 1 or input_mk == 1 or input_hk == 1 then
button_count = button_count + 1
else
button_count = 0
end
--ãðµ½çorµÁÏȵ¾Á½ç
if up_count == 1 or (up_count >= 20 and up_count % 6 == 0) then
--J[\ðãÉÚ®
cursorY = cursorY - 1
--êÔãðz¦½çêÔºÉÚ®
if cursorY == 0 then
cursorY = #menu
end
--Ú®æÉÚª¶ÝµÈ¯êÎ
while menu[cursorY][cursorX] == 0 do
--XÉêÂæÖÚ®·é
cursorY = cursorY - 1
--êÔãðz¦½çêÔºÉÚ®
if cursorY == 0 then
cursorY = #menu
end
end
end
--ºðµ½çorµÁÏȵ¾Á½ç
if down_count == 1 or (down_count >= 20 and down_count % 6 == 0) then
cursorY = cursorY + 1
if cursorY == #menu+1 then
cursorY = 1
end
while menu[cursorY][cursorX] == 0 do
cursorY = cursorY + 1
if cursorY == #menu+1 then
cursorY = 1
end
end
end
--Eðµ½çorµÁÏȵ¾Á½ç
if right_count == 1 or (right_count >= 20 and right_count % 6 == 0) then
cursorX = cursorX + 1
if cursorX == #menu[cursorY]+1 then
cursorX = 1
end
while menu[cursorY][cursorX] == 0 do
cursorX = cursorX + 1
if cursorX == #menu[cursorY]+1 then
cursorX = 1
end
end
end
--¶ðµ½çorµÁÏȵ¾Á½ç
if left_count == 1 or (left_count >= 20 and left_count % 6 == 0) then
cursorX = cursorX - 1
if cursorX == 0 then
cursorX = #menu[cursorY]
end
while menu[cursorY][cursorX] == 0 do
cursorX = cursorX - 1
if cursorX == 0 then
cursorX = #menu[cursorY]
end
end
end
if button_count == 1 or (button_count >= 20 and button_count % 6 == 0) then
inputView = cursorToCheat(1,1,inputView,inputView_on,inputView_off)
tameView = cursorToCheat(1,2,tameView,tameView_on,tameView_off)
rendaView = cursorToCheat(1,3,rendaView,rendaView_on,rendaView_off)
kaitenView = cursorToCheat(1,4,kaitenView,kaitenView_on,kaitenView_off)
denjinView = cursorToCheat(1,5,denjinView,denjinView_on,denjinView_off)
BLView = cursorToCheat(1,6,BLView,BLView_on,BLView_off)
airTimerView = cursorToCheat(1,7,airTimerView,airTimerView_on,airTimerView_off)
trainingMode = cursorToCheat(2,1,trainingMode,trainingMode_on,trainingMode_off)
stunMax = cursorToCheat(2,2,stunMax,stunMax_on,stunMax_off)
gaugeMax = cursorToCheat(3,2,gaugeMax,gaugeMax_on,gaugeMax_off)
airComboInf = cursorToCheat(3,3,airComboInf,airComboInf_on,airComboInf_off)
longHitStop = cursorToCheat(3,4,longHitStop,longHitStop_on,longHitStop_off)
zeroHitStop = cursorToCheat(3,5,zeroHitStop,zeroHitStop_on,zeroHitStop_off)
end
end
--********lvalueÌAbitnumÔÚÌrbgðÔ·Ö********
--@param value ²×½¢Ï
--@param bitnum ½ÔÚð²×½¢©iźÊ
Í0j
function bitReturn(value,bitnum)
re = value
--bitnumæèãÊ
ðØèÌÄé
re = SHIFT(re,bitnum-31)
--bitnumæèºÊ
ðØèÌÄé
re = SHIFT(re,31)
return re
end
--********ßñßQ[Wð\¦·éÖ********
--@param image Q[W̶É\¦·éæiZ¼ACRj
--@param x úxÀW
--@param y úyÀW
--@param address_tame ßt[ðǵĢéAhX
--@param address_timer ñßt[ðǵĢéAhX
function tameGauge(image, x, y, address_tame, address_timer)
--æð\¦ixÀW, yÀW, æÌüÁ½Ï¼jB
gui.image(4,y-3,image)
--ªòFßt[ªFFÅȯêÎ
if memory.readbyte(address_tame) ~= 0xFF then
--lp`ð\¦in_ÌxÀW, n_ÌyÀW, I_ÌxÀW, I_ÌyÀW, gÌF, gÌFjB
--FͶ©çQ
¸ÂuÔvuÎvuÂvus§¾xvB
--s§¾xð00©FFÈOÉ·éÆA®ìªÉ[ÉdÈéÌÅÓB
--gð̧¾AgðÌs§¾ÉµÄ¢éÌÅA±ÌlpÍo[ÌgªB
gui.drawbox(x,y,x+84,y+6,0x00000000,0x000000FF)
--lp`ð\¦B
--gð
FÌs§¾Agð̧¾ÉµÄ¢éÌÅA±ÌlpÍo[ÌgªB
gui.drawbox(x,y,x+(memory.readbyte(address_tame)*2),y+6,0x0080FFFF,0x000000FF)
--ßt[ªFFÅ êÎ
else
--¢g¾¯\¦·éB
gui.drawbox(x,y,x+84,y+6,0x00000000,0xFFFFFFFF)
end
--Íñßt[̪à`æµ½¢ÌÅAcÀWð8hbg¸ç·
y = y + 8
--ªòFñßt[ªFFÅȯêÎ
if memory.readbyte(address_timer) ~= 0xFF then
--lp`ð\¦B
--gð̧¾AgðÌs§¾ÉµÄ¢éÌÅA±ÌlpÍo[ÌgªB
gui.drawbox(x,y,x+84,y+6,0x00000000,0x000000FF)
--lp`ð\¦B
--gðIWFÌs§¾Agð̧¾ÉµÄ¢éÌÅA±ÌlpÍo[ÌgªB
gui.drawbox(x,y,x+(memory.readbyte(address_timer)*2),y+6,0xFF8000FF,0x000000FF)
--G{[Ìñßt[ªFFÅ êÎ
else
--¢g¾¯\¦·éB
gui.drawbox(x,y,x+84,y+6,0x00000000,0x000000FF)
end
end
--********c^ÌQ[Wð\¦·éÖ********
--@param image Q[WÌßÉ\¦·éæ
--@param x úxÀW
--@param y úyÀW
--@param xLen x·³
--@param yLen y·³
--@param value l
--@param maxValue Åål
--@param offset lÌY
--@param color FiÔAÎAÂAs§¾xj
function tateGauge(image, x, y, xLen, yLen, value, maxValue, offset, color)
gui.drawbox(x-1,y+1,x+xLen+1,y-yLen-1,0x00000000,0xFFFFFFFF)
gui.drawbox(x,y,x+xLen,y-yLen,0x00000000,0x000000FF)
gui.drawbox(x,y,x+xLen,y-(yLen*(value/maxValue)),color,0x00000000)
gui.drawtext(x+xLen+4,y-(yLen*(value/maxValue)),value+offset)
end
--********¡^ÌQ[Wð\¦·éÖ********
--@param image Q[WÌßÉ\¦·éæ
--@param x úxÀW
--@param y úyÀW
--@param xLen x·³
--@param yLen y·³
--@param value l
--@param maxValue Åål
--@param offset lÌY
--@param color FiÔAÎAÂAs§¾xj
function yokoGauge(image, x, y, xLen, yLen, value, maxValue, offset, color)
gui.drawbox(x-1,y-1,x+xLen+1,y+yLen+1,0x00000000,0xFFFFFFFF)
gui.drawbox(x,y,x+xLen,y+yLen,0x000000FF,0x000000FF)
gui.drawbox(x-1,y-1,x+((xLen+1)*(value/maxValue)),y+yLen+1,color,0x00000000)
gui.drawtext(x+(xLen*(value/maxValue)),y+yLen,value+offset)
end
function yokoGauge2(image, x, y, xLen, yLen, value, maxValue, offset, color)
gui.drawbox(x-1,y-1,x+xLen+1,y+yLen+1,0x00000000,0xFFFFFFFF)
gui.drawbox(x,y,x+xLen,y+yLen,0x000000FF,0x000000FF)
gui.drawbox(x-1,y-1,x+((xLen+1)*(value/maxValue)),y+yLen+1,color,0x00000000)
gui.drawtext(x+xLen+3,y-1,value+offset)
end
--********o[êñ]ZÌîóÆ^C}[ð\¦·éÖ********
--@param image Z¼ACRÌæ
--@param x úxÀW
--@param y úyÀW
--@param address_juji o[üÍðǵĢéAhX
--@param address_timer ^C}[ðǵĢéAhX
function kaiten(image, x, y, address_juji, address_timer)
gui.image(4,y-3,image)
juji_up = bitReturn(memory.readbyte(address_juji),0)
juji_down = bitReturn(memory.readbyte(address_juji),1)
juji_right = bitReturn(memory.readbyte(address_juji),2)
juji_left = bitReturn(memory.readbyte(address_juji),3)
--ãûüªüÍÏÝÅ êÎ
if juji_up == 1 then
gui.image(x+48,y-12,arrow_up3)
else
gui.image(x+48,y-12,arrow_up1)
end
--ºûüªüÍÏÝÅ êÎ
if juji_down == 1 then
gui.image(x+24,y-12,arrow_down3)
else
gui.image(x+24,y-12,arrow_down1)
end
--EûüªüÍÏÝÅ êÎ
if juji_right == 1 then
gui.image(x+72,y-12,arrow_right3)
else
gui.image(x+72,y-12,arrow_right1)
end
--¶ûüªüÍÏÝÅ êÎ
if juji_left == 1 then
gui.image(x,y-12,arrow_left3)
else
gui.image(x,y-12,arrow_left1)
end
gui.drawbox(x,y+12,x+96,y+18,0x00000000,0x000000FF)
gui.drawbox(x,y+12,x+(memory.readbyte(address_timer)*3),y+18,0x00C080FF,0x000000FF)
end
--********SôrÌ{^ACRð\¦·éÖ********
--@param image Z¼ACRÌæ
--@param image_button1 ³ê½Æ«Ì{^ACR
--@param image_button2 ³êĢȢƫÌ{^ACR
--@param x úxÀW
--@param y úyÀW
--@param address_count {^ðµ½ñðǵĢéAhX
function hyakuretsu(image, image_button1, image_button2, x, y, address_count)
gui.image(4,y-3,image)
for i = 1, memory.readbyte(address_count), 1 do
gui.image(x,y-3,image_button1)
x = x + 24
end
for i = 1, 4-memory.readbyte(address_count), 1 do
gui.image(x,y-3,image_button2)
x = x + 24
end
end
--*******L[fBXvC»ÌP*******
function keyDisplay(image_l1, image_l2, image_m1, image_m2, image_h1, image_h2, image_s1, image_s2, x, y, buttonAddress,startAddress)
--üÍÌàeðA»ê¼êÌÏɪ¯Äí©èâ··é
input_up = bitReturn(memory.readbyte(buttonAddress),0)
input_down = bitReturn(memory.readbyte(buttonAddress),1)
input_left = bitReturn(memory.readbyte(buttonAddress),2)
input_right = bitReturn(memory.readbyte(buttonAddress),3)
input_lp = bitReturn(memory.readbyte(buttonAddress),4)
input_mp = bitReturn(memory.readbyte(buttonAddress),5)
input_hp = bitReturn(memory.readbyte(buttonAddress),6)
input_lk = bitReturn(memory.readbyte(buttonAddress-1),0)
input_mk = bitReturn(memory.readbyte(buttonAddress-1),1)
input_hk = bitReturn(memory.readbyte(buttonAddress-1),2)
input_s = (memory.readbyte(startAddress) - (memory.readbyte(startAddress) % 16)) / 16
--üÍóÔÉæÁÄA\¦·éæÔðè·é
if input_up == 1 then
if input_right == 1 then
reba_num = 9
elseif input_left == 1 then
reba_num = 7
else
reba_num = 8
end
elseif input_down == 1 then
if input_right == 1 then
reba_num = 3
elseif input_left == 1 then
reba_num = 1
else
reba_num = 2
end
elseif input_right == 1 then
reba_num = 6
elseif input_left == 1 then
reba_num = 4
else
reba_num = 5
end
--æÌÇÝÝÆ\¦ð¯ÉsÁÄ¢é
reba = gd.createFromPng("resources/command/reba"..reba_num..".png"):gdStr()
gui.image(x, y, reba)
x = x + 24
--üÍɶÄ{^ðõç¹é
if input_lp == 1 then
gui.image(x, y, image_l2)
else
gui.image(x, y, image_l1)
end
x = x + 12
if input_mp == 1 then
gui.image(x, y, image_m2)
else
gui.image(x, y, image_m1)
end
x = x + 12
if input_hp == 1 then
gui.image(x, y, image_h2)
else
gui.image(x, y, image_h1)
end
x = x - 12 - 12 + 2
y = y + 12
if input_lk == 1 then
gui.image(x, y, image_l2)
else
gui.image(x, y, image_l1)
end
x = x + 12
if input_mk == 1 then
gui.image(x, y, image_m2)
else
gui.image(x, y, image_m1)
end
x = x + 12
if input_hk == 1 then
gui.image(x, y, image_h2)
else
gui.image(x, y, image_h1)
end
x = x + 16
y = y - 8
if input_s == 1 then
gui.image(x, y, image_s2)
else
gui.image(x, y, image_s1)
end
end
--*******L[fBXvC»ÌQÌQ*******
function keyDisplay2_2(image_l1, image_l2, image_m1, image_m2, image_h1, image_h2, image_s1, image_s2, x, y, player)
dispNumber=16
offsetX1P2P = 270
if player == 1 then
--Q[àÔÌæ¤ÈàÌ
before_time_in_game1P = time_in_game1P
time_in_game1P = memory.readbyte(0x020157CF)
--Q[àÅÔªoÁÄ¢½çAüÍððXVµ½¢
if before_time_in_game1P ~= time_in_game1P then
reba_flame_from_before_input1P = reba_flame_from_before_input1P+1
button_flame_from_before_input1P = button_flame_from_before_input1P+1
buttonAddress = 0x0202564B
startAddress = 0x0206AA8C
dirAddress = 0x2068C77
--LÌü«
direction1P = memory.readbyte(dirAddress)
--üÍÌàeðA»ê¼êÌÏɪ¯Äí©èⷵĨ
input_up = bitReturn(memory.readbyte(buttonAddress),0)
input_down = bitReturn(memory.readbyte(buttonAddress),1)
input_left = bitReturn(memory.readbyte(buttonAddress),2)
input_right = bitReturn(memory.readbyte(buttonAddress),3)
input_lp1P = bitReturn(memory.readbyte(buttonAddress),4)
input_mp1P = bitReturn(memory.readbyte(buttonAddress),5)
input_hp1P = bitReturn(memory.readbyte(buttonAddress),6)
input_lk1P = bitReturn(memory.readbyte(buttonAddress-1),0)
input_mk1P = bitReturn(memory.readbyte(buttonAddress-1),1)
input_hk1P = bitReturn(memory.readbyte(buttonAddress-1),2)
input_s = (memory.readbyte(startAddress) - (memory.readbyte(startAddress) % 16)) / 16
if input_down==1 and input_right==0 and input_left==1 then
reba1P = 1
end
if input_down==1 and input_right==0 and input_left==0 then
reba1P = 2
end
if input_down==1 and input_right==1 and input_left==0 then
reba1P = 3
end
if input_up==0 and input_down==0 and input_left==1 then
reba1P = 4
end
if input_up==0 and input_down==0 and input_right==0 and input_left==0 then
reba1P = 5
end
if input_down==0 and input_right==1 and input_left==0 then
reba1P = 6
end
if input_up==1 and input_right==0 and input_left==1 then
reba1P = 7
end
if input_up==1 and input_right==0 and input_left==0 then
reba1P = 8
end
if input_up==1 and input_right==1 and input_left==0 then
reba1P = 9
end
if input_down==1 and input_right==1 and input_left==1 then
reba1P = 3
end
--»ÝÌóÔâüÍðêIÉi[µÄ¨½ßÌ
input_temp = {0,0,"",0}
input_temp[1] = reba_flame_from_before_input1P
input_temp[4] = button_flame_from_before_input1P
input_temp[2] = direction1P
input_temp[3] = reba1P..input_lp..input_mp..input_hp..input_lk..input_mk..input_hk
--½©ªüͳê½çAzñðP¸ç·
if (reba1P ~= before_reba1P and reba1P ~= 5)
or input_lp1P > before_input_lp1P
or input_mp1P > before_input_mp1P
or input_hp1P > before_input_hp1P
or input_lk1P > before_input_lk1P
or input_mk1P > before_input_mk1P
or input_hk1P > before_input_hk1P then
for i = dispNumber, 2, -1 do
keyDisplay2_box1P[i] = keyDisplay2_box1P[i-1]
end
--o[Ìüͪ³êÄ¢½ç
if (reba1P ~= before_reba1P and reba1P ~= 5) then
reba_flame_from_before_input1P = 0
end
--{^Ìüͪ³êÄ¢½ç
if input_lp1P > before_input_lp1P
or input_mp1P > before_input_mp1P
or input_hp1P > before_input_hp1P
or input_lk1P > before_input_lk1P
or input_mk1P > before_input_mk1P
or input_hk1P > before_input_hk1P then
button_flame_from_before_input1P = 0
end
--zñÌPÂÚÉA»ÝÌüÍði[·é
keyDisplay2_box1P[1] = input_temp
if reba_flame_from_before_input1P ~= 0 then
keyDisplay2_box1P[1][1] = 0
end
if button_flame_from_before_input1P ~= 0 then
keyDisplay2_box1P[1][4] = 0
end
no_input_time1P = 0
end
if reba1P == 5
and input_lp1P == 0
and input_mp1P == 0
and input_hp1P == 0
and input_lk1P == 0
and input_mk1P == 0
and input_hk1P == 0 then
--½àüͳêĢȯêÎA³üÍÔðâ·
no_input_time1P = no_input_time1P+1
if no_input_time1P > no_input_limit then
for i = 1, dispNumber-1, 1 do
keyDisplay2_box1P[i]={"","","0000000"}
end
no_input_time1P = 0
end
end
before_reba1P = reba1P
before_input_lp1P = input_lp1P
before_input_mp1P = input_mp1P
before_input_hp1P = input_hp1P
before_input_lk1P = input_lk1P
before_input_mk1P = input_mk1P
before_input_hk1P = input_hk1P
end
--æ£ÁÄ`æ
offsetY=46
if direction1P == 0 then
gui.image(42,36,keyDisp2_dir0_real)
else
gui.image(42,36,keyDisp2_dir1_real)
end
for i = 1, dispNumber-1, 1 do
reba1P = string.sub(keyDisplay2_box1P[i][3],1,1)+0
--üÍðª Á½ç
if reba1P ~= 0 then
offsetX=2
if keyDisplay2_box1P[i][1] ~= 0 then
gui.text(offsetX,offsetY+6,numSpaceLeft(keyDisplay2_box1P[i][1],4))
end
offsetX=offsetX+16
if keyDisplay2_box1P[i][4] ~= 0 then
gui.text(offsetX,offsetY+6,numSpaceLeft(keyDisplay2_box1P[i][4],4))
end
offsetX=offsetX+16
if keyDisplay2_box1P[i][2] == 0 then
gui.image(offsetX,offsetY,keyDisp2_dir0)
else
gui.image(offsetX,offsetY,keyDisp2_dir1)
end
offsetX=offsetX+16
gui.image(offsetX,offsetY,keyDisp2Reba[reba1P])
offsetX=offsetX+12
if string.sub(keyDisplay2_box1P[i][3],2,2)+0 == 1 then
gui.image(offsetX,offsetY,keyDisp2_lp1)
offsetX=offsetX+8
end
if string.sub(keyDisplay2_box1P[i][3],3,3)+0 == 1 then
gui.image(offsetX,offsetY,keyDisp2_mp1)
offsetX=offsetX+8
end
if string.sub(keyDisplay2_box1P[i][3],4,4)+0 == 1 then
gui.image(offsetX,offsetY,keyDisp2_hp1)
offsetX=offsetX+8
end
if string.sub(keyDisplay2_box1P[i][3],5,5)+0 == 1 then
gui.image(offsetX,offsetY,keyDisp2_lk1)
offsetX=offsetX+8
end
if string.sub(keyDisplay2_box1P[i][3],6,6)+0 == 1 then
gui.image(offsetX,offsetY,keyDisp2_mk1)
offsetX=offsetX+8
end
if string.sub(keyDisplay2_box1P[i][3],7,7)+0 == 1 then
gui.image(offsetX,offsetY,keyDisp2_hk1)
offsetX=offsetX+8
end
offsetY=offsetY+9
end
end
else
--Q[àÔÌæ¤ÈàÌ
before_time_in_game2P = time_in_game2P
time_in_game2P = memory.readbyte(0x020157CF)
--Q[àÅÔªoÁÄ¢½çAüÍððXVµ½¢
if before_time_in_game2P ~= time_in_game2P then
reba_flame_from_before_input2P = reba_flame_from_before_input2P+1
button_flame_from_before_input2P = button_flame_from_before_input2P+1
buttonAddress = 0x0202568F
startAddress = 0x0206AA90
dirAddress = 0x0206910F
--LÌü«
direction2P = memory.readbyte(dirAddress)
--üÍÌàeðA»ê¼êÌÏɪ¯Äí©èⷵĨ
input_up = bitReturn(memory.readbyte(buttonAddress),0)
input_down = bitReturn(memory.readbyte(buttonAddress),1)
input_left = bitReturn(memory.readbyte(buttonAddress),2)
input_right = bitReturn(memory.readbyte(buttonAddress),3)
input_lp2P = bitReturn(memory.readbyte(buttonAddress),4)
input_mp2P = bitReturn(memory.readbyte(buttonAddress),5)
input_hp2P = bitReturn(memory.readbyte(buttonAddress),6)
input_lk2P = bitReturn(memory.readbyte(buttonAddress-1),0)
input_mk2P = bitReturn(memory.readbyte(buttonAddress-1),1)
input_hk2P = bitReturn(memory.readbyte(buttonAddress-1),2)
input_s = (memory.readbyte(startAddress) - (memory.readbyte(startAddress) % 16)) / 16
if input_down==1 and input_right==0 and input_left==1 then
reba2P = 1
end
if input_down==1 and input_right==0 and input_left==0 then
reba2P = 2
end
if input_down==1 and input_right==1 and input_left==0 then
reba2P = 3
end
if input_up==0 and input_down==0 and input_left==1 then
reba2P = 4
end
if input_up==0 and input_down==0 and input_right==0 and input_left==0 then
reba2P = 5
end
if input_down==0 and input_right==1 and input_left==0 then
reba2P = 6
end
if input_up==1 and input_right==0 and input_left==1 then
reba2P = 7
end
if input_up==1 and input_right==0 and input_left==0 then
reba2P = 8
end
if input_up==1 and input_right==1 and input_left==0 then
reba2P = 9
end
if input_down==1 and input_right==1 and input_left==1 then
reba2P = 3
end
--»ÝÌóÔâüÍðêIÉi[µÄ¨½ßÌ
input_temp = {0,0,"",0}
input_temp[1] = reba_flame_from_before_input2P
input_temp[4] = button_flame_from_before_input2P
input_temp[2] = direction2P
input_temp[3] = reba2P..input_lp..input_mp..input_hp..input_lk..input_mk..input_hk
--½©ªüͳê½çAzñðP¸ç·
if (reba2P ~= before_reba2P and reba2P ~= 5)
or input_lp2P > before_input_lp2P
or input_mp2P > before_input_mp2P
or input_hp2P > before_input_hp2P
or input_lk2P > before_input_lk2P
or input_mk2P > before_input_mk2P
or input_hk2P > before_input_hk2P then
for i = dispNumber, 2, -1 do
keyDisplay2_box2P[i] = keyDisplay2_box2P[i-1]
end
--o[Ìüͪ³êÄ¢½ç
if (reba2P ~= before_reba2P and reba2P ~= 5) then
reba_flame_from_before_input2P = 0
end
--{^Ìüͪ³êÄ¢½ç
if input_lp2P > before_input_lp2P
or input_mp2P > before_input_mp2P
or input_hp2P > before_input_hp2P
or input_lk2P > before_input_lk2P
or input_mk2P > before_input_mk2P
or input_hk2P > before_input_hk2P then
button_flame_from_before_input2P = 0
end
--zñÌPÂÚÉA»ÝÌüÍði[·é
keyDisplay2_box2P[1] = input_temp
if reba_flame_from_before_input2P ~= 0 then
keyDisplay2_box2P[1][1] = 0
end
if button_flame_from_before_input2P ~= 0 then
keyDisplay2_box2P[1][4] = 0
end
no_input_time2P = 0
end
if reba2P == 5
and input_lp2P == 0
and input_mp2P == 0
and input_hp2P == 0
and input_lk2P == 0
and input_mk2P == 0
and input_hk2P == 0 then
--½àüͳêĢȯêÎA³üÍÔðâ·
no_input_time2P = no_input_time2P+1
if no_input_time2P > no_input_limit then
for i = 1, dispNumber-1, 1 do
keyDisplay2_box2P[i]={"","","0000000"}
end
no_input_time2P = 0
end
end
before_reba2P = reba2P
before_input_lp2P = input_lp2P
before_input_mp2P = input_mp2P
before_input_hp2P = input_hp2P
before_input_lk2P = input_lk2P
before_input_mk2P = input_mk2P
before_input_hk2P = input_hk2P
end
--æ£ÁÄ`æ
offsetY=46
if direction2P == 0 then
gui.image(42+offsetX1P2P,36,keyDisp2_dir0_real)
else
gui.image(42+offsetX1P2P,36,keyDisp2_dir1_real)
end
for i = 1, dispNumber-1, 1 do
reba2P = string.sub(keyDisplay2_box2P[i][3],1,1)+0
--üÍðª Á½ç
if reba2P ~= 0 then
offsetX=2+offsetX1P2P
if keyDisplay2_box2P[i][1] ~= 0 then
gui.text(offsetX,offsetY+6,numSpaceLeft(keyDisplay2_box2P[i][1],4))
end
offsetX=offsetX+16
if keyDisplay2_box2P[i][4] ~= 0 then
gui.text(offsetX,offsetY+6,numSpaceLeft(keyDisplay2_box2P[i][4],4))
end
offsetX=offsetX+16
if keyDisplay2_box2P[i][2] == 0 then
gui.image(offsetX,offsetY,keyDisp2_dir0)
else
gui.image(offsetX,offsetY,keyDisp2_dir1)
end
offsetX=offsetX+16
gui.image(offsetX,offsetY,keyDisp2Reba[reba2P])
offsetX=offsetX+12
if string.sub(keyDisplay2_box2P[i][3],2,2)+0 == 1 then
gui.image(offsetX,offsetY,keyDisp2_lp1)
offsetX=offsetX+8
end
if string.sub(keyDisplay2_box2P[i][3],3,3)+0 == 1 then
gui.image(offsetX,offsetY,keyDisp2_mp1)
offsetX=offsetX+8
end
if string.sub(keyDisplay2_box2P[i][3],4,4)+0 == 1 then
gui.image(offsetX,offsetY,keyDisp2_hp1)
offsetX=offsetX+8
end
if string.sub(keyDisplay2_box2P[i][3],5,5)+0 == 1 then
gui.image(offsetX,offsetY,keyDisp2_lk1)
offsetX=offsetX+8
end
if string.sub(keyDisplay2_box2P[i][3],6,6)+0 == 1 then
gui.image(offsetX,offsetY,keyDisp2_mk1)
offsetX=offsetX+8
end
if string.sub(keyDisplay2_box2P[i][3],7,7)+0 == 1 then
gui.image(offsetX,offsetY,keyDisp2_hk1)
offsetX=offsetX+8
end
offsetY=offsetY+9
end
end
end
end
--ðüêéÆAwèµ½
ÅEñ¹ÉµÄêé
function numSpaceLeft(val,keta)
temp=""
for i = 1, keta-#(val..""), 1 do
temp = temp.." "
end
temp = temp..val
return temp
end
--********wèµ½AhXÌlð©ìtHgÅ\¦·éÖ********
--@param nums ÌüÁ½zñ¼
--@param x xÀW
--@param y yÀW
--@param value l
--@param keta
B]Á½êÍOªtÁ³êéB
--@param offsetX ÆÆÌ¡ÌÔuB
function drawOriginNum(nums, x, y, value, keta, offsetX)
for i = keta, 1, -1 do
--ܸA²×½¢
ÈOÌ
ðOÉ·é
num_pinpoint = ((value%(10^i))-(value%10^(i-1)))
--»µÄê
É·é
num_hitoketa = num_pinpoint / (10^(i-1))
--e[uÍzñÆáÁÄvfÌÔªP©çÈÌÅAP«·
gui.image(x, y, nums[num_hitoketa+1])
value = value % (10^(i-1))
x = x + offsetX
end
end
function training()
if startButton == 1 then
if trainingModeCount == 0 then
trainingModeCount = 20
else
memory.writebyte(0x02011377,0x64)
memory.writebyte(0x02011379,0x00)
memory.writebyte(0x02010D61,0x00)
memory.writebyte(0x020691A3,0xA0)
memory.writebyte(0x02069611,0x00)
memory.writebyte(0x02069612,0x00)
if stunMax == 1 then
memory.writebyte(0x02069611,0xFF)
end
end
end
if trainingModeCount > 0 then
trainingModeCount = trainingModeCount - 1
end
if maxDamagevalue < memory.readbyte(0x02010D61) then
maxDamagevalue = memory.readbyte(0x02010D61)
end
if maxCombovalue < memory.readbyte(0x020696C5) then
maxCombovalue = memory.readbyte(0x020696C5)
end
offsetX = 200
offsetY = 60
gui.image(offsetX, offsetY, totalDamage)
drawOriginNum(nums0, offsetX+124, offsetY, memory.readbyte(0x02010D61) + 10, 3, 10)
offsetY = offsetY + 20
gui.image(offsetX, offsetY, maxDamage)
drawOriginNum(nums0, offsetX+124, offsetY, maxDamagevalue, 3, 10)
offsetY = offsetY + 20
gui.image(offsetX, offsetY, combo)
drawOriginNum(nums0, offsetX+124, offsetY, memory.readbyte(0x020696C5), 3, 10)
offsetY = offsetY + 20
gui.image(offsetX, offsetY, maxCombo)
drawOriginNum(nums0, offsetX+124, offsetY, maxCombovalue, 3, 10)
end
--- Returns HEX representation of num
--10Vð16VÉÏ·µÄêéÖB
--hitboxÌlua©çqØB
function num2hex(num)
local hexstr = '0123456789ABCDEF'
local s = ''
while num > 0 do
local mod = math.fmod(num, 16)
s = string.sub(hexstr, mod+1, mod+1) .. s
num = math.floor(num / 16)
end
if s == '' then
s = '0'
end
return s
end
--D«ÈoCgª«±ñÅêéÖ
function write(addr,num,byte)
for i=1,byte,1 do
memory.writebyte(addr,num)
addr = addr + 1
num = ((num-(num%0x100)) / 0x100)
end
end
--D«ÈoCgªtü«É«ñÅêéÖ
function writeReverse(addr,num,byte)
for i=1,byte,1 do
memory.writebyte(addr,(num % 0x100))
addr = addr - 1
num = ((num-(num%0x100)) / 0x100)
end
end
--D«ÈoCgªÇݱñÅêéÖ
function read(addr,byte)
value = 0
for i=1,byte,1 do
value = (value + memory.readbyte(addr+i-1)) * 0x100
end
return value / 0x100
end
--D«ÈoCgªtü«ÉÇÝñÅêéÖ
function readReverse(addr,byte)
value = 0
for i=1,byte,1 do
value = value + (memory.readbyte(addr-(i-1)) * (0x100^(i-1)))
end
return value
end
--àÌlðA^C©½¢Æ«Ég¤B
--AhXªÉA©½¢AhXÌlðüÍ·éÆA»ÌüÓÌlª©¦éB
function viewMemory(addr)
for i=0,20,1 do
gui.text(10,14+i*8,num2hex(addr+(i*0x10)))
for j=0,15,1 do
gui.text(48+j*16,4,num2hex(j))
gui.text(48+j*16,14+i*8,num2hex(memory.readbyte((addr)+j+(i*0x10))))
end
end
end
--gui.register(function()
function c_cube_script()
--************************************************************
--************************************************************
--************************************************************
--±±Ét[̼OÉÀs³¹½¢ð¢Ä¾³¢
--it[ÅÌüÍÌæ¾EÝèAÖÌ«ÝÈÇj
--************************************************************
--************************************************************
--************************************************************
--â~Ôð\¦
STOP1 = read(0x2068CB1,1)
if STOP1 > 127 then
STOP1 = 256 - STOP1
end
--gui.text(140,40,"STOP:"..STOP1)
STOP2 = read(0x2069149,1)
if STOP2 > 127 then
STOP2 = 256 - STOP2
end
--gui.text(220,40,"STOP:"..STOP2)
--sèÌoK`ªè[h
if startButton == 1 then
writeReverse(0x20695F9,149,2)
TIME = 0
end
if readReverse(0x20695F9,2) > 0 then
writeReverse(0x020695F9,readReverse(0x20695F9,2),2)
end
--drawOriginNum(nums0, 10, 40, readReverse(0x20695F9,2), 4, 10)
--cèÌs^C}[ð\¦
--memory.writebyte(0x02011377,0x64)
if readReverse(0x20695F9,2) == 0 then
TIME = TIME
else
if readReverse(0x20695F9,2) < 149 then
TIME = TIME + 1
else
TIME = TIME
end
end
--sAÜÅÉ©©Á½Ôð\¦
--drawOriginNum(nums0, 10, 60, TIME, 4, 10)
--BGM¹Ê
--memory.writebyte(0x02078D06,0x80)
--íÉubLOÂ\
--nãO
--memory.writebyte(0x02026335,0x0A)
--nãº
--memory.writebyte(0x02026337,0x0A)
--ó
--memory.writebyte(0x02026339,0x07)
--Îó
--memory.writebyte(0x02026347,0x05)
--1PÌÌÌü«
--memory.writebyte(0x02068C76,0x01)
--2PÌÌÌü«
--memory.writebyte(0x0206910E,0x00)
--Mðg¢½¢êͱêð00ɵÄ
--memory.writebyte(0x02011387,0x0F)
--memory.writebyte(0x02011388,0x00)
--Xe[WðGiXe[Wɵ½¢Æ«Í±êð
--memory.writebyte(0x020154F5,0x08)
--ÌÍð160Åèɵ½¢Æ«Í±êð
--memory.writebyte(0x020691A3,160)
--ªòF¾Á½ê
if memory.readbyte(0x020154A7) == 1 or memory.readbyte(0x020154A7) == 2 or memory.readbyte(0x020154A7) == 6
or memory.readbyte(0x020154A7) == 3 or memory.readbyte(0x020154A7) == 7 or memory.readbyte(0x020154A7) == 8 then
--X^[g{^ª³êÄ¢½ç
if memory.readbyte(0x206AA8C) == 16 then
startButton = startButton + 1
--writeReverse(0x02068CD2,0xF2,1)
X1P = readReverse(0x02068CD2,2)
--writeReverse(0x02068CD2,X1P+2,2)
--writeReverse(0x02069169,X1P-0x50,2)
if startButton == 1 then
--writeReverse(0x0206916A,0x80,1)
end
else
startButton = 0
end
--X^[g{^ª30FÔ³ê½ç
if startButton == 30 then
--`[g[hª0ÌÆ«Í1ÉA0ÈãÌÆ«Í0É·é
if cheatModeNum == 0 then
cheatModeNum = 1
elseif cheatModeNum >= 1 then
cheatModeNum = 0
startButton = 0
end
print("cheatModeNum = "..cheatModeNum)
elseif startButton == 60 then
--`[g[hð2É·é
cheatModeNum = 2
print("cheatModeNum = "..cheatModeNum)
end
if cheatModeNum == 2 then
memory.writebyte(0x02068CB1,0x01)
memory.writebyte(0x02069149,0x01)
gachaTrainingMode()
end
if cheatModeNum == 1 then
memory.writebyte(0x02068CB1,0x01)
memory.writebyte(0x02069149,0x01)
cheatMode()
end
gui.image(blank2)
if cheatModeNum == 0 then
if inputView == 1 then
--L[fBXvC»ÌPiPP¤j
keyDisplay(button_l1, button_l2, button_m1, button_m2, button_h1, button_h2, button_s1, button_s2, 40, 184, 0x0202564B, 0x206AA8C)
--L[fBXvC»ÌQ JvXiPP¤j
keyDisplay2_2(button_l1, button_l2, button_m1, button_m2, button_h1, button_h2, button_s1, button_s2, 40, 184, 1)
--L[fBXvC»ÌPiQP¤j
keyDisplay(button_l1, button_l2, button_m1, button_m2, button_h1, button_h2, button_s1, button_s2, 280, 184, 0x0202568F, 0x0206AA90)
--L[fBXvC»ÌQ JvXiQP¤j
keyDisplay2_2(button_l1, button_l2, button_m1, button_m2, button_h1, button_h2, button_s1, button_s2, 40, 184, 2)
end
--ªòFgpLªM¾Á½ç
if memory.readbyte(0x2011387) == 0x00 then
--±±ÉðLq·é
end
--ªòFgpLªAbNX¾Á½ç
if memory.readbyte(0x2011387) == 0x01 then
--Q[Wâæð\¦·é½ßÌÀW
offsetX = 30
offsetY = 50
if tameView == 1 then
--XbV
G{[
tameGauge(alex_1, offsetX, offsetY, 0x02025A49, 0x02025A47)
offsetY = offsetY + 28
--GAX^s[g
tameGauge(alex_2, offsetX, offsetY, 0x02025A2D, 0x02025A2B)
offsetY = offsetY + 28
end
----------------------nCp[{----------------------
if kaitenView == 1 then
--nCp[{ðIðµÄ¢½ç
if memory.readbyte(0x020154D3) == 0 then
kaiten(alex_3, offsetX, offsetY, 0x0202590F, 0x020258F7)
end
end
end
--ªòFgpLª²¾Á½ç
if memory.readbyte(0x2011387) == 0x02 then
offsetX = 30
offsetY = 50
if denjinView == 1 then
--dng®ðIðµÄ¢½ç
if memory.readbyte(0x020154D3) == 2 then
if memory.readbyte(0x02069520) ~= 0 then
-- denjin start detection...
iChargeFrames = 0
bDenjinStarted = true
else
if bDenjinStarted == true then
if memory.readbyte(0x02068D2D) == 19 and memory.readbyte(0x02068D27) == 0 then
-- denjin charge reached...
else
iChargeFrames = iChargeFrames + 1
end
sDenjin = "CHARGE COUNT : "..string.format("%03s", iChargeFrames)
gui.text(100, 50, sDenjin, 0x80FFFFFF, 0x000000FF)
end
end
gui.image(4,offsetY,ryu_1)
drawOriginNum(nums0,offsetX,offsetY,memory.readbyte(0x02068D27),2,10)
offsetX = offsetX + 3
offsetY = offsetY + 16
gui.drawbox(offsetX,offsetY,offsetX+16,offsetY+6,0x00000000,0x000000FF)
gui.drawbox(offsetX,offsetY,offsetX+48,offsetY+6,0x00000000,0x000000FF)
gui.drawbox(offsetX,offsetY,offsetX+96,offsetY+6,0x00000000,0x000000FF)
gui.drawbox(offsetX,offsetY,offsetX+160,offsetY+6,0x00000000,0x000000FF)
--dnÌxɶÄlªÏíéÏ
-- «
denjin = memory.readbyte(0x02068D2D)
if denjin == 3 then
gui.drawbox(offsetX,offsetY,offsetX+(memory.readbyte(0x02068D27)*2),offsetY+6,0x0080FFFF,0x000000FF)
elseif denjin == 9 then
gui.drawbox(offsetX,offsetY,offsetX+(memory.readbyte(0x02068D27)*2),offsetY+6,0x00FFFFFF,0x000000FF)
elseif denjin == 14 then
gui.drawbox(offsetX,offsetY,offsetX+(memory.readbyte(0x02068D27)*2),offsetY+6,0x80FFFFFF,0x000000FF)
elseif denjin == 19 then
gui.drawbox(offsetX,offsetY,offsetX+(memory.readbyte(0x02068D27)*2),offsetY+6,0xFFFFFFFF,0x000000FF)
end
if memory.readbyte(0x02068D27) ~= 0 then
--dnÌßðÔŸçÈ¢æ¤É·éƫͱêðg¤
--memory.writebyte(0x02068D27,memory.readbyte(0x02068D27)+1)
end
end
end
end
--ªòFgpLª¾Á½ç
if memory.readbyte(0x2011387) == 0x03 then
--±±ÉðLq·é
end
--ªòFgpLª_bh[¾Á½ç
if memory.readbyte(0x2011387) == 0x04 then
--±±ÉðLq·é
end
--ªòFgpLªlN¾Á½ç
if memory.readbyte(0x2011387) == 0x05 then
--±±ÉðLq·é
end
--ªòFgpLªq
[S[¾Á½ç
if memory.readbyte(0x2011387) == 0x06 then
offsetX = 30
offsetY = 50
if kaitenView == 1 then
--[TgvX
kaiten(hugo_1, offsetX, offsetY, 0x020259EF, 0x020259D7)
offsetY = offsetY + 30
--~[gXJbV[
kaiten(hugo_2, offsetX, offsetY, 0x02025A0B, 0x020259F3)
offsetY = offsetY + 30
----------------------MKXu[J[----------------------
--MKXu[J[ðIðµÄ¢½ç
if memory.readbyte(0x020154D3) == 0 then
gui.image(4,offsetY-3,hugo_3)
juji_up = bitReturn(memory.readbyte(0x0202590F),0);
juji_down = bitReturn(memory.readbyte(0x0202590F),1);
juji_right = bitReturn(memory.readbyte(0x0202590F),2);
juji_left = bitReturn(memory.readbyte(0x0202590F),3);
--Pñ]ÚÅ êÎ
if memory.readbyte(0x020258FF) == 48 then
--ãûüªüÍÏÝÅ êÎ
if juji_up == 1 then
gui.image(offsetX+48,offsetY-12,arrow_up3)
else
gui.image(offsetX+48,offsetY-12,arrow_up1)
end
--ºûüªüÍÏÝÅ êÎ
if juji_down == 1 then
gui.image(offsetX+24,offsetY-12,arrow_down3)
else
gui.image(offsetX+24,offsetY-12,arrow_down1)
end
--EûüªüÍÏÝÅ êÎ
if juji_right == 1 then
gui.image(offsetX+72,offsetY-12,arrow_right3)
else
gui.image(offsetX+72,offsetY-12,arrow_right1)
end
--¶ûüªüÍÏÝÅ êÎ
if juji_left == 1 then
gui.image(offsetX,offsetY-12,arrow_left3)
else
gui.image(offsetX,offsetY-12,arrow_left1)
end
else
--ãûüªüÍÏÝÅ êÎ
if juji_up == 1 then
gui.image(offsetX+48,offsetY-12,arrow_up2)
else
gui.image(offsetX+48,offsetY-12,arrow_up3)
end
--ºûüªüÍÏÝÅ êÎ
if juji_down == 1 then
gui.image(offsetX+24,offsetY-12,arrow_down2)
else
gui.image(offsetX+24,offsetY-12,arrow_down3)
end
--EûüªüÍÏÝÅ êÎ
if juji_right == 1 then
gui.image(offsetX+72,offsetY-12,arrow_right2)
else
gui.image(offsetX+72,offsetY-12,arrow_right3)
end
--¶ûüªüÍÏÝÅ êÎ
if juji_left == 1 then
gui.image(offsetX,offsetY-12,arrow_left2)
else
gui.image(offsetX,offsetY-12,arrow_left3)
end
end
gui.drawbox(offsetX,offsetY+12,offsetX+96,offsetY+18,0x00000000,0x000000FF)
gui.drawbox(offsetX,offsetY+12,offsetX+(memory.readbyte(0x020258F7)*3),offsetY+18,0x00C080FF,0x000000FF)
end
----------------------MKXu[J[----------------------
end
end
--ªòFgpLª¢Ô«¾Á½ç
if memory.readbyte(0x2011387) == 0x07 then
--±±ÉðLq·é
end
--ªòFgpLªGi¾Á½ç
if memory.readbyte(0x2011387) == 0x08 then
--±±ÉðLq·é
end
--ªòFgpLªI¾Á½ç
if memory.readbyte(0x2011387) == 0x09 then
offsetX = 30
offsetY = 50
if tameView == 1 then
--úÖ¶
tameGauge(oro_1, offsetX, offsetY, 0x02025A11, 0x02025A0F)
offsetY = offsetY + 28
--S}
tameGauge(oro_2, offsetX, offsetY, 0x020259D9, 0x020259D7)
end
end
--ªòFgpLª¾Á½ç
if memory.readbyte(0x2011387) == 0x0A then
--±±ÉðLq·é
end
--ªòFgpLª¾Á½ç
if memory.readbyte(0x2011387) == 0x0B then
--±±ÉðLq·é
end
--ªòFgpLªV[¾Á½ç
if memory.readbyte(0x2011387) == 0x0C then
--±±ÉðLq·é
end
--ªòFgpLªA¾Á½ç
if memory.readbyte(0x2011387) == 0x0D then
offsetX = 30
offsetY = 50
if tameView == 1 then
--`Ibg^bN
tameGauge(urien_1, offsetX, offsetY, 0x020259D9, 0x020259D7)
offsetY = offsetY + 28
--oCIXj[hbv
tameGauge(urien_2, offsetX, offsetY, 0x02025A2D, 0x02025A2B)
offsetY = offsetY + 28
--fWXwbhobg
tameGauge(urien_3, offsetX, offsetY, 0x020259F5, 0x020259F3)
end
end
--ªòFgpLªS¾Á½ç
if memory.readbyte(0x2011387) == 0x0E then
--±±ÉðLq·é
end
--ªòFgpLª^S¾Á½ç
if memory.readbyte(0x2011387) == 0x0F then
--±±ÉðLq·é
end
--ªòFgpLªtí¾Á½ç
if memory.readbyte(0x2011387) == 0x10 then
--Q[Wâæð\¦·é½ßÌÀW
offsetX = 30
offsetY = 50
if rendaView == 1 then
--ãSôr
hyakuretsu(chun_1, kick_1, kick_1_2, offsetX, offsetY, 0x02025A03)
offsetY = offsetY + 28
----------------------Sôr----------------------
hyakuretsu(chun_2, kick_2, kick_2_2, offsetX, offsetY, 0x02025A05)
offsetY = offsetY + 28
----------------------Sôr----------------------
hyakuretsu(chun_3, kick_3, kick_3_2, offsetX, offsetY, 0x02025A07)
offsetY = offsetY + 28
----------------------AÅ^C}[----------------------
if memory.readbyte(0x02025A2D) ~= 0xFF then
gui.drawbox(offsetX,offsetY,offsetX+98,offsetY+6,0x00000000,0x000000FF)
gui.drawbox(offsetX,offsetY,offsetX+(memory.readbyte(0x020259f3)),offsetY+6,0xFF8080FF,0x000000FF)
else
gui.drawbox(offsetX,offsetY,offsetX+98,offsetY+6,0x00000000,0xFFFFFFFF)
end
----------------------AÅ^C}[----------------------
offsetY = offsetY + 28
end
if tameView == 1 then
--XsjOo[hLbN
tameGauge(chun_4, offsetX, offsetY, 0x020259D9, 0x020259D7)
end
end
--ªòFgpLªÜ±Æ¾Á½ç
if memory.readbyte(0x2011387) == 0x11 then
--±±ÉðLq·é
end
--ªòFgpLªQ¾Á½ç
if memory.readbyte(0x2011387) == 0x12 then
offsetX = 30
offsetY = 50
if tameView == 1 then
--ËiªÅi¼j
tameGauge(q_1, offsetX, offsetY, 0x020259D9, 0x020259D7)
offsetY = offsetY + 28
--ËiºÅi¼j
tameGauge(q_2, offsetX, offsetY, 0x020259F5, 0x020259F3)
end
end
--ªòFgpLªgDG¾Á½ç
if memory.readbyte(0x2011387) == 0x13 then
--±±ÉðLq·é
end
--ªòFgpLª~[¾Á½ç
if memory.readbyte(0x2011387) == 0x14 then
offsetX = 30
offsetY = 50
if tameView == 1 then
--Fe
ÌcõEIbg
tameGauge(remy_1, offsetX, offsetY, 0x020259F5, 0x020259F3)
offsetY = offsetY + 28
--Fe
ÌcõEoX
tameGauge(remy_2, offsetX, offsetY, 0x02025A11, 0x02025A0F)
offsetY = offsetY + 28
--}EVFÌߣ
tameGauge(remy_3, offsetX, offsetY, 0x020259D9, 0x020259D7)
end
end
----------------------í¸l----------------------
offsetX = 240
offsetY = 50
if airTimerView == 1 then
gui.drawtext(offsetX,offsetY,tostring(memory.readbyte(0x020694C9)))
offsetX = offsetX + 8
gui.drawbox(offsetX,offsetY,offsetX+121,offsetY+6,0x00000000,0x000000FF)
gui.drawline(offsetX+101,offsetY,offsetX+101,offsetY+6,0x000000FF)
gui.drawline(offsetX+81,offsetY,offsetX+81,offsetY+6,0x000000FF)
gui.drawline(offsetX+61,offsetY,offsetX+61,offsetY+6,0x000000FF)
gui.drawline(offsetX+41,offsetY,offsetX+41,offsetY+6,0x000000FF)
gui.drawline(offsetX+21,offsetY,offsetX+21,offsetY+6,0x000000FF)
gui.drawline(offsetX+11,offsetY,offsetX+11,offsetY+6,0x000000FF)
gui.drawline(offsetX+5,offsetY,offsetX+5,offsetY+6,0x000000FF)
gui.drawline(offsetX+2,offsetY,offsetX+2,offsetY+6,0x000000FF)
gui.drawline(offsetX+1,offsetY,offsetX+1,offsetY+6,0x000000FF)
if memory.readbyte(0x020694C7) ~= 0xFF then
gui.drawbox(offsetX,offsetY,offsetX+((memory.readbyte(0x020694C7)+1)/2),offsetY+6,0x00C080FF,0x000000FF)
if memory.readbyte(0x020694C7) > 0 then
gui.drawtext(offsetX+((memory.readbyte(0x020694C7)+1)/2),offsetY+12,((memory.readbyte(0x020694C7)+1)/2))
end
end
----------------------í¸l----------------------
end
--X^lðMAXɵ½¢Æ«Í±êðg¤
--memory.writebyte(0x02069611,0xFF)
--g[jO[h
if trainingMode == 1 then
training()
end
--`[ggpÍACRª\¦³êé
if gaugeMax == 1 or airComboInf == 1 or longHitStop == 1 or zeroHitStop == 1 then
--gui.image(284,204,cheat_on)
end
--Q[WMAX`[g
if gaugeMax == 1 then
gauge = memory.readbyte(0x020286AD)
memory.writebyte(0x02028695,0xFF)
memory.writebyte(0x020695B5,0xFF)
memory.writebyte(0x020286AB,gauge)
memory.writebyte(0x020695BF,gauge)
memory.writebyte(0x020695BD,gauge)
gauge2 = memory.readbyte(0x020286E1)
memory.writebyte(0x020695E1,0xFF)
memory.writebyte(0x020286DF,gauge2)
memory.writebyte(0x0206940D,gauge2)
memory.writebyte(0x020695EB,gauge2)
end
--óÇÔ³À`[g
if airComboInf == 1 then
memory.writebyte(0x020694C7,0xFF)
end
--qbgXgbvå`[g
if longHitStop == 1 then
--2PªZðòçÁ½ç
if memory.readbyte(0x0206914B) > 0x00 then
hitStopCount = hitStopCount + 1
end
if hitStopCount == 1 then
memory.writebyte(0x02069149,0x80)
end
if memory.readbyte(0x0206914B) == 0x00 then
hitStopCount = 0
end
end
--qbgXgbv[`[g
if zeroHitStop == 1 then
--2PªZðòçÁ½ç
if memory.readbyte(0x0206914B) > 0x00 then
zeroStopCount = zeroStopCount + 1
end
if zeroStopCount == 1 then
memory.writebyte(0x02068CB3,0)
if memory.readbyte(0x02068CB1) > 80 then
memory.writebyte(0x02068CB1,0xFF)
else
memory.writebyte(0x02068CB1,0x00)
end
if longHitStop ~= 1 then
memory.writebyte(0x0206914B,0x00)
if memory.readbyte(0x02069149) > 80 then
memory.writebyte(0x02069149,0xFF)
elseif memory.readbyte(0x02069149) > 0 then
memory.writebyte(0x02069149,0x01)
end
end
end
if memory.readbyte(0x02069149) == 0x00 then
zeroStopCount = 0
end
end
if BLView == 1 then
--write(0x02026335,0x0A,1)
--write(0x02026337,0x0A,1)
--uótÔ\¦
BLY = 50
BLoffsetY = 6
gui.drawtext(18,BLY-1,"FRONT")
yokoGauge2(nil, 40, BLY, 40, 4, memory.readbyte(0x02026335), 10, 0, 0x00C0FFFF)
if memory.readbyte(0x02025731) ~= 0xFF then
yokoGauge2(nil, 40, BLY+BLoffsetY, 84, 4, memory.readbyte(0x02025731), 21, 0, 0xFF8000FF)
else
yokoGauge2(nil, 40, BLY+BLoffsetY, 84, 4, -1, 21, 0, 0xFF800000)
end
gui.drawtext(14,BLY-1+BLoffsetY*3,"BOTTOM")
yokoGauge2(nil, 40, BLY+BLoffsetY*3, 40, 4, memory.readbyte(0x02026337), 10, 0, 0x00C0FFFF)
if memory.readbyte(0x0202574D) ~= 0xFF then
yokoGauge2(nil, 40, BLY+BLoffsetY*4, 84, 4, memory.readbyte(0x0202574D), 21, 0, 0xFF8000FF)
else
yokoGauge2(nil, 40, BLY+BLoffsetY*4, 84, 4, -1, 21, 0, 0xFF800000)
end
gui.drawtext(26,BLY-1+BLoffsetY*6,"AIR")
yokoGauge2(nil, 40, BLY+BLoffsetY*6, 28, 4, memory.readbyte(0x02026339), 7, 0, 0x00C0FFFF)
if memory.readbyte(0x02025769) ~= 0xFF then
yokoGauge2(nil, 40, BLY+BLoffsetY*7, 72, 4, memory.readbyte(0x02025769), 18, 0, 0xFF8000FF)
else
yokoGauge2(nil, 40, BLY+BLoffsetY*7, 72, 4, -1, 18, 0, 0xFF800000)
end
gui.drawtext(5,BLY-1+BLoffsetY*9,"ANTI-AIR")
yokoGauge2(nil, 40, BLY+BLoffsetY*9, 20, 4, memory.readbyte(0x02026347), 5, 0, 0x00C0FFFF)
if memory.readbyte(0x0202582D) ~= 0xFF then
yokoGauge2(nil, 40, BLY+BLoffsetY*10, 64, 4, memory.readbyte(0x0202582D), 16, 0, 0xFF8000FF)
else
yokoGauge2(nil, 40, BLY+BLoffsetY*10, 64, 4, -1, 16, 0, 0xFF800000)
end
end
end
--ÅȯêÎ
else
--ã©ç§¾Èæð©Ô¹éB
--±êðâçÈ¢ÆAo[âæªÁ¦ÄêȢ椾B
gui.image(0,0,blank2)
end
end
--end) | mit |
serl/vlc | share/lua/playlist/pluzz.lua | 105 | 3740 | --[[
$Id$
Copyright © 2011 VideoLAN
Authors: Ludovic Fauvet <etix at l0cal dot com>
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, "pluzz.fr/%w+" )
or string.match( vlc.path, "info.francetelevisions.fr/.+")
or string.match( vlc.path, "france4.fr/%w+")
end
-- Helpers
function key_match( line, key )
return string.match( line, "name=\"" .. key .. "\"" )
end
function get_value( line )
local _,_,r = string.find( line, "content=\"(.*)\"" )
return r
end
-- Parse function.
function parse()
p = {}
if string.match ( vlc.path, "www.pluzz.fr/%w+" ) then
while true do
line = vlc.readline()
if not line then break end
if string.match( line, "id=\"current_video\"" ) then
_,_,redirect = string.find (line, "href=\"(.-)\"" )
print ("redirecting to: " .. redirect )
return { { path = redirect } }
end
end
end
if string.match ( vlc.path, "www.france4.fr/%w+" ) then
while true do
line = vlc.readline()
if not line then break end
-- maybe we should get id from tags having video/cappuccino type instead
if string.match( line, "id=\"lavideo\"" ) then
_,_,redirect = string.find (line, "href=\"(.-)\"" )
print ("redirecting to: " .. redirect )
return { { path = redirect } }
end
end
end
if string.match ( vlc.path, "info.francetelevisions.fr/.+" ) then
title = ""
arturl = "http://info.francetelevisions.fr/video-info/player_sl/Images/PNG/gene_ftv.png"
while true do
line = vlc.readline()
if not line then break end
-- Try to find the video's path
if key_match( line, "urls--url--video" ) then
video = get_value( line )
end
-- Try to find the video's title
if key_match( line, "vignette--titre--court" ) then
title = get_value( line )
title = vlc.strings.resolve_xml_special_chars( title )
print ("playing: " .. title )
end
-- Try to find the video's thumbnail
if key_match( line, "vignette" ) then
arturl = get_value( line )
if not string.match( line, "http://" ) then
arturl = "http://info.francetelevisions.fr/" .. arturl
end
end
end
if video then
-- base url is hardcoded inside a js source file
-- see http://www.pluzz.fr/layoutftv/arches/common/javascripts/jquery.player-min.js
base_url = "mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/"
table.insert( p, { path = base_url .. video; name = title; arturl = arturl; } )
end
end
return p
end
| gpl-2.0 |
geanux/darkstar | scripts/zones/Windurst_Woods/npcs/Spare_Four.lua | 17 | 1507 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Spare Four
-- Working 100%
-- Involved in quest: A Greeting Cardian
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/globals/quests"] = nil;
require("scripts/globals/quests");
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
AGreetingCardian = player:getQuestStatus(WINDURST,A_GREETING_CARDIAN);
local AGCcs = player:getVar("AGreetingCardian_Event");
if (AGreetingCardian == QUEST_ACCEPTED and AGCcs == 2) then
player:startEvent(0x0127); -- A Greeting Cardian step two
else player:startEvent(0x119); -- standard dialog
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 == 0x0127) then
player:setVar("AGreetingCardian_Event",3);
end
end;
| gpl-3.0 |
geanux/darkstar | scripts/commands/zone.lua | 24 | 13672 | ---------------------------------------------------------------------------------------------------
-- func: zone
-- desc: Teleports a player to the given zone.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "s"
};
---------------------------------------------------------------------------------------------------
-- desc: List of zones with their auto-translated group and message id.
-- note: The format is as follows: groupId, messageId, zoneId
---------------------------------------------------------------------------------------------------
local zone_list =
{
{ 0x14, 0xA9, 1 }, -- Phanauet Channel
{ 0x14, 0xAA, 2 }, -- Carpenters' Landing
{ 0x14, 0x84, 3 }, -- Manaclipper
{ 0x14, 0x85, 4 }, -- Bibiki Bay
{ 0x14, 0x8A, 5 }, -- Uleguerand Range
{ 0x14, 0x8B, 6 }, -- Bearclaw Pinnacle
{ 0x14, 0x86, 7 }, -- Attohwa Chasm
{ 0x14, 0x87, 8 }, -- Boneyard Gully
{ 0x14, 0x88, 9 }, -- Pso'Xja
{ 0x14, 0x89, 10 }, -- The Shrouded Maw
{ 0x14, 0x8C, 11 }, -- Oldton Movalpolos
{ 0x14, 0x8D, 12 }, -- Newton Movalpolos
{ 0x14, 0x8E, 13 }, -- Mine Shaft #2716
{ 0x14, 0xDC, 13 }, -- Mine Shaft #2716
{ 0x14, 0xAB, 14 }, -- Hall of Transference
{ 0x14, 0x9B, 16 }, -- Promyvion - Holla
{ 0x14, 0x9A, 16 }, -- Promyvion - Holla
{ 0x14, 0x9C, 17 }, -- Spire of Holla
{ 0x14, 0x9E, 18 }, -- Promyvion - Dem
{ 0x14, 0x9D, 18 }, -- Promyvion - Dem
{ 0x14, 0x9F, 19 }, -- Spire of Dem
{ 0x14, 0xA0, 20 }, -- Promyvion - Mea
{ 0x14, 0xA1, 20 }, -- Promyvion - Mea
{ 0x14, 0xA2, 21 }, -- Spire of Mea
{ 0x14, 0xA3, 22 }, -- Promyvion - Vahzl
{ 0x14, 0xA4, 22 }, -- Promyvion - Vahzl
{ 0x14, 0xA5, 22 }, -- Promyvion - Vahzl
{ 0x14, 0xA6, 22 }, -- Promyvion - Vahzl
{ 0x14, 0xA7, 23 }, -- Spire of Vahzl
{ 0x14, 0xA8, 23 }, -- Spire of Vahzl
{ 0x14, 0x90, 24 }, -- Lufaise Meadows
{ 0x14, 0x91, 25 }, -- Misareaux Coast
{ 0x14, 0x8F, 26 }, -- Tavnazian Safehold
{ 0x14, 0x93, 27 }, -- Phomiuna Aqueducts
{ 0x14, 0x94, 28 }, -- Sacrarium
{ 0x14, 0x96, 29 }, -- Riverne - Site #B01
{ 0x14, 0x95, 29 }, -- Riverne - Site #B01
{ 0x14, 0x98, 30 }, -- Riverne - Site #A01
{ 0x14, 0x97, 30 }, -- Riverne - Site #A01
{ 0x14, 0x99, 31 }, -- Monarch Linn
{ 0x14, 0x92, 32 }, -- Sealion's Den
{ 0x14, 0xAC, 33 }, -- Al'Taieu
{ 0x14, 0xAD, 34 }, -- Grand Palace of Hu'Xzoi
{ 0x14, 0xAE, 35 }, -- The Garden of Ru'Hmet
{ 0x14, 0xB0, 36 }, -- Empyreal Paradox
{ 0x14, 0xB1, 37 }, -- Temenos
{ 0x14, 0xB2, 38 }, -- Apollyon
{ 0x14, 0xB4, 39 }, -- Dynamis - Valkurm
{ 0x14, 0xB5, 40 }, -- Dynamis - Buburimu
{ 0x14, 0xB6, 41 }, -- Dynamis - Qufim
{ 0x14, 0xB7, 42 }, -- Dynamis - Tavnazia
{ 0x14, 0xAF, 43 }, -- Diorama Abdhaljs-Ghelsba
{ 0x14, 0xB8, 44 }, -- Abdhaljs Isle-Purgonorgo
{ 0x14, 0xB9, 46 }, -- Open sea route to Al Zahbi
{ 0x14, 0xBA, 47 }, -- Open sea route to Mhaura
{ 0x14, 0xBB, 48 }, -- Al Zahbi
{ 0x14, 0xDB, 50 }, -- Aht Urhgan Whitegate
{ 0x14, 0xBC, 50 }, -- Aht Urhgan Whitegate
{ 0x14, 0xBD, 51 }, -- Wajaom Woodlands
{ 0x14, 0xBE, 52 }, -- Bhaflau Thickets
{ 0x14, 0xBF, 53 }, -- Nashmau
{ 0x14, 0xC0, 54 }, -- Arrapago Reef
{ 0x14, 0xC1, 55 }, -- Ilrusi Atoll
{ 0x14, 0xC2, 56 }, -- Periqia
{ 0x14, 0xC3, 57 }, -- Talacca Cove
{ 0x14, 0xC4, 58 }, -- Silver Sea route to Nashmau
{ 0x14, 0xC5, 59 }, -- Silver Sea route to Al Zahbi
{ 0x14, 0xC6, 60 }, -- The Ashu Talif
{ 0x14, 0xC7, 61 }, -- Mount Zhayolm
{ 0x14, 0xC8, 62 }, -- Halvung
{ 0x14, 0xC9, 63 }, -- Lebros Cavern
{ 0x14, 0xCA, 64 }, -- Navukgo Execution Chamber
{ 0x14, 0xCB, 65 }, -- Mamook
{ 0x14, 0xCC, 66 }, -- Mamool Ja Training Grounds
{ 0x14, 0xCD, 67 }, -- Jade Sepulcher
{ 0x14, 0xCE, 68 }, -- Aydeewa Subterrane
{ 0x14, 0xCF, 69 }, -- Leujaoam Sanctum
{ 0x27, 0x0F, 70 }, -- Chocobo Circuit
{ 0x27, 0x10, 71 }, -- The Colosseum
{ 0x14, 0xDD, 72 }, -- Alzadaal Undersea Ruins
{ 0x14, 0xDE, 73 }, -- Zhayolm Remnants
{ 0x14, 0xDF, 74 }, -- Arrapago Remnants
{ 0x14, 0xE0, 75 }, -- Bhaflau Remnants
{ 0x14, 0xE1, 76 }, -- Silver Sea Remnants
{ 0x14, 0xE2, 77 }, -- Nyzul Isle
{ 0x14, 0xDA, 78 }, -- Hazhalm Testing Grounds
{ 0x14, 0xD0, 79 }, -- Caedarva Mire
{ 0x27, 0x11, 80 }, -- Southern San d'Oria [S]
{ 0x27, 0x13, 81 }, -- East Ronfaure [S]
{ 0x27, 0x15, 82 }, -- Jugner Forest [S]
{ 0x27, 0x23, 83 }, -- Vunkerl Inlet [S]
{ 0x27, 0x17, 84 }, -- Batallia Downs [S]
{ 0x27, 0x3E, 85 }, -- La Vaule [S]
{ 0x27, 0x40, 85 }, -- La Vaule [S]
{ 0x27, 0x19, 86 }, -- Everbloom Hollow
{ 0x27, 0x1C, 87 }, -- Bastok Markets [S]
{ 0x27, 0x1E, 88 }, -- North Gustaberg [S]
{ 0x27, 0x20, 89 }, -- Grauberg [S]
{ 0x27, 0x25, 90 }, -- Pashhow Marshlands [S]
{ 0x27, 0x27, 91 }, -- Rolanberry Fields [S]
{ 0x27, 0x42, 92 }, -- Beadeaux [S]
{ 0x27, 0x22, 93 }, -- Ruhotz Silvermines
{ 0x27, 0x2B, 94 }, -- Windurst Waters [S]
{ 0x27, 0x2D, 95 }, -- West Sarutabaruta [S]
{ 0x27, 0x2F, 96 }, -- Fort Karugo-Narugo [S]
{ 0x27, 0x32, 97 }, -- Meriphataud Mountains [S]
{ 0x27, 0x34, 98 }, -- Sauromugue Champaign [S]
{ 0x27, 0x44, 99 }, -- Castle Oztroja [S]
{ 0x14, 0x11, 100 }, -- West Ronfaure
{ 0x14, 0x0F, 101 }, -- East Ronfaure
{ 0x14, 0x51, 102 }, -- La Theine Plateau
{ 0x14, 0x60, 103 }, -- Valkurm Dunes
{ 0x14, 0x01, 104 }, -- Jugner Forest
{ 0x14, 0x02, 105 }, -- Batallia Downs
{ 0x14, 0x64, 106 }, -- North Gustaberg
{ 0x14, 0x63, 107 }, -- South Gustaberg
{ 0x14, 0x69, 108 }, -- Konschtat Highlands
{ 0x14, 0x2B, 109 }, -- Pashhow Marshlands
{ 0x14, 0x07, 110 }, -- Rolanberry Fields
{ 0x14, 0x24, 111 }, -- Beaucedine Glacier
{ 0x14, 0x4D, 112 }, -- Xarcabard
{ 0x14, 0x3D, 113 }, -- Cape Teriggan
{ 0x14, 0x3E, 114 }, -- Eastern Altepa Desert
{ 0x14, 0x18, 115 }, -- West Sarutabaruta
{ 0x14, 0x27, 116 }, -- East Sarutabaruta
{ 0x14, 0x17, 117 }, -- Tahrongi Canyon
{ 0x14, 0x16, 118 }, -- Buburimu Peninsula
{ 0x14, 0x20, 119 }, -- Meriphataud Mountains
{ 0x14, 0x2E, 120 }, -- Sauromugue Champaign
{ 0x14, 0x3F, 121 }, -- The Sanctuary of Zi'Tah
{ 0x14, 0x7D, 122 }, -- Ro'Maeve
{ 0x14, 0x7C, 122 }, -- Ro'Maeve
{ 0x14, 0x40, 123 }, -- Yuhtunga Jungle
{ 0x14, 0x41, 124 }, -- Yhoator Jungle
{ 0x14, 0x42, 125 }, -- Western Altepa Desert
{ 0x14, 0x08, 126 }, -- Qufim Island
{ 0x14, 0x0A, 127 }, -- Behemoth's Dominion
{ 0x14, 0x43, 128 }, -- Valley of Sorrows
{ 0x27, 0x31, 129 }, -- Ghoyu's Reverie
{ 0x14, 0x6F, 130 }, -- Ru'Aun Gardens
{ 0x14, 0x82, 134 }, -- Dynamis - Beaucedine
{ 0x14, 0x83, 135 }, -- Dynamis - Xarcabard
{ 0x27, 0x46, 136 }, -- Beaucedine Glacier [S]
{ 0x27, 0x48, 137 }, -- Xarcabard [S]
{ 0x14, 0x65, 139 }, -- Horlais Peak
{ 0x14, 0x6C, 140 }, -- Ghelsba Outpost
{ 0x14, 0x1F, 141 }, -- Fort Ghelsba
{ 0x14, 0x5E, 142 }, -- Yughott Grotto
{ 0x14, 0x66, 143 }, -- Palborough Mines
{ 0x14, 0x1A, 144 }, -- Waughroon Shrine
{ 0x14, 0x21, 145 }, -- Giddeus
{ 0x14, 0x19, 146 }, -- Balga's Dais
{ 0x14, 0x2A, 147 }, -- Beadeaux
{ 0x14, 0x28, 148 }, -- Qulun Dome
{ 0x14, 0x68, 149 }, -- Davoi
{ 0x14, 0x6D, 150 }, -- Monastic Cavern
{ 0x14, 0x23, 151 }, -- Castle Oztroja
{ 0x14, 0x04, 152 }, -- Altar Room
{ 0x14, 0x44, 153 }, -- The Boyahda Tree
{ 0x14, 0x37, 154 }, -- Dragon's Aery
{ 0x14, 0x0C, 157 }, -- Middle Delkfutt's Tower
{ 0x14, 0x0B, 158 }, -- Upper Delkfutt's Tower
{ 0x14, 0x36, 159 }, -- Temple of Uggalepih
{ 0x14, 0x35, 160 }, -- Den of Rancor
{ 0x14, 0x26, 161 }, -- Castle Zvahl Baileys
{ 0x14, 0x25, 161 }, -- Castle Zvahl Baileys
{ 0x14, 0x50, 162 }, -- Castle Zvahl Keep
{ 0x14, 0x4F, 162 }, -- Castle Zvahl Keep
{ 0x14, 0x39, 163 }, -- Sacrificial Chamber
{ 0x27, 0x36, 164 }, -- Garlaige Citadel [S]
{ 0x14, 0x5D, 165 }, -- Throne Room
{ 0x14, 0x2D, 166 }, -- Ranguemont Pass
{ 0x14, 0x32, 167 }, -- Bostaunieux Oubliette
{ 0x14, 0x3B, 168 }, -- Chamber of Oracles
{ 0x14, 0x1D, 169 }, -- Toraimarai Canal
{ 0x14, 0x5C, 170 }, -- Full Moon Fountain
{ 0x27, 0x29, 171 }, -- Crawlers' Nest [S]
{ 0x14, 0x61, 172 }, -- Zeruhn Mines
{ 0x14, 0x5B, 173 }, -- Korroloka Tunnel
{ 0x14, 0x5A, 174 }, -- Kuftal Tunnel
{ 0x27, 0x1A, 175 }, -- The Eldieme Necropolis [S]
{ 0x14, 0x59, 176 }, -- Sea Serpent Grotto
{ 0x14, 0x71, 177 }, -- Ve'Lugannon Palace
{ 0x14, 0x70, 177 }, -- Ve'Lugannon Palace
{ 0x14, 0x72, 178 }, -- The Shrine of Ru'Avitau
{ 0x14, 0xB3, 179 }, -- Stellar Fulcrum
{ 0x14, 0x73, 180 }, -- La'Loff Amphitheater
{ 0x14, 0x74, 181 }, -- The Celestial Nexus
{ 0x14, 0x0D, 184 }, -- Lower Delkfutt's Tower
{ 0x14, 0x7E, 185 }, -- Dynamis - San d'Oria
{ 0x14, 0x7F, 186 }, -- Dynamis - Bastok
{ 0x14, 0x80, 187 }, -- Dynamis - Windurst
{ 0x14, 0x81, 188 }, -- Dynamis - Jeuno
{ 0x14, 0x6E, 190 }, -- King Ranperre's Tomb
{ 0x14, 0x62, 191 }, -- Dangruf Wadi
{ 0x14, 0x1C, 192 }, -- Inner Horutoto Ruins
{ 0x14, 0x03, 193 }, -- Ordelle's Caves
{ 0x14, 0x1B, 194 }, -- Outer Horutoto Ruins
{ 0x14, 0x6A, 195 }, -- The Eldieme Necropolis
{ 0x14, 0x67, 196 }, -- Gusgen Mines
{ 0x14, 0x2C, 197 }, -- Crawlers' Nest
{ 0x14, 0x15, 198 }, -- Maze of Shakhrami
{ 0x14, 0x14, 200 }, -- Garlaige Citadel
{ 0x14, 0x77, 201 }, -- Cloister of Gales
{ 0x14, 0x75, 202 }, -- Cloister of Storms
{ 0x14, 0x7A, 203 }, -- Cloister of Frost
{ 0x14, 0x4A, 204 }, -- Fei'Yin
{ 0x14, 0x58, 205 }, -- Ifrit's Cauldron
{ 0x14, 0x6B, 206 }, -- Qu'Bia Arena
{ 0x14, 0x78, 207 }, -- Cloister of Flames
{ 0x14, 0x57, 208 }, -- Quicksand Caves
{ 0x14, 0x76, 209 }, -- Cloister of Tremors
{ 0x14, 0x79, 211 }, -- Cloister of Tides
{ 0x14, 0x34, 212 }, -- Gustav Tunnel
{ 0x14, 0x33, 213 }, -- Labyrinth of Onzozo
{ 0x14, 0x4C, 230 }, -- Southern San d'Oria
{ 0x14, 0x30, 231 }, -- Northern San d'Oria
{ 0x14, 0x52, 232 }, -- Port San d'Oria
{ 0x14, 0x22, 233 }, -- Chateau d'Oraguille
{ 0x14, 0x46, 234 }, -- Bastok Mines
{ 0x14, 0x56, 235 }, -- Bastok Markets
{ 0x14, 0x3C, 236 }, -- Port Bastok
{ 0x14, 0x2F, 237 }, -- Metalworks
{ 0x14, 0x3A, 238 }, -- Windurst Waters
{ 0x14, 0x54, 239 }, -- Windurst Walls
{ 0x14, 0x45, 240 }, -- Port Windurst
{ 0x14, 0x38, 241 }, -- Windurst Woods
{ 0x14, 0x55, 242 }, -- Heavens Tower
{ 0x14, 0x13, 243 }, -- Ru'Lude Gardens
{ 0x14, 0x4E, 244 }, -- Upper Jeuno
{ 0x14, 0x0E, 245 }, -- Lower Jeuno
{ 0x14, 0x06, 246 }, -- Port Jeuno
{ 0x14, 0x31, 247 }, -- Rabao
{ 0x14, 0x5F, 248 }, -- Selbina
{ 0x14, 0x1E, 249 }, -- Mhaura
{ 0x14, 0x29, 250 }, -- Kazham
{ 0x14, 0x7B, 251 }, -- Hall of the Gods
{ 0x14, 0x09, 252 }, -- Norg
{ 0x27, 0x4C, 256 }, -- Western Adoulin
{ 0x27, 0x4D, 257 }, -- Eastern Adoulin
{ 0x27, 0x4E, 259 }, -- Rala Waterways [U]
{ 0x27, 0x4F, 260 }, -- Yahse Hunting Grounds
{ 0x27, 0x50, 261 }, -- Ceizak Battlegrounds
{ 0x27, 0x51, 262 }, -- Foret de Hennetiel
{ 0x27, 0x56, 264 }, -- Yorcia Weald [U]
{ 0x27, 0x52, 265 }, -- Morimar Basalt Fields
{ 0x27, 0x57, 266 }, -- Marjami Ravine
{ 0x27, 0x5C, 267 }, -- Kamihr Drifts
{ 0x27, 0x53, 268 }, -- Sih Gates
{ 0x27, 0x54, 269 }, -- Moh Gates
{ 0x27, 0x55, 271 }, -- Cirdas Caverns [U]
{ 0x27, 0x58, 272 }, -- Dho Gates
{ 0x27, 0x5D, 273 }, -- Woh Gates
{ 0x27, 0x12, 275 }, -- Outer Ra'Kaznar [U]
{ 0x27, 0x5A, 280 }, -- Mog Garden
{ 0x27, 0x59, 284 }, -- Celennia Memorial Library
{ 0x27, 0x5B, 285 }, -- Feretory
};
---------------------------------------------------------------------------------------------------
-- func: onTrigger
-- desc: Called when this command is invoked.
---------------------------------------------------------------------------------------------------
function onTrigger(player, zoneId)
local word = "";
local i = 0;
local zone = zoneId;
-- Ensure a zone was given..
if (zoneId == nil) then
player:PrintToPlayer("You must enter a zone id.");
return;
end
-- Was the zone auto-translated..
if (string.sub(zoneId, 1, 2) == '\253\02' and string.byte(zoneId, 5) ~= nil and string.byte(zoneId, 6) == 0xFD) then
-- Pull the group and message id from the translated string..
local groupId = string.byte(zoneId, 4);
local messageId = string.byte(zoneId, 5);
-- Attempt to lookup this zone..
for k, v in pairs(zone_list) do
if (v[1] == groupId and v[2] == messageId) then
player:setPos(0, 0, 0, 0, v[3]);
return;
end
end
-- Zone was not found, allow the user to know..
player:PrintToPlayer('Unknown zone, could not teleport.');
return;
end
player:setPos(0, 0, 0, 0, zoneId);
end
| gpl-3.0 |
geanux/darkstar | scripts/zones/Ranguemont_Pass/npcs/Perchond.lua | 19 | 1579 | -----------------------------------
-- Area: Ranguemont Pass
-- NPC: Perchond
-- @pos -182.844 4 -164.948 166
-----------------------------------
package.loaded["scripts/zones/Ranguemont_Pass/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(1107,1) and trade:getItemCount() == 1) then -- glitter sand
local SinHunting = player:getVar("sinHunting"); -- RNG AF1
if (SinHunting == 2) then
player:startEvent(0x0005);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local SinHunting = player:getVar("sinHunting"); -- RNG AF1
if (SinHunting == 1) then
player:startEvent(0x0003, 0, 1107);
else
player:startEvent(0x0002);
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 == 3) then
player:setVar("sinHunting",2);
elseif (csid == 5) then
player:tradeComplete();
player:addKeyItem(PERCHONDS_ENVELOPE);
player:messageSpecial(KEYITEM_OBTAINED,PERCHONDS_ENVELOPE);
player:setVar("sinHunting",3);
end
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Quicksand_Caves/npcs/_5s2.lua | 17 | 1275 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: Ornate Door
-- Door blocked by Weight system
-- @pos -574 0 -420 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()-(-565);
local difZ = player:getZPos()-(-420);
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 |
geanux/darkstar | scripts/zones/King_Ranperres_Tomb/npcs/_5a0.lua | 17 | 2401 | -----------------------------------
-- Area: King Ranperre's Tomb
-- DOOR: _5a0 (Heavy Stone Door)
-- @pos -39.000 4.823 20.000 190
-----------------------------------
package.loaded["scripts/zones/King_Ranperres_Tomb/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/King_Ranperres_Tomb/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local currentMission = player:getCurrentMission(SANDORIA);
local MissionStatus = player:getVar("MissionStatus");
if (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 1) then
if (GetMobAction(17555898) == 0 and GetMobAction(17555899) == 0 and GetMobAction(17555900) == 0) then
if (player:getVar("Mission6-2MobKilled") == 1) then
player:setVar("Mission6-2MobKilled",0);
player:setVar("MissionStatus",2);
else
SpawnMob(17555898):updateClaim(player);
SpawnMob(17555899):updateClaim(player);
SpawnMob(17555900):updateClaim(player);
end
end
elseif (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 2) then
player:startEvent(0x0006);
elseif (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 3) then
player:startEvent(0x0007);
elseif (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 8) then
player:startEvent(0x0005);
elseif (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 6) then
player:startEvent(0x000e);
else
player:messageSpecial(HEAVY_DOOR);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0005) then
player:setVar("MissionStatus",9);
elseif (csid == 0x000e) then
player:setVar("MissionStatus",7);
-- at this point 3 optional cs are available and open until watched (add 3 var to char?)
end
end;
| gpl-3.0 |
geanux/darkstar | scripts/globals/spells/bluemagic/magic_fruit.lua | 18 | 1794 | -----------------------------------------
-- Spell: Magic Fruit
-- Restores HP for the target party member
-- Spell cost: 72 MP
-- Monster Type: Beasts
-- Spell Type: Magical (Light)
-- Blue Magic Points: 3
-- Stat Bonus: CHR+1 HP+5
-- Level: 58
-- Casting Time: 3.5 seconds
-- Recast Time: 6 seconds
--
-- Combos: Resist Sleep
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local minCure = 250;
local divisor = 0.6666;
local constant = 130;
local power = getCurePowerOld(caster);
local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,true);
local diff = (target:getMaxHP() - target:getHP());
if (power > 559) then
divisor = 2.8333;
constant = 391.2
elseif (power > 319) then
divisor = 1;
constant = 210;
end
final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100));
if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then
--Applying server mods....
final = final * CURE_POWER;
end
if (final > diff) then
final = diff;
end
target:addHP(final);
target:wakeUp();
caster:updateEnmityFromCure(target,final);
spell:setMsg(7);
return final;
end; | gpl-3.0 |
geanux/darkstar | scripts/zones/Giddeus/npcs/HomePoint#1.lua | 17 | 1234 | -----------------------------------
-- Area: Giddeus
-- NPC: HomePoint#1
-- @pos -132 -3 -303 145
-----------------------------------
package.loaded["scripts/zones/Giddeus/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Giddeus/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 54);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end;
| gpl-3.0 |
tonylauCN/tutorials | openresty/debugger/lualibs/luacheck/lua_fs.lua | 5 | 1954 | local utils = require "luacheck.utils"
local lua_fs = {}
-- Quotes an argument for a command for os.execute or io.popen.
-- Same code has been contributed to pl.
local function quote_arg(argument)
if utils.is_windows then
if argument == "" or argument:find('[ \f\t\v]') then
-- Need to quote the argument.
-- Quotes need to be escaped with backslashes;
-- additionally, backslashes before a quote, escaped or not,
-- need to be doubled.
-- See documentation for CommandLineToArgvW Windows function.
argument = '"' .. argument:gsub([[(\*)"]], [[%1%1\"]]):gsub([[\+$]], "%0%0") .. '"'
end
-- os.execute() uses system() C function, which on Windows passes command
-- to cmd.exe. Escape its special characters.
return (argument:gsub('["^<>!|&%%]', "^%0"))
else
if argument == "" or argument:find('[^a-zA-Z0-9_@%+=:,./-]') then
-- To quote arguments on posix-like systems use single quotes.
-- To represent an embedded single quote close quoted string ('),
-- add escaped quote (\'), open quoted string again (').
argument = "'" .. argument:gsub("'", [['\'']]) .. "'"
end
return argument
end
end
local mode_cmd_template
if utils.is_windows then
mode_cmd_template = [[if exist %s\* (echo directory) else (if exist %s echo file)]]
else
mode_cmd_template = [[if [ -d %s ]; then echo directory; elif [ -f %s ]; then echo file; fi]]
end
function lua_fs.get_mode(path)
local quoted_path = quote_arg(path)
local fh = assert(io.popen(mode_cmd_template:format(quoted_path, quoted_path)))
local mode = fh:read("*a"):match("^(%S*)")
fh:close()
return mode
end
local pwd_cmd = utils.is_windows and "cd" or "pwd"
function lua_fs.get_current_dir()
local fh = assert(io.popen(pwd_cmd))
local current_dir = fh:read("*a"):gsub("\n$", "")
fh:close()
return current_dir
end
return lua_fs
| apache-2.0 |
geanux/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Ezura-Romazura.lua | 34 | 1541 | -----------------------------------
-- Area: Windurst Waters [S]
-- NPC: Ezura-Romazura
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/zones/Windurst_Waters_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,EZURAROMAZURA_SHOP_DIALOG);
stock = {0x12a3,123750, -- Scroll of Stone V
0x12ad,133110, -- Scroll of Water V
0x129e,144875, -- Scroll of Aero V
0x1294,162500, -- Scroll of Fire V
0x1299,186375, -- Scroll of Blizzard V
0x131d,168150, -- Scroll of Stoneja
0x131f,176700, -- Scroll of Waterja
0x131a,193800, -- Scroll of Firaja
0x131c,185240, -- Scroll of Aeroja
0x12ff,126000} -- Scroll of Break
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 |
geanux/darkstar | scripts/zones/Phomiuna_Aqueducts/npcs/_ir7.lua | 17 | 1502 | -----------------------------------
-- Area: Phomiuna_Aqueducts
-- NPC: _ir7 (Iron Gate)
-- @pos -70.800 -1.500 60.000 27
-----------------------------------
package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Phomiuna_Aqueducts/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(1660,1) and trade:getItemCount() == 1) then -- Bronze Key
player:tradeComplete();
npc:openDoor(15);
elseif (trade:hasItemQty(1022,1) and trade:getItemCount() == 1 and player:getMainJob() == 6) then -- thief's tool
player:tradeComplete();
npc:openDoor(15);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getXPos() <= -71) then
npc:openDoor(15); -- Retail timed
else
player:messageSpecial(DOOR_LOCKED,1660);
end
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 |
geanux/darkstar | scripts/zones/Port_Jeuno/npcs/Challoux.lua | 37 | 1148 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Challoux
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,CHALLOUX_SHOP_DIALOG);
stock = {0x11C1,62, --Gysahl Greens
0x0348,4, --Chocobo Feather
0x439B,9} --Dart
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 |
geanux/darkstar | scripts/globals/spells/raiton_ichi.lua | 17 | 1257 | -----------------------------------------
-- Spell: Raiton: Ichi
-- Deals lightning damage to an enemy and lowers its resistance against earth.
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
--doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus)
local duration = 15 + caster:getMerit(MERIT_RAITON_EFFECT) -- T1 bonus debuff duration
local bonusAcc = 0;
local bonusMab = caster:getMerit(MERIT_RAITON_EFFECT) + caster:getMod(MOD_NIN_NUKE_BONUS); -- T1 mag atk + "enhances Ninjustu damage" mod
if (caster:isBehind(target,15) and caster:hasStatusEffect(EFFECT_INNIN)) then -- Innin mag atk bonus from behind, guesstimating angle at 15 degrees
bonusMab = bonusMab + caster:getStatusEffect(EFFECT_INNIN):getPower();
end
local dmg = doNinjutsuNuke(28,1,caster,spell,target,false,bonusAcc,bonusMab);
handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_EARTHRES);
return dmg;
end; | gpl-3.0 |
evilexecutable/ResourceKeeper | install/Lua/lib/lua/pl/data.lua | 12 | 18170 | --- Reading and querying simple tabular data.
--
-- data.read 'test.txt'
-- ==> {{10,20},{2,5},{40,50},fieldnames={'x','y'},delim=','}
--
-- Provides a way of creating basic SQL-like queries.
--
-- require 'pl'
-- local d = data.read('xyz.txt')
-- local q = d:select('x,y,z where x > 3 and z < 2 sort by y')
-- for x,y,z in q do
-- print(x,y,z)
-- end
--
-- See @{06-data.md.Reading_Columnar_Data|the Guide}
--
-- Dependencies: `pl.utils`, `pl.array2d` (fallback methods)
-- @module pl.data
local utils = require 'pl.utils'
local _DEBUG = rawget(_G,'_DEBUG')
local patterns,function_arg,usplit = utils.patterns,utils.function_arg,utils.split
local append,concat = table.insert,table.concat
local gsub = string.gsub
local io = io
local _G,print,type,tonumber,ipairs,setmetatable,pcall,error,setfenv = _G,print,type,tonumber,ipairs,setmetatable,pcall,error,setfenv
local data = {}
local parse_select
local function count(s,chr)
chr = utils.escape(chr)
local _,cnt = s:gsub(chr,' ')
return cnt
end
local function rstrip(s)
return s:gsub('%s+$','')
end
local function make_list(l)
return setmetatable(l,utils.stdmt.List)
end
local function split(s,delim)
return make_list(usplit(s,delim))
end
local function map(fun,t)
local res = {}
for i = 1,#t do
append(res,fun(t[i]))
end
return res
end
local function find(t,v)
for i = 1,#t do
if v == t[i] then return i end
end
end
local DataMT = {
column_by_name = function(self,name)
if type(name) == 'number' then
name = '$'..name
end
local arr = {}
for res in data.query(self,name) do
append(arr,res)
end
return make_list(arr)
end,
copy_select = function(self,condn)
condn = parse_select(condn,self)
local iter = data.query(self,condn)
local res = {}
local row = make_list{iter()}
while #row > 0 do
append(res,row)
row = make_list{iter()}
end
res.delim = self.delim
return data.new(res,split(condn.fields,','))
end,
column_names = function(self)
return self.fieldnames
end,
}
local array2d
DataMT.__index = function(self,name)
local f = DataMT[name]
if f then return f end
if not array2d then
array2d = require 'pl.array2d'
end
return array2d[name]
end
--- return a particular column as a list of values (method).
-- @param name either name of column, or numerical index.
-- @function Data.column_by_name
--- return a query iterator on this data (method).
-- @param condn the query expression
-- @function Data.select
-- @see data.query
--- return a row iterator on this data (method).
-- @param condn the query expression
-- @function Data.select_row
--- return a new data object based on this query (method).
-- @param condn the query expression
-- @function Data.copy_select
--- return the field names of this data object (method).
-- @function Data.column_names
--- write out a row (method).
-- @param f file-like object
-- @function Data.write_row
--- write data out to file (method).
-- @param f file-like object
-- @function Data.write
-- [guessing delimiter] We check for comma, tab and spaces in that order.
-- [issue] any other delimiters to be checked?
local delims = {',','\t',' ',';'}
local function guess_delim (line)
if line=='' then return ' ' end
for _,delim in ipairs(delims) do
if count(line,delim) > 0 then
return delim == ' ' and '%s+' or delim
end
end
return ' '
end
-- [file parameter] If it's a string, we try open as a filename. If nil, then
-- either stdin or stdout depending on the mode. Otherwise, check if this is
-- a file-like object (implements read or write depending)
local function open_file (f,mode)
local opened, err
local reading = mode == 'r'
if type(f) == 'string' then
if f == 'stdin' then
f = io.stdin
elseif f == 'stdout' then
f = io.stdout
else
f,err = io.open(f,mode)
if not f then return nil,err end
opened = true
end
end
if f and ((reading and not f.read) or (not reading and not f.write)) then
return nil, "not a file-like object"
end
return f,nil,opened
end
local function all_n ()
end
--- read a delimited file in a Lua table.
-- By default, attempts to treat first line as separated list of fieldnames.
-- @param file a filename or a file-like object (default stdin)
-- @param cnfg options table: can override delim (a string pattern), fieldnames (a list),
-- specify no_convert (default is to convert), numfields (indices of columns known
-- to be numbers) and thousands_dot (thousands separator in Excel CSV is '.')
function data.read(file,cnfg)
local convert,err,opened
local D = {}
if not cnfg then cnfg = {} end
local f,err,opened = open_file(file,'r')
if not f then return nil, err end
local thousands_dot = cnfg.thousands_dot
local function try_tonumber(x)
if thousands_dot then x = x:gsub('%.(...)','%1') end
return tonumber(x)
end
local line = f:read()
if not line then return nil, "empty file" end
-- first question: what is the delimiter?
D.delim = cnfg.delim and cnfg.delim or guess_delim(line)
local delim = D.delim
local collect_end = cnfg.last_field_collect
local numfields = cnfg.numfields
-- some space-delimited data starts with a space. This should not be a column,
-- although it certainly would be for comma-separated, etc.
local strip
if delim == '%s+' and line:find(delim) == 1 then
strip = function(s) return s:gsub('^%s+','') end
line = strip(line)
end
-- first line will usually be field names. Unless fieldnames are specified,
-- we check if it contains purely numerical values for the case of reading
-- plain data files.
if not cnfg.fieldnames then
local fields = split(line,delim)
local nums = map(tonumber,fields)
if #nums == #fields then
convert = tonumber
append(D,nums)
numfields = {}
for i = 1,#nums do numfields[i] = i end
else
cnfg.fieldnames = fields
end
line = f:read()
if strip then line = strip(line) end
elseif type(cnfg.fieldnames) == 'string' then
cnfg.fieldnames = split(cnfg.fieldnames,delim)
end
-- at this point, the column headers have been read in. If the first
-- row consisted of numbers, it has already been added to the dataset.
if cnfg.fieldnames then
D.fieldnames = cnfg.fieldnames
-- [conversion] unless @no_convert, we need the numerical field indices
-- of the first data row. Can also be specified by @numfields.
if not cnfg.no_convert then
if not numfields then
numfields = {}
local fields = split(line,D.delim)
for i = 1,#fields do
if tonumber(fields[i]) then
append(numfields,i)
end
end
end
if #numfields > 0 then -- there are numerical fields
-- note that using dot as the thousands separator (@thousands_dot)
-- requires a special conversion function!
convert = thousands_dot and try_tonumber or tonumber
end
end
end
-- keep going until finished
while line do
if not line:find ('^%s*$') then
if strip then line = strip(line) end
local fields = split(line,delim)
if convert then
for k = 1,#numfields do
local i = numfields[k]
local val = convert(fields[i])
if val == nil then
return nil, "not a number: "..fields[i]
else
fields[i] = val
end
end
end
-- [collecting end field] If @last_field_collect then we will collect
-- all extra space-delimited fields into a single last field.
if collect_end and #fields > #D.fieldnames then
local ends,N = {},#D.fieldnames
for i = N+1,#fields do
append(ends,fields[i])
end
ends = concat(ends,' ')
local cfields = {}
for i = 1,N do cfields[i] = fields[i] end
cfields[N] = cfields[N]..' '..ends
fields = cfields
end
append(D,fields)
end
line = f:read()
end
if opened then f:close() end
if delim == '%s+' then D.delim = ' ' end
if not D.fieldnames then D.fieldnames = {} end
return data.new(D)
end
local function write_row (data,f,row,delim)
f:write(concat(row,delim),'\n')
end
function DataMT:write_row(f,row)
write_row(self,f,row,self.delim)
end
--- write 2D data to a file.
-- Does not assume that the data has actually been
-- generated with `new` or `read`.
-- @param data 2D array
-- @param file filename or file-like object
-- @param fieldnames list of fields (optional)
-- @param delim delimiter (default tab)
function data.write (data,file,fieldnames,delim)
local f,err,opened = open_file(file,'w')
if not f then return nil, err end
if fieldnames and #fieldnames > 0 then
f:write(concat(data.fieldnames,delim),'\n')
end
delim = delim or '\t'
for i = 1,#data do
write_row(data,f,data[i],delim)
end
if opened then f:close() end
end
function DataMT:write(file)
data.write(self,file,self.fieldnames,self.delim)
end
local function massage_fieldnames (fields)
-- fieldnames must be valid Lua identifiers; ignore any surrounding padding
for i = 1,#fields do
fields[i] = rstrip(fields[i]):gsub('^%s*',''):gsub('%W','_')
end
end
--- create a new dataset from a table of rows.
-- Can specify the fieldnames, else the table must have a field called
-- 'fieldnames', which is either a string of delimiter-separated names,
-- or a table of names. <br>
-- If the table does not have a field called 'delim', then an attempt will be
-- made to guess it from the fieldnames string, defaults otherwise to tab.
-- @param d the table.
-- @param fieldnames optional fieldnames
-- @return the table.
function data.new (d,fieldnames)
d.fieldnames = d.fieldnames or fieldnames or ''
if not d.delim and type(d.fieldnames) == 'string' then
d.delim = guess_delim(d.fieldnames)
d.fieldnames = split(d.fieldnames,d.delim)
end
d.fieldnames = make_list(d.fieldnames)
massage_fieldnames(d.fieldnames)
setmetatable(d,DataMT)
-- a query with just the fieldname will return a sequence
-- of values, which seq.copy turns into a table.
return d
end
local sorted_query = [[
return function (t)
local i = 0
local v
local ls = {}
for i,v in ipairs(t) do
if CONDITION then
ls[#ls+1] = v
end
end
table.sort(ls,function(v1,v2)
return SORT_EXPR
end)
local n = #ls
return function()
i = i + 1
v = ls[i]
if i > n then return end
return FIELDLIST
end
end
]]
-- question: is this optimized case actually worth the extra code?
local simple_query = [[
return function (t)
local n = #t
local i = 0
local v
return function()
repeat
i = i + 1
v = t[i]
until i > n or CONDITION
if i > n then return end
return FIELDLIST
end
end
]]
local function is_string (s)
return type(s) == 'string'
end
local field_error
local function fieldnames_as_string (data)
return concat(data.fieldnames,',')
end
local function massage_fields(data,f)
local idx
if f:find '^%d+$' then
idx = tonumber(f)
else
idx = find(data.fieldnames,f)
end
if idx then
return 'v['..idx..']'
else
field_error = f..' not found in '..fieldnames_as_string(data)
return f
end
end
local function process_select (data,parms)
--- preparing fields ----
local res,ret
field_error = nil
local fields = parms.fields
local numfields = fields:find '%$' or #data.fieldnames == 0
if fields:find '^%s*%*%s*' then
if not numfields then
fields = fieldnames_as_string(data)
else
local ncol = #data[1]
fields = {}
for i = 1,ncol do append(fields,'$'..i) end
fields = concat(fields,',')
end
end
local idpat = patterns.IDEN
if numfields then
idpat = '%$(%d+)'
else
-- massage field names to replace non-identifier chars
fields = rstrip(fields):gsub('[^,%w]','_')
end
local massage_fields = utils.bind1(massage_fields,data)
ret = gsub(fields,idpat,massage_fields)
if field_error then return nil,field_error end
parms.fields = fields
parms.proc_fields = ret
parms.where = parms.where or 'true'
if is_string(parms.where) then
parms.where = gsub(parms.where,idpat,massage_fields)
field_error = nil
end
return true
end
parse_select = function(s,data)
local endp
local parms = {}
local w1,w2 = s:find('where ')
local s1,s2 = s:find('sort by ')
if w1 then -- where clause!
endp = (s1 or 0)-1
parms.where = s:sub(w2+1,endp)
end
if s1 then -- sort by clause (must be last!)
parms.sort_by = s:sub(s2+1)
end
endp = (w1 or s1 or 0)-1
parms.fields = s:sub(1,endp)
local status,err = process_select(data,parms)
if not status then return nil,err
else return parms end
end
--- create a query iterator from a select string.
-- Select string has this format: <br>
-- FIELDLIST [ where LUA-CONDN [ sort by FIELD] ]<br>
-- FIELDLIST is a comma-separated list of valid fields, or '*'. <br> <br>
-- The condition can also be a table, with fields 'fields' (comma-sep string or
-- table), 'sort_by' (string) and 'where' (Lua expression string or function)
-- @param data table produced by read
-- @param condn select string or table
-- @param context a list of tables to be searched when resolving functions
-- @param return_row if true, wrap the results in a row table
-- @return an iterator over the specified fields, or nil
-- @return an error message
function data.query(data,condn,context,return_row)
local err
if is_string(condn) then
condn,err = parse_select(condn,data)
if not condn then return nil,err end
elseif type(condn) == 'table' then
if type(condn.fields) == 'table' then
condn.fields = concat(condn.fields,',')
end
if not condn.proc_fields then
local status,err = process_select(data,condn)
if not status then return nil,err end
end
else
return nil, "condition must be a string or a table"
end
local query, k
if condn.sort_by then -- use sorted_query
query = sorted_query
else
query = simple_query
end
local fields = condn.proc_fields or condn.fields
if return_row then
fields = '{'..fields..'}'
end
query,k = query:gsub('FIELDLIST',fields)
if is_string(condn.where) then
query = query:gsub('CONDITION',condn.where)
condn.where = nil
else
query = query:gsub('CONDITION','_condn(v)')
condn.where = function_arg(0,condn.where,'condition.where must be callable')
end
if condn.sort_by then
local expr,sort_var,sort_dir
local sort_by = condn.sort_by
local i1,i2 = sort_by:find('%s+')
if i1 then
sort_var,sort_dir = sort_by:sub(1,i1-1),sort_by:sub(i2+1)
else
sort_var = sort_by
sort_dir = 'asc'
end
if sort_var:match '^%$' then sort_var = sort_var:sub(2) end
sort_var = massage_fields(data,sort_var)
if field_error then return nil,field_error end
if sort_dir == 'asc' then
sort_dir = '<'
else
sort_dir = '>'
end
expr = ('%s %s %s'):format(sort_var:gsub('v','v1'),sort_dir,sort_var:gsub('v','v2'))
query = query:gsub('SORT_EXPR',expr)
end
if condn.where then
query = 'return function(_condn) '..query..' end'
end
if _DEBUG then print(query) end
local fn,err = loadstring(query,'tmp')
if not fn then return nil,err end
fn = fn() -- get the function
if condn.where then
fn = fn(condn.where)
end
local qfun = fn(data)
if context then
-- [specifying context for condition] @context is a list of tables which are
-- 'injected'into the condition's custom context
append(context,_G)
local lookup = {}
setfenv(qfun,lookup)
setmetatable(lookup,{
__index = function(tbl,key)
-- _G.print(tbl,key)
for k,t in ipairs(context) do
if t[key] then return t[key] end
end
end
})
end
return qfun
end
DataMT.select = data.query
DataMT.select_row = function(d,condn,context)
return data.query(d,condn,context,true)
end
--- Filter input using a query.
-- @param Q a query string
-- @param infile filename or file-like object
-- @param outfile filename or file-like object
-- @param dont_fail true if you want to return an error, not just fail
function data.filter (Q,infile,outfile,dont_fail)
local err
local d = data.read(infile or 'stdin')
local out = open_file(outfile or 'stdout')
local iter,err = d:select(Q)
local delim = d.delim
if not iter then
err = 'error: '..err
if dont_fail then
return nil,err
else
utils.quit(1,err)
end
end
while true do
local res = {iter()}
if #res == 0 then break end
out:write(concat(res,delim),'\n')
end
end
return data
| gpl-2.0 |
blackops97/SAJJAD.iq | tg/lock_media.lua | 14 | 1480 | --[[
#
#ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ
#:((
# For More Information ....!
# Developer : Aziz < @TH3_GHOST >
# our channel: @DevPointTeam
# Version: 1.1
#:))
#ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ
#
]]
local function DevPoint(msg, matches)
if is_momod(msg) then
return
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['media'] then
lock_media = data[tostring(msg.to.id)]['settings']['media']
end
end
end
local chat = get_receiver(msg)
local user = "user#id"..msg.from.id
if lock_media == "yes" then
delete_msg(msg.id, ok_cb, true)
send_large_msg(get_receiver(msg), 'عزيزي " '..msg.from.first_name..' "\nممنوع مشاركة " الصور - الروابط - الاعلانات - المواقع " هنا التزم بقوانين المجموعة 👮\n#Username : @'..msg.from.username)
end
end
return {
patterns = {
"%[(photo)%]",
"%[(document)%]",
"%[(video)%]",
"%[(audio)%]",
"%[(gif)%]",
"%[(sticker)%]",
},
run = DevPoint
} | gpl-2.0 |
geanux/darkstar | scripts/zones/Vunkerl_Inlet_[S]/npcs/qm7.lua | 45 | 2168 | -----------------------------------
-- Area: Vunkerl Inlet (S) (H-6)
-- NPC: ???
-- Involved in Quests
-- @pos -26 -31 364
-----------------------------------
package.loaded["scripts/zones/Vunkerl_Inlet_[S]/TextIDs"] = nil;
package.loaded["scripts/globals/quests"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Vunkerl_Inlet_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(CRYSTAL_WAR, BOY_AND_THE_BEAST) == QUEST_AVAILABLE and player:getVar("BoyAndTheBeast") == 2) then
player:startEvent(0x0069);
elseif (player:getQuestStatus(CRYSTAL_WAR, BOY_AND_THE_BEAST) == QUEST_ACCEPTED and player:getVar("BoyAndTheBeast") == 3) then
player:startEvent(0x006C);
elseif (player:getQuestStatus(CRYSTAL_WAR, BOY_AND_THE_BEAST) == QUEST_ACCEPTED and player:getVar("BoyAndTheBeast") == 4) then
player:startEvent(0x006D);
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0069) then
player:addQuest(CRYSTAL_WAR, BOY_AND_THE_BEAST);
player:addKeyItem(VUNKERL_HERB_MEMO);
player:messageSpecial(KEYITEM_OBTAINED, VUNKERL_HERB_MEMO);
elseif (csid == 0x006C) then
if(player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17384); -- Carbon Fishing Rod
else
player:completeQuest(CRYSTAL_WAR, BOY_AND_THE_BEAST);
player:delKeyItem(VUNKERL_HERB_MEMO);
player:delKeyItem(VUNKERL_HERB);
player:addItem(17384);
player:messageSpecial(ITEM_OBTAINED,17384); --Carbon Fishing Rod
end
elseif (csid == 0x006D) then
player:delKeyItem(VUNKERL_HERB);
player:setVar("BoyAndTheBeast",2);
end
end;
| gpl-3.0 |
geanux/darkstar | scripts/globals/mobskills/Ill_Wind.lua | 15 | 1309 | ---------------------------------------------
-- Ill Wind
-- Description: Deals Wind damage to enemies within an area of effect. Additional effect: Dispel
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes Shadows
-- Range: Unknown radial
-- Notes: Only used by Puks in Mamook, Besieged, and the following Notorious Monsters: Vulpangue, Nis Puk, Nguruvilu, Seps , Phantom Puk and Waugyl. Dispels one effect.
---------------------------------------------
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)
target:dispelStatusEffect();
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*2.5,ELE_WIND,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS);
target:delHP(dmg);
--printf("[TP MOVE] Zone: %u Monster: %u Mob lvl: %u TP: %u TP Move: %u Damage: %u on Player: %u Level: %u HP: %u",mob:getZoneID(),mob:getID(),mob:getMainLvl(),skill:getTP(),skill:getID(),dmg,target:getID(),target:getMainLvl(),target:getMaxHP());
return dmg;
end;
| gpl-3.0 |
kaen/Zero-K | LuaRules/Gadgets/mod_stats.lua | 7 | 7701 | -- $Id: unit_noselfpwn.lua 3171 2008-11-06 09:06:29Z det $
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Mod statistics",
desc = "Gathers mod statistics",
author = "Licho",
date = "29.3.2009",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if VFS.FileExists("mission.lua") then
-- stats are meaningless in missions
return
end
if (not gadgetHandler:IsSyncedCode()) then
return false -- silent removal
end
local damages = {} -- damages[attacker][victim] = { damage, emp}
local unitCounts = {} -- unitCounts[defID] = { created, destroyed}
local lastPara = {}
local plops = {}
local Echo = Spring.Echo
local spGameOver = Spring.IsGameOver
local spGetUnitHealth = Spring.GetUnitHealth
local spAreTeamsAllied = Spring.AreTeamsAllied
local gaiaTeamID = Spring.GetGaiaTeamID()
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- drones are counted as parent for damage done, ignored for damage received
-- key = drone, value = parent
local drones = {
carrydrone = "reef",
wolverine_mine = "corgarp",
}
-- fallback for when attacker is already dead at damage event - attackerDefID == nil
-- probably should be autogenerated but meh
local weaponIDToUnitDefIDRaw = {
logkoda_napalm_bomblet = "logkoda",
firewalker_napalm_mortar = "firewalker",
corhurc2_napalm = "corhurc2",
corpyro_napalm = "corpyro",
corpyro_flamethrower = "corpyro",
dante_napalm_rockets = "dante",
dante_napalm_rocket_salvo = "dante",
dante_dante_flamer = "dante",
armtick_death = "armtick",
tacnuke_weapon = "tacnuke",
napalmmissile_weapon = "napalmmissile",
seismic_seismic_weapon = "seismic",
empmissile_emp_weapon = "emp",
wolverine_mine_bomblet = "corgarp",
}
local weaponIDToUnitDefID = {}
for weapon,unit in pairs(weaponIDToUnitDefIDRaw) do
if WeaponDefNames[weapon] and UnitDefNames[unit] then
local weaponDefID = WeaponDefNames[weapon].id
weaponIDToUnitDefID[weaponDefID] = UnitDefNames[unit].id
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Factory Plop
local function AddFactoryPlop(teamID, plopUnitDefID)
plops[#plops + 1] = {
teamID = teamID,
plopUnitDefID = plopUnitDefID,
}
end
GG.mod_stats_AddFactoryPlop = AddFactoryPlop
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:UnitDamaged(unitID, unitDefID, unitTeam, damage, paralyzer,
weaponID, attackerID, attackerDefID, attackerTeam)
if unitTeam == gaiaTeamID then
return
end
if weaponID and (not attackerDefID) then
attackerDefID = weaponIDToUnitDefID[weaponID]
--Spring.Echo(UnitDefs[attackerDefID].humanName)
end
if (attackerDefID == nil or unitDefID == nil or damage == nil) or (not attackerTeam) or (attackerTeam == unitTeam) or (damage < 0) or spAreTeamsAllied(attackerTeam, unitTeam) then
if (paralyzer) then
local hp, maxHp, paraDam = spGetUnitHealth(unitID)
local paraHp = maxHp - paraDam
if paraHp < 0 then paraHp = 0 end
lastPara[unitID] = paraHp
end
return
end
-- treat as different unit as needed
if drones[UnitDefs[unitDefID].name] then
return
end
if drones[UnitDefs[attackerDefID].name] then
local name = drones[UnitDefs[attackerDefID].name]
attackerDefID = (UnitDefNames[name] and UnitDefNames[name].id) or attackerDefID
end
local attackerAlias = UnitDefs[attackerDefID].customParams.statsname
if attackerAlias and UnitDefNames[attackerAlias] then
attackerDefID = UnitDefNames[attackerAlias].id
end
local defenderAlias = UnitDefs[unitDefID].customParams.statsname
if defenderAlias and UnitDefNames[defenderAlias] then
unitDefID = UnitDefNames[defenderAlias].id
end
local hp, maxHp, paraDam, capture, build = spGetUnitHealth(unitID)
if build >= 1 then
local tab = damages[attackerDefID]
if (tab == nil) then
tab = {}
damages[attackerDefID] = tab
end
local dam = tab[unitDefID]
if (dam == nil) then
dam = {0,0}
tab[unitDefID] = dam
end
local h
if (paralyzer) then h = lastPara[unitID] or maxHp
else h = hp + damage end
if h < 0 then h = 0 end
if h > maxHp then h = maxHp end
if (damage > h) then damage = h end
if (paralyzer) then
dam[2] = dam[2] + damage
else
dam[1] = dam[1] + damage
end
end
local paraHp = maxHp - paraDam
if paraHp < 0 then paraHp = 0 end
lastPara[unitID] = paraHp
end
function gadget:UnitCreated(unitID, unitDefID, unitTeam, builderID)
lastPara[unitID] = nil
local unitAlias = UnitDefs[unitDefID].customParams.statsname
if unitAlias and UnitDefNames[unitAlias] then
unitDefID = UnitDefNames[unitAlias].id
end
if (builderID == nil) then
local tab = unitCounts[unitDefID]
if (tab == nil) then
tab = {0,0}
unitCounts[unitDefID] = tab
end
tab[1] = tab[1] + 1
end
end
function gadget:UnitFinished(unitID, unitDefID, unitTeam)
lastPara[unitID] = nil
local unitAlias = UnitDefs[unitDefID].customParams.statsname
if unitAlias and UnitDefNames[unitAlias] then
unitDefID = UnitDefNames[unitAlias].id
end
local tab = unitCounts[unitDefID]
if (tab == nil) then
tab = {0,0}
unitCounts[unitDefID] = tab
end
tab[1] = tab[1] + 1
end
function gadget:UnitDestroyed(unitID, unitDefID, unitTeam)
lastPara[unitID] = nil
local unitAlias = UnitDefs[unitDefID].customParams.statsname
if unitAlias and UnitDefNames[unitAlias] then
unitDefID = UnitDefNames[unitAlias].id
end
local tab = unitCounts[unitDefID]
if (tab == nil) then
tab = {0,0}
unitCounts[unitDefID] = tab
end
tab[2] = tab[2] + 1
end
function SendData(statsData)
Spring.SendCommands("wbynum 255 SPRINGIE:stats,".. statsData)
end
function gadget:GameOver()
if GG.Chicken then
Spring.Log(gadget:GetInfo().name, LOG.INFO, "Chicken game; unit stats disabled")
return -- don't report stats in chicken
end
Spring.Echo("Submitting stats")
for atk, victims in pairs(damages) do
for victim, dam in pairs(victims) do
SendData("dmg,"..UnitDefs[atk].name .. ",".. UnitDefs[victim].name .. "," .. dam[1] .. "," .. dam[2])
end
end
for unit, counts in pairs(unitCounts) do
SendData("unit,"..UnitDefs[unit].name .. ",".. UnitDefs[unit].metalCost ..",".. counts[1] .. "," .. counts[2] .. "," .. UnitDefs[unit].health)
end
for _, data in ipairs(plops) do
-- Send Data here
end
local teams = Spring.GetTeamList()
local humanAlly = {}
local players = 0
gaiaTeam = Spring.GetGaiaTeamID()
for _, teamID in ipairs(teams) do
local teamLuaAI = Spring.GetTeamLuaAI(teamID)
if ((teamLuaAI == nil or teamLuaAI == "") and teamID ~= gaiaTeam) then
local _,_,_,ai,side,ally = Spring.GetTeamInfo(teamID)
if (not ai) then
humanAlly[ally] = 1
players = players + 1
end
end
end
local allycount = 0
for _,_ in pairs(humanAlly) do allycount = allycount + 1 end
SendData("teams,"..players .. ",".. allycount)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
geanux/darkstar | scripts/zones/Port_Jeuno/npcs/Zona_Shodhun.lua | 34 | 3745 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Zona Shodhun
-- Starts and Finishes Quest: Pretty Little Things
-- @zone 246
-- @pos -175 -5 -4
-----------------------------------
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
count = trade:getItemCount();
gil = trade:getGil();
itemQuality = 0;
if (trade:getItemCount() == 1 and trade:getGil() == 0) then
if (trade:hasItemQty(771,1)) then -- Yellow Rock
itemQuality = 2;
elseif (trade:hasItemQty(769,1) or -- Red Rock
trade:hasItemQty(770,1) or -- Blue Rock
trade:hasItemQty(772,1) or -- Green Rock
trade:hasItemQty(773,1) or -- Translucent Rock
trade:hasItemQty(774,1) or -- Purple Rock
trade:hasItemQty(775,1) or -- Black Rock
trade:hasItemQty(776,1) or -- White Rock
trade:hasItemQty(957,1) or -- Amaryllis
trade:hasItemQty(2554,1) or -- Asphodel
trade:hasItemQty(948,1) or -- Carnation
trade:hasItemQty(1120,1) or -- Casablanca
trade:hasItemQty(1413,1) or -- Cattleya
trade:hasItemQty(636,1) or -- Chamomile
trade:hasItemQty(959,1) or -- Dahlia
trade:hasItemQty(835,1) or -- Flax Flower
trade:hasItemQty(956,1) or -- Lilac
trade:hasItemQty(2507,1) or -- Lycopodium Flower
trade:hasItemQty(958,1) or -- Marguerite
trade:hasItemQty(1412,1) or -- Olive Flower
trade:hasItemQty(938,1) or -- Papaka Grass
trade:hasItemQty(1411,1) or -- Phalaenopsis
trade:hasItemQty(949,1) or -- Rain Lily
trade:hasItemQty(941,1) or -- Red Rose
trade:hasItemQty(1725,1) or -- Snow Lily
trade:hasItemQty(1410,1) or -- Sweet William
trade:hasItemQty(950,1) or -- Tahrongi Cactus
trade:hasItemQty(2960,1) or -- Water Lily
trade:hasItemQty(951,1)) then -- Wijnruit
itemQuality = 1;
end
end
PrettyLittleThings = player:getQuestStatus(JEUNO,PRETTY_LITTLE_THINGS);
if (itemQuality == 2) then
if (PrettyLittleThings == QUEST_COMPLETED) then
player:startEvent(0x2727, 0, 246, 4);
else
player:startEvent(0x2727, 0, 246, 2);
end
elseif (itemQuality == 1) then
if (PrettyLittleThings == QUEST_COMPLETED) then
player:startEvent(0x2727, 0, 246, 5);
elseif (PrettyLittleThings == QUEST_ACCEPTED) then
player:startEvent(0x2727, 0, 246, 3);
else
player:startEvent(0x2727, 0, 246, 1);
end
else
player:startEvent(0x2727, 0, 246, 0);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x2727, 0, 246, 10);
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 == 0x2727 and option == 4002) then
player:moghouseFlag(8);
player:messageSpecial(MOGHOUSE_EXIT);
player:addFame(JEUNO, JEUNO_FAME*30);
player:tradeComplete();
player:completeQuest(JEUNO,PRETTY_LITTLE_THINGS);
elseif (csid == 0x2727 and option == 1) then
player:tradeComplete();
player:addQuest(JEUNO,PRETTY_LITTLE_THINGS);
end
end; | gpl-3.0 |
tonylauCN/tutorials | lua/debugger/lualibs/lexers/rexx.lua | 5 | 3991 | -- Copyright 2006-2016 Mitchell mitchell.att.foicica.com. See LICENSE.
-- Rexx LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'rexx'}
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local line_comment = '--' * l.nonnewline_esc^0
local block_comment = l.nested_pair('/*', '*/')
local comment = token(l.COMMENT, line_comment + block_comment)
-- Strings.
local sq_str = l.delimited_range("'", true, true)
local dq_str = l.delimited_range('"', true, true)
local string = token(l.STRING, sq_str + dq_str)
-- Numbers.
local number = token(l.NUMBER, l.float + l.integer)
-- Preprocessor.
local preproc = token(l.PREPROCESSOR, l.starts_line('#') * l.nonnewline^0)
-- Keywords.
local keyword = token(l.KEYWORD, word_match({
'address', 'arg', 'by', 'call', 'class', 'do', 'drop', 'else', 'end', 'exit',
'expose', 'forever', 'forward', 'guard', 'if', 'interpret', 'iterate',
'leave', 'method', 'nop', 'numeric', 'otherwise', 'parse', 'procedure',
'pull', 'push', 'queue', 'raise', 'reply', 'requires', 'return', 'routine',
'result', 'rc', 'say', 'select', 'self', 'sigl', 'signal', 'super', 'then',
'to', 'trace', 'use', 'when', 'while', 'until'
}, nil, true))
-- Functions.
local func = token(l.FUNCTION, word_match({
'abbrev', 'abs', 'address', 'arg', 'beep', 'bitand', 'bitor', 'bitxor', 'b2x',
'center', 'changestr', 'charin', 'charout', 'chars', 'compare', 'consition',
'copies', 'countstr', 'c2d', 'c2x', 'datatype', 'date', 'delstr', 'delword',
'digits', 'directory', 'd2c', 'd2x', 'errortext', 'filespec', 'form',
'format', 'fuzz', 'insert', 'lastpos', 'left', 'length', 'linein', 'lineout',
'lines', 'max', 'min', 'overlay', 'pos', 'queued', 'random', 'reverse',
'right', 'sign', 'sourceline', 'space', 'stream', 'strip', 'substr',
'subword', 'symbol', 'time', 'trace', 'translate', 'trunc', 'value', 'var',
'verify', 'word', 'wordindex', 'wordlength', 'wordpos', 'words', 'xrange',
'x2b', 'x2c', 'x2d', 'rxfuncadd', 'rxfuncdrop', 'rxfuncquery', 'rxmessagebox',
'rxwinexec', 'sysaddrexxmacro', 'sysbootdrive', 'sysclearrexxmacrospace',
'syscloseeventsem', 'sysclosemutexsem', 'syscls', 'syscreateeventsem',
'syscreatemutexsem', 'syscurpos', 'syscurstate', 'sysdriveinfo',
'sysdrivemap', 'sysdropfuncs', 'sysdroprexxmacro', 'sysdumpvariables',
'sysfiledelete', 'sysfilesearch', 'sysfilesystemtype', 'sysfiletree',
'sysfromunicode', 'systounicode', 'sysgeterrortext', 'sysgetfiledatetime',
'sysgetkey', 'sysini', 'sysloadfuncs', 'sysloadrexxmacrospace', 'sysmkdir',
'sysopeneventsem', 'sysopenmutexsem', 'sysposteventsem', 'syspulseeventsem',
'sysqueryprocess', 'sysqueryrexxmacro', 'sysreleasemutexsem',
'sysreorderrexxmacro', 'sysrequestmutexsem', 'sysreseteventsem', 'sysrmdir',
'syssaverexxmacrospace', 'syssearchpath', 'syssetfiledatetime',
'syssetpriority', 'syssleep', 'sysstemcopy', 'sysstemdelete', 'syssteminsert',
'sysstemsort', 'sysswitchsession', 'syssystemdirectory', 'systempfilename',
'systextscreenread', 'systextscreensize', 'sysutilversion', 'sysversion',
'sysvolumelabel', 'syswaiteventsem', 'syswaitnamedpipe', 'syswindecryptfile',
'syswinencryptfile', 'syswinver'
}, '2', true))
-- Identifiers.
local word = l.alpha * (l.alnum + S('@#$\\.!?_'))^0
local identifier = token(l.IDENTIFIER, word)
-- Operators.
local operator = token(l.OPERATOR, S('=!<>+-/\\*%&|^~.,:;(){}'))
M._rules = {
{'whitespace', ws},
{'keyword', keyword},
{'function', func},
{'identifier', identifier},
{'string', string},
{'comment', comment},
{'number', number},
{'preproc', preproc},
{'operator', operator},
}
M._foldsymbols = {
_patterns = {'[a-z]+', '/%*', '%*/', '%-%-', ':'},
[l.KEYWORD] = {['do'] = 1, select = 1, ['end'] = -1, ['return'] = -1},
[l.COMMENT] = {
['/*'] = 1, ['*/'] = -1, ['--'] = l.fold_line_comments('--')
},
[l.OPERATOR] = {[':'] = 1}
}
return M
| apache-2.0 |
renchunxiao/sailor | src/remy/mod_plua.lua | 4 | 1934 | -- Remy - mod_pLua compatibility
-- Copyright (c) 2014 Felipe Daragon
-- License: MIT
-- TODO: implement all functions from mod_lua's request_rec
local request = {
-- ENCODING/DECODING FUNCTIONS
base64_decode = function(_,...) return string.decode64(...) end,
base64_encode = function(_,...) return string.encode64(...) end,
md5 = function(_,...) return string.md5(...) end,
-- REQUEST PARSING FUNCTIONS
parseargs = function(_) return parseGet(), {} end,
parsebody = function(_) return parsePost(), {} end,
requestbody = function(_,...) return getRequestBody(...) end,
-- REQUEST RESPONSE FUNCTIONS
sendfile = function(_,...) return file.send(...) end,
puts = function(_,...) echo(...) end,
write = function(_,...) echo(...) end
}
local M = {
mode = "mod_plua",
request = request
}
function M.init()
local env = getEnv()
local r = request
local auth = string.decode64((env["Authorization"] or ""):sub(7))
local _,_,user,pass = auth:find("([^:]+)%:([^:]+)")
local filename = env["Filename"]
apache2.version = env["Server-Banner"]
r = remy.loadrequestrec(r)
r.method = env["Request-Method"]
r.args = remy.splitstring(env["Unparsed-URI"],'?')
r.banner = apache2.version
r.basic_auth_pw = pass
r.canonical_filename = filename
r.context_document_root = env["Working-Directory"]
r.document_root = r.context_document_root
r.filename = filename
r.hostname = env["Host"]
r.path_info = env["Path-Info"]
r.range = env["Range"]
r.server_name = r.hostname
r.the_request = env["Request"]
r.unparsed_uri = env["Unparsed-URI"]
r.uri = env["URI"]
r.user = user
r.useragent_ip = env["Remote-Address"]
end
function M.contentheader(content_type)
request.content_type = content_type
setContentType(content_type)
end
function M.finish(code)
-- mod_pLua uses text/html as default content type
if request.content_type ~= nil then
setContentType(request.content_type)
end
setReturnCode(code)
end
return M
| mit |
LiangMa/skynet | lualib/sharemap.lua | 78 | 1496 | local stm = require "stm"
local sprotoloader = require "sprotoloader"
local sproto = require "sproto"
local setmetatable = setmetatable
local sharemap = {}
function sharemap.register(protofile)
-- use global slot 0 for type define
sprotoloader.register(protofile, 0)
end
local sprotoobj
local function loadsp()
if sprotoobj == nil then
sprotoobj = sprotoloader.load(0)
end
return sprotoobj
end
function sharemap:commit()
self.__obj(sprotoobj:encode(self.__typename, self.__data))
end
function sharemap:copy()
return stm.copy(self.__obj)
end
function sharemap.writer(typename, obj)
local sp = loadsp()
obj = obj or {}
local stmobj = stm.new(sp:encode(typename,obj))
local ret = {
__typename = typename,
__obj = stmobj,
__data = obj,
commit = sharemap.commit,
copy = sharemap.copy,
}
return setmetatable(ret, { __index = obj, __newindex = obj })
end
local function decode(msg, sz, self)
local data = self.__data
for k in pairs(data) do
data[k] = nil
end
return sprotoobj:decode(self.__typename, msg, sz, data)
end
function sharemap:update()
return self.__obj(decode, self)
end
function sharemap.reader(typename, stmcpy)
local sp = loadsp()
local stmobj = stm.newcopy(stmcpy)
local _, data = stmobj(function(msg, sz)
return sp:decode(typename, msg, sz)
end)
local obj = {
__typename = typename,
__obj = stmobj,
__data = data,
update = sharemap.update,
}
return setmetatable(obj, { __index = data, __newindex = error })
end
return sharemap
| mit |
geanux/darkstar | scripts/zones/North_Gustaberg/TextIDs.lua | 7 | 1306 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED_TWICE = 6551; -- You cannot obtain the item <item>.
ITEM_CANNOT_BE_OBTAINED = 6552; -- You cannot obtain the item <item>. Come back after sorting your inventory.
FULL_INVENTORY_AFTER_TRADE = 6555; -- You cannot obtain the #. Try trading again after sorting your inventory.
ITEM_OBTAINED = 6556; -- Obtained: <item>.
GIL_OBTAINED = 6557; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6559; -- Obtained key item: <keyitem>.
ITEMS_OBTAINED = 6565; -- You obtain
FISHING_MESSAGE_OFFSET = 7213; -- You can't fish here.
-- Conquest
CONQUEST = 7459; -- You've earned conquest points!
-- Quests
SHINING_OBJECT_SLIPS_AWAY = 7416; -- The shining object slips through your fingers and is washed further down the stream.
-- Other Dialog
NOTHING_HAPPENS = 292; -- Nothing happens...
NOTHING_OUT_OF_ORDINARY = 6570; -- There is nothing out of the ordinary here.
REACH_WATER_FROM_HERE = 7423; -- You can reach the water from here.
-- conquest Base
CONQUEST_BASE = 0;
--chocobo digging
DIG_THROW_AWAY = 7226; -- You dig up$, but your inventory is full. You regretfully throw the # away.
FIND_NOTHING = 7228; -- You dig and you dig, but find nothing.
| gpl-3.0 |
legend18/dragonbone_cocos2dx-3.x | demos/cocos2d-x-3.x/DragonBonesCppDemos/cocos2d/cocos/scripting/lua-bindings/auto/api/Animate.lua | 6 | 1297 |
--------------------------------
-- @module Animate
-- @extend ActionInterval
-- @parent_module cc
--------------------------------
-- @overload self
-- @overload self
-- @function [parent=#Animate] getAnimation
-- @param self
-- @return Animation#Animation ret (retunr value: cc.Animation)
--------------------------------
-- @function [parent=#Animate] setAnimation
-- @param self
-- @param #cc.Animation animation
--------------------------------
-- @function [parent=#Animate] create
-- @param self
-- @param #cc.Animation animation
-- @return Animate#Animate ret (return value: cc.Animate)
--------------------------------
-- @function [parent=#Animate] startWithTarget
-- @param self
-- @param #cc.Node node
--------------------------------
-- @function [parent=#Animate] clone
-- @param self
-- @return Animate#Animate ret (return value: cc.Animate)
--------------------------------
-- @function [parent=#Animate] stop
-- @param self
--------------------------------
-- @function [parent=#Animate] reverse
-- @param self
-- @return Animate#Animate ret (return value: cc.Animate)
--------------------------------
-- @function [parent=#Animate] update
-- @param self
-- @param #float float
return nil
| mit |
jcjohnson/torch-rnn | TemporalCrossEntropyCriterion.lua | 20 | 3816 | require 'nn'
local crit, parent = torch.class('nn.TemporalCrossEntropyCriterion', 'nn.Criterion')
--[[
A TemporalCrossEntropyCriterion is used for classification tasks that occur
at every point in time for a timeseries; it works for minibatches and has a
null token that allows for predictions at arbitrary timesteps to be ignored.
This allows it to be used for sequence-to-sequence tasks where each minibatch
element has a different size; just pad the targets of the shorter sequences
with null tokens.
The criterion operates on minibatches of size N, with a sequence length of T,
with C classes over which classification is performed. The sequence length T
and the minibatch size N can be different on every forward pass.
On the forward pass we take the following inputs:
- input: Tensor of shape (N, T, C) giving classification scores for all C
classes for every timestep of every sequence in the minibatch.
- target: Tensor of shape (N, T) where each element is an integer in the
range [0, C]. If target[{n, t}] == 0 then the predictions at input[{n, t}]
are ignored, and result in 0 loss and gradient; otherwise if
target[{n, t}] = c then we expect that input[{n, t, c}] is the largest
element of input[{n, t}], and compute loss and gradient in the same way as
nn.CrossEntropyCriterion.
You can control whether loss is averaged over the minibatch N and sequence
length T by setting the instance variables crit.batch_average (default true)
and crit.time_average (default false).
--]]
function crit:__init()
parent.__init(self)
-- Set up a little net to compute LogSoftMax
self.lsm = nn.Sequential()
self.lsm:add(nn.View(1, 1, -1):setNumInputDims(3))
self.lsm:add(nn.LogSoftMax())
self.lsm:add(nn.View(1, -1):setNumInputDims(2))
-- self.lsm = nn.Identity()
-- Whether to average over space and batch
self.batch_average = true
self.time_average = false
-- Intermediates
self.grad_logprobs = torch.Tensor()
self.losses = torch.Tensor()
end
function crit:clearState()
self.lsm:clearState()
self.grad_logprobs:set()
self.losses:set()
end
-- Implementation note: We compute both loss and gradient in updateOutput, and
-- just return the gradient from updateGradInput.
function crit:updateOutput(input, target)
local N, T, C = input:size(1), input:size(2), input:size(3)
assert(target:dim() == 2 and target:size(1) == N and target:size(2) == T)
self.lsm:get(1):resetSize(N * T, -1)
self.lsm:get(3):resetSize(N, T, -1)
-- For CPU tensors, target should be a LongTensor but for GPU tensors
-- it should be the same type as input ... gross.
if input:type() == 'torch.FloatTensor' or input:type() == 'torch.DoubleTensor' then
target = target:long()
end
-- Figure out which elements are null. We want to use target as an index
-- tensor for gather and scatter, so temporarily replace 0s with 1s.
local null_mask = torch.eq(target, 0)
target[null_mask] = 1
-- Forward pass: compute losses and mask out null tokens
local logprobs = self.lsm:forward(input)
self.losses:resize(N, T, 1):gather(logprobs, 3, target:view(N, T, 1)):mul(-1)
self.losses = self.losses:view(N, T)
self.losses[null_mask] = 0
-- Backward pass: Compute grad_logprobs
self.grad_logprobs:resizeAs(logprobs):zero()
self.grad_logprobs:scatter(3, target:view(N, T, 1), -1)
self.grad_logprobs[null_mask:view(N, T, 1):expand(N, T, C)] = 0
if self.batch_average then
self.losses:div(N)
self.grad_logprobs:div(N)
end
if self.time_average then
self.losses:div(T)
self.grad_logprobs:div(T)
end
self.output = self.losses:sum()
self.gradInput = self.lsm:backward(input, self.grad_logprobs)
target[null_mask] = 0
return self.output
end
function crit:updateGradInput(input, target)
return self.gradInput
end
| mit |
sunu/splash | splash/lua_modules/sandbox.lua | 4 | 6185 | -------------------
----- sandbox -----
-------------------
local sandbox = {}
sandbox.allowed_require_names = {}
sandbox.env = {
--
-- 6.1 Basic Functions
-- http://www.lua.org/manual/5.2/manual.html#6.1
assert = assert,
error = error,
ipairs = ipairs,
next = next,
pairs = pairs,
pcall = pcall,
print = print, -- should we disable it?
select = select,
tonumber = tonumber,
tostring = tostring, -- Mike Pall says it is unsafe; why? See http://lua-users.org/lists/lua-l/2011-02/msg01595.html
type = type,
xpcall = xpcall,
--
-- 6.2 Coroutine Manipulation
-- http://www.lua.org/manual/5.2/manual.html#6.2
--
-- Disabled because:
-- 1. coroutines are used internally - users shouldn't yield to Splash themselves;
-- 2. debug hooks are per-coroutine in 'standard' Lua (not LuaJIT) - this requires a workaround.
--
-- 6.3 Modules
-- http://www.lua.org/manual/5.2/manual.html#6.3
--
require = function(name)
if sandbox.allowed_require_names[name] then
local ok, res = pcall(function() return require(name) end)
if ok then
return res
end
end
error("module '" .. name .. "' not found", 2)
end,
--
-- 6.4 String Manipulation
-- http://www.lua.org/manual/5.2/manual.html#6.4
string = {
byte = string.byte,
char = string.char,
find = string.find,
format = string.format,
-- gmatch = string.gmatch, -- can be CPU intensive
-- gsub = string.gsub, -- can be CPU intensive; can result in arbitrary native code execution (in 5.1)?
len = string.len,
lower = string.lower,
-- match = string.match, -- can be CPU intensive
-- rep = string.rep, -- can eat memory
reverse = string.reverse,
sub = string.sub,
upper = string.upper,
},
--
-- 6.5 Table Manipulation
-- http://www.lua.org/manual/5.2/manual.html#6.5
table = {
concat = table.concat,
insert = table.insert,
pack = table.pack,
remove = table.remove,
-- sort = table.sort, -- can result in arbitrary native code execution (in 5.1)?
unpack = table.unpack,
},
--
-- 6.6 Mathematical Functions
-- http://www.lua.org/manual/5.2/manual.html#6.6
math = {
abs = math.abs,
acos = math.acos,
asin = math.asin,
atan = math.atan,
atan2 = math.atan2,
ceil = math.ceil,
cos = math.cos,
cosh = math.cosh,
deg = math.deg,
exp = math.exp,
floor = math.floor,
fmod = math.fmod,
frexp = math.frexp,
huge = math.huge,
ldexp = math.ldexp,
log = math.log,
max = math.max,
min = math.min,
modf = math.modf,
pi = math.pi,
pow = math.pow,
rad = math.rad,
random = math.random,
randomseed = math.randomseed,
sin = math.sin,
sinh = math.sinh,
sqrt = math.sqrt,
tan = math.tan,
tanh = math.tanh,
},
--
-- 6.7 Bitwise Operations
-- http://www.lua.org/manual/5.2/manual.html#6.7
--
-- Disabled: if anyone cares we may add them.
--
-- 6.8 Input and Output Facilities
-- http://www.lua.org/manual/5.2/manual.html#6.8
--
-- Disabled.
--
-- 6.9 Operating System Facilities
-- http://www.lua.org/manual/5.2/manual.html#6.9
os = {
clock = os.clock,
-- date = os.date, -- from wiki: "This can crash on some platforms (undocumented). For example, os.date'%v'. It is reported that this will be fixed in 5.2 or 5.1.3."
difftime = os.difftime,
time = os.time,
},
--
-- 6.10 The Debug Library
-- http://www.lua.org/manual/5.2/manual.html#6.10
--
-- Disabled.
}
-------------------------------------------------------------
--
-- Fix metatables. Some of the functions are available
-- via metatables of primitive types; disable them all.
--
sandbox.fix_metatables = function()
-- 1. TODO: change string metatable to the sandboxed version
-- (it is now just disabled)
debug.setmetatable('', nil)
-- 2. Make sure there are no other metatables:
debug.setmetatable(1, nil)
debug.setmetatable(function() end, nil)
debug.setmetatable(true, nil)
end
-------------------------------------------------------------
--
-- Basic memory and CPU limits.
-- Based on code by Roberto Ierusalimschy.
-- http://lua-users.org/lists/lua-l/2013-12/msg00406.html
--
-- maximum memory (in KB) that can be used by Lua script
sandbox.mem_limit = 10000
function sandbox.enable_memory_limit()
if sandbox._memory_tracking_enabled then
return
end
local mt = {__gc = function (u)
if collectgarbage("count") > sandbox.mem_limit then
error("script uses too much memory")
else
setmetatable({}, getmetatable(u))
end
end}
setmetatable({}, mt)
sandbox._memory_tracking_enabled = true
end
-- Maximum number of instructions that can be executed.
-- XXX: the slowdown only becomes percievable at ~5m instructions.
sandbox.instruction_limit = 1e6
sandbox.instruction_count = 0
function sandbox.enable_instruction_limit()
local function _debug_step(event, line)
sandbox.instruction_count = sandbox.instruction_count + 1
if sandbox.instruction_count > sandbox.instruction_limit then
error("script uses too much CPU", 2)
end
end
debug.sethook(_debug_step, '', 1)
end
-- In Lua (but not in LuaJIT) debug hooks are per-coroutine.
-- Use this function as a replacement for `coroutine.create` to ensure
-- instruction limit is enforced in coroutines.
function sandbox.create_coroutine(f, ...)
return coroutine.create(function(...)
sandbox.enable_instruction_limit()
return f(...)
end, ...)
end
-------------------------------------------------------------
--
-- Lua 5.2 sandbox.
--
-- Note that it changes the global state: after the first `sandbox.run`
-- call the runtime becomes restricted in CPU and memory, and
-- "string":methods() like "foo":upper() stop working.
--
function sandbox.run(untrusted_code)
sandbox.fix_metatables()
sandbox.enable_instruction_limit()
sandbox.enable_memory_limit()
local untrusted_function, message = load(untrusted_code, nil, 't', sandbox.env)
if not untrusted_function then return nil, message end
return pcall(untrusted_function)
end
return sandbox
| bsd-3-clause |
evilexecutable/ResourceKeeper | install/Lua/lib/lua/loop/object/Exception.lua | 12 | 2141 | --------------------------------------------------------------------------------
---------------------- ## ##### ##### ###### -----------------------
---------------------- ## ## ## ## ## ## ## -----------------------
---------------------- ## ## ## ## ## ###### -----------------------
---------------------- ## ## ## ## ## ## -----------------------
---------------------- ###### ##### ##### ## -----------------------
---------------------- -----------------------
----------------------- Lua Object-Oriented Programming ------------------------
--------------------------------------------------------------------------------
-- Project: LOOP Class Library --
-- Release: 2.3 beta --
-- Title : Data structure to hold information about exceptions in Lua --
-- Author : Renato Maia <maia@inf.puc-rio.br> --
--------------------------------------------------------------------------------
local error = error
local type = type
local traceback = debug and debug.traceback
local table = require "table"
local oo = require "loop.base"
module("loop.object.Exception", oo.class)
function __init(class, object)
if traceback then
if not object then
object = { traceback = traceback() }
elseif object.traceback == nil then
object.traceback = traceback()
end
end
return oo.rawnew(class, object)
end
function __concat(op1, op2)
if type(op1) == "table" and type(op1.__tostring) == "function" then
op1 = op1:__tostring()
end
if type(op2) == "table" and type(op2.__tostring) == "function" then
op2 = op2:__tostring()
end
return op1..op2
end
function __tostring(self)
local message = { self[1] or self._NAME or "Exception"," raised" }
if self.message then
message[#message + 1] = ": "
message[#message + 1] = self.message
end
if self.traceback then
message[#message + 1] = "\n"
message[#message + 1] = self.traceback
end
return table.concat(message)
end
| gpl-2.0 |
forward619/luci | applications/luci-app-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo_mini.lua | 141 | 1031 | --[[
smap_devinfo - SIP Device Information
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.model.uci")
require("luci.controller.luci_diag.smap_common")
require("luci.controller.luci_diag.devinfo_common")
local debug = false
m = SimpleForm("luci-smap-to-devinfo", translate("Phone Information"), translate("Scan for supported SIP devices on specified networks."))
m.reset = false
m.submit = false
local outnets = luci.controller.luci_diag.smap_common.get_params()
luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.smap_common.command_function)
luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, true, "smap", true, debug)
luci.controller.luci_diag.smap_common.action_links(m, true)
return m
| apache-2.0 |
kobreu/compiler | testinput/lua5.1-tests/db.lua | 18 | 12088 | -- testing debug library
local function dostring(s) return assert(loadstring(s))() end
print"testing debug library and debug information"
do
local a=1
end
function test (s, l, p)
collectgarbage() -- avoid gc during trace
local function f (event, line)
assert(event == 'line')
local l = table.remove(l, 1)
if p then print(l, line) end
assert(l == line, "wrong trace!!")
end
debug.sethook(f,"l"); loadstring(s)(); debug.sethook()
assert(table.getn(l) == 0)
end
do
local a = debug.getinfo(print)
assert(a.what == "C" and a.short_src == "[C]")
local b = debug.getinfo(test, "SfL")
assert(b.name == nil and b.what == "Lua" and b.linedefined == 11 and
b.lastlinedefined == b.linedefined + 10 and
b.func == test and not string.find(b.short_src, "%["))
assert(b.activelines[b.linedefined + 1] and
b.activelines[b.lastlinedefined])
assert(not b.activelines[b.linedefined] and
not b.activelines[b.lastlinedefined + 1])
end
-- test file and string names truncation
a = "function f () end"
local function dostring (s, x) return loadstring(s, x)() end
dostring(a)
assert(debug.getinfo(f).short_src == string.format('[string "%s"]', a))
dostring(a..string.format("; %s\n=1", string.rep('p', 400)))
assert(string.find(debug.getinfo(f).short_src, '^%[string [^\n]*%.%.%."%]$'))
dostring("\n"..a)
assert(debug.getinfo(f).short_src == '[string "..."]')
dostring(a, "")
assert(debug.getinfo(f).short_src == '[string ""]')
dostring(a, "@xuxu")
assert(debug.getinfo(f).short_src == "xuxu")
dostring(a, "@"..string.rep('p', 1000)..'t')
assert(string.find(debug.getinfo(f).short_src, "^%.%.%.p*t$"))
dostring(a, "=xuxu")
assert(debug.getinfo(f).short_src == "xuxu")
dostring(a, string.format("=%s", string.rep('x', 500)))
assert(string.find(debug.getinfo(f).short_src, "^x*"))
dostring(a, "=")
assert(debug.getinfo(f).short_src == "")
a = nil; f = nil;
repeat
local g = {x = function ()
local a = debug.getinfo(2)
assert(a.name == 'f' and a.namewhat == 'local')
a = debug.getinfo(1)
assert(a.name == 'x' and a.namewhat == 'field')
return 'xixi'
end}
local f = function () return 1+1 and (not 1 or g.x()) end
assert(f() == 'xixi')
g = debug.getinfo(f)
assert(g.what == "Lua" and g.func == f and g.namewhat == "" and not g.name)
function f (x, name) -- local!
name = name or 'f'
local a = debug.getinfo(1)
assert(a.name == name and a.namewhat == 'local')
return x
end
-- breaks in different conditions
if 3>4 then break end; f()
if 3<4 then a=1 else break end; f()
while 1 do local x=10; break end; f()
local b = 1
if 3>4 then return math.sin(1) end; f()
a = 3<4; f()
a = 3<4 or 1; f()
repeat local x=20; if 4>3 then f() else break end; f() until 1
g = {}
f(g).x = f(2) and f(10)+f(9)
assert(g.x == f(19))
function g(x) if not x then return 3 end return (x('a', 'x')) end
assert(g(f) == 'a')
until 1
test([[if
math.sin(1)
then
a=1
else
a=2
end
]], {2,4,7})
test([[--
if nil then
a=1
else
a=2
end
]], {2,5,6})
test([[a=1
repeat
a=a+1
until a==3
]], {1,3,4,3,4})
test([[ do
return
end
]], {2})
test([[local a
a=1
while a<=3 do
a=a+1
end
]], {2,3,4,3,4,3,4,3,5})
test([[while math.sin(1) do
if math.sin(1)
then
break
end
end
a=1]], {1,2,4,7})
test([[for i=1,3 do
a=i
end
]], {1,2,1,2,1,2,1,3})
test([[for i,v in pairs{'a','b'} do
a=i..v
end
]], {1,2,1,2,1,3})
test([[for i=1,4 do a=1 end]], {1,1,1,1,1})
print'+'
a = {}; L = nil
local glob = 1
local oldglob = glob
debug.sethook(function (e,l)
collectgarbage() -- force GC during a hook
local f, m, c = debug.gethook()
assert(m == 'crl' and c == 0)
if e == "line" then
if glob ~= oldglob then
L = l-1 -- get the first line where "glob" has changed
oldglob = glob
end
elseif e == "call" then
local f = debug.getinfo(2, "f").func
a[f] = 1
else assert(e == "return")
end
end, "crl")
function f(a,b)
collectgarbage()
local _, x = debug.getlocal(1, 1)
local _, y = debug.getlocal(1, 2)
assert(x == a and y == b)
assert(debug.setlocal(2, 3, "pera") == "AA".."AA")
assert(debug.setlocal(2, 4, "maçã") == "B")
x = debug.getinfo(2)
assert(x.func == g and x.what == "Lua" and x.name == 'g' and
x.nups == 0 and string.find(x.source, "^@.*db%.lua"))
glob = glob+1
assert(debug.getinfo(1, "l").currentline == L+1)
assert(debug.getinfo(1, "l").currentline == L+2)
end
function foo()
glob = glob+1
assert(debug.getinfo(1, "l").currentline == L+1)
end; foo() -- set L
-- check line counting inside strings and empty lines
_ = 'alo\
alo' .. [[
]]
--[[
]]
assert(debug.getinfo(1, "l").currentline == L+11) -- check count of lines
function g(...)
do local a,b,c; a=math.sin(40); end
local feijao
local AAAA,B = "xuxu", "mamão"
f(AAAA,B)
assert(AAAA == "pera" and B == "maçã")
do
local B = 13
local x,y = debug.getlocal(1,5)
assert(x == 'B' and y == 13)
end
end
g()
assert(a[f] and a[g] and a[assert] and a[debug.getlocal] and not a[print])
-- tests for manipulating non-registered locals (C and Lua temporaries)
local n, v = debug.getlocal(0, 1)
assert(v == 0 and n == "(*temporary)")
local n, v = debug.getlocal(0, 2)
assert(v == 2 and n == "(*temporary)")
assert(not debug.getlocal(0, 3))
assert(not debug.getlocal(0, 0))
function f()
assert(select(2, debug.getlocal(2,3)) == 1)
assert(not debug.getlocal(2,4))
debug.setlocal(2, 3, 10)
return 20
end
function g(a,b) return (a+1) + f() end
assert(g(0,0) == 30)
debug.sethook(nil);
assert(debug.gethook() == nil)
-- testing access to function arguments
X = nil
a = {}
function a:f (a, b, ...) local c = 13 end
debug.sethook(function (e)
assert(e == "call")
dostring("XX = 12") -- test dostring inside hooks
-- testing errors inside hooks
assert(not pcall(loadstring("a='joao'+1")))
debug.sethook(function (e, l)
assert(debug.getinfo(2, "l").currentline == l)
local f,m,c = debug.gethook()
assert(e == "line")
assert(m == 'l' and c == 0)
debug.sethook(nil) -- hook is called only once
assert(not X) -- check that
X = {}; local i = 1
local x,y
while 1 do
x,y = debug.getlocal(2, i)
if x==nil then break end
X[x] = y
i = i+1
end
end, "l")
end, "c")
a:f(1,2,3,4,5)
assert(X.self == a and X.a == 1 and X.b == 2 and X.arg.n == 3 and X.c == nil)
assert(XX == 12)
assert(debug.gethook() == nil)
-- testing upvalue access
local function getupvalues (f)
local t = {}
local i = 1
while true do
local name, value = debug.getupvalue(f, i)
if not name then break end
assert(not t[name])
t[name] = value
i = i + 1
end
return t
end
local a,b,c = 1,2,3
local function foo1 (a) b = a; return c end
local function foo2 (x) a = x; return c+b end
assert(debug.getupvalue(foo1, 3) == nil)
assert(debug.getupvalue(foo1, 0) == nil)
assert(debug.setupvalue(foo1, 3, "xuxu") == nil)
local t = getupvalues(foo1)
assert(t.a == nil and t.b == 2 and t.c == 3)
t = getupvalues(foo2)
assert(t.a == 1 and t.b == 2 and t.c == 3)
assert(debug.setupvalue(foo1, 1, "xuxu") == "b")
assert(({debug.getupvalue(foo2, 3)})[2] == "xuxu")
-- cannot manipulate C upvalues from Lua
assert(debug.getupvalue(io.read, 1) == nil)
assert(debug.setupvalue(io.read, 1, 10) == nil)
-- testing count hooks
local a=0
debug.sethook(function (e) a=a+1 end, "", 1)
a=0; for i=1,1000 do end; assert(1000 < a and a < 1012)
debug.sethook(function (e) a=a+1 end, "", 4)
a=0; for i=1,1000 do end; assert(250 < a and a < 255)
local f,m,c = debug.gethook()
assert(m == "" and c == 4)
debug.sethook(function (e) a=a+1 end, "", 4000)
a=0; for i=1,1000 do end; assert(a == 0)
debug.sethook(print, "", 2^24 - 1) -- count upperbound
local f,m,c = debug.gethook()
assert(({debug.gethook()})[3] == 2^24 - 1)
debug.sethook()
-- tests for tail calls
local function f (x)
if x then
assert(debug.getinfo(1, "S").what == "Lua")
local tail = debug.getinfo(2)
assert(not pcall(getfenv, 3))
assert(tail.what == "tail" and tail.short_src == "(tail call)" and
tail.linedefined == -1 and tail.func == nil)
assert(debug.getinfo(3, "f").func == g1)
assert(getfenv(3))
assert(debug.getinfo(4, "S").what == "tail")
assert(not pcall(getfenv, 5))
assert(debug.getinfo(5, "S").what == "main")
assert(getfenv(5))
print"+"
end
end
function g(x) return f(x) end
function g1(x) g(x) end
local function h (x) local f=g1; return f(x) end
h(true)
local b = {}
debug.sethook(function (e) table.insert(b, e) end, "cr")
h(false)
debug.sethook()
local res = {"return", -- first return (from sethook)
"call", "call", "call", "call",
"return", "tail return", "return", "tail return",
"call", -- last call (to sethook)
}
for _, k in ipairs(res) do assert(k == table.remove(b, 1)) end
lim = 30000
local function foo (x)
if x==0 then
assert(debug.getinfo(lim+2).what == "main")
for i=2,lim do assert(debug.getinfo(i, "S").what == "tail") end
else return foo(x-1)
end
end
foo(lim)
print"+"
-- testing traceback
assert(debug.traceback(print) == print)
assert(debug.traceback(print, 4) == print)
assert(string.find(debug.traceback("hi", 4), "^hi\n"))
assert(string.find(debug.traceback("hi"), "^hi\n"))
assert(not string.find(debug.traceback("hi"), "'traceback'"))
assert(string.find(debug.traceback("hi", 0), "'traceback'"))
assert(string.find(debug.traceback(), "^stack traceback:\n"))
-- testing debugging of coroutines
local function checktraceback (co, p)
local tb = debug.traceback(co)
local i = 0
for l in string.gmatch(tb, "[^\n]+\n?") do
assert(i == 0 or string.find(l, p[i]))
i = i+1
end
assert(p[i] == nil)
end
local function f (n)
if n > 0 then return f(n-1)
else coroutine.yield() end
end
local co = coroutine.create(f)
coroutine.resume(co, 3)
checktraceback(co, {"yield", "db.lua", "tail", "tail", "tail"})
co = coroutine.create(function (x)
local a = 1
coroutine.yield(debug.getinfo(1, "l"))
coroutine.yield(debug.getinfo(1, "l").currentline)
return a
end)
local tr = {}
local foo = function (e, l) table.insert(tr, l) end
debug.sethook(co, foo, "l")
local _, l = coroutine.resume(co, 10)
local x = debug.getinfo(co, 1, "lfLS")
assert(x.currentline == l.currentline and x.activelines[x.currentline])
assert(type(x.func) == "function")
for i=x.linedefined + 1, x.lastlinedefined do
assert(x.activelines[i])
x.activelines[i] = nil
end
assert(next(x.activelines) == nil) -- no 'extra' elements
assert(debug.getinfo(co, 2) == nil)
local a,b = debug.getlocal(co, 1, 1)
assert(a == "x" and b == 10)
a,b = debug.getlocal(co, 1, 2)
assert(a == "a" and b == 1)
debug.setlocal(co, 1, 2, "hi")
assert(debug.gethook(co) == foo)
assert(table.getn(tr) == 2 and
tr[1] == l.currentline-1 and tr[2] == l.currentline)
a,b,c = pcall(coroutine.resume, co)
assert(a and b and c == l.currentline+1)
checktraceback(co, {"yield", "in function <"})
a,b = coroutine.resume(co)
assert(a and b == "hi")
assert(table.getn(tr) == 4 and tr[4] == l.currentline+2)
assert(debug.gethook(co) == foo)
assert(debug.gethook() == nil)
checktraceback(co, {})
-- check traceback of suspended (or dead with error) coroutines
function f(i) if i==0 then error(i) else coroutine.yield(); f(i-1) end end
co = coroutine.create(function (x) f(x) end)
a, b = coroutine.resume(co, 3)
t = {"'yield'", "'f'", "in function <"}
while coroutine.status(co) == "suspended" do
checktraceback(co, t)
a, b = coroutine.resume(co)
table.insert(t, 2, "'f'") -- one more recursive call to 'f'
end
t[1] = "'error'"
checktraceback(co, t)
-- test acessing line numbers of a coroutine from a resume inside
-- a C function (this is a known bug in Lua 5.0)
local function g(x)
coroutine.yield(x)
end
local function f (i)
debug.sethook(function () end, "l")
for j=1,1000 do
g(i+j)
end
end
local co = coroutine.wrap(f)
co(10)
pcall(co)
pcall(co)
assert(type(debug.getregistry()) == "table")
print"OK"
| gpl-3.0 |
geanux/darkstar | scripts/globals/weaponskills/dragon_kick.lua | 30 | 1693 | -----------------------------------
-- Dragon Kick
-- Hand-to-Hand weapon skill
-- Skill Level: 225
-- Damage varies with TP.
-- Despite the name, Dragon Kick damage is not affected by Kick Attacks or equipment that enhances kick attacks such as Dune Boots. http://www.bluegartr.com/threads/121610-Rehauled-Weapon-Skills-tier-lists?p=6140907&viewfull=1#post6140907
-- Will stack with Sneak Attack.
-- Aligned with the Breeze Gorget & Thunder Gorget.
-- Aligned with the Breeze Belt & Thunder Belt.
-- Element: None
-- Modifiers: STR:50% ; VIT:50%
-- 100%TP 200%TP 300%TP
-- 2.00 2.75 3.50
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 2; params.ftp200 = 2.75; params.ftp300 = 3.5;
params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.5; 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; params.ftp200 = 3.6; params.ftp300 = 6.5;
params.str_wsc = 0.5; params.dex_wsc = 0.5; params.vit_wsc = 0.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
geanux/darkstar | scripts/zones/Port_Windurst/npcs/Kohlo-Lakolo.lua | 36 | 10182 | -----------------------------------
-- Area: Port Windurst
-- NPC: Kohlo-Lakolo
-- Invloved In Quests: Truth, Justice, and the Onion Way!,
-- Know One's Onions,
-- Inspector's Gadget,
-- Onion Rings,
-- Crying Over Onions,
-- Wild Card,
-- The Promise
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY);
KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS);
if (KnowOnesOnions == QUEST_ACCEPTED) then
count = trade:getItemCount();
WildOnion = trade:hasItemQty(4387,4);
if (WildOnion == true and count == 4) then
player:startEvent(0x018e,0,4387);
end
elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then
count = trade:getItemCount();
RarabTail = trade:hasItemQty(4444,1);
if (RarabTail == true and count == 1) then
player:startEvent(0x017a,0,4444);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY);
KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS);
InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET);
OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS);
CryingOverOnions = player:getQuestStatus(WINDURST,CRYING_OVER_ONIONS);
WildCard = player:getQuestStatus(WINDURST,WILD_CARD);
ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE);
NeedToZone = player:needToZone();
Level = player:getMainLvl();
Fame = player:getFameLevel(WINDURST);
if (ThePromise == QUEST_COMPLETED) then
player:startEvent(0x0220);
elseif (ThePromise == QUEST_ACCEPTED) then
InvisibleManSticker = player:hasKeyItem(INVISIBLE_MAN_STICKER);
if (InvisibleManSticker == true) then
ThePromiseCS_Seen = player:getVar("ThePromiseCS_Seen");
if (ThePromiseCS_Seen == 1) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
player:completeQuest(WINDURST,THE_PROMISE);
player:addFame(WINDURST,WIN_FAME*150);
player:delKeyItem(INVISIBLE_MAN_STICKER);
player:addItem(13135);
player:messageSpecial(ITEM_OBTAINED,13135);
player:setVar("ThePromise",0);
player:setVar("ThePromiseCS_Seen",0);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13135);
end
else
player:startEvent(0x020a,0,INVISIBLE_MAN_STICKER);
end
else
player:startEvent(0x0202);
end
elseif (WildCard == QUEST_COMPLETED) then
player:startEvent(0x0201,0,INVISIBLE_MAN_STICKER);
elseif (WildCard == QUEST_ACCEPTED) then
WildCardVar = player:getVar("WildCard");
if (WildCardVar == 0) then
player:setVar("WildCard",1);
end
player:showText(npc,KOHLO_LAKOLO_DIALOG_A);
elseif (CryingOverOnions == QUEST_COMPLETED) then
player:startEvent(0x01f9);
elseif (CryingOverOnions == QUEST_ACCEPTED) then
CryingOverOnionsVar = player:getVar("CryingOverOnions");
if (CryingOverOnionsVar == 3) then
player:startEvent(0x0200);
elseif (CryingOverOnionsVar == 2) then
player:startEvent(0x01f1);
else
player:startEvent(0x01f2);
end
elseif (OnionRings == QUEST_COMPLETED) then
if (NeedToZone == false and Fame >= 5) then
player:startEvent(0x01f0);
else
player:startEvent(0x01b8);
end
elseif (OnionRings == QUEST_ACCEPTED) then
OldRing = player:hasKeyItem(OLD_RING);
if (OldRing == true) then
OnionRingsTime = player:getVar("OnionRingsTime");
CurrentTime = os.time();
if (CurrentTime >= OnionRingsTime) then
player:startEvent(0x01b1);
else
player:startEvent(0x01af);
end
end
elseif (InspectorsGadget == QUEST_COMPLETED) then
if (NeedToZone == false and Fame >= 3) then
OldRing = player:hasKeyItem(OLD_RING);
if (OldRing == true) then
OnionRingsVar = player:getVar("OnionRings");
if (OnionRingsVar == 1) then
player:startEvent(0x01ae,0,OLD_RING);
else
player:startEvent(0x01b0,0,OLD_RING);
end
else
player:startEvent(0x01ad);
end
else
player:startEvent(0x01a6);
end
elseif (InspectorsGadget == QUEST_ACCEPTED) then
FakeMoustache = player:hasKeyItem(FAKE_MOUSTACHE);
if (FakeMoustache == true) then
player:startEvent(0x01a5);
else
player:startEvent(0x019e);
end
elseif (KnowOnesOnions == QUEST_COMPLETED) then
if (NeedToZone == false and Fame >= 2) then
player:startEvent(0x019d);
else
player:startEvent(0x0191);
end
elseif (KnowOnesOnions == QUEST_ACCEPTED) then
KnowOnesOnionsVar = player:getVar("KnowOnesOnions");
KnowOnesOnionsTime = player:getVar("KnowOnesOnionsTime");
CurrentTime = os.time();
if (KnowOnesOnionsVar == 2) then
player:startEvent(0x0190);
elseif (KnowOnesOnionsVar == 1 and CurrentTime >= KnowOnesOnionsTime) then
player:startEvent(0x0182);
elseif (KnowOnesOnionsVar == 1) then
player:startEvent(0x018f,0,4387);
else
player:startEvent(0x0188,0,4387);
end
elseif (TruthJusticeOnionWay == QUEST_COMPLETED) then
if (NeedToZone == false and Level >= 5) then
player:startEvent(0x0187,0,4387);
else
player:startEvent(0x017b);
end
elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then
player:startEvent(0x0173);
elseif (TruthJusticeOnionWay == QUEST_AVAILABLE) then
player:startEvent(0x0170);
else
player:startEvent(0x0169);
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 == 0x0170 and option == 0) then
player:addQuest(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY);
elseif (csid == 0x017a) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
player:completeQuest(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY);
player:addFame(WINDURST,WIN_FAME*75);
player:addTitle(STAR_ONION_BRIGADE_MEMBER);
player:tradeComplete();
player:addItem(13093);
player:messageSpecial(ITEM_OBTAINED,13093);
player:needToZone(true);
else
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,13093);
end
elseif (csid == 0x0187) then
player:addQuest(WINDURST,KNOW_ONE_S_ONIONS);
elseif (csid == 0x018e) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
TradeTime = os.time();
player:tradeComplete();
player:addItem(4857);
player:messageSpecial(ITEM_OBTAINED,4857);
player:setVar("KnowOnesOnions",1);
player:setVar("KnowOnesOnionsTime", TradeTime + 86400);
else
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,4857);
end
elseif (csid == 0x0182 or csid == 0x0190) then
player:completeQuest(WINDURST,KNOW_ONE_S_ONIONS);
player:addFame(WINDURST,WIN_FAME*80);
player:addTitle(SOB_SUPER_HERO);
player:setVar("KnowOnesOnions",0);
player:setVar("KnowOnesOnionsTime",0);
player:needToZone(true);
elseif (csid == 0x019d and option == 0) then
player:addQuest(WINDURST,INSPECTOR_S_GADGET);
elseif (csid == 0x01a5) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
player:completeQuest(WINDURST,INSPECTOR_S_GADGET);
player:addFame(WINDURST,WIN_FAME*90);
player:addTitle(FAKEMOUSTACHED_INVESTIGATOR);
player:addItem(13204);
player:messageSpecial(ITEM_OBTAINED,13204);
player:needToZone(true);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13204);
end
elseif (csid == 0x01ad) then
player:setVar("OnionRings",1);
elseif (csid == 0x01ae) then
OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS);
if (OnionRings == QUEST_AVAILABLE) then
CurrentTime = os.time();
player:addQuest(WINDURST,ONION_RINGS);
player:setVar("OnionRingsTime", CurrentTime + 86400);
end
elseif (csid == 0x01b0 or csid == 0x01b1) then
player:completeQuest(WINDURST,ONION_RINGS);
player:addFame(WINDURST,WIN_FAME*100);
player:addTitle(STAR_ONION_BRIGADIER);
player:delKeyItem(OLD_RING);
player:setVar("OnionRingsTime",0);
player:needToZone(true);
elseif (csid == 0x01b8) then
OnionRingsVar = player:getVar("OnionRings");
NeedToZone = player:getVar("NeedToZone");
if (OnionRingsVar == 2 and NeedToZone == 0) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
player:setVar("OnionRings",0);
player:addItem(17029);
player:messageSpecial(ITEM_OBTAINED,17029);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17029);
end
end
elseif (csid == 0x01f0) then
player:addQuest(WINDURST,CRYING_OVER_ONIONS);
elseif (csid == 0x01f1) then
player:setVar("CryingOverOnions",3);
elseif (csid == 0x0201) then
player:addQuest(WINDURST,THE_PROMISE);
elseif (csid == 0x020a) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
player:completeQuest(WINDURST,THE_PROMISE);
player:addFame(WINDURST,WIN_FAME*150);
player:delKeyItem(INVISIBLE_MAN_STICKER);
player:addItem(13135);
player:messageSpecial(ITEM_OBTAINED,13135);
player:setVar("ThePromise",0);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13135);
player:setVar("ThePromiseCS_Seen",1);
end
end
end; | gpl-3.0 |
evilexecutable/ResourceKeeper | install/Lua/share/lua/5.1/cjson/util.lua | 170 | 6837 | local json = require "cjson"
-- Various common routines used by the Lua CJSON package
--
-- Mark Pulford <mark@kyne.com.au>
-- Determine with a Lua table can be treated as an array.
-- Explicitly returns "not an array" for very sparse arrays.
-- Returns:
-- -1 Not an array
-- 0 Empty table
-- >0 Highest index in the array
local function is_array(table)
local max = 0
local count = 0
for k, v in pairs(table) do
if type(k) == "number" then
if k > max then max = k end
count = count + 1
else
return -1
end
end
if max > count * 2 then
return -1
end
return max
end
local serialise_value
local function serialise_table(value, indent, depth)
local spacing, spacing2, indent2
if indent then
spacing = "\n" .. indent
spacing2 = spacing .. " "
indent2 = indent .. " "
else
spacing, spacing2, indent2 = " ", " ", false
end
depth = depth + 1
if depth > 50 then
return "Cannot serialise any further: too many nested tables"
end
local max = is_array(value)
local comma = false
local fragment = { "{" .. spacing2 }
if max > 0 then
-- Serialise array
for i = 1, max do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment, serialise_value(value[i], indent2, depth))
comma = true
end
elseif max < 0 then
-- Serialise table
for k, v in pairs(value) do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment,
("[%s] = %s"):format(serialise_value(k, indent2, depth),
serialise_value(v, indent2, depth)))
comma = true
end
end
table.insert(fragment, spacing .. "}")
return table.concat(fragment)
end
function serialise_value(value, indent, depth)
if indent == nil then indent = "" end
if depth == nil then depth = 0 end
if value == json.null then
return "json.null"
elseif type(value) == "string" then
return ("%q"):format(value)
elseif type(value) == "nil" or type(value) == "number" or
type(value) == "boolean" then
return tostring(value)
elseif type(value) == "table" then
return serialise_table(value, indent, depth)
else
return "\"<" .. type(value) .. ">\""
end
end
local function file_load(filename)
local file
if filename == nil then
file = io.stdin
else
local err
file, err = io.open(filename, "rb")
if file == nil then
error(("Unable to read '%s': %s"):format(filename, err))
end
end
local data = file:read("*a")
if filename ~= nil then
file:close()
end
if data == nil then
error("Failed to read " .. filename)
end
return data
end
local function file_save(filename, data)
local file
if filename == nil then
file = io.stdout
else
local err
file, err = io.open(filename, "wb")
if file == nil then
error(("Unable to write '%s': %s"):format(filename, err))
end
end
file:write(data)
if filename ~= nil then
file:close()
end
end
local function compare_values(val1, val2)
local type1 = type(val1)
local type2 = type(val2)
if type1 ~= type2 then
return false
end
-- Check for NaN
if type1 == "number" and val1 ~= val1 and val2 ~= val2 then
return true
end
if type1 ~= "table" then
return val1 == val2
end
-- check_keys stores all the keys that must be checked in val2
local check_keys = {}
for k, _ in pairs(val1) do
check_keys[k] = true
end
for k, v in pairs(val2) do
if not check_keys[k] then
return false
end
if not compare_values(val1[k], val2[k]) then
return false
end
check_keys[k] = nil
end
for k, _ in pairs(check_keys) do
-- Not the same if any keys from val1 were not found in val2
return false
end
return true
end
local test_count_pass = 0
local test_count_total = 0
local function run_test_summary()
return test_count_pass, test_count_total
end
local function run_test(testname, func, input, should_work, output)
local function status_line(name, status, value)
local statusmap = { [true] = ":success", [false] = ":error" }
if status ~= nil then
name = name .. statusmap[status]
end
print(("[%s] %s"):format(name, serialise_value(value, false)))
end
local result = { pcall(func, unpack(input)) }
local success = table.remove(result, 1)
local correct = false
if success == should_work and compare_values(result, output) then
correct = true
test_count_pass = test_count_pass + 1
end
test_count_total = test_count_total + 1
local teststatus = { [true] = "PASS", [false] = "FAIL" }
print(("==> Test [%d] %s: %s"):format(test_count_total, testname,
teststatus[correct]))
status_line("Input", nil, input)
if not correct then
status_line("Expected", should_work, output)
end
status_line("Received", success, result)
print()
return correct, result
end
local function run_test_group(tests)
local function run_helper(name, func, input)
if type(name) == "string" and #name > 0 then
print("==> " .. name)
end
-- Not a protected call, these functions should never generate errors.
func(unpack(input or {}))
print()
end
for _, v in ipairs(tests) do
-- Run the helper if "should_work" is missing
if v[4] == nil then
run_helper(unpack(v))
else
run_test(unpack(v))
end
end
end
-- Run a Lua script in a separate environment
local function run_script(script, env)
local env = env or {}
local func
-- Use setfenv() if it exists, otherwise assume Lua 5.2 load() exists
if _G.setfenv then
func = loadstring(script)
if func then
setfenv(func, env)
end
else
func = load(script, nil, nil, env)
end
if func == nil then
error("Invalid syntax.")
end
func()
return env
end
-- Export functions
return {
serialise_value = serialise_value,
file_load = file_load,
file_save = file_save,
compare_values = compare_values,
run_test_summary = run_test_summary,
run_test = run_test,
run_test_group = run_test_group,
run_script = run_script
}
-- vi:ai et sw=4 ts=4:
| gpl-2.0 |
semyon422/lua-mania | alpha/conf.lua | 1 | 1072 | --[[ lua-mania
Copyright (C) 2016 Semyon Jolnirov (semyon422)
This program licensed under the GNU GPLv3. ]]
function love.conf(t)
t.identity = nil
t.version = "0.10.1"
t.console = true
t.accelerometerjoystick = true
t.gammacorrect = false
t.window.title = "lua-mania"
t.window.icon = nil
t.window.width = 800
t.window.height = 600
t.window.borderless = false
t.window.resizable = true
t.window.minwidth = 1
t.window.minheight = 1
t.window.fullscreen = false
t.window.fullscreentype = "desktop" -- "desktop" or "exclusive"
t.window.vsync = false
t.window.msaa = 0
t.window.display = 1
t.window.highdpi = false
t.window.x = nil
t.window.y = nil
t.modules.audio = true
t.modules.event = true
t.modules.graphics = true
t.modules.image = true
t.modules.joystick = true
t.modules.keyboard = true
t.modules.math = true
t.modules.mouse = true
t.modules.physics = true
t.modules.sound = true
t.modules.system = true
t.modules.timer = true
t.modules.touch = true
t.modules.video = true
t.modules.window = true
t.modules.thread = true
end
| gpl-3.0 |
geanux/darkstar | scripts/zones/Caedarva_Mire/npcs/Jazaraat_s_Headstone.lua | 21 | 1901 | -----------------------------------
-- Area: Caedarva Mire
-- NPC: Jazaraat's Headstone
-- Involved in mission: The Lost Kingdom (TOAUM 13)
-- @pos -389 6 -570 79
-----------------------------------
package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil;
require("scripts/zones/Caedarva_Mire/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(TOAU) == LOST_KINGDOM and player:hasKeyItem(VIAL_OF_SPECTRAL_SCENT) and player:getVar("TOAUM13") == 0) then
player:startEvent(0x0008);
elseif (player:getVar("TOAUM13") == 1) then
if (GetMobAction(17101146) == 0) then
SpawnMob(17101146):updateEnmity(player);
end
elseif (player:getVar("TOAUM13") ==2) then
player:startEvent(0x0009);
elseif (player:getVar("TOAUM13") ==3) then
player:setVar("TOAUM13",0);
player:addKeyItem(EPHRAMADIAN_GOLD_COIN);
player:messageSpecial(KEYITEM_OBTAINED,EPHRAMADIAN_GOLD_COIN);
player:completeMission(TOAU,LOST_KINGDOM);
player:addMission(TOAU,THE_DOLPHIN_CREST);
else
player:messageSpecial(JAZARAATS_HEADSTONE);
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 == 0x0008) then
player:setVar("TOAUM13",1);
elseif (csid == 0x0009) then
player:setVar("TOAUM13",3);
end
end;
| gpl-3.0 |
Pritchy96/OpenRA | lua/stacktraceplus.lua | 59 | 12006 | -- tables
local _G = _G
local string, io, debug, coroutine = string, io, debug, coroutine
-- functions
local tostring, print, require = tostring, print, require
local next, assert = next, assert
local pcall, type, pairs, ipairs = pcall, type, pairs, ipairs
local error = error
assert(debug, "debug table must be available at this point")
local io_open = io.open
local string_gmatch = string.gmatch
local string_sub = string.sub
local table_concat = table.concat
local _M = {
max_tb_output_len = 70 -- controls the maximum length of the 'stringified' table before cutting with ' (more...)'
}
-- this tables should be weak so the elements in them won't become uncollectable
local m_known_tables = { [_G] = "_G (global table)" }
local function add_known_module(name, desc)
local ok, mod = pcall(require, name)
if ok then
m_known_tables[mod] = desc
end
end
add_known_module("string", "string module")
add_known_module("io", "io module")
add_known_module("os", "os module")
add_known_module("table", "table module")
add_known_module("math", "math module")
add_known_module("package", "package module")
add_known_module("debug", "debug module")
add_known_module("coroutine", "coroutine module")
-- lua5.2
add_known_module("bit32", "bit32 module")
-- luajit
add_known_module("bit", "bit module")
add_known_module("jit", "jit module")
local m_user_known_tables = {}
local m_known_functions = {}
for _, name in ipairs{
-- Lua 5.2, 5.1
"assert",
"collectgarbage",
"dofile",
"error",
"getmetatable",
"ipairs",
"load",
"loadfile",
"next",
"pairs",
"pcall",
"print",
"rawequal",
"rawget",
"rawlen",
"rawset",
"require",
"select",
"setmetatable",
"tonumber",
"tostring",
"type",
"xpcall",
-- Lua 5.1
"gcinfo",
"getfenv",
"loadstring",
"module",
"newproxy",
"setfenv",
"unpack",
-- TODO: add table.* etc functions
} do
if _G[name] then
m_known_functions[_G[name]] = name
end
end
local m_user_known_functions = {}
local function safe_tostring (value)
local ok, err = pcall(tostring, value)
if ok then return err else return ("<failed to get printable value>: '%s'"):format(err) end
end
-- Private:
-- Parses a line, looking for possible function definitions (in a very naïve way)
-- Returns '(anonymous)' if no function name was found in the line
local function ParseLine(line)
assert(type(line) == "string")
--print(line)
local match = line:match("^%s*function%s+(%w+)")
if match then
--print("+++++++++++++function", match)
return match
end
match = line:match("^%s*local%s+function%s+(%w+)")
if match then
--print("++++++++++++local", match)
return match
end
match = line:match("^%s*local%s+(%w+)%s+=%s+function")
if match then
--print("++++++++++++local func", match)
return match
end
match = line:match("%s*function%s*%(") -- this is an anonymous function
if match then
--print("+++++++++++++function2", match)
return "(anonymous)"
end
return "(anonymous)"
end
-- Private:
-- Tries to guess a function's name when the debug info structure does not have it.
-- It parses either the file or the string where the function is defined.
-- Returns '?' if the line where the function is defined is not found
local function GuessFunctionName(info)
--print("guessing function name")
if type(info.source) == "string" and info.source:sub(1,1) == "@" then
local file, err = io_open(info.source:sub(2), "r")
if not file then
print("file not found: "..tostring(err)) -- whoops!
return "?"
end
local line
for i = 1, info.linedefined do
line = file:read("*l")
end
if not line then
print("line not found") -- whoops!
return "?"
end
return ParseLine(line)
else
local line
local lineNumber = 0
for l in string_gmatch(info.source, "([^\n]+)\n-") do
lineNumber = lineNumber + 1
if lineNumber == info.linedefined then
line = l
break
end
end
if not line then
print("line not found") -- whoops!
return "?"
end
return ParseLine(line)
end
end
---
-- Dumper instances are used to analyze stacks and collect its information.
--
local Dumper = {}
Dumper.new = function(thread)
local t = { lines = {} }
for k,v in pairs(Dumper) do t[k] = v end
t.dumping_same_thread = (thread == coroutine.running())
-- if a thread was supplied, bind it to debug.info and debug.get
-- we also need to skip this additional level we are introducing in the callstack (only if we are running
-- in the same thread we're inspecting)
if type(thread) == "thread" then
t.getinfo = function(level, what)
if t.dumping_same_thread and type(level) == "number" then
level = level + 1
end
return debug.getinfo(thread, level, what)
end
t.getlocal = function(level, loc)
if t.dumping_same_thread then
level = level + 1
end
return debug.getlocal(thread, level, loc)
end
else
t.getinfo = debug.getinfo
t.getlocal = debug.getlocal
end
return t
end
-- helpers for collecting strings to be used when assembling the final trace
function Dumper:add (text)
self.lines[#self.lines + 1] = text
end
function Dumper:add_f (fmt, ...)
self:add(fmt:format(...))
end
function Dumper:concat_lines ()
return table_concat(self.lines)
end
---
-- Private:
-- Iterates over the local variables of a given function.
--
-- @param level The stack level where the function is.
--
function Dumper:DumpLocals (level)
local prefix = "\t "
local i = 1
if self.dumping_same_thread then
level = level + 1
end
local name, value = self.getlocal(level, i)
if not name then
return
end
self:add("\tLocal variables:\r\n")
while name do
if type(value) == "number" then
self:add_f("%s%s = number: %g\r\n", prefix, name, value)
elseif type(value) == "boolean" then
self:add_f("%s%s = boolean: %s\r\n", prefix, name, tostring(value))
elseif type(value) == "string" then
self:add_f("%s%s = string: %q\r\n", prefix, name, value)
elseif type(value) == "userdata" then
self:add_f("%s%s = %s\r\n", prefix, name, safe_tostring(value))
elseif type(value) == "nil" then
self:add_f("%s%s = nil\r\n", prefix, name)
elseif type(value) == "table" then
if m_known_tables[value] then
self:add_f("%s%s = %s\r\n", prefix, name, m_known_tables[value])
elseif m_user_known_tables[value] then
self:add_f("%s%s = %s\r\n", prefix, name, m_user_known_tables[value])
else
local txt = "{"
for k,v in pairs(value) do
txt = txt..safe_tostring(k)..":"..safe_tostring(v)
if #txt > _M.max_tb_output_len then
txt = txt.." (more...)"
break
end
if next(value, k) then txt = txt..", " end
end
self:add_f("%s%s = %s %s\r\n", prefix, name, safe_tostring(value), txt.."}")
end
elseif type(value) == "function" then
local info = self.getinfo(value, "nS")
local fun_name = info.name or m_known_functions[value] or m_user_known_functions[value]
if info.what == "C" then
self:add_f("%s%s = C %s\r\n", prefix, name, (fun_name and ("function: " .. fun_name) or tostring(value)))
else
local source = info.short_src
if source:sub(2,7) == "string" then
source = source:sub(9)
end
--for k,v in pairs(info) do print(k,v) end
fun_name = fun_name or GuessFunctionName(info)
self:add_f("%s%s = Lua function '%s' (defined at line %d of chunk %s)\r\n", prefix, name, fun_name, info.linedefined, source)
end
elseif type(value) == "thread" then
self:add_f("%sthread %q = %s\r\n", prefix, name, tostring(value))
end
i = i + 1
name, value = self.getlocal(level, i)
end
end
---
-- Public:
-- Collects a detailed stack trace, dumping locals, resolving function names when they're not available, etc.
-- This function is suitable to be used as an error handler with pcall or xpcall
--
-- @param thread An optional thread whose stack is to be inspected (defaul is the current thread)
-- @param message An optional error string or object.
-- @param level An optional number telling at which level to start the traceback (default is 1)
--
-- Returns a string with the stack trace and a string with the original error.
--
function _M.stacktrace(thread, message, level)
if type(thread) ~= "thread" then
-- shift parameters left
thread, message, level = nil, thread, message
end
thread = thread or coroutine.running()
level = level or 1
local dumper = Dumper.new(thread)
local original_error
if type(message) == "table" then
dumper:add("an error object {\r\n")
local first = true
for k,v in pairs(message) do
if first then
dumper:add(" ")
first = false
else
dumper:add(",\r\n ")
end
dumper:add(safe_tostring(k))
dumper:add(": ")
dumper:add(safe_tostring(v))
end
dumper:add("\r\n}")
original_error = dumper:concat_lines()
elseif type(message) == "string" then
dumper:add(message)
original_error = message
end
dumper:add("\r\n")
dumper:add[[
Stack Traceback
===============
]]
--print(error_message)
local level_to_show = level
if dumper.dumping_same_thread then level = level + 1 end
local info = dumper.getinfo(level, "nSlf")
while info do
if info.what == "main" then
if string_sub(info.source, 1, 1) == "@" then
dumper:add_f("(%d) main chunk of file '%s' at line %d\r\n", level_to_show, string_sub(info.source, 2), info.currentline)
else
dumper:add_f("(%d) main chunk of %s at line %d\r\n", level_to_show, info.short_src, info.currentline)
end
elseif info.what == "C" then
--print(info.namewhat, info.name)
--for k,v in pairs(info) do print(k,v, type(v)) end
local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name or tostring(info.func)
dumper:add_f("(%d) %s C function '%s'\r\n", level_to_show, info.namewhat, function_name)
--dumper:add_f("%s%s = C %s\r\n", prefix, name, (m_known_functions[value] and ("function: " .. m_known_functions[value]) or tostring(value)))
elseif info.what == "tail" then
--print("tail")
--for k,v in pairs(info) do print(k,v, type(v)) end--print(info.namewhat, info.name)
dumper:add_f("(%d) tail call\r\n", level_to_show)
dumper:DumpLocals(level)
elseif info.what == "Lua" then
local source = info.short_src
local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name
if source:sub(2, 7) == "string" then
source = source:sub(9)
end
local was_guessed = false
if not function_name or function_name == "?" then
--for k,v in pairs(info) do print(k,v, type(v)) end
function_name = GuessFunctionName(info)
was_guessed = true
end
-- test if we have a file name
local function_type = (info.namewhat == "") and "function" or info.namewhat
if info.source and info.source:sub(1, 1) == "@" then
dumper:add_f("(%d) Lua %s '%s' at file '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "")
elseif info.source and info.source:sub(1,1) == '#' then
dumper:add_f("(%d) Lua %s '%s' at template '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "")
else
dumper:add_f("(%d) Lua %s '%s' at line %d of chunk '%s'\r\n", level_to_show, function_type, function_name, info.currentline, source)
end
dumper:DumpLocals(level)
else
dumper:add_f("(%d) unknown frame %s\r\n", level_to_show, info.what)
end
level = level + 1
level_to_show = level_to_show + 1
info = dumper.getinfo(level, "nSlf")
end
return dumper:concat_lines(), original_error
end
--
-- Adds a table to the list of known tables
function _M.add_known_table(tab, description)
if m_known_tables[tab] then
error("Cannot override an already known table")
end
m_user_known_tables[tab] = description
end
--
-- Adds a function to the list of known functions
function _M.add_known_function(fun, description)
if m_known_functions[fun] then
error("Cannot override an already known function")
end
m_user_known_functions[fun] = description
end
return _M
| gpl-3.0 |
kaen/Zero-K | LuaUI/Widgets/gfx_halo.lua | 12 | 10613 | -- $Id: gfx_halo.lua 3171 2008-11-06 09:06:29Z det $
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- file: gfx_halo.lua
-- brief:
-- author: jK
--
-- Copyright (C) 2008.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Halo",
desc = "Shows a halo in teamcolors around units. (Doesn't work on ati cards!)",
author = "jK",
date = "Jan, 2008",
license = "GNU GPL, v2 or later",
layer = -10,
enabled = false -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// user var
local gAlpha = 0.7
local limitToCommanders = false
local limitToWorkers = false
--// app var
local offscreentex
local depthtex
local blurtex
local fbo
local blurShader_h
local blurShader_v
local uniformScreenX, uniformScreenY
local vsx, vsy = 0,0
local resChanged = false
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// gl const
local GL_DEPTH_BITS = 0x0D56
local GL_DEPTH_COMPONENT = 0x1902
local GL_DEPTH_COMPONENT16 = 0x81A5
local GL_DEPTH_COMPONENT24 = 0x81A6
local GL_DEPTH_COMPONENT32 = 0x81A7
local GL_COLOR_ATTACHMENT0_EXT = 0x8CE0
local GL_COLOR_ATTACHMENT1_EXT = 0x8CE1
local GL_COLOR_ATTACHMENT2_EXT = 0x8CE2
local GL_COLOR_ATTACHMENT3_EXT = 0x8CE3
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// speed ups
local ALL_UNITS = Spring.ALL_UNITS
local GetVisibleUnits = Spring.GetVisibleUnits
local GetUnitTeam = Spring.GetUnitTeam
local GL_FRONT = GL.FRONT
local GL_BACK = GL.BACK
local GL_MODELVIEW = GL.MODELVIEW
local GL_PROJECTION = GL.PROJECTION
local GL_COLOR_BUFFER_BIT = GL.COLOR_BUFFER_BIT
local glUnit = gl.Unit
local glCopyToTexture = gl.CopyToTexture
local glRenderToTexture = gl.RenderToTexture
local glCallList = gl.CallList
local glActiveFBO = gl.ActiveFBO
local glUseShader = gl.UseShader
local glUniform = gl.Uniform
local glUniformInt = gl.UniformInt
local glClear = gl.Clear
local glTexRect = gl.TexRect
local glColor = gl.Color
local glTexture = gl.Texture
local glCulling = gl.Culling
local glDepthTest = gl.DepthTest
local glResetMatrices = gl.ResetMatrices
local glMatrixMode = gl.MatrixMode
local glPushMatrix = gl.PushMatrix
local glLoadIdentity = gl.LoadIdentity
local glPopMatrix = gl.PopMatrix
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Initialize()
if (not gl.CreateShader)or(not gl.CreateFBO) then
Spring.Echo("Halo widget: your card is unsupported!")
widgetHandler:RemoveWidget()
return
end
vsx, vsy = widgetHandler:GetViewSizes()
blurShader_h = gl.CreateShader({
fragment = [[
float kernel[7]; // = float[7]( 0.013, 0.054, 0.069, 0.129, 0.212, 0.301, 0.372);
uniform sampler2D tex0;
uniform int screenX;
void InitKernel(void) {
kernel[0] = 0.013;
kernel[1] = 0.054;
kernel[2] = 0.069;
kernel[3] = 0.129;
kernel[4] = 0.212;
kernel[5] = 0.301;
kernel[6] = 0.372;
}
void main(void) {
InitKernel();
int n;
float pixelsize = 1.0/float(screenX);
gl_FragColor = 0.4 * texture2D(tex0, gl_TexCoord[0].st );
vec2 tc1 = gl_TexCoord[0].st;
vec2 tc2 = gl_TexCoord[0].st;
for(n=6; n>= 0; --n){
tc1.s += pixelsize;
tc2.s -= pixelsize;
gl_FragColor += kernel[n] * ( texture2D(tex0, tc1 )+texture2D(tex0, tc2 ) );
}
}
]],
uniformInt = {
tex0 = 0,
screenX = math.ceil(vsx*0.5),
},
})
if (blurShader_h == nil) then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "Halo widget: hblur shader error: "..gl.GetShaderLog())
widgetHandler:RemoveWidget()
return false
end
blurShader_v = gl.CreateShader({
fragment = [[
float kernel[7]; // = float[7]( 0.013, 0.054, 0.069, 0.129, 0.212, 0.301, 0.372);
uniform sampler2D tex0;
uniform int screenY;
void InitKernel(void) {
kernel[0] = 0.013;
kernel[1] = 0.054;
kernel[2] = 0.069;
kernel[3] = 0.129;
kernel[4] = 0.212;
kernel[5] = 0.301;
kernel[6] = 0.372;
}
void main(void) {
InitKernel();
int n;
float pixelsize = 1.0/float(screenY);
gl_FragColor = 0.4 * texture2D(tex0, gl_TexCoord[0].st );
vec2 tc1 = gl_TexCoord[0].st;
vec2 tc2 = gl_TexCoord[0].st;
for(n=6; n>= 0; --n){
tc1.t += pixelsize;
tc2.t -= pixelsize;
gl_FragColor += kernel[n] * ( texture2D(tex0, tc1 )+texture2D(tex0, tc2 ) );
}
}
]],
uniformInt = {
tex0 = 0,
screenY = math.ceil(vsy*0.5),
},
})
if (blurShader_v == nil) then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "Halo widget: vblur shader error: "..gl.GetShaderLog())
widgetHandler:RemoveWidget()
return false
end
uniformScreenX = gl.GetUniformLocation(blurShader_h, 'screenX')
uniformScreenY = gl.GetUniformLocation(blurShader_v, 'screenY')
fbo = gl.CreateFBO()
self:ViewResize(vsx,vsy)
enter2d = gl.CreateList(function()
glUseShader(0)
glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity()
glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity()
end)
leave2d = gl.CreateList(function()
glMatrixMode(GL_PROJECTION); glPopMatrix()
glMatrixMode(GL_MODELVIEW); glPopMatrix()
glTexture(false)
glUseShader(0)
end)
end
function widget:ViewResize(viewSizeX, viewSizeY)
vsx = viewSizeX
vsy = viewSizeY
fbo.color0 = nil
gl.DeleteTexture(depthtex or 0)
gl.DeleteTextureFBO(offscreentex or 0)
gl.DeleteTextureFBO(blurtex or 0)
depthtex = gl.CreateTexture(vsx,vsy, {
border = false,
format = GL_DEPTH_COMPONENT24,
min_filter = GL.NEAREST,
mag_filter = GL.NEAREST,
})
offscreentex = gl.CreateTexture(vsx,vsy, {
border = false,
min_filter = GL.LINEAR,
mag_filter = GL.LINEAR,
wrap_s = GL.CLAMP,
wrap_t = GL.CLAMP,
fbo = true,
})
blurtex = gl.CreateTexture(math.floor(vsx*0.5),math.floor(vsy*0.5), {
border = false,
min_filter = GL.LINEAR,
mag_filter = GL.LINEAR,
wrap_s = GL.CLAMP,
wrap_t = GL.CLAMP,
fbo = true,
})
fbo.depth = depthtex
fbo.color0 = offscreentex
fbo.drawbuffers = GL_COLOR_ATTACHMENT0_EXT
resChanged = true
end
function widget:Shutdown()
gl.DeleteTexture(depthtex)
if (gl.DeleteTextureFBO) then
gl.DeleteTextureFBO(offscreentex)
gl.DeleteTextureFBO(blurtex)
end
if (gl.DeleteFBO) then
gl.DeleteFBO(fbo or 0)
end
if (gl.DeleteShader) then
gl.DeleteShader(blurShader_h or 0)
gl.DeleteShader(blurShader_v or 0)
end
gl.DeleteList(enter2d)
gl.DeleteList(leave2d)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Spring.GetTeamColor = Spring.GetTeamColor or function(teamID) local _,_,_,_,_,_,r,g,b = Spring.GetTeamInfo(teamID); return r,g,b end
local teamColors = {}
local function SetTeamColor(teamID)
local teamColor = teamColors[teamID]
if (teamColor) then glColor(teamColor) return end
teamColors[teamID] = {Spring.GetTeamColor(teamID)}
glColor(teamColors[teamID])
end
local function DrawVisibleUnitsAll()
local visibleUnits = GetVisibleUnits(ALL_UNITS,nil,true)
for i=1,#visibleUnits do
local unitID = visibleUnits[i]
SetTeamColor(GetUnitTeam(unitID))
glUnit(unitID,true)
end
end
local function DrawVisibleUnitsLimited()
local teams = Spring.GetTeamList()
for _,teamID in ipairs(teams) do
glColor(Spring.GetTeamColor(teamID))
teamUnits = Spring.GetTeamUnitsSorted(teamID)
teamUnits.n = nil -- REMOVE IN 0.83
for unitDefID,unitIDs in pairs(teamUnits) do
local UnitDef = UnitDefs[unitDefID]
if (limitToCommanders and UnitDef.customParams.commtype)or
(limitToWorkers and UnitDef.isBuilder)
then
for _,unitID in ipairs(unitIDs) do
local losState = Spring.GetUnitLosState(unitID)
if (Spring.IsUnitInView(unitID))and(((losState)and(losState.los))or(true)) then
glUnit(unitID,true)
end
end
end
end
end
end
local DrawVisibleUnits
if (limitToCommanders or limitToWorkers) then
DrawVisibleUnits = DrawVisibleUnitsLimited
else
DrawVisibleUnits = DrawVisibleUnitsAll
end
local MyDrawVisibleUnits = function()
glClear(GL_COLOR_BUFFER_BIT,0,0,0,0)
--glCulling(GL_FRONT)
DrawVisibleUnits()
--glCulling(GL_BACK)
--glCulling(false)
glColor(1,1,1,1)
end
local blur_h = function()
glClear(GL_COLOR_BUFFER_BIT,0,0,0,0)
glUseShader(blurShader_h)
glTexRect(-1-0.25/vsx,1+0.25/vsy,1+0.25/vsx,-1-0.25/vsy)
end
local blur_v = function()
--glClear(GL_COLOR_BUFFER_BIT,0,0,0,0)
glUseShader(blurShader_v)
glTexRect(-1-0.25/vsx,1+0.25/vsy,1+0.25/vsx,-1-0.25/vsy)
end
function widget:DrawWorldPreUnit()
glCopyToTexture(depthtex, 0, 0, 0, 0, vsx, vsy)
if (resChanged) then
resChanged = false
if (vsx==1) or (vsy==1) then return end
glUseShader(blurShader_h)
glUniformInt(uniformScreenX, math.ceil(vsx*0.5) )
glUseShader(blurShader_v)
glUniformInt(uniformScreenY, math.ceil(vsy*0.5) )
end
glDepthTest(true)
glActiveFBO(fbo,MyDrawVisibleUnits)
glDepthTest(false)
glTexture(offscreentex)
glRenderToTexture(blurtex, blur_h)
glTexture(blurtex)
glRenderToTexture(offscreentex, blur_v)
glColor(1,1,1,gAlpha)
glCallList(enter2d)
glTexture(offscreentex)
glTexRect(-1-0.5/vsx,1+0.5/vsy,1+0.5/vsx,-1-0.5/vsy)
glCallList(leave2d)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
geanux/darkstar | scripts/zones/Port_Bastok/npcs/Sugandhi.lua | 30 | 1587 | -----------------------------------
-- Area: Port Bastok
-- NPC: Sugandhi
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,SUGANDHI_SHOP_DIALOG);
local stock = {
0x4059, 5589,1, --Kukri
0x40A1, 21067,1, --Broadsword
0x4081, 11588,1, --Tuck
0x40AE, 61200,1, --Falchion
0x4052, 2182,2, --Knife
0x4099, 30960,2, --Mythril Sword
0x40A8, 4072,2, --Scimitar
0x4051, 147,3, --Bronze Knife
0x4015, 104,3, --Cat Baghnakhs
0x4097, 241,3, --Bronze Sword
0x4098, 7128,3, --Iron Sword
0x4085, 9201,3, --Degen
0x40A7, 698,3 --Sapara
}
showNationShop(player, BASTOK, 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 |
omidtarh/wizard | bot/bot.lua | 1 | 67257 | struct random2local {
long long random_id;
int local_id;
};
static int id_cmp (struct tgl_message *M1, struct tgl_message *M2);
#define peer_cmp(a,b) (tgl_cmp_peer_id (a->id, b->id))
#define peer_cmp_name(a,b) (strcmp (a->print_name, b->print_name))
static int random_id_cmp (struct random2local *L, struct random2local *R) {
if (L->random_id < R->random_id) { return -1; }
if (L->random_id > R->random_id) { return 1; }
return 0;
}
static int photo_id_cmp (struct tgl_photo *L, struct tgl_photo *R) {
if (L->id < R->id) { return -1; }
if (L->id > R->id) { return 1; }
return 0;
}
static int document_id_cmp (struct tgl_document *L, struct tgl_document *R) {
if (L->id < R->id) { return -1; }
if (L->id > R->id) { return 1; }
return 0;
}
static int webpage_id_cmp (struct tgl_webpage *L, struct tgl_webpage *R) {
if (L->id < R->id) { return -1; }
if (L->id > R->id) { return 1; }
return 0;
}
DEFINE_TREE(peer,tgl_peer_t *,peer_cmp,0)
DEFINE_TREE(peer_by_name,tgl_peer_t *,peer_cmp_name,0)
DEFINE_TREE(message,struct tgl_message *,id_cmp,0)
DEFINE_TREE(random_id,struct random2local *, random_id_cmp,0)
DEFINE_TREE(photo,struct tgl_photo *,photo_id_cmp,0)
DEFINE_TREE(document,struct tgl_document *,document_id_cmp,0)
DEFINE_TREE(webpage,struct tgl_webpage *,webpage_id_cmp,0)
char *tgls_default_create_print_name (struct tgl_state *TLS, tgl_peer_id_t id, const char *a1, const char *a2, const char *a3, const char *a4) {
const char *d[4];
d[0] = a1; d[1] = a2; d[2] = a3; d[3] = a4;
static char buf[10000];
buf[0] = 0;
int i;
int p = 0;
for (i = 0; i < 4; i++) {
if (d[i] && strlen (d[i])) {
p += tsnprintf (buf + p, 9999 - p, "%s%s", p ? "_" : "", d[i]);
assert (p < 9990);
}
}
char *s = buf;
while (*s) {
if (((unsigned char)*s) <= ' ') { *s = '_'; }
if (*s == '#') { *s = '@'; }
s++;
}
s = buf;
int fl = strlen (s);
int cc = 0;
while (1) {
tgl_peer_t *P = tgl_peer_get_by_name (TLS, s);
if (!P || !tgl_cmp_peer_id (P->id, id)) {
break;
}
cc ++;
assert (cc <= 9999);
tsnprintf (s + fl, 9999 - fl, "#%d", cc);
}
return tstrdup (s);
}
enum tgl_typing_status tglf_fetch_typing_new (struct tl_ds_send_message_action *DS_SMA) {
if (!DS_SMA) { return 0; }
switch (DS_SMA->magic) {
case CODE_send_message_typing_action:
return tgl_typing_typing;
case CODE_send_message_cancel_action:
return tgl_typing_cancel;
case CODE_send_message_record_video_action:
return tgl_typing_record_video;
case CODE_send_message_upload_video_action:
return tgl_typing_upload_video;
case CODE_send_message_record_audio_action:
return tgl_typing_record_audio;
case CODE_send_message_upload_audio_action:
return tgl_typing_upload_audio;
case CODE_send_message_upload_photo_action:
return tgl_typing_upload_photo;
case CODE_send_message_upload_document_action:
return tgl_typing_upload_document;
case CODE_send_message_geo_location_action:
return tgl_typing_geo;
case CODE_send_message_choose_contact_action:
return tgl_typing_choose_contact;
default:
assert (0);
return tgl_typing_none;
}
}
enum tgl_typing_status tglf_fetch_typing (void) {
struct tl_ds_send_message_action *DS_SMA = fetch_ds_type_send_message_action (TYPE_TO_PARAM (send_message_action));
enum tgl_typing_status res = tglf_fetch_typing_new (DS_SMA);
free_ds_type_send_message_action (DS_SMA, TYPE_TO_PARAM (send_message_action));
return res;
}
/* {{{ Fetch */
int tglf_fetch_file_location_new (struct tgl_state *TLS, struct tgl_file_location *loc, struct tl_ds_file_location *DS_FL) {
if (!DS_FL) { return 0; }
loc->dc = DS_LVAL (DS_FL->dc_id);
loc->volume = DS_LVAL (DS_FL->volume_id);
loc->local_id = DS_LVAL (DS_FL->local_id);
loc->secret = DS_LVAL (DS_FL->secret);
return 0;
}
int tglf_fetch_user_status_new (struct tgl_state *TLS, struct tgl_user_status *S, struct tgl_user *U, struct tl_ds_user_status *DS_US) {
if (!DS_US) { return 0; }
switch (DS_US->magic) {
case CODE_user_status_empty:
if (S->online) {
tgl_insert_status_update (TLS, U);
if (S->online == 1) {
tgl_remove_status_expire (TLS, U);
}
}
S->online = 0;
S->when = 0;
break;
case CODE_user_status_online:
{
if (S->online != 1) {
S->when = DS_LVAL (DS_US->expires);
if (S->online) {
tgl_insert_status_update (TLS, U);
}
tgl_insert_status_expire (TLS, U);
S->online = 1;
} else {
if (DS_LVAL (DS_US->expires) != S->when) {
S->when = DS_LVAL (DS_US->expires);
tgl_remove_status_expire (TLS, U);
tgl_insert_status_expire (TLS, U);
}
}
}
break;
case CODE_user_status_offline:
if (S->online != -1) {
if (S->online) {
tgl_insert_status_update (TLS, U);
}
if (S->online == 1) {
tgl_remove_status_expire (TLS, U);
}
}
S->online = -1;
S->when = DS_LVAL (DS_US->was_online);
break;
case CODE_user_status_recently:
if (S->online != -2) {
if (S->online) {
tgl_insert_status_update (TLS, U);
}
if (S->online == 1) {
tgl_remove_status_expire (TLS, U);
}
}
S->online = -2;
break;
case CODE_user_status_last_week:
if (S->online != -3) {
if (S->online) {
tgl_insert_status_update (TLS, U);
}
if (S->online == 1) {
tgl_remove_status_expire (TLS, U);
}
}
S->online = -3;
break;
case CODE_user_status_last_month:
if (S->online != -4) {
if (S->online) {
tgl_insert_status_update (TLS, U);
}
if (S->online == 1) {
tgl_remove_status_expire (TLS, U);
}
}
S->online = -4;
break;
default:
assert (0);
}
return 0;
}
int tglf_fetch_user_new (struct tgl_state *TLS, struct tgl_user *U, struct tl_ds_user *DS_U) {
if (!DS_U) { return 0; }
U->id = TGL_MK_USER (DS_LVAL (DS_U->id));
if (DS_U->magic == CODE_user_empty) {
return 0;
}
int flags = U->flags & 0xffff;
if (DS_LVAL (DS_U->flags) & (1 << 10)) {
bl_do_set_our_id (TLS, tgl_get_peer_id (U->id));
flags |= TGLUF_SELF;
}
if (DS_LVAL (DS_U->flags) & (1 << 11)) {
flags |= TGLUF_CONTACT;
}
if (DS_LVAL (DS_U->flags) & (1 << 12)) {
flags |= TGLUF_MUTUAL_CONTACT;
}
if (DS_LVAL (DS_U->flags) & (1 << 14)) {
flags |= TGLUF_BOT;
}
/*
if (DS_LVAL (DS_U->flags) & (1 << 15)) {
flags |= TGLUF_BOT_FULL_ACCESS;
}
if (DS_LVAL (DS_U->flags) & (1 << 16)) {
flags |= TGLUF_BOT_NO_GROUPS;
}*/
if (!(flags & TGLUF_CREATED)) {
flags |= TGLUF_CREATE | TGLUF_CREATED;
}
bl_do_user_new (TLS, tgl_get_peer_id (U->id),
DS_U->access_hash,
DS_STR (DS_U->first_name),
DS_STR (DS_U->last_name),
DS_STR (DS_U->phone),
DS_STR (DS_U->username),
NULL,
NULL, 0, NULL, 0,
DS_U->photo,
NULL, NULL,
NULL,
flags
);
if (DS_U->status) {
assert (tglf_fetch_user_status_new (TLS, &U->status, U, DS_U->status) >= 0);
}
if (DS_LVAL (DS_U->flags) & (1 << 13)) {
if (!(U->flags & TGLUF_DELETED)) {
bl_do_user_delete (TLS, U);
}
}
return 0;
}
void tglf_fetch_user_full_new (struct tgl_state *TLS, struct tgl_user *U, struct tl_ds_user_full *DS_UF) {
if (!DS_UF) { return; }
tglf_fetch_user_new (TLS, U, DS_UF->user);
int flags = U->flags & 0xffff;
if (DS_BVAL (DS_UF->blocked)) {
flags |= TGLUF_BLOCKED;
} else {
flags &= ~TGLUF_BLOCKED;
}
bl_do_user_new (TLS, tgl_get_peer_id (U->id),
NULL,
NULL, 0,
NULL, 0,
NULL, 0,
NULL, 0,
DS_UF->profile_photo,
//DS_STR (DS_UF->real_first_name), DS_STR (DS_UF->real_last_name),
NULL, 0, NULL, 0,
NULL,
NULL, NULL,
DS_UF->bot_info,
flags
);
}
void str_to_256 (unsigned char *dst, char *src, int src_len) {
if (src_len >= 256) {
memcpy (dst, src + src_len - 256, 256);
} else {
bzero (dst, 256 - src_len);
memcpy (dst + 256 - src_len, src, src_len);
}
}
void str_to_32 (unsigned char *dst, char *src, int src_len) {
if (src_len >= 32) {
memcpy (dst, src + src_len - 32, 32);
} else {
bzero (dst, 32 - src_len);
memcpy (dst + 32 - src_len, src, src_len);
}
}
void tglf_fetch_encrypted_chat_new (struct tgl_state *TLS, struct tgl_secret_chat *U, struct tl_ds_encrypted_chat *DS_EC) {
if (!DS_EC) { return; }
U->id = TGL_MK_ENCR_CHAT (DS_LVAL (DS_EC->id));
if (DS_EC->magic == CODE_encrypted_chat_empty) {
return;
}
int new = !(U->flags & TGLPF_CREATED);
if (DS_EC->magic == CODE_encrypted_chat_discarded) {
if (new) {
vlogprintf (E_WARNING, "Unknown chat in deleted state. May be we forgot something...\n");
return;
}
bl_do_encr_chat_delete (TLS, U);
//write_secret_chat_file ();
return;
}
static unsigned char g_key[256];
if (new) {
if (DS_EC->magic != CODE_encrypted_chat_requested) {
vlogprintf (E_WARNING, "Unknown chat. May be we forgot something...\n");
return;
}
str_to_256 (g_key, DS_STR (DS_EC->g_a));
int user_id = DS_LVAL (DS_EC->participant_id) + DS_LVAL (DS_EC->admin_id) - TLS->our_id;
int r = sc_request;
bl_do_encr_chat_new (TLS, tgl_get_peer_id (U->id),
DS_EC->access_hash,
DS_EC->date,
DS_EC->admin_id,
&user_id,
NULL,
(void *)g_key,
NULL,
&r,
NULL, NULL, NULL, NULL, NULL,
NULL,
TGLECF_CREATE | TGLECF_CREATED
);
} else {
if (DS_EC->magic == CODE_encrypted_chat_waiting) {
int r = sc_waiting;
bl_do_encr_chat_new (TLS, tgl_get_peer_id (U->id),
DS_EC->access_hash,
DS_EC->date,
NULL,
NULL,
NULL,
NULL,
NULL,
&r,
NULL, NULL, NULL, NULL, NULL,
NULL,
TGL_FLAGS_UNCHANGED
);
return; // We needed only access hash from here
}
str_to_256 (g_key, DS_STR (DS_EC->g_a_or_b));
//write_secret_chat_file ();
int r = sc_ok;
bl_do_encr_chat_new (TLS, tgl_get_peer_id (U->id),
DS_EC->access_hash,
DS_EC->date,
NULL,
NULL,
NULL,
g_key,
NULL,
&r,
NULL, NULL, NULL, NULL, NULL,
DS_EC->key_fingerprint,
TGL_FLAGS_UNCHANGED
);
}
}
void tglf_fetch_chat_new (struct tgl_state *TLS, struct tgl_chat *C, struct tl_ds_chat *DS_C) {
if (!DS_C) { return; }
C->id = TGL_MK_CHAT (DS_LVAL (DS_C->id));
if (DS_C->magic == CODE_chat_empty) {
return;
}
int flags = C->flags & 0xffff;
if (!(flags & TGLCF_CREATED)) {
flags |= TGLCF_CREATE | TGLCF_CREATED;
}
bl_do_chat_new (TLS, tgl_get_peer_id (C->id),
DS_STR (DS_C->title),
DS_C->participants_count,
DS_C->date,
NULL,
NULL,
DS_C->photo,
NULL,
NULL,
NULL, NULL,
flags
);
}
void tglf_fetch_chat_full_new (struct tgl_state *TLS, struct tgl_chat *C, struct tl_ds_messages_chat_full *DS_MCF) {
if (!DS_MCF) { return; }
struct tl_ds_chat_full *DS_CF = DS_MCF->full_chat;
C->id = TGL_MK_CHAT (DS_LVAL (DS_CF->id));
bl_do_chat_new (TLS, tgl_get_peer_id (C->id),
NULL, 0,
NULL,
NULL,
DS_CF->participants->version,
(struct tl_ds_vector *)DS_CF->participants->participants,
NULL,
DS_CF->chat_photo,
DS_CF->participants->admin_id,
NULL, NULL,
C->flags & 0xffff
);
if (DS_MCF->users) {
int i;
for (i = 0; i < DS_LVAL (DS_MCF->users->cnt); i++) {
tglf_fetch_alloc_user_new (TLS, DS_MCF->users->data[i]);
}
}
if (DS_MCF->chats) {
int i;
for (i = 0; i < DS_LVAL (DS_MCF->chats->cnt); i++) {
tglf_fetch_alloc_chat_new (TLS, DS_MCF->chats->data[i]);
}
}
if (DS_CF->bot_info) {
int n = DS_LVAL (DS_CF->bot_info->cnt);
int i;
for (i = 0; i < n; i++) {
struct tl_ds_bot_info *DS_BI = DS_CF->bot_info->data[i];
tgl_peer_t *P = tgl_peer_get (TLS, TGL_MK_USER (DS_LVAL (DS_BI->user_id)));
if (P && (P->flags & TGLCF_CREATED)) {
bl_do_user_new (TLS, tgl_get_peer_id (P->id),
NULL,
NULL, 0,
NULL, 0,
NULL, 0,
NULL, 0,
NULL,
NULL, 0, NULL, 0,
NULL,
NULL, NULL,
DS_BI,
TGL_FLAGS_UNCHANGED
);
}
}
}
}
void tglf_fetch_photo_size_new (struct tgl_state *TLS, struct tgl_photo_size *S, struct tl_ds_photo_size *DS_PS) {
memset (S, 0, sizeof (*S));
S->type = DS_STR_DUP (DS_PS->type);
S->w = DS_LVAL (DS_PS->w);
S->h = DS_LVAL (DS_PS->h);
S->size = DS_LVAL (DS_PS->size);
if (DS_PS->bytes) {
S->size = DS_PS->bytes->len;
}
tglf_fetch_file_location_new (TLS, &S->loc, DS_PS->location);
}
void tglf_fetch_geo_new (struct tgl_state *TLS, struct tgl_geo *G, struct tl_ds_geo_point *DS_GP) {
G->longitude = DS_LVAL (DS_GP->longitude);
G->latitude = DS_LVAL (DS_GP->latitude);
}
struct tgl_photo *tglf_fetch_alloc_photo_new (struct tgl_state *TLS, struct tl_ds_photo *DS_P) {
if (!DS_P) { return NULL; }
if (DS_P->magic == CODE_photo_empty) { return NULL; }
struct tgl_photo *P = tgl_photo_get (TLS, DS_LVAL (DS_P->id));
if (P) {
P->refcnt ++;
return P;
}
P = talloc0 (sizeof (*P));
P->id = DS_LVAL (DS_P->id);
P->refcnt = 1;
tgl_photo_insert (TLS, P);
P->access_hash = DS_LVAL (DS_P->access_hash);
P->user_id = DS_LVAL (DS_P->user_id);
P->date = DS_LVAL (DS_P->date);
P->caption = NULL;//DS_STR_DUP (DS_P->caption);
tglf_fetch_geo_new (TLS, &P->geo, DS_P->geo);
P->sizes_num = DS_LVAL (DS_P->sizes->cnt);
P->sizes = talloc (sizeof (struct tgl_photo_size) * P->sizes_num);
int i;
for (i = 0; i < P->sizes_num; i++) {
tglf_fetch_photo_size_new (TLS, &P->sizes[i], DS_P->sizes->data[i]);
}
return P;
}
struct tgl_document *tglf_fetch_alloc_video_new (struct tgl_state *TLS, struct tl_ds_video *DS_V) {
if (!DS_V) { return NULL; }
if (DS_V->magic == CODE_video_empty) { return NULL; }
struct tgl_document *D = tgl_document_get (TLS, DS_LVAL (DS_V->id));
if (D) {
D->refcnt ++;
return D;
}
D = talloc0 (sizeof (*D));
D->id = DS_LVAL (DS_V->id);
D->refcnt = 1;
tgl_document_insert (TLS, D);
D->access_hash = DS_LVAL (DS_V->access_hash);
D->user_id = DS_LVAL (DS_V->user_id);
D->date = DS_LVAL (DS_V->date);
D->caption = NULL;//DS_STR_DUP (DS_V->caption);
D->duration = DS_LVAL (DS_V->duration);
D->mime_type = tstrdup ("video/");//DS_STR_DUP (DS_V->mime_type);
D->size = DS_LVAL (DS_V->size);
tglf_fetch_photo_size_new (TLS, &D->thumb, DS_V->thumb);
D->dc_id = DS_LVAL (DS_V->dc_id);
D->w = DS_LVAL (DS_V->w);
D->h = DS_LVAL (DS_V->h);
return D;
}
struct tgl_document *tglf_fetch_alloc_audio_new (struct tgl_state *TLS, struct tl_ds_audio *DS_A) {
if (!DS_A) { return NULL; }
if (DS_A->magic == CODE_audio_empty) { return NULL; }
struct tgl_document *D = tgl_document_get (TLS, DS_LVAL (DS_A->id));
if (D) {
D->refcnt ++;
return D;
}
D = talloc0 (sizeof (*D));
D->id = DS_LVAL (DS_A->id);
D->refcnt = 1;
tgl_document_insert (TLS, D);
D->flags = TGLDF_AUDIO;
D->access_hash = DS_LVAL (DS_A->access_hash);
D->user_id = DS_LVAL (DS_A->user_id);
D->date = DS_LVAL (DS_A->date);
D->duration = DS_LVAL (DS_A->duration);
D->mime_type = DS_STR_DUP (DS_A->mime_type);
D->size = DS_LVAL (DS_A->size);
D->dc_id = DS_LVAL (DS_A->dc_id);
return D;
}
void tglf_fetch_document_attribute_new (struct tgl_state *TLS, struct tgl_document *D, struct tl_ds_document_attribute *DS_DA) {
switch (DS_DA->magic) {
case CODE_document_attribute_image_size:
D->flags |= TGLDF_IMAGE;
D->w = DS_LVAL (DS_DA->w);
D->h = DS_LVAL (DS_DA->h);
return;
case CODE_document_attribute_animated:
D->flags |= TGLDF_ANIMATED;
return;
case CODE_document_attribute_sticker:
case CODE_document_attribute_sticker_l28:
D->flags |= TGLDF_STICKER;
return;
case CODE_document_attribute_video:
D->flags |= TGLDF_VIDEO;
D->duration = DS_LVAL (DS_DA->duration);
D->w = DS_LVAL (DS_DA->w);
D->h = DS_LVAL (DS_DA->h);
return;
case CODE_document_attribute_audio:
D->flags |= TGLDF_AUDIO;
D->duration = DS_LVAL (DS_DA->duration);
return;
case CODE_document_attribute_filename:
D->caption = DS_STR_DUP (DS_DA->file_name);
return;
default:
assert (0);
}
}
struct tgl_document *tglf_fetch_alloc_document_new (struct tgl_state *TLS, struct tl_ds_document *DS_D) {
if (!DS_D) { return NULL; }
if (DS_D->magic == CODE_document_empty) { return NULL; }
struct tgl_document *D = tgl_document_get (TLS, DS_LVAL (DS_D->id));
if (D) {
D->refcnt ++;
return D;
}
D = talloc0 (sizeof (*D));
D->id = DS_LVAL (DS_D->id);
D->refcnt = 1;
tgl_document_insert (TLS, D);
D->access_hash = DS_LVAL (DS_D->access_hash);
D->user_id = DS_LVAL (DS_D->user_id);
D->date = DS_LVAL (DS_D->date);
D->caption = DS_STR_DUP (DS_D->file_name);
D->mime_type = DS_STR_DUP (DS_D->mime_type);
D->size = DS_LVAL (DS_D->size);
D->dc_id = DS_LVAL (DS_D->dc_id);
tglf_fetch_photo_size_new (TLS, &D->thumb, DS_D->thumb);
if (DS_D->attributes) {
int i;
for (i = 0; i < DS_LVAL (DS_D->attributes->cnt); i++) {
tglf_fetch_document_attribute_new (TLS, D, DS_D->attributes->data[i]);
}
}
return D;
}
struct tgl_webpage *tglf_fetch_alloc_webpage_new (struct tgl_state *TLS, struct tl_ds_web_page *DS_W) {
if (!DS_W) { return NULL; }
struct tgl_webpage *W = tgl_webpage_get (TLS, DS_LVAL (DS_W->id));
if (W) {
W->refcnt ++;
} else {
W = talloc0 (sizeof (*W));
W->id = DS_LVAL (DS_W->id);
W->refcnt = 1;
tgl_webpage_insert (TLS, W);
}
if (!W->url) {
W->url = DS_STR_DUP (DS_W->url);
}
if (!W->display_url) {
W->display_url = DS_STR_DUP (DS_W->display_url);
}
if (!W->type) {
W->type = DS_STR_DUP (DS_W->type);
}
if (!W->site_name) {
W->site_name = DS_STR_DUP (DS_W->site_name);
}
if (!W->title) {
W->title = DS_STR_DUP (DS_W->title);
}
if (!W->photo) {
W->photo = tglf_fetch_alloc_photo_new (TLS, DS_W->photo);
}
if (!W->description) {
W->description = DS_STR_DUP (DS_W->description);
}
if (!W->embed_url) {
W->embed_url = DS_STR_DUP (DS_W->embed_url);
}
if (!W->embed_type) {
W->embed_type = DS_STR_DUP (DS_W->embed_type);
}
W->embed_width = DS_LVAL (DS_W->embed_width);
W->embed_height = DS_LVAL (DS_W->embed_height);
W->duration = DS_LVAL (DS_W->duration);
if (!W->author) {
W->author = DS_STR_DUP (DS_W->author);
}
return W;
}
void tglf_fetch_message_action_new (struct tgl_state *TLS, struct tgl_message_action *M, struct tl_ds_message_action *DS_MA) {
if (!DS_MA) { return; }
memset (M, 0, sizeof (*M));
switch (DS_MA->magic) {
case CODE_message_action_empty:
M->type = tgl_message_action_none;
break;
case CODE_message_action_geo_chat_create:
{
M->type = tgl_message_action_geo_chat_create;
assert (0);
}
break;
case CODE_message_action_geo_chat_checkin:
M->type = tgl_message_action_geo_chat_checkin;
break;
case CODE_message_action_chat_create:
{
M->type = tgl_message_action_chat_create;
M->title = DS_STR_DUP (DS_MA->title);
M->user_num = DS_LVAL (DS_MA->users->cnt);
M->users = talloc (M->user_num * 4);
int i;
for (i = 0; i < M->user_num; i++) {
M->users[i] = DS_LVAL (DS_MA->users->data[i]);
}
}
break;
case CODE_message_action_chat_edit_title:
M->type = tgl_message_action_chat_edit_title;
M->new_title = DS_STR_DUP (DS_MA->title);
break;
case CODE_message_action_chat_edit_photo:
M->type = tgl_message_action_chat_edit_photo;
M->photo = tglf_fetch_alloc_photo_new (TLS, DS_MA->photo);
break;
case CODE_message_action_chat_delete_photo:
M->type = tgl_message_action_chat_delete_photo;
break;
case CODE_message_action_chat_add_user:
M->type = tgl_message_action_chat_add_user;
M->user = DS_LVAL (DS_MA->user_id);
break;
case CODE_message_action_chat_delete_user:
M->type = tgl_message_action_chat_delete_user;
M->user = DS_LVAL (DS_MA->user_id);
break;
case CODE_message_action_chat_joined_by_link:
M->type = tgl_message_action_chat_add_user_by_link;
M->user = DS_LVAL (DS_MA->inviter_id);
break;
default:
assert (0);
}
}
void tglf_fetch_message_short_new (struct tgl_state *TLS, struct tgl_message *M, struct tl_ds_updates *DS_U) {
tgl_peer_t *P = tgl_peer_get (TLS, TGL_MK_USER (DS_LVAL (DS_U->user_id)));
if (!P || !(P->flags & TGLPF_CREATED)) {
tgl_do_get_difference (TLS, 0, 0, 0);
return;
}
int flags = M->flags & 0xffff;
if (M->flags & TGLMF_PENDING) {
M->flags ^= TGLMF_PENDING;
}
if (!(flags & TGLMF_CREATED)) {
flags |= TGLMF_CREATE | TGLMF_CREATED;
}
int f = DS_LVAL (DS_U->flags);
if (f & 1) {
flags |= TGLMF_UNREAD;
}
if (f & 2) {
flags |= TGLMF_OUT;
}
if (f & 16) {
flags |= TGLMF_MENTION;
}
struct tl_ds_message_media A;
A.magic = CODE_message_media_empty;
int type = TGL_PEER_USER;
bl_do_create_message_new (TLS, DS_LVAL (DS_U->id),
(f & 2) ? &TLS->our_id : DS_U->user_id,
&type, (f & 2) ? DS_U->user_id : &TLS->our_id,
DS_U->fwd_from_id,
DS_U->fwd_date,
DS_U->date,
DS_STR (DS_U->message),
&A,
NULL,
DS_U->reply_to_msg_id,
NULL,
flags
);
}
void tglf_fetch_message_short_chat_new (struct tgl_state *TLS, struct tgl_message *M, struct tl_ds_updates *DS_U) {
tgl_peer_t *P = tgl_peer_get (TLS, TGL_MK_USER (DS_LVAL (DS_U->from_id)));
if (!P || !(P->flags & TGLPF_CREATED)) {
tgl_do_get_difference (TLS, 0, 0, 0);
return;
}
P = tgl_peer_get (TLS, TGL_MK_CHAT (DS_LVAL (DS_U->chat_id)));
if (!P || !(P->flags & TGLPF_CREATED)) {
tgl_do_get_difference (TLS, 0, 0, 0);
return;
}
int flags = M->flags & 0xffff;
if (M->flags & TGLMF_PENDING) {
M->flags ^= TGLMF_PENDING;
}
if (!(flags & TGLMF_CREATED)) {
flags |= TGLMF_CREATE | TGLMF_CREATED;
}
int f = DS_LVAL (DS_U->flags);
if (f & 1) {
flags |= TGLMF_UNREAD;
}
if (f & 2) {
flags |= TGLMF_OUT;
}
if (f & 16) {
flags |= TGLMF_MENTION;
}
struct tl_ds_message_media A;
A.magic = CODE_message_media_empty;
int type = TGL_PEER_CHAT;
bl_do_create_message_new (TLS, DS_LVAL (DS_U->id),
DS_U->from_id,
&type, DS_U->chat_id,
DS_U->fwd_from_id,
DS_U->fwd_date,
DS_U->date,
DS_STR (DS_U->message),
&A,
NULL,
DS_U->reply_to_msg_id,
NULL,
flags
);
}
void tglf_fetch_message_media_new (struct tgl_state *TLS, struct tgl_message_media *M, struct tl_ds_message_media *DS_MM) {
if (!DS_MM) { return; }
memset (M, 0, sizeof (*M));
switch (DS_MM->magic) {
case CODE_message_media_empty:
M->type = tgl_message_media_none;
break;
case CODE_message_media_photo:
case CODE_message_media_photo_l27:
M->type = tgl_message_media_photo;
M->photo = tglf_fetch_alloc_photo_new (TLS, DS_MM->photo);
M->caption = DS_STR_DUP (DS_MM->caption);
break;
case CODE_message_media_video:
case CODE_message_media_video_l27:
M->type = tgl_message_media_document;
M->document = tglf_fetch_alloc_video_new (TLS, DS_MM->video);
M->caption = DS_STR_DUP (DS_MM->caption);
break;
case CODE_message_media_audio:
M->type = tgl_message_media_document;
M->document = tglf_fetch_alloc_audio_new (TLS, DS_MM->audio);
break;
case CODE_message_media_document:
M->type = tgl_message_media_document;
M->document = tglf_fetch_alloc_document_new (TLS, DS_MM->document);
break;
case CODE_message_media_geo:
M->type = tgl_message_media_geo;
tglf_fetch_geo_new (TLS, &M->geo, DS_MM->geo);
break;
case CODE_message_media_contact:
M->type = tgl_message_media_contact;
M->phone = DS_STR_DUP (DS_MM->phone_number);
M->first_name = DS_STR_DUP (DS_MM->first_name);
M->last_name = DS_STR_DUP (DS_MM->last_name);
M->user_id = DS_LVAL (DS_MM->user_id);
break;
case CODE_message_media_unsupported:
//case CODE_message_media_unsupported_l22:
M->type = tgl_message_media_unsupported;
break;
case CODE_message_media_web_page:
M->type = tgl_message_media_webpage;
M->webpage = tglf_fetch_alloc_webpage_new (TLS, DS_MM->webpage);
break;
case CODE_message_media_venue:
M->type = tgl_message_media_venue;
tglf_fetch_geo_new (TLS, &M->venue.geo, DS_MM->geo);
M->venue.title = DS_STR_DUP (DS_MM->title);
M->venue.address = DS_STR_DUP (DS_MM->address);
M->venue.provider = DS_STR_DUP (DS_MM->provider);
M->venue.venue_id = DS_STR_DUP (DS_MM->venue_id);
break;
default:
assert (0);
}
}
void tglf_fetch_message_media_encrypted_new (struct tgl_state *TLS, struct tgl_message_media *M, struct tl_ds_decrypted_message_media *DS_DMM) {
if (!DS_DMM) { return; }
memset (M, 0, sizeof (*M));
switch (DS_DMM->magic) {
case CODE_decrypted_message_media_empty:
M->type = tgl_message_media_none;
//M->type = CODE_message_media_empty;
break;
case CODE_decrypted_message_media_photo:
case CODE_decrypted_message_media_video:
case CODE_decrypted_message_media_video_l12:
case CODE_decrypted_message_media_document:
case CODE_decrypted_message_media_audio:
//M->type = CODE_decrypted_message_media_video;
M->type = tgl_message_media_document_encr;
M->encr_document = talloc0 (sizeof (*M->encr_document));
switch (DS_DMM->magic) {
case CODE_decrypted_message_media_photo:
M->encr_document->flags = TGLDF_IMAGE;
break;
case CODE_decrypted_message_media_video:
case CODE_decrypted_message_media_video_l12:
M->encr_document->flags = TGLDF_VIDEO;
break;
case CODE_decrypted_message_media_document:
//M->encr_document->flags = TGLDF_DOCUMENT;
break;
case CODE_decrypted_message_media_audio:
M->encr_document->flags = TGLDF_AUDIO;
break;
}
M->encr_document->w = DS_LVAL (DS_DMM->w);
M->encr_document->h = DS_LVAL (DS_DMM->h);
M->encr_document->size = DS_LVAL (DS_DMM->size);
M->encr_document->duration = DS_LVAL (DS_DMM->duration);
M->encr_document->mime_type = DS_STR_DUP (DS_DMM->mime_type);
M->encr_document->key = talloc (32);
str_to_32 (M->encr_document->key, DS_STR (DS_DMM->key));
M->encr_document->iv = talloc (32);
str_to_32 (M->encr_document->iv, DS_STR (DS_DMM->iv));
break;
case CODE_decrypted_message_media_geo_point:
M->type = tgl_message_media_geo;
M->geo.latitude = DS_LVAL (DS_DMM->latitude);
M->geo.longitude = DS_LVAL (DS_DMM->longitude);
break;
case CODE_decrypted_message_media_contact:
M->type = tgl_message_media_contact;
M->phone = DS_STR_DUP (DS_DMM->phone_number);
M->first_name = DS_STR_DUP (DS_DMM->first_name);
M->last_name = DS_STR_DUP (DS_DMM->last_name);
M->user_id = DS_LVAL (DS_DMM->user_id);
break;
default:
assert (0);
}
}
void tglf_fetch_message_action_encrypted_new (struct tgl_state *TLS, struct tgl_message_action *M, struct tl_ds_decrypted_message_action *DS_DMA) {
if (!DS_DMA) { return; }
switch (DS_DMA->magic) {
case CODE_decrypted_message_action_set_message_t_t_l:
M->type = tgl_message_action_set_message_ttl;
M->ttl = DS_LVAL (DS_DMA->ttl_seconds);
break;
case CODE_decrypted_message_action_read_messages:
M->type = tgl_message_action_read_messages;
{
M->read_cnt = DS_LVAL (DS_DMA->random_ids->cnt);
int i;
for (i = 0; i < M->read_cnt; i++) {
struct tgl_message *N = tgl_message_get (TLS, DS_LVAL (DS_DMA->random_ids->data[i]));
if (N) {
N->flags &= ~TGLMF_UNREAD;
}
}
}
break;
case CODE_decrypted_message_action_delete_messages:
M->type = tgl_message_action_delete_messages;
break;
case CODE_decrypted_message_action_screenshot_messages:
M->type = tgl_message_action_screenshot_messages;
{
M->screenshot_cnt = DS_LVAL (DS_DMA->random_ids->cnt);
}
break;
case CODE_decrypted_message_action_notify_layer:
M->type = tgl_message_action_notify_layer;
M->layer = DS_LVAL (DS_DMA->layer);
break;
case CODE_decrypted_message_action_flush_history:
M->type = tgl_message_action_flush_history;
break;
case CODE_decrypted_message_action_typing:
M->type = tgl_message_action_typing;
M->typing = tglf_fetch_typing_new (DS_DMA->action);
break;
case CODE_decrypted_message_action_resend:
M->type = tgl_message_action_resend;
M->start_seq_no = DS_LVAL (DS_DMA->start_seq_no);
M->end_seq_no = DS_LVAL (DS_DMA->end_seq_no);
break;
case CODE_decrypted_message_action_noop:
M->type = tgl_message_action_noop;
break;
case CODE_decrypted_message_action_request_key:
M->type = tgl_message_action_request_key;
M->exchange_id = DS_LVAL (DS_DMA->exchange_id);
M->g_a = talloc (256);
str_to_256 (M->g_a, DS_STR (DS_DMA->g_a));
break;
case CODE_decrypted_message_action_accept_key:
M->type = tgl_message_action_accept_key;
M->exchange_id = DS_LVAL (DS_DMA->exchange_id);
M->g_a = talloc (256);
str_to_256 (M->g_a, DS_STR (DS_DMA->g_b));
M->key_fingerprint = DS_LVAL (DS_DMA->key_fingerprint);
break;
case CODE_decrypted_message_action_commit_key:
M->type = tgl_message_action_commit_key;
M->exchange_id = DS_LVAL (DS_DMA->exchange_id);
M->key_fingerprint = DS_LVAL (DS_DMA->key_fingerprint);
break;
case CODE_decrypted_message_action_abort_key:
M->type = tgl_message_action_abort_key;
M->exchange_id = DS_LVAL (DS_DMA->exchange_id);
break;
default:
assert (0);
}
}
tgl_peer_id_t tglf_fetch_peer_id_new (struct tgl_state *TLS, struct tl_ds_peer *DS_P) {
if (DS_P->magic == CODE_peer_user) {
return TGL_MK_USER (DS_LVAL (DS_P->user_id));
} else {
return TGL_MK_CHAT (DS_LVAL (DS_P->chat_id));
}
}
void tglf_fetch_message_new (struct tgl_state *TLS, struct tgl_message *M, struct tl_ds_message *DS_M) {
if (!DS_M || DS_M->magic == CODE_message_empty) { return; }
assert (M->id == DS_LVAL (DS_M->id));
tgl_peer_id_t to_id = tglf_fetch_peer_id_new (TLS, DS_M->to_id);
{
tgl_peer_t *P = tgl_peer_get (TLS, to_id);
if (!P || !(P->flags & TGLPF_CREATED)) {
tgl_do_get_difference (TLS, 0, 0, 0);
return;
}
P = tgl_peer_get (TLS, TGL_MK_USER (DS_LVAL (DS_M->from_id)));
if (!P || !(P->flags & TGLPF_CREATED)) {
tgl_do_get_difference (TLS, 0, 0, 0);
return;
}
}
int new = !(M->flags & TGLMF_CREATED);
if (new) {
int peer_id = tgl_get_peer_id (to_id);
int peer_type = tgl_get_peer_type (to_id);
int flags = 0;
if (DS_LVAL (DS_M->flags) & 1) {
flags |= TGLMF_UNREAD;
}
if (DS_LVAL (DS_M->flags) & 2) {
flags |= TGLMF_OUT;
}
if (DS_LVAL (DS_M->flags) & 16) {
flags |= TGLMF_MENTION;
}
bl_do_create_message_new (TLS, DS_LVAL (DS_M->id),
DS_M->from_id,
&peer_type, &peer_id,
DS_M->fwd_from_id, DS_M->fwd_date,
DS_M->date,
DS_STR (DS_M->message),
DS_M->media,
DS_M->action,
DS_M->reply_to_msg_id,
DS_M->reply_markup,
flags | TGLMF_CREATE | TGLMF_CREATED
);
}
}
static int *decr_ptr;
static int *decr_end;
static int decrypt_encrypted_message (struct tgl_secret_chat *E) {
int *msg_key = decr_ptr;
decr_ptr += 4;
assert (decr_ptr < decr_end);
static unsigned char sha1a_buffer[20];
static unsigned char sha1b_buffer[20];
static unsigned char sha1c_buffer[20];
static unsigned char sha1d_buffer[20];
static unsigned char buf[64];
int *e_key = E->exchange_state != tgl_sce_committed ? E->key : E->exchange_key;
memcpy (buf, msg_key, 16);
memcpy (buf + 16, e_key, 32);
sha1 (buf, 48, sha1a_buffer);
memcpy (buf, e_key + 8, 16);
memcpy (buf + 16, msg_key, 16);
memcpy (buf + 32, e_key + 12, 16);
sha1 (buf, 48, sha1b_buffer);
memcpy (buf, e_key + 16, 32);
memcpy (buf + 32, msg_key, 16);
sha1 (buf, 48, sha1c_buffer);
memcpy (buf, msg_key, 16);
memcpy (buf + 16, e_key + 24, 32);
sha1 (buf, 48, sha1d_buffer);
static unsigned char key[32];
memcpy (key, sha1a_buffer + 0, 8);
memcpy (key + 8, sha1b_buffer + 8, 12);
memcpy (key + 20, sha1c_buffer + 4, 12);
static unsigned char iv[32];
memcpy (iv, sha1a_buffer + 8, 12);
memcpy (iv + 12, sha1b_buffer + 0, 8);
memcpy (iv + 20, sha1c_buffer + 16, 4);
memcpy (iv + 24, sha1d_buffer + 0, 8);
AES_KEY aes_key;
AES_set_decrypt_key (key, 256, &aes_key);
AES_ige_encrypt ((void *)decr_ptr, (void *)decr_ptr, 4 * (decr_end - decr_ptr), &aes_key, iv, 0);
memset (&aes_key, 0, sizeof (aes_key));
int x = *(decr_ptr);
if (x < 0 || (x & 3)) {
return -1;
}
assert (x >= 0 && !(x & 3));
sha1 ((void *)decr_ptr, 4 + x, sha1a_buffer);
if (memcmp (sha1a_buffer + 4, msg_key, 16)) {
return -1;
}
return 0;
}
void tglf_fetch_encrypted_message_new (struct tgl_state *TLS, struct tgl_message *M, struct tl_ds_encrypted_message *DS_EM) {
if (!DS_EM) { return; }
int new = !(M->flags & TGLMF_CREATED);
if (!new) {
return;
}
tgl_peer_t *P = tgl_peer_get (TLS, TGL_MK_ENCR_CHAT (DS_LVAL (DS_EM->chat_id)));
if (!P || P->encr_chat.state != sc_ok) {
vlogprintf (E_WARNING, "Encrypted message to unknown chat. Dropping\n");
return;
}
decr_ptr = (void *)DS_EM->bytes->data;
decr_end = decr_ptr + (DS_EM->bytes->len / 4);
if (P->encr_chat.exchange_state == tgl_sce_committed && P->encr_chat.key_fingerprint == *(long long *)decr_ptr) {
tgl_do_confirm_exchange (TLS, (void *)P, 0);
assert (P->encr_chat.exchange_state == tgl_sce_none);
}
long long key_fingerprint = P->encr_chat.exchange_state != tgl_sce_committed ? P->encr_chat.key_fingerprint : P->encr_chat.exchange_key_fingerprint;
if (*(long long *)decr_ptr != key_fingerprint) {
vlogprintf (E_WARNING, "Encrypted message with bad fingerprint to chat %s\n", P->print_name);
return;
}
decr_ptr += 2;
if (decrypt_encrypted_message (&P->encr_chat) < 0) {
vlogprintf (E_WARNING, "can not decrypt message\n");
return;
}
int *save_in_ptr = in_ptr;
int *save_in_end = in_end;
in_ptr = decr_ptr;
int ll = *in_ptr;
in_end = in_ptr + ll / 4 + 1;
assert (fetch_int () == ll);
if (skip_type_decrypted_message_layer (TYPE_TO_PARAM (decrypted_message_layer)) < 0 || in_ptr != in_end) {
vlogprintf (E_WARNING, "can not fetch message\n");
in_ptr = save_in_ptr;
in_end = save_in_end;
return;
}
in_ptr = decr_ptr;
assert (fetch_int () == ll);
struct tl_ds_decrypted_message_layer *DS_DML = fetch_ds_type_decrypted_message_layer (TYPE_TO_PARAM (decrypted_message_layer));
assert (DS_DML);
in_ptr = save_in_ptr;
in_end = save_in_end;
//bl_do_encr_chat_set_layer (TLS, (void *)P, DS_LVAL (DS_DML->layer));
bl_do_encr_chat_new (TLS, tgl_get_peer_id (P->id),
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, DS_DML->layer, NULL, NULL, NULL, NULL,
TGL_FLAGS_UNCHANGED
);
int in_seq_no = DS_LVAL (DS_DML->out_seq_no);
int out_seq_no = DS_LVAL (DS_DML->in_seq_no);
if (in_seq_no / 2 != P->encr_chat.in_seq_no) {
vlogprintf (E_WARNING, "Hole in seq in secret chat. in_seq_no = %d, expect_seq_no = %d\n", in_seq_no / 2, P->encr_chat.in_seq_no);
free_ds_type_decrypted_message_layer (DS_DML, TYPE_TO_PARAM(decrypted_message_layer));
return;
}
if ((in_seq_no & 1) != 1 - (P->encr_chat.admin_id == TLS->our_id) ||
(out_seq_no & 1) != (P->encr_chat.admin_id == TLS->our_id)) {
vlogprintf (E_WARNING, "Bad msg admin\n");
free_ds_type_decrypted_message_layer (DS_DML, TYPE_TO_PARAM(decrypted_message_layer));
return;
}
if (out_seq_no / 2 > P->encr_chat.out_seq_no) {
vlogprintf (E_WARNING, "In seq no is bigger than our's out seq no (out_seq_no = %d, our_out_seq_no = %d). Drop\n", out_seq_no / 2, P->encr_chat.out_seq_no);
free_ds_type_decrypted_message_layer (DS_DML, TYPE_TO_PARAM(decrypted_message_layer));
return;
}
if (out_seq_no / 2 < P->encr_chat.last_in_seq_no) {
vlogprintf (E_WARNING, "Clients in_seq_no decreased (out_seq_no = %d, last_out_seq_no = %d). Drop\n", out_seq_no / 2, P->encr_chat.last_in_seq_no);
free_ds_type_decrypted_message_layer (DS_DML, TYPE_TO_PARAM(decrypted_message_layer));
return;
}
struct tl_ds_decrypted_message *DS_DM = DS_DML->message;
if (M->id != DS_LVAL (DS_DM->random_id)) {
vlogprintf (E_ERROR, "Incorrect message: id = %lld, new_id = %lld\n", M->id, DS_LVAL (DS_DM->random_id));
free_ds_type_decrypted_message_layer (DS_DML, TYPE_TO_PARAM(decrypted_message_layer));
return;
}
int peer_type = TGL_PEER_ENCR_CHAT;
int peer_id = tgl_get_peer_id (P->id);
bl_do_create_message_encr_new (TLS, M->id, &P->encr_chat.user_id, &peer_type, &peer_id, DS_EM->date, DS_STR (DS_DM->message), DS_DM->media, DS_DM->action, DS_EM->file, TGLMF_CREATE | TGLMF_CREATED | TGLMF_ENCRYPTED);
if (in_seq_no >= 0 && out_seq_no >= 0) {
//bl_do_encr_chat_update_seq (TLS, (void *)P, in_seq_no / 2 + 1, out_seq_no / 2);
in_seq_no = in_seq_no / 2 + 1;
out_seq_no = out_seq_no / 2;
bl_do_encr_chat_new (TLS, tgl_get_peer_id (P->id),
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, NULL, &in_seq_no, &out_seq_no, NULL, NULL,
TGL_FLAGS_UNCHANGED
);
assert (P->encr_chat.in_seq_no == in_seq_no);
}
free_ds_type_decrypted_message_layer (DS_DML, TYPE_TO_PARAM(decrypted_message_layer));
}
void tglf_fetch_encrypted_message_file_new (struct tgl_state *TLS, struct tgl_message_media *M, struct tl_ds_encrypted_file *DS_EF) {
if (DS_EF->magic == CODE_encrypted_file_empty) {
assert (M->type != tgl_message_media_document_encr);
} else {
assert (M->type == tgl_message_media_document_encr);
assert (M->encr_document);
M->encr_document->id = DS_LVAL (DS_EF->id);
M->encr_document->access_hash = DS_LVAL (DS_EF->access_hash);
if (!M->encr_document->size) {
M->encr_document->size = DS_LVAL (DS_EF->size);
}
M->encr_document->dc_id = DS_LVAL (DS_EF->dc_id);
M->encr_document->key_fingerprint = DS_LVAL (DS_EF->key_fingerprint);
}
}
static int id_cmp (struct tgl_message *M1, struct tgl_message *M2) {
if (M1->id < M2->id) { return -1; }
else if (M1->id > M2->id) { return 1; }
else { return 0; }
}
static void increase_peer_size (struct tgl_state *TLS) {
if (TLS->peer_num == TLS->peer_size) {
int new_size = TLS->peer_size ? 2 * TLS->peer_size : 10;
int old_size = TLS->peer_size;
if (old_size) {
TLS->Peers = trealloc (TLS->Peers, old_size * sizeof (void *), new_size * sizeof (void *));
} else {
TLS->Peers = talloc (new_size * sizeof (void *));
}
TLS->peer_size = new_size;
}
}
struct tgl_user *tglf_fetch_alloc_user_new (struct tgl_state *TLS, struct tl_ds_user *DS_U) {
tgl_peer_t *U = tgl_peer_get (TLS, TGL_MK_USER (DS_LVAL (DS_U->id)));
if (!U) {
TLS->users_allocated ++;
U = talloc0 (sizeof (*U));
U->id = TGL_MK_USER (DS_LVAL (DS_U->id));
TLS->peer_tree = tree_insert_peer (TLS->peer_tree, U, lrand48 ());
increase_peer_size (TLS);
TLS->Peers[TLS->peer_num ++] = U;
}
tglf_fetch_user_new (TLS, &U->user, DS_U);
return &U->user;
}
struct tgl_secret_chat *tglf_fetch_alloc_encrypted_chat_new (struct tgl_state *TLS, struct tl_ds_encrypted_chat *DS_EC) {
tgl_peer_t *U = tgl_peer_get (TLS, TGL_MK_ENCR_CHAT (DS_LVAL (DS_EC->id)));
if (!U) {
U = talloc0 (sizeof (*U));
U->id = TGL_MK_ENCR_CHAT (DS_LVAL (DS_EC->id));
TLS->encr_chats_allocated ++;
TLS->peer_tree = tree_insert_peer (TLS->peer_tree, U, lrand48 ());
increase_peer_size (TLS);
TLS->Peers[TLS->peer_num ++] = U;
}
tglf_fetch_encrypted_chat_new (TLS, &U->encr_chat, DS_EC);
return &U->encr_chat;
}
struct tgl_user *tglf_fetch_alloc_user_full_new (struct tgl_state *TLS, struct tl_ds_user_full *DS_U) {
tgl_peer_t *U = tgl_peer_get (TLS, TGL_MK_USER (DS_LVAL (DS_U->user->id)));
if (U) {
tglf_fetch_user_full_new (TLS, &U->user, DS_U);
return &U->user;
} else {
TLS->users_allocated ++;
U = talloc0 (sizeof (*U));
U->id = TGL_MK_USER (DS_LVAL (DS_U->user->id));
TLS->peer_tree = tree_insert_peer (TLS->peer_tree, U, lrand48 ());
tglf_fetch_user_full_new (TLS, &U->user, DS_U);
increase_peer_size (TLS);
TLS->Peers[TLS->peer_num ++] = U;
return &U->user;
}
}
struct tgl_message *tglf_fetch_alloc_message_new (struct tgl_state *TLS, struct tl_ds_message *DS_M) {
struct tgl_message *M = tgl_message_get (TLS, DS_LVAL (DS_M->id));
if (!M) {
M = tglm_message_alloc (TLS, DS_LVAL (DS_M->id));
}
tglf_fetch_message_new (TLS, M, DS_M);
return M;
}
struct tgl_message *tglf_fetch_alloc_encrypted_message_new (struct tgl_state *TLS, struct tl_ds_encrypted_message *DS_EM) {
struct tgl_message *M = tgl_message_get (TLS, DS_LVAL (DS_EM->random_id));
if (!M) {
M = talloc0 (sizeof (*M));
M->id = DS_LVAL (DS_EM->random_id);
tglm_message_insert_tree (TLS, M);
TLS->messages_allocated ++;
assert (tgl_message_get (TLS, M->id) == M);
}
tglf_fetch_encrypted_message_new (TLS, M, DS_EM);
if (M->flags & TGLMF_CREATED) {
tgl_peer_t *_E = tgl_peer_get (TLS, M->to_id);
assert (_E);
struct tgl_secret_chat *E = &_E->encr_chat;
if (M->action.type == tgl_message_action_request_key) {
if (E->exchange_state == tgl_sce_none || (E->exchange_state == tgl_sce_requested && E->exchange_id > M->action.exchange_id )) {
tgl_do_accept_exchange (TLS, E, M->action.exchange_id, M->action.g_a);
} else {
vlogprintf (E_WARNING, "Exchange: Incorrect state (received request, state = %d)\n", E->exchange_state);
}
}
if (M->action.type == tgl_message_action_accept_key) {
if (E->exchange_state == tgl_sce_requested && E->exchange_id == M->action.exchange_id) {
tgl_do_commit_exchange (TLS, E, M->action.g_a);
} else {
vlogprintf (E_WARNING, "Exchange: Incorrect state (received accept, state = %d)\n", E->exchange_state);
}
}
if (M->action.type == tgl_message_action_commit_key) {
if (E->exchange_state == tgl_sce_accepted && E->exchange_id == M->action.exchange_id) {
tgl_do_confirm_exchange (TLS, E, 1);
} else {
vlogprintf (E_WARNING, "Exchange: Incorrect state (received commit, state = %d)\n", E->exchange_state);
}
}
if (M->action.type == tgl_message_action_abort_key) {
if (E->exchange_state != tgl_sce_none && E->exchange_id == M->action.exchange_id) {
tgl_do_abort_exchange (TLS, E);
} else {
vlogprintf (E_WARNING, "Exchange: Incorrect state (received abort, state = %d)\n", E->exchange_state);
}
}
if (M->action.type == tgl_message_action_notify_layer) {
bl_do_encr_chat_new (TLS, tgl_get_peer_id (E->id),
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, &M->action.layer, NULL, NULL, NULL, NULL,
TGL_FLAGS_UNCHANGED
);
}
if (M->action.type == tgl_message_action_set_message_ttl) {
//bl_do_encr_chat_set_ttl (TLS, E, M->action.ttl);
bl_do_encr_chat_new (TLS, tgl_get_peer_id (E->id),
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
&M->action.ttl, NULL, NULL, NULL, NULL, NULL,
TGL_FLAGS_UNCHANGED
);
}
}
return M;
}
struct tgl_message *tglf_fetch_alloc_message_short_new (struct tgl_state *TLS, struct tl_ds_updates *DS_U) {
int id = DS_LVAL (DS_U->id);
struct tgl_message *M = tgl_message_get (TLS, id);
if (!M) {
M = talloc0 (sizeof (*M));
M->id = id;
tglm_message_insert_tree (TLS, M);
TLS->messages_allocated ++;
}
tglf_fetch_message_short_new (TLS, M, DS_U);
return M;
}
struct tgl_message *tglf_fetch_alloc_message_short_chat_new (struct tgl_state *TLS, struct tl_ds_updates *DS_U) {
int id = DS_LVAL (DS_U->id);
struct tgl_message *M = tgl_message_get (TLS, id);
if (!M) {
M = talloc0 (sizeof (*M));
M->id = id;
tglm_message_insert_tree (TLS, M);
TLS->messages_allocated ++;
}
tglf_fetch_message_short_chat_new (TLS, M, DS_U);
return M;
}
struct tgl_chat *tglf_fetch_alloc_chat_new (struct tgl_state *TLS, struct tl_ds_chat *DS_C) {
tgl_peer_t *U = tgl_peer_get (TLS, TGL_MK_CHAT (DS_LVAL (DS_C->id)));
if (!U) {
TLS->chats_allocated ++;
U = talloc0 (sizeof (*U));
U->id = TGL_MK_CHAT (DS_LVAL (DS_C->id));
TLS->peer_tree = tree_insert_peer (TLS->peer_tree, U, lrand48 ());
increase_peer_size (TLS);
TLS->Peers[TLS->peer_num ++] = U;
}
tglf_fetch_chat_new (TLS, &U->chat, DS_C);
return &U->chat;
}
struct tgl_chat *tglf_fetch_alloc_chat_full_new (struct tgl_state *TLS, struct tl_ds_messages_chat_full *DS_MCF) {
tgl_peer_t *U = tgl_peer_get (TLS, TGL_MK_CHAT (DS_LVAL (DS_MCF->full_chat->id)));
if (U) {
tglf_fetch_chat_full_new (TLS, &U->chat, DS_MCF);
return &U->chat;
} else {
TLS->chats_allocated ++;
U = talloc0 (sizeof (*U));
U->id = TGL_MK_CHAT (DS_LVAL (DS_MCF->full_chat->id));
TLS->peer_tree = tree_insert_peer (TLS->peer_tree, U, lrand48 ());
tglf_fetch_chat_full_new (TLS, &U->chat, DS_MCF);
increase_peer_size (TLS);
TLS->Peers[TLS->peer_num ++] = U;
return &U->chat;
}
}
struct tgl_bot_info *tglf_fetch_alloc_bot_info (struct tgl_state *TLS, struct tl_ds_bot_info *DS_BI) {
if (!DS_BI || DS_BI->magic == CODE_bot_info_empty) { return NULL; }
struct tgl_bot_info *B = talloc (sizeof (*B));
B->version = DS_LVAL (DS_BI->version);
B->share_text = DS_STR_DUP (DS_BI->share_text);
B->description = DS_STR_DUP (DS_BI->description);
B->commands_num = DS_LVAL (DS_BI->commands->cnt);
B->commands = talloc (sizeof (struct tgl_bot_command) * B->commands_num);
int i;
for (i = 0; i < B->commands_num; i++) {
struct tl_ds_bot_command *BC = DS_BI->commands->data[i];
B->commands[i].command = DS_STR_DUP (BC->command);
B->commands[i].description = DS_STR_DUP (BC->description);
}
return B;
}
struct tgl_message_reply_markup *tglf_fetch_alloc_reply_markup (struct tgl_state *TLS, struct tgl_message *M, struct tl_ds_reply_markup *DS_RM) {
if (!DS_RM) { return NULL; }
struct tgl_message_reply_markup *R = talloc0 (sizeof (*R));
R->flags = DS_LVAL (DS_RM->flags);
R->refcnt = 1;
R->rows = DS_RM->rows ? DS_LVAL (DS_RM->rows->cnt) : 0;
int total = 0;
R->row_start = talloc ((R->rows + 1) * 4);
R->row_start[0] = 0;
int i;
for (i = 0; i < R->rows; i++) {
struct tl_ds_keyboard_button_row *DS_K = DS_RM->rows->data[i];
total += DS_LVAL (DS_K->buttons->cnt);
R->row_start[i + 1] = total;
}
R->buttons = talloc (sizeof (void *) * total);
int r = 0;
for (i = 0; i < R->rows; i++) {
struct tl_ds_keyboard_button_row *DS_K = DS_RM->rows->data[i];
int j;
for (j = 0; j < DS_LVAL (DS_K->buttons->cnt); j++) {
struct tl_ds_keyboard_button *DS_KB = DS_K->buttons->data[j];
R->buttons[r ++] = DS_STR_DUP (DS_KB->text);
}
}
assert (r == total);
return R;
}
/* }}} */
void tglp_insert_encrypted_chat (struct tgl_state *TLS, tgl_peer_t *P) {
TLS->encr_chats_allocated ++;
TLS->peer_tree = tree_insert_peer (TLS->peer_tree, P, lrand48 ());
increase_peer_size (TLS);
TLS->Peers[TLS->peer_num ++] = P;
}
void tglp_insert_user (struct tgl_state *TLS, tgl_peer_t *P) {
TLS->users_allocated ++;
TLS->peer_tree = tree_insert_peer (TLS->peer_tree, P, lrand48 ());
increase_peer_size (TLS);
TLS->Peers[TLS->peer_num ++] = P;
}
void tglp_insert_chat (struct tgl_state *TLS, tgl_peer_t *P) {
TLS->chats_allocated ++;
TLS->peer_tree = tree_insert_peer (TLS->peer_tree, P, lrand48 ());
increase_peer_size (TLS);
TLS->Peers[TLS->peer_num ++] = P;
}
void tgl_insert_empty_user (struct tgl_state *TLS, int uid) {
tgl_peer_id_t id = TGL_MK_USER (uid);
if (tgl_peer_get (TLS, id)) { return; }
tgl_peer_t *P = talloc0 (sizeof (*P));
P->id = id;
tglp_insert_user (TLS, P);
}
void tgl_insert_empty_chat (struct tgl_state *TLS, int cid) {
tgl_peer_id_t id = TGL_MK_CHAT (cid);
if (tgl_peer_get (TLS, id)) { return; }
tgl_peer_t *P = talloc0 (sizeof (*P));
P->id = id;
tglp_insert_chat (TLS, P);
}
/* {{{ Free */
void tgls_free_photo_size (struct tgl_state *TLS, struct tgl_photo_size *S) {
tfree_str (S->type);
if (S->data) {
tfree (S->data, S->size);
}
}
void tgls_free_photo (struct tgl_state *TLS, struct tgl_photo *P) {
if (--P->refcnt) {
assert (P->refcnt > 0);
return;
}
if (P->caption) { tfree_str (P->caption); }
if (P->sizes) {
int i;
for (i = 0; i < P->sizes_num; i++) {
tgls_free_photo_size (TLS, &P->sizes[i]);
}
tfree (P->sizes, sizeof (struct tgl_photo_size) * P->sizes_num);
}
TLS->photo_tree = tree_delete_photo (TLS->photo_tree, P);
tfree (P, sizeof (*P));
}
void tgls_free_document (struct tgl_state *TLS, struct tgl_document *D) {
if (--D->refcnt) {
assert (D->refcnt);
return;
}
if (D->mime_type) { tfree_str (D->mime_type);}
if (D->caption) {tfree_str (D->caption);}
tgls_free_photo_size (TLS, &D->thumb);
TLS->document_tree = tree_delete_document (TLS->document_tree, D);
tfree (D, sizeof (*D));
}
void tgls_free_webpage (struct tgl_state *TLS, struct tgl_webpage *W) {
if (--W->refcnt) {
assert (W->refcnt);
return;
}
if (W->url) { tfree_str (W->url); }
if (W->display_url) { tfree_str (W->display_url); }
if (W->title) { tfree_str (W->title); }
if (W->site_name) { tfree_str (W->site_name); }
if (W->type) { tfree_str (W->type); }
if (W->description) { tfree_str (W->description); }
if (W->photo) { tgls_free_photo (TLS, W->photo); }
if (W->embed_url) { tfree_str (W->embed_url); }
if (W->embed_type) { tfree_str (W->embed_type); }
if (W->author) { tfree_str (W->author); }
TLS->webpage_tree = tree_delete_webpage (TLS->webpage_tree, W);
tfree (W, sizeof (*W));
}
void tgls_free_message_media (struct tgl_state *TLS, struct tgl_message_media *M) {
switch (M->type) {
case tgl_message_media_none:
case tgl_message_media_geo:
return;
case tgl_message_media_photo:
tgls_free_photo (TLS, M->photo);
M->photo = NULL;
return;
case tgl_message_media_contact:
tfree_str (M->phone);
tfree_str (M->first_name);
tfree_str (M->last_name);
return;
case tgl_message_media_document:
tgls_free_document (TLS, M->document);
return;
case tgl_message_media_unsupported:
tfree (M->data, M->data_size);
return;
case tgl_message_media_document_encr:
tfree_secure (M->encr_document->key, 32);
tfree_secure (M->encr_document->iv, 32);
tfree (M->encr_document, sizeof (*M->encr_document));
return;
case tgl_message_media_webpage:
tgls_free_webpage (TLS, M->webpage);
return;
case tgl_message_media_venue:
if (M->venue.title) { tfree_str (M->venue.title); }
if (M->venue.address) { tfree_str (M->venue.address); }
if (M->venue.provider) { tfree_str (M->venue.provider); }
if (M->venue.venue_id) { tfree_str (M->venue.venue_id); }
return;
default:
vlogprintf (E_ERROR, "type = 0x%08x\n", M->type);
assert (0);
}
}
void tgls_free_message_action (struct tgl_state *TLS, struct tgl_message_action *M) {
switch (M->type) {
case tgl_message_action_none:
return;
case tgl_message_action_chat_create:
tfree_str (M->title);
tfree (M->users, M->user_num * 4);
return;
case tgl_message_action_chat_edit_title:
tfree_str (M->new_title);
return;
case tgl_message_action_chat_edit_photo:
tgls_free_photo (TLS, M->photo);
M->photo = NULL;
return;
case tgl_message_action_chat_delete_photo:
case tgl_message_action_chat_add_user:
case tgl_message_action_chat_add_user_by_link:
case tgl_message_action_chat_delete_user:
case tgl_message_action_geo_chat_create:
case tgl_message_action_geo_chat_checkin:
case tgl_message_action_set_message_ttl:
case tgl_message_action_read_messages:
case tgl_message_action_delete_messages:
case tgl_message_action_screenshot_messages:
case tgl_message_action_flush_history:
case tgl_message_action_typing:
case tgl_message_action_resend:
case tgl_message_action_notify_layer:
case tgl_message_action_commit_key:
case tgl_message_action_abort_key:
case tgl_message_action_noop:
return;
case tgl_message_action_request_key:
case tgl_message_action_accept_key:
tfree (M->g_a, 256);
return;
/* default:
vlogprintf (E_ERROR, "type = 0x%08x\n", M->type);
assert (0);*/
}
vlogprintf (E_ERROR, "type = 0x%08x\n", M->type);
assert (0);
}
void tgls_clear_message (struct tgl_state *TLS, struct tgl_message *M) {
if (!(M->flags & TGLMF_SERVICE)) {
if (M->message) { tfree (M->message, M->message_len + 1); }
tgls_free_message_media (TLS, &M->media);
} else {
tgls_free_message_action (TLS, &M->action);
}
}
void tgls_free_reply_markup (struct tgl_state *TLS, struct tgl_message_reply_markup *R) {
if (!--R->refcnt) {
tfree (R->buttons, R->row_start[R->rows] * sizeof (void *));
tfree (R->row_start, 4 * (R->rows + 1));
tfree (R, sizeof (*R));
} else {
assert (R->refcnt > 0);
}
}
void tgls_free_message (struct tgl_state *TLS, struct tgl_message *M) {
tgls_clear_message (TLS, M);
if (M->reply_markup) {
tgls_free_reply_markup (TLS, M->reply_markup);
}
tfree (M, sizeof (*M));
}
void tgls_free_chat (struct tgl_state *TLS, struct tgl_chat *U) {
if (U->title) { tfree_str (U->title); }
if (U->print_title) { tfree_str (U->print_title); }
if (U->user_list) {
tfree (U->user_list, U->user_list_size * 12);
}
if (U->photo) { tgls_free_photo (TLS, U->photo); }
tfree (U, sizeof (*U));
}
void tgls_free_user (struct tgl_state *TLS, struct tgl_user *U) {
if (U->first_name) { tfree_str (U->first_name); }
if (U->last_name) { tfree_str (U->last_name); }
if (U->print_name) { tfree_str (U->print_name); }
if (U->phone) { tfree_str (U->phone); }
if (U->real_first_name) { tfree_str (U->real_first_name); }
if (U->real_last_name) { tfree_str (U->real_last_name); }
if (U->status.ev) { tgl_remove_status_expire (TLS, U); }
if (U->photo) { tgls_free_photo (TLS, U->photo); }
tfree (U, sizeof (*U));
}
void tgls_free_encr_chat (struct tgl_state *TLS, struct tgl_secret_chat *U) {
if (U->print_name) { tfree_str (U->print_name); }
if (U->g_key) { tfree (U->g_key, 256); }
tfree (U, sizeof (*U));
}
void tgls_free_peer (struct tgl_state *TLS, tgl_peer_t *P) {
if (tgl_get_peer_type (P->id) == TGL_PEER_USER) {
tgls_free_user (TLS, (void *)P);
} else if (tgl_get_peer_type (P->id) == TGL_PEER_CHAT) {
tgls_free_chat (TLS, (void *)P);
} else if (tgl_get_peer_type (P->id) == TGL_PEER_ENCR_CHAT) {
tgls_free_encr_chat (TLS, (void *)P);
} else {
assert (0);
}
}
void tgls_free_bot_info (struct tgl_state *TLS, struct tgl_bot_info *B) {
if (!B) { return; }
int i;
for (i = 0; i < B->commands_num; i++) {
tfree_str (B->commands[i].command);
tfree_str (B->commands[i].description);
}
tfree (B->commands, sizeof (struct tgl_bot_command) * B->commands_num);
tfree_str (B->share_text);
tfree_str (B->description);
tfree (B, sizeof (*B));
}
/* }}} */
/* Messages {{{ */
void tglm_message_del_use (struct tgl_state *TLS, struct tgl_message *M) {
M->next_use->prev_use = M->prev_use;
M->prev_use->next_use = M->next_use;
}
void tglm_message_add_use (struct tgl_state *TLS, struct tgl_message *M) {
M->next_use = TLS->message_list.next_use;
M->prev_use = &TLS->message_list;
M->next_use->prev_use = M;
M->prev_use->next_use = M;
}
void tglm_message_add_peer (struct tgl_state *TLS, struct tgl_message *M) {
tgl_peer_id_t id;
if (!tgl_cmp_peer_id (M->to_id, TGL_MK_USER (TLS->our_id))) {
id = M->from_id;
} else {
id = M->to_id;
}
tgl_peer_t *P = tgl_peer_get (TLS, id);
if (!P) {
P = talloc0 (sizeof (*P));
P->id = id;
switch (tgl_get_peer_type (id)) {
case TGL_PEER_USER:
TLS->users_allocated ++;
break;
case TGL_PEER_CHAT:
TLS->chats_allocated ++;
break;
case TGL_PEER_GEO_CHAT:
TLS->geo_chats_allocated ++;
break;
case TGL_PEER_ENCR_CHAT:
TLS->encr_chats_allocated ++;
break;
}
TLS->peer_tree = tree_insert_peer (TLS->peer_tree, P, lrand48 ());
increase_peer_size (TLS);
TLS->Peers[TLS->peer_num ++] = P;
}
if (!P->last) {
P->last = M;
M->prev = M->next = 0;
} else {
if (tgl_get_peer_type (P->id) != TGL_PEER_ENCR_CHAT) {
struct tgl_message *N = P->last;
struct tgl_message *NP = 0;
while (N && N->id > M->id) {
NP = N;
N = N->next;
}
if (N) {
assert (N->id < M->id);
}
M->next = N;
M->prev = NP;
if (N) { N->prev = M; }
if (NP) { NP->next = M; }
else { P->last = M; }
} else {
struct tgl_message *N = P->last;
struct tgl_message *NP = 0;
M->next = N;
M->prev = NP;
if (N) { N->prev = M; }
if (NP) { NP->next = M; }
else { P->last = M; }
}
}
}
void tglm_message_del_peer (struct tgl_state *TLS, struct tgl_message *M) {
tgl_peer_id_t id;
if (!tgl_cmp_peer_id (M->to_id, TGL_MK_USER (TLS->our_id))) {
id = M->from_id;
} else {
id = M->to_id;
}
tgl_peer_t *P = tgl_peer_get (TLS, id);
if (M->prev) {
M->prev->next = M->next;
}
if (M->next) {
M->next->prev = M->prev;
}
if (P && P->last == M) {
P->last = M->next;
}
}
struct tgl_message *tglm_message_alloc (struct tgl_state *TLS, long long id) {
struct tgl_message *M = talloc0 (sizeof (*M));
M->id = id;
tglm_message_insert_tree (TLS, M);
TLS->messages_allocated ++;
return M;
}
void tglm_message_insert_tree (struct tgl_state *TLS, struct tgl_message *M) {
assert (M->id);
TLS->message_tree = tree_insert_message (TLS->message_tree, M, lrand48 ());
}
void tglm_message_remove_tree (struct tgl_state *TLS, struct tgl_message *M) {
assert (M->id);
TLS->message_tree = tree_delete_message (TLS->message_tree, M);
}
void tglm_message_insert (struct tgl_state *TLS, struct tgl_message *M) {
tglm_message_add_use (TLS, M);
tglm_message_add_peer (TLS, M);
}
void tglm_message_insert_unsent (struct tgl_state *TLS, struct tgl_message *M) {
TLS->message_unsent_tree = tree_insert_message (TLS->message_unsent_tree, M, lrand48 ());
}
void tglm_message_remove_unsent (struct tgl_state *TLS, struct tgl_message *M) {
TLS->message_unsent_tree = tree_delete_message (TLS->message_unsent_tree, M);
}
static void __send_msg (struct tgl_message *M, void *_TLS) {
struct tgl_state *TLS = _TLS;
vlogprintf (E_NOTICE, "Resending message...\n");
//print_message (M);
if (M->media.type != tgl_message_media_none) {
assert (M->flags & TGLMF_ENCRYPTED);
bl_do_message_delete (TLS, M);
} else {
tgl_do_send_msg (TLS, M, 0, 0);
}
}
void tglm_send_all_unsent (struct tgl_state *TLS) {
tree_act_ex_message (TLS->message_unsent_tree, __send_msg, TLS);
}
/* }}} */
struct tgl_photo *tgl_photo_get (struct tgl_state *TLS, long long id) {
struct tgl_photo P;
P.id = id;
return tree_lookup_photo (TLS->photo_tree, &P);
}
void tgl_photo_insert (struct tgl_state *TLS, struct tgl_photo *P) {
TLS->photo_tree = tree_insert_photo (TLS->photo_tree, P, lrand48 ());
}
struct tgl_document *tgl_document_get (struct tgl_state *TLS, long long id) {
struct tgl_document P;
P.id = id;
return tree_lookup_document (TLS->document_tree, &P);
}
void tgl_document_insert (struct tgl_state *TLS, struct tgl_document *P) {
TLS->document_tree = tree_insert_document (TLS->document_tree, P, lrand48 ());
}
struct tgl_webpage *tgl_webpage_get (struct tgl_state *TLS, long long id) {
struct tgl_webpage P;
P.id = id;
return tree_lookup_webpage (TLS->webpage_tree, &P);
}
void tgl_webpage_insert (struct tgl_state *TLS, struct tgl_webpage *P) {
TLS->webpage_tree = tree_insert_webpage (TLS->webpage_tree, P, lrand48 ());
}
void tglp_peer_insert_name (struct tgl_state *TLS, tgl_peer_t *P) {
TLS->peer_by_name_tree = tree_insert_peer_by_name (TLS->peer_by_name_tree, P, lrand48 ());
}
void tglp_peer_delete_name (struct tgl_state *TLS, tgl_peer_t *P) {
TLS->peer_by_name_tree = tree_delete_peer_by_name (TLS->peer_by_name_tree, P);
}
tgl_peer_t *tgl_peer_get (struct tgl_state *TLS, tgl_peer_id_t id) {
static tgl_peer_t U;
U.id = id;
return tree_lookup_peer (TLS->peer_tree, &U);
}
struct tgl_message *tgl_message_get (struct tgl_state *TLS, long long id) {
struct tgl_message M;
M.id = id;
return tree_lookup_message (TLS->message_tree, &M);
}
tgl_peer_t *tgl_peer_get_by_name (struct tgl_state *TLS, const char *s) {
static tgl_peer_t P;
P.print_name = (void *)s;
tgl_peer_t *R = tree_lookup_peer_by_name (TLS->peer_by_name_tree, &P);
return R;
}
void tgl_peer_iterator_ex (struct tgl_state *TLS, void (*it)(tgl_peer_t *P, void *extra), void *extra) {
tree_act_ex_peer (TLS->peer_tree, it, extra);
}
int tgl_complete_user_list (struct tgl_state *TLS, int index, const char *text, int len, char **R) {
index ++;
while (index < TLS->peer_num && (!TLS->Peers[index]->print_name || strncmp (TLS->Peers[index]->print_name, text, len) || tgl_get_peer_type (TLS->Peers[index]->id) != TGL_PEER_USER)) {
index ++;
}
if (index < TLS->peer_num) {
*R = strdup (TLS->Peers[index]->print_name);
assert (*R);
return index;
} else {
return -1;
}
}
int tgl_complete_chat_list (struct tgl_state *TLS, int index, const char *text, int len, char **R) {
index ++;
while (index < TLS->peer_num && (!TLS->Peers[index]->print_name || strncmp (TLS->Peers[index]->print_name, text, len) || tgl_get_peer_type (TLS->Peers[index]->id) != TGL_PEER_CHAT)) {
index ++;
}
if (index < TLS->peer_num) {
*R = strdup (TLS->Peers[index]->print_name);
assert (*R);
return index;
} else {
return -1;
}
}
int tgl_complete_encr_chat_list (struct tgl_state *TLS, int index, const char *text, int len, char **R) {
index ++;
while (index < TLS->peer_num && (!TLS->Peers[index]->print_name || strncmp (TLS->Peers[index]->print_name, text, len) || tgl_get_peer_type (TLS->Peers[index]->id) != TGL_PEER_ENCR_CHAT)) {
index ++;
}
if (index < TLS->peer_num) {
*R = strdup (TLS->Peers[index]->print_name);
assert (*R);
return index;
} else {
return -1;
}
}
int tgl_complete_peer_list (struct tgl_state *TLS, int index, const char *text, int len, char **R) {
index ++;
while (index < TLS->peer_num && (!TLS->Peers[index]->print_name || strncmp (TLS->Peers[index]->print_name, text, len))) {
index ++;
}
if (index < TLS->peer_num) {
*R = strdup (TLS->Peers[index]->print_name);
assert (*R);
return index;
} else {
return -1;
}
}
int tgl_secret_chat_for_user (struct tgl_state *TLS, tgl_peer_id_t user_id) {
int index = 0;
while (index < TLS->peer_num && (tgl_get_peer_type (TLS->Peers[index]->id) != TGL_PEER_ENCR_CHAT || TLS->Peers[index]->encr_chat.user_id != tgl_get_peer_id (user_id) || TLS->Peers[index]->encr_chat.state != sc_ok)) {
index ++;
}
if (index < TLS->peer_num) {
return tgl_get_peer_id (TLS->Peers[index]->encr_chat.id);
} else {
return -1;
}
}
void tgls_free_peer_gw (tgl_peer_t *P, void *TLS) {
tgls_free_peer (TLS, P);
}
void tgls_free_message_gw (struct tgl_message *M, void *TLS) {
tgls_free_message (TLS, M);
}
void tgl_free_all (struct tgl_state *TLS) {
tree_act_ex_peer (TLS->peer_tree, tgls_free_peer_gw, TLS);
TLS->peer_tree = tree_clear_peer (TLS->peer_tree);
TLS->peer_by_name_tree = tree_clear_peer_by_name (TLS->peer_by_name_tree);
tree_act_ex_message (TLS->message_tree, tgls_free_message_gw, TLS);
TLS->message_tree = tree_clear_message (TLS->message_tree);
tree_act_ex_message (TLS->message_unsent_tree, tgls_free_message_gw, TLS);
TLS->message_unsent_tree = tree_clear_message (TLS->message_unsent_tree);
tglq_query_free_all (TLS);
if (TLS->encr_prime) { tfree (TLS->encr_prime, 256); }
if (TLS->binlog_name) { tfree_str (TLS->binlog_name); }
if (TLS->auth_file) { tfree_str (TLS->auth_file); }
if (TLS->downloads_directory) { tfree_str (TLS->downloads_directory); }
int i;
for (i = 0; i < TLS->rsa_key_num; i++) {
tfree_str (TLS->rsa_key_list[i]);
}
for (i = 0; i <= TLS->max_dc_num; i++) if (TLS->DC_list[i]) {
tgls_free_dc (TLS, TLS->DC_list[i]);
}
BN_CTX_free (TLS->BN_ctx);
tgls_free_pubkey (TLS);
if (TLS->ev_login) { TLS->timer_methods->free (TLS->ev_login); }
if (TLS->online_updates_timer) { TLS->timer_methods->free (TLS->online_updates_timer); }
}
int tgl_print_stat (struct tgl_state *TLS, char *s, int len) {
return tsnprintf (s, len,
"users_allocated\t%d\n"
"chats_allocated\t%d\n"
"encr_chats_allocated\t%d\n"
"peer_num\t%d\n"
"messages_allocated\t%d\n",
TLS->users_allocated,
TLS->chats_allocated,
TLS->encr_chats_allocated,
TLS->peer_num,
TLS->messages_allocated
);
}
void tglf_fetch_int_array (int *dst, struct tl_ds_vector *src, int len) {
int i;
assert (len <= *src->f1);
for (i = 0; i < len; i++) {
dst[i] = *(int *)src->f2[i];
}
}
void tglf_fetch_int_tuple (int *dst, int **src, int len) {
int i;
for (i = 0; i < len; i++) {
dst[i] = *src[i];
}
}
void tgls_messages_mark_read (struct tgl_state *TLS, struct tgl_message *M, int out, int seq) {
while (M && M->id > seq) {
if ((M->flags & TGLMF_OUT) == out) {
if (!(M->flags & TGLMF_UNREAD)) {
return;
}
}
M = M->next;
}
while (M) {
if ((M->flags & TGLMF_OUT) == out) {
if (M->flags & TGLMF_UNREAD) {
M->flags &= ~TGLMF_UNREAD;
TLS->callback.marked_read (TLS, 1, &M);
} else {
return;
}
}
M = M->next;
}
}
void tgls_insert_random2local (struct tgl_state *TLS, long long random_id, int local_id) {
struct random2local *X = talloc (sizeof (*X));
X->random_id = random_id;
X->local_id = local_id;
struct random2local *R = tree_lookup_random_id (TLS->random_id_tree, X);
assert (!R);
TLS->random_id_tree = tree_insert_random_id (TLS->random_id_tree, X, lrand48 ());
}
int tgls_get_local_by_random (struct tgl_state *TLS, long long random_id) {
struct random2local X;
X.random_id = random_id;
struct random2local *Y = tree_lookup_random_id (TLS->random_id_tree, &X);
if (Y) {
TLS->random_id_tree = tree_delete_random_id (TLS->random_id_tree, Y);
int y = Y->local_id;
tfree (Y, sizeof (*Y));
return y;
} else {
return 0;
}
}
| gpl-2.0 |
kaen/Zero-K | units/roostfac.lua | 6 | 3153 | unitDef = {
unitname = [[roostfac]],
name = [[Roost]],
description = [[Spawns Big Chickens]],
acceleration = 0,
bmcode = [[0]],
brakeRate = 0,
buildAngle = 4096,
buildCostEnergy = 0,
buildCostMetal = 0,
builder = true,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 11,
buildingGroundDecalSizeY = 11,
buildingGroundDecalType = [[roostfac_aoplane.dds]],
buildoptions = {
[[chicken_drone]],
[[chickenf]],
[[chicken_blimpy]],
[[chicken_listener]],
[[chickena]],
[[chickenc]],
[[chickenblobber]],
[[chicken_spidermonkey]],
[[chicken_tiamat]],
[[chicken_dragon]],
},
buildPic = [[roostfac.png]],
buildTime = 200,
canMove = true,
canPatrol = true,
canstop = [[1]],
category = [[SINK UNARMED]],
commander = false,
customParams = {
description_de = [[Erzeugt große Chicken]],
description_pl = [[Rozmnaza wieksze kurczaki]],
helptext = [[Roosts such as this one are where the more powerful Thunderbirds are hatched.]],
helptext_de = [[Mächtige Kreaturen werden hier erzeugt und losgelassen.]],
helptext_pl = [[W tym gniezdzie rodza sie wieksze, bardziej zaawansowane kurczaki.]],
chickenFac = [[true]],
},
energyMake = 1,
energyStorage = 50,
energyUse = 0,
explodeAs = [[NOWEAPON]],
footprintX = 8,
footprintZ = 8,
iconType = [[factory]],
idleAutoHeal = 5,
idleTime = 1800,
mass = 380,
maxDamage = 8000,
maxSlope = 15,
maxVelocity = 0,
metalMake = 1.05,
metalStorage = 50,
minCloakDistance = 150,
noAutoFire = false,
objectName = [[roostfac_big]],
power = 1000,
seismicSignature = 4,
selfDestructAs = [[NOWEAPON]],
sfxtypes = {
explosiongenerators = {
[[custom:dirt2]],
[[custom:dirt3]],
[[custom:Nano]],
},
},
showNanoSpray = false,
side = [[THUNDERBIRDS]],
sightDistance = 273,
smoothAnim = true,
TEDClass = [[PLANT]],
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = 42,
yardMap = [[ooccccoo ooccccoo ooccccoo ooccccoo ooccccoo ooccccoo ooccccoo ooccccoo ]],
featureDefs = {
},
}
return lowerkeys({ roostfac = unitDef })
| gpl-2.0 |
371816210/vlc_vlc | share/lua/playlist/vimeo.lua | 65 | 3213 | --[[
$Id$
Copyright © 2009-2013 the VideoLAN team
Authors: Konstantin Pavlov (thresh@videolan.org)
François Revol (revol@free.fr)
Pierre Ynard
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.
--]]
function get_prefres()
local prefres = -1
if vlc.var and vlc.var.inherit then
prefres = vlc.var.inherit(nil, "preferred-resolution")
if prefres == nil then
prefres = -1
end
end
return prefres
end
-- Probe function.
function probe()
return ( vlc.access == "http" or vlc.access == "https" )
and ( string.match( vlc.path, "vimeo%.com/%d+$" )
or string.match( vlc.path, "player%.vimeo%.com" ) )
-- do not match other addresses,
-- else we'll also try to decode the actual video url
end
-- Parse function.
function parse()
if not string.match( vlc.path, "player%.vimeo%.com" ) then -- Web page URL
while true do
local line = vlc.readline()
if not line then break end
path = string.match( line, "data%-config%-url=\"(.-)\"" )
if path then
path = vlc.strings.resolve_xml_special_chars( path )
return { { path = path } }
end
end
vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" )
return { }
else -- API URL
local prefres = get_prefres()
local line = vlc.readline() -- data is on one line only
for stream in string.gmatch( line, "{([^}]*\"profile\":[^}]*)}" ) do
local url = string.match( stream, "\"url\":\"(.-)\"" )
if url then
path = url
if prefres < 0 then
break
end
local height = string.match( stream, "\"height\":(%d+)[,}]" )
if not height or tonumber(height) <= prefres then
break
end
end
end
if not path then
vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" )
return { }
end
local name = string.match( line, "\"title\":\"(.-)\"" )
local artist = string.match( line, "\"owner\":{[^}]-\"name\":\"(.-)\"" )
local arturl = string.match( line, "\"thumbs\":{\"[^\"]+\":\"(.-)\"" )
local duration = string.match( line, "\"duration\":(%d+)[,}]" )
return { { path = path; name = name; artist = artist; arturl = arturl; duration = duration } }
end
end
| gpl-2.0 |
geanux/darkstar | scripts/zones/The_Eldieme_Necropolis/Zone.lua | 30 | 2110 | -----------------------------------
--
-- Zone: The_Eldieme_Necropolis (195)
--
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/zone");
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local tomes = {17576425,17576426,17576427,17576428};
SetGroundsTome(tomes);
UpdateTreasureSpawnPoint(17576352);
UpdateTreasureSpawnPoint(17576353);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
-- rng af2
local FireAndBrimstoneCS = player:getVar("fireAndBrimstone");
if (FireAndBrimstoneCS == 2) then
return 4;
end
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-438.878,-26.091,540.004,126);
end
return cs;
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;
-----------------------------------
-- 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 == 4) then
player:setVar("fireAndBrimstone",3);
end
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.