repo_name stringlengths 6 78 | path stringlengths 4 206 | copies stringclasses 281
values | size stringlengths 4 7 | content stringlengths 625 1.05M | license stringclasses 15
values |
|---|---|---|---|---|---|
MonokuroInzanaito/ygopro-777DIY | expansions/script/c114000460.lua | 1 | 2394 | --未来への追憶の夢(ノスタルジーカ)
function c114000460.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOGRAVE+CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,0x1e0)
e1:SetCost(c114000460.cost)
e1:SetCondition(c114000460.condition)
e1:SetTarget(c114000460.target)
e1:SetOperation(c114000460.activate)
c:RegisterEffect(e1)
end
function c114000460.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFlagEffect(tp,114000376)==0 end
Duel.RegisterFlagEffect(tp,114000376,RESET_PHASE+PHASE_END,EFFECT_FLAG_OATH,1)
end
function c114000460.filter(c)
return ( c:IsSetCard(0x221) or c:IsCode(114000231) ) and c:IsFaceup()
end
function c114000460.condition(e,c) --xc:GetControler()
return Duel.GetMatchingGroup(c114000460.filter,tp,LOCATION_MZONE,0,nil):GetClassCount(Card.GetCode)>=2
end
function c114000460.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chkc then return chkc:IsLocation(LOCATION_REMOVED) end
if chk==0 then return Duel.IsExistingMatchingCard(nil,tp,LOCATION_REMOVED,LOCATION_REMOVED,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,PLAYER_ALL,LOCATION_REMOVED)
end
function c114000460.activate(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetRange(LOCATION_REMOVED)
e1:SetCountLimit(1)
e1:SetOperation(c114000460.operation)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c114000460.spfilter(c,e,tp)
return c:IsCanBeSpecialSummoned(e,0,tp,false,false)
and ( c:IsSetCard(0x221) or c:IsCode(114000231) )
and c:IsRace(RACE_MACHINE)
and c:IsLevelBelow(4)
end
function c114000460.operation(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetFieldGroup(tp,LOCATION_REMOVED,LOCATION_REMOVED)
if g:GetCount()>0 then
Duel.SendtoGrave(g,REASON_EFFECT+REASON_RETURN)
if Duel.IsExistingMatchingCard(c114000460.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.SelectYesNo(tp,aux.Stringid(114000460,0)) then
Duel.BreakEffect()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g2=Duel.SelectMatchingCard(tp,c114000460.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
Duel.SpecialSummon(g2,0,tp,tp,false,false,POS_FACEUP)
end
end
end | gpl-3.0 |
martin-eden/workshop | concepts/json/load/via_parser/syntaxes/strict.lua | 1 | 2674 | -- Maximum explicit definition of syntax.
-- Intended to verify results from optimized syntaxes
local processor_handy = request('!.mechs.processor.handy')
local cho = processor_handy.cho
local opt_rep = processor_handy.opt_rep
local opt = processor_handy.opt
local rep = processor_handy.rep
local is_not = processor_handy.is_not
local opt_rep = processor_handy.opt_rep
local list = processor_handy.list
local any_char = request('!.mechs.parser.handy').any_char
local opt_spc =
opt_rep(cho(' ', '\n', '\r', '\t'))
local open_brace = '{'
local close_brace = {opt_spc, '}'}
local open_bracket = '['
local close_bracket = {opt_spc, ']'}
local colon = {opt_spc, ':'}
local comma = {opt_spc, ','}
local null =
{opt_spc, {name = 'null', 'null'}}
local boolean =
{opt_spc, {name = 'boolean', cho('true', 'false')}}
local zero_digit = '0'
local nonzero_dec_digit = cho('9', '8', '7', '6', '5', '4', '3', '2', '1')
local dec_digit = cho(nonzero_dec_digit, zero_digit)
local number =
{
opt_spc,
{
name = 'number',
opt('-'),
cho(
zero_digit,
{nonzero_dec_digit, opt_rep(dec_digit)}
),
opt({'.', rep(dec_digit)}),
opt(cho('e', 'E'), opt(cho('+', '-')), rep(dec_digit))
},
}
local control_char =
cho(
'\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
'\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f',
'\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
'\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f'
)
local hex_only_digit =
cho('a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F')
local hex_dig =
cho(dec_digit, hex_only_digit)
local utf_code_point =
{'u', hex_dig, hex_dig, hex_dig, hex_dig}
local json_string =
{
opt_spc,
{
name = 'string',
'"',
opt_rep(
cho(
{is_not(cho('"', [[\]], control_char)), any_char},
{
[[\]],
cho('"', [[\]], '/', 'b', 'f', 'n', 'r', 't', utf_code_point)
}
)
),
'"'
},
}
local array =
{
opt_spc,
{
name = 'array',
open_bracket,
opt(list('>value', comma)),
close_bracket
},
}
local object =
{
opt_spc,
{
name = 'object',
open_brace,
opt(list(json_string, colon, '>value', comma)),
close_brace,
},
}
local value =
cho(
number,
json_string,
array,
object,
boolean,
null
)
value.inner_name = 'value'
local link = request('!.mechs.processor.link')
link(value)
local optimize = request('!.mechs.processor.optimize')
optimize(object)
return cho(object, array)
| gpl-3.0 |
MonokuroInzanaito/ygopro-777DIY | expansions/script/c75646025.lua | 1 | 2178 | --太郎丸
function c75646025.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),1)
c:EnableReviveLimit()
--search
local e2=Effect.CreateEffect(c)
e2:SetCategory(0x20008)
e2:SetType(0x81)
e2:SetProperty(0x10000)
e2:SetCode(1102)
e2:SetTarget(c75646025.thtg)
e2:SetCountLimit(1,75646025)
e2:SetOperation(c75646025.thop)
c:RegisterEffect(e2)
--atk
local e1=Effect.CreateEffect(c)
e1:SetCategory(0x200000)
e1:SetProperty(0x4000)
e1:SetHintTiming(0x2000)
e1:SetType(0x100)
e1:SetCode(1002)
e1:SetCountLimit(1)
e1:SetRange(0x4)
e1:SetCost(c75646025.cost)
e1:SetOperation(c75646025.operation)
c:RegisterEffect(e1)
end
function c75646025.thfilter(c)
return c:GetAttack()==1750 and c:GetDefense()==1350 and c:IsAbleToHand()
end
function c75646025.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c75646025.thfilter,tp,0x1,0,1,nil) end
Duel.SetOperationInfo(0,0x8,nil,1,tp,0x1)
end
function c75646025.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(3,tp,506)
local g=Duel.SelectMatchingCard(tp,c75646025.thfilter,tp,0x1,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,0x40)
Duel.ConfirmCards(1-tp,g)
end
end
function c75646025.cfilter(c)
return c:GetAttack()==1750 and c:GetDefense()==1350 and c:IsReleasableByEffect() and not c:IsCode(75646025)
end
function c75646025.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroupEx(tp,c75646025.cfilter,1,nil) end
local g=Duel.SelectReleaseGroupEx(tp,c75646025.cfilter,1,1,nil)
Duel.Release(g,0x80)
end
function c75646025.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and c:IsFaceup() then
local e1=Effect.CreateEffect(c)
e1:SetType(0x1)
e1:SetCode(102)
e1:SetValue(c:GetBaseAttack()*2)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(0x1)
e2:SetProperty(0x20000)
e2:SetRange(0x4)
e2:SetCode(1)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
e2:SetValue(c75646025.efilter)
c:RegisterEffect(e2)
end
end
function c75646025.efilter(e,te)
return te:IsActiveType(0x6)
end | gpl-3.0 |
tinybearc/sdkbox-vungle-sample | cpp/cocos2d/plugin/luabindings/auto/api/lua_cocos2dx_pluginx_auto_api.lua | 146 | 1793 | --------------------------------
-- @module plugin
--------------------------------------------------------
-- the plugin PluginProtocol
-- @field [parent=#plugin] PluginProtocol#PluginProtocol PluginProtocol preloaded module
--------------------------------------------------------
-- the plugin PluginManager
-- @field [parent=#plugin] PluginManager#PluginManager PluginManager preloaded module
--------------------------------------------------------
-- the plugin ProtocolAnalytics
-- @field [parent=#plugin] ProtocolAnalytics#ProtocolAnalytics ProtocolAnalytics preloaded module
--------------------------------------------------------
-- the plugin ProtocolIAP
-- @field [parent=#plugin] ProtocolIAP#ProtocolIAP ProtocolIAP preloaded module
--------------------------------------------------------
-- the plugin ProtocolAds
-- @field [parent=#plugin] ProtocolAds#ProtocolAds ProtocolAds preloaded module
--------------------------------------------------------
-- the plugin ProtocolShare
-- @field [parent=#plugin] ProtocolShare#ProtocolShare ProtocolShare preloaded module
--------------------------------------------------------
-- the plugin ProtocolSocial
-- @field [parent=#plugin] ProtocolSocial#ProtocolSocial ProtocolSocial preloaded module
--------------------------------------------------------
-- the plugin ProtocolUser
-- @field [parent=#plugin] ProtocolUser#ProtocolUser ProtocolUser preloaded module
--------------------------------------------------------
-- the plugin AgentManager
-- @field [parent=#plugin] AgentManager#AgentManager AgentManager preloaded module
--------------------------------------------------------
-- the plugin FacebookAgent
-- @field [parent=#plugin] FacebookAgent#FacebookAgent FacebookAgent preloaded module
return nil
| mit |
kidaa/darkstar | scripts/globals/items/skewer_of_m&p_chicken.lua | 36 | 1336 | -----------------------------------------
-- ID: 5639
-- Item: Skewer of M&P Chicken
-- Food Effect: 3Min, All Races
-----------------------------------------
-- Strength 5
-- Intelligence -5
-- Attack % 25
-- Attack Cap 154
-----------------------------------------
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,180,5639);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 5);
target:addMod(MOD_INT, -5);
target:addMod(MOD_FOOD_ATTP, 25);
target:addMod(MOD_FOOD_ATT_CAP, 154);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 5);
target:delMod(MOD_INT, -5);
target:delMod(MOD_FOOD_ATTP, 25);
target:delMod(MOD_FOOD_ATT_CAP, 154);
end;
| gpl-3.0 |
will4wachter/Project1 | scripts/zones/Lower_Jeuno/npcs/Domenic.lua | 34 | 1998 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Domenic
-- BCNM/KSNM Teleporter
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Lower_Jeuno/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/teleports");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasCompleteQuest(JEUNO,BEYOND_INFINITY) == true) then
player:startEvent(0x2783,player:getGil());
else
player:startEvent(0x2784);
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 == 0x2783) then
if (option == 1 and player:getGil() >= 750) then
player:delGil(750);
toGhelsba(player);
elseif (option == 2 and player:getGil() >= 750) then
player:delGil(750);
player:setPos(0, 0, 0, 0, 139);
elseif (option == 3 and player:getGil() >= 750) then
player:delGil(750);
player:setPos(0, 0, 0, 0, 144);
elseif (option == 4 and player:getGil() >= 750) then
player:delGil(750);
player:setPos(0, 0, 0, 0, 146);
elseif (option == 5 and player:getGil() >= 1000) then
player:delGil(1000);
player:setPos(0, 0, 0, 0, 206);
end
end
end; | gpl-3.0 |
kidaa/darkstar | scripts/zones/Dynamis-Jeuno/mobs/Goblin_Statue.lua | 17 | 5156 | -----------------------------------
-- Area: Dynamis Jeuno
-- NPC: Goblin Statue
-- Map1 Position: http://images3.wikia.nocookie.net/__cb20090312005127/ffxi/images/b/bb/Jeu1.jpg
-- Map2 Position: http://images4.wikia.nocookie.net/__cb20090312005155/ffxi/images/3/31/Jeu2.jpg
-- Vanguard Position: http://faranim.livejournal.com/39860.html
-----------------------------------
package.loaded["scripts/zones/Dynamis-Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Jeuno/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
local X = mob:getXPos();
local Y = mob:getYPos();
local Z = mob:getZPos();
local spawnList = jeunoList;
if(mob:getStatPoppedMobs() == false) then
mob:setStatPoppedMobs(true);
for nb = 1, table.getn(spawnList), 2 do
if(mob:getID() == spawnList[nb]) then
for nbi = 1, table.getn(spawnList[nb + 1]), 1 do
if((nbi % 2) == 0) then X=X+2; Z=Z+2; else X=X-2; Z=Z-2; end
local mobNBR = spawnList[nb + 1][nbi];
if(mobNBR <= 20) then
if(mobNBR == 0) then mobNBR = math.random(1,15); end -- Spawn random Vanguard (TEMPORARY)
local DynaMob = getDynaMob(target,mobNBR,1);
--printf("Goblin Statue => mob %u \n",DynaMob);
if(DynaMob ~= nil) then
-- Spawn Mob
SpawnMob(DynaMob):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(DynaMob):setPos(X,Y,Z);
GetMobByID(DynaMob):setSpawn(X,Y,Z);
-- Spawn Pet for BST, DRG, and SMN
if(mobNBR == 9 or mobNBR == 15) then
SpawnMob(DynaMob + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(DynaMob + 1):setPos(X,Y,Z);
GetMobByID(DynaMob + 1):setSpawn(X,Y,Z);
end
end
elseif(mobNBR > 20) then
SpawnMob(mobNBR):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
local MJob = GetMobByID(mobNBR):getMainJob();
if(MJob == 9 or MJob == 15) then
-- Spawn Pet for BST, DRG, and SMN
SpawnMob(mobNBR + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(mobNBR + 1):setPos(X,Y,Z);
GetMobByID(mobNBR + 1):setSpawn(X,Y,Z);
end
end
end
end
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
mobID = mob:getID();
-- HP Bonus: 005 011 016 023 026 031 040 057 063 065 068 077 079 080 082 083 084 093 102 119 | 123 126 128
if(mobID == 17547534 or mobID == 17547540 or mobID == 17547545 or mobID == 17547552 or mobID == 17547555 or mobID == 17547560 or mobID == 17547569 or mobID == 17547586 or
mobID == 17547592 or mobID == 17547594 or mobID == 17547597 or mobID == 17547606 or mobID == 17547608 or mobID == 17547609 or mobID == 17547612 or mobID == 17547613 or
mobID == 17547622 or mobID == 17547631 or mobID == 17547647 or mobID == 17547651 or mobID == 17547654 or mobID == 17547656) then
killer:restoreHP(3000);
killer:messageBasic(024,(killer:getMaxHP()-killer:getHP()));
-- MP Bonus: 009 012 017 024 025 030 039 044 056 062 064 067 076 078 081 082 085 094 095 101 118 | 122 127 129 150
elseif(mobID == 17547538 or mobID == 17547541 or mobID == 17547546 or mobID == 17547553 or mobID == 17547554 or mobID == 17547559 or mobID == 17547568 or mobID == 17547573 or
mobID == 17547585 or mobID == 17547591 or mobID == 17547593 or mobID == 17547596 or mobID == 17547605 or mobID == 17547607 or mobID == 17547610 or mobID == 17547611 or
mobID == 17547614 or mobID == 17547623 or mobID == 17547624 or mobID == 17547630 or mobID == 17547646 or mobID == 17547650 or mobID == 17547655 or mobID == 17547657 or
mobID == 17547678) then
killer:restoreMP(3000);
killer:messageBasic(025,(killer:getMaxMP()-killer:getMP()));
end
-- Spawn 089-097 when statue 044 is defeated
if(mobID == 17547573) then
for nbx = 17547618, 17547626, 1 do SpawnMob(nbx); end
end
-- Spawn 114-120 when statue 064 is defeated
if(mobID == 17547593) then
for nbx = 17547642, 17547648, 1 do SpawnMob(nbx); end
local spawn = {17547265,17547608,17547609,17547610,17547611,17547612,17547613,17547614,17547615,17547616,17547617};
for nbi = 1, table.getn(spawn), 1 do
SpawnMob(spawn[nbi]);
end
end
-- Spawn 098-100 when statue 073 074 075 are defeated
if((mobID == 17547602 or mobID == 17547603 or mobID == 17547604) and
GetMobAction(17547602) ~= 16 and GetMobAction(17547603) ~= 16 and GetMobAction(17547604) ~= 16) then
SpawnMob(17547627); -- 098
SpawnMob(17547628); -- 099
SpawnMob(17547629); -- 100
end
-- Spawn 101-112 when statue Center of 098 099 100 is defeated
if(mobID == 17547628) then
for nbx = 17547630, 17547641, 1 do SpawnMob(nbx); end
end
end; | gpl-3.0 |
will4wachter/Project1 | scripts/zones/The_Shrine_of_RuAvitau/npcs/blank_4.lua | 22 | 4957 | -----------------------------------
-- Area: The Shrine of Ru'Avitau
-- NPC: ??? divine might mission
-- @pos -40 0 -151 178
-----------------------------------
package.loaded["scripts/zones/The_Shrine_of_RuAvitau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Shrine_of_RuAvitau/TextIDs");
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local CurrentZM = player:getCurrentMission(ZILART);
local ZMProgress = player:getVar("ZilartStatus");
local DMStatus = player:getQuestStatus(OUTLANDS,DIVINE_MIGHT);
local DMRepeat = player:getQuestStatus(OUTLANDS,DIVINE_MIGHT_REPEAT);
local AAKeyitems = 0;
local DMEarrings = 0;
local DivineStatus = player:getVar("DivineMight");
local MoonOre = player:hasKeyItem(MOONLIGHT_ORE);
-- Count keyitems
for i=SHARD_OF_APATHY, SHARD_OF_RAGE do
if (player:hasKeyItem(i) == true) then
AAKeyitems = AAKeyitems + 1;
end
end
-- Count Earrings
for i=14739, 14743 do
if (player:hasItem(i) == true) then
DMEarrings = DMEarrings + 1;
end
end
if(CurrentZM == ARK_ANGELS and ZMProgress == 0 and DMEarrings <= NUMBER_OF_DM_EARRINGS) then -- First step in Ark Angels
player:startEvent(53,917,1408,1550);
elseif(CurrentZM == ARK_ANGELS and ZMProgress == 1 and DivineStatus < 2) then -- Reminder CS/starts Divine Might (per Wiki)
player:startEvent(54,917,1408,1550);
elseif(CurrentZM >= ARK_ANGELS and DMStatus == QUEST_AVAILABLE and AAKeyitems > 0) then -- Alternative cutscene for those that have done one or more AA fight
player:startEvent(56,917,1408,1550);
elseif(DMStatus == QUEST_ACCEPTED and DivineStatus >= 2) then -- CS when player has completed Divine might, award earring
player:startEvent(55,14739,14740,14741,14742,14743);
elseif(DMStatus == QUEST_COMPLETED and DMEarrings < NUMBER_OF_DM_EARRINGS and DMRepeat ~= QUEST_ACCEPTED) then -- You threw away old Earring, start the repeat quest
player:startEvent(57,player:getVar("DM_Earring"));
elseif(DMRepeat == QUEST_ACCEPTED and DivineStatus < 2) then
if (MoonOre == false) then
player:startEvent(58); -- Reminder for Moonlight Ore
else
player:startEvent(56,917,1408,1550); -- Reminder for Ark Pentasphere
end
elseif(DMRepeat == QUEST_ACCEPTED and DivineStatus == 2 and MoonOre == true) then -- Repeat turn in
player:startEvent(59);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY); -- Need some kind of feedback
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 59 and option == 2) then
player:updateEvent(14739,14740,14741,14742,14743);
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 53) then -- Got the required cutscene for AA
player:setVar("ZilartStatus",1);
elseif((csid == 54 or csid == 56) and player:getQuestStatus(OUTLANDS,DIVINE_MIGHT) == QUEST_AVAILABLE) then -- Flag Divine Might
player:addQuest(OUTLANDS,DIVINE_MIGHT);
elseif(csid == 57) then -- Divine Might Repeat
player:delQuest(OUTLANDS,DIVINE_MIGHT_REPEAT);
player:addQuest(OUTLANDS,DIVINE_MIGHT_REPEAT);
elseif(csid == 55 or csid == 59) then -- Turning in Divine Might or Repeat
local reward = 0;
if (option == 1) then
reward = 14739; -- Suppanomimi
elseif (option == 2) then
reward = 14740; -- Knight's Earring
elseif (option == 3) then
reward = 14741; -- Abyssal Earring
elseif (option == 4) then
reward = 14742; -- Beastly Earring
elseif (option == 5) then
reward = 14743; -- Bushinomimi
end
if (reward ~= 0) then
if (player:getFreeSlotsCount() >= 1 and player:hasItem(reward) == false) then
player:addItem(reward);
player:messageSpecial(ITEM_OBTAINED,reward);
if (csid == 55) then
player:completeQuest(OUTLANDS,DIVINE_MIGHT);
else
player:completeQuest(OUTLANDS,DIVINE_MIGHT_REPEAT);
player:delKeyItem(MOONLIGHT_ORE);
end
player:setVar("DivineMight",0);
player:setVar("DM_Earring",reward);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,reward);
end
end
end
end; | gpl-3.0 |
will4wachter/Project1 | scripts/zones/Castle_Oztroja/npcs/_47x.lua | 17 | 1245 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _47x (Handle)
-- Notes: Opens door _477
-- @pos -99 -71 -41 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DoorID = npc:getID() - 1;
local DoorA = GetNPCByID(DoorID):getAnimation();
if(player:getZPos() > -45) then
if(DoorA == 9 and npc:getAnimation() == 9) then
npc:openDoor(6.5);
-- Should be a ~1 second delay here before the door opens
GetNPCByID(DoorID):openDoor(4.5);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
davidedmonds/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 |
davidedmonds/darkstar | scripts/zones/Southern_San_dOria/npcs/Ailevia.lua | 30 | 1902 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Ailevia
-- Adventurer's Assistant
-- Only recieving Adv.Coupon and simple talk event are scripted
-- This NPC participates in Quests and Missions
-- @zone 230
-- @pos -8 1 1
-------------------------------------
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)
--Adventurer coupon
if (trade:getItemCount() == 1 and trade:hasItemQty(0x218,1) == true) then
player:startEvent(0x028f);
end
-- "Flyers for Regine" conditional script
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0267); -- i know a thing or 2 about these streets
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 == 0x028f) then
player:addGil(GIL_RATE*50);
player:tradeComplete();
player:messageSpecial(GIL_OBTAINED,GIL_RATE*50);
end
end;
| gpl-3.0 |
MonokuroInzanaito/ygopro-777DIY | expansions/script/c33700164.lua | 1 | 2480 | --永堕幻梦
function c33700164.initial_effect(c)
c:SetUniqueOnField(1,0,33700164)
--avoid battle damage
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_AVOID_BATTLE_DAMAGE)
e1:SetRange(LOCATION_SZONE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,0)
e1:SetCondition(c33700164.con)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_NO_EFFECT_DAMAGE)
c:RegisterEffect(e2)
--Activate
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_ACTIVATE)
e3:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e3)
--maintain
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(33700164,0))
e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e4:SetCode(EVENT_PHASE+PHASE_END)
e4:SetRange(LOCATION_SZONE)
e4:SetCountLimit(1)
e4:SetOperation(c33700164.mtop)
c:RegisterEffect(e4)
--leave
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e5:SetCode(EVENT_LEAVE_FIELD)
e5:SetCondition(c33700164.damcon)
e5:SetTarget(c33700164.damtg)
e5:SetOperation(c33700164.damop)
c:RegisterEffect(e5)
end
function c33700164.con(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetLP(tp)>Duel.GetLP(1-tp)
end
function c33700164.mtop(e,tp,eg,ep,ev,re,r,rp)
if Duel.CheckLPCost(tp,500) then
Duel.PayLPCost(tp,500)
end
end
function c33700164.damcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousLocation(LOCATION_ONFIELD) and c:IsPreviousPosition(POS_FACEUP) and not c:IsLocation(LOCATION_DECK)
end
function c33700164.damtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(3000)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,tp,3000)
end
function c33700164.damop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Damage(p,d,REASON_EFFECT)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CHANGE_DAMAGE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,0)
e1:SetValue(c33700164.damval)
if Duel.GetTurnPlayer()~=tp then
e1:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN,2)
else
e1:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN)
end
Duel.RegisterEffect(e1,tp)
end
function c33700164.damval(e,re,val,r,rp,rc)
if bit.band(r,REASON_BATTLE+REASON_EFFECT)==0 then return val end
return val*2
end
| gpl-3.0 |
davidedmonds/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Hieroglyphics.lua | 17 | 2356 | -----------------------------------
-- Area: Tavnazian_Safehold
-- NPC: Hieroglyphics
-- Notes: Dynamis Tavnazia Enter
-- @pos 3.674 -7.278 -27.856 26
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/dynamis");
require("scripts/globals/missions");
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if ( (player:hasCompletedMission(COP,DARKNESS_NAMED) or FREE_COP_DYNAMIS == 1) and player:hasKeyItem(DYNAMIS_BUBURIMU_SLIVER ) and player:hasKeyItem(DYNAMIS_QUFIM_SLIVER ) and player:hasKeyItem(DYNAMIS_VALKURM_SLIVER )) then
local firstDyna = 0;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if (player:getMainLvl() < DYNA_LEVEL_MIN) then
player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN);
elseif ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaTavnazia]UniqueID")) then
player:startEvent(0x024C,10,0,0,BETWEEN_2DYNA_WAIT_TIME,32,VIAL_OF_SHROUDED_SAND,4236,4237);
else
dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456);
printf("dayRemaining : %u",dayRemaining );
player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,10);
end
else
player:messageSpecial(MYSTERIOUS_VOICE);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("updateRESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("finishRESULT: %u",option);
if (csid == 0x024C and option == 0) then
player:setPos(0.1,-7,-21,190,42);
end
end; | gpl-3.0 |
will4wachter/Project1 | scripts/zones/Upper_Delkfutts_Tower/Zone.lua | 2 | 2290 | -----------------------------------
--
-- Zone: Upper_Delkfutts_Tower (158)
--
-----------------------------------
package.loaded["scripts/zones/Upper_Delkfutts_Tower/TextIDs"] = nil;
-----------------------------------
require("/scripts/globals/common");
require("/scripts/globals/settings");
require("scripts/globals/teleports");
require("scripts/zones/Upper_Delkfutts_Tower/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1, -369, -146, 83, -365, -145, 89); -- Tenth Floor F-6 porter to Middle Delkfutt's Tower
zone:registerRegion(2, -369, -178, -49, -365, -177, -43); -- Twelfth Floor F-10 porter to Stellar Fulcrum
-- print("Upper Delkfutt's Tower Teleporters initialized.");
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(12.098,-105.408,27.683,239);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
switch (region:GetRegionID()): caseof
{
[1] = function (x)
--player:setVar("porter_lock",1);
player:startEvent(1);
end,
[2] = function (x)
--player:setVar("porter_lock",1);
player:startEvent(2);
end,
}
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 1 and option == 1) then
player:setPos(-490, -130, 81, 231, 157);
elseif(csid == 2 and option == 1) then
player:setPos(-520 , 1 , -23, 192, 0xB3); -- to stellar fulcrum
end
end;
| gpl-3.0 |
kidaa/darkstar | scripts/zones/Southern_San_dOria/npcs/Ferdoulemiont.lua | 36 | 2182 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Ferdoulemiont
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
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:showText(npc,FERDOULEMIONT_SHOP_DIALOG);
stock = {0x034d,1125,1, --Black Chocobo Feather
0x439b,9,2, --Dart
0x45c6,680,3, --Bug Broth
0x45ca,680,3, --Carrion Broth
0x45c4,81,3, --Carrot Broth
0x45c8,124,3, --Herbal Broth
0x0348,7,3, --Chocobo Feather
0x11c1,61,3, --Gysahl Greens
0x4278,10,3, --Pet Food Alpha Biscuit
0x4279,81,3, --Pet Food Beta Biscuit
0x13d1,49680,3, --Scroll of Chocobo Mazurka
0x1385,16,3, --Scroll of Knight's Minne
0x1386,864,3, --Scroll of Knight's Minne II
0x1387,5148,3, --Scroll of Knight's Minne III
0x0927,1984,3} --La Theine Millet
showNationShop(player, SANDORIA, 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 |
will4wachter/Project1 | scripts/zones/RuLude_Gardens/npcs/Trail_Markings.lua | 2 | 2732 | -----------------------------------
-- Area: Rulude Gardens
-- NPC: Trail Markings
-- Dynamis-Jeuno Enter
-- @pos 35 9 -51 243
-----------------------------------
package.loaded["scripts/zones/Rulude_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/dynamis");
require("scripts/zones/Rulude_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getVar("Dynamis_Status") == 1) then
player:startEvent(0x2720); -- cs with Cornelia
elseif(player:getVar("DynaJeuno_Win") == 1) then
player:startEvent(0x272a,HYDRA_CORPS_TACTICAL_MAP); -- Win CS
elseif(player:hasKeyItem(VIAL_OF_SHROUDED_SAND)) then
local firstDyna = 0;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if(checkFirstDyna(player,4)) then -- First Dyna-Jeuno => CS
firstDyna = 1;
end
if(player:getMainLvl() < DYNA_LEVEL_MIN) then
player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN);
elseif((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaJeuno]UniqueID")) then
player:startEvent(0x271c,4,firstDyna,0,BETWEEN_2DYNA_WAIT_TIME,64,VIAL_OF_SHROUDED_SAND,4236,4237);
else
dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456);
player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,4);
end
else
player:messageSpecial(UNUSUAL_ARRANGEMENT_LEAVES);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("updateRESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("finishRESULT: %u",option);
if(csid == 0x2720) then
player:addKeyItem(VIAL_OF_SHROUDED_SAND);
player:messageSpecial(KEYITEM_OBTAINED,VIAL_OF_SHROUDED_SAND);
player:setVar("Dynamis_Status",0);
elseif(csid == 0x272a) then
player:setVar("DynaJeuno_Win",0);
elseif(csid == 0x271c and option == 0) then
if(checkFirstDyna(player,4)) then
player:setVar("Dynamis_Status",player:getVar("Dynamis_Status") + 16);
end
player:setPos(48.930,10.002,-71.032,195,0xBC);
end
end; | gpl-3.0 |
will4wachter/Project1 | scripts/zones/Lower_Jeuno/npcs/Ruslan.lua | 37 | 2004 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Ruslan
-- Involved In Quest: Wondering Minstrel
-- Working 100%
-- @zone = 245
-- @pos = -19 -1 -58
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
wonderingstatus = player:getQuestStatus(WINDURST,WONDERING_MINSTREL);
if (wonderingstatus == QUEST_ACCEPTED) then
prog = player:getVar("QuestWonderingMin_var")
if (prog == 0) then -- WONDERING_MINSTREL + Rosewood Lumber: During Quest / Progression
player:startEvent(0x2719,0,718);
player:setVar("QuestWonderingMin_var",1);
elseif (prog == 1) then -- WONDERING_MINSTREL + Rosewood Lumber: Quest Objective Reminder
player:startEvent(0x271a,0,718);
end
elseif (wonderingstatus == QUEST_COMPLETED) then
rand = math.random(3);
if (rand == 1) then
player:startEvent(0x271b); -- WONDERING_MINSTREL: After Quest
else
player:startEvent(0x2718); -- Standard Conversation
end
else
player:startEvent(0x2718); -- Standard Conversation
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 |
MonokuroInzanaito/ygopro-777DIY | expansions/script/c66600620.lua | 1 | 1038 | --6th-深渊的回音
function c66600620.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,66600620)
e1:SetTarget(c66600620.target)
e1:SetOperation(c66600620.activate)
c:RegisterEffect(e1)
end
function c66600620.filter(c)
return c:IsAbleToGrave() and c:IsFaceup() and c:IsSetCard(0x66e)
end
function c66600620.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,2) and Duel.IsExistingTarget(c66600620.filter,tp,LOCATION_MZONE,0,1,nil) end
local g=Duel.SelectTarget(tp,c66600620.filter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,2)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,g,g:GetCount(),0,0)
end
function c66600620.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if Duel.Draw(tp,2,REASON_EFFECT)>1 and tc and tc:IsRelateToEffect(e) then
Duel.SendtoGrave(tc,REASON_EFFECT)
end
end | gpl-3.0 |
waterlgndx/darkstar | scripts/zones/Port_San_dOria/npcs/Vounebariont.lua | 2 | 1620 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Vounebariont
-- Starts and Finishes Quest: Thick Shells
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,THICK_SHELLS) ~= QUEST_AVAILABLE) then
if (trade:hasItemQty(889,5) and trade:getItemCount() == 5) then -- Trade Beetle Shell
player:startEvent(514);
end
end
end;
function onTrigger(player,npc)
if (player:getFameLevel(SANDORIA) >= 2) then
player:startEvent(516);
else
player:startEvent(568);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 516) then
if (player:getQuestStatus(SANDORIA,THICK_SHELLS) == QUEST_AVAILABLE) then
player:addQuest(SANDORIA,THICK_SHELLS);
end
elseif (csid == 514) then
if (player:getQuestStatus(SANDORIA,THICK_SHELLS) == QUEST_ACCEPTED) then
player:completeQuest(SANDORIA,THICK_SHELLS);
player:addFame(SANDORIA,30);
else
player:addFame(SANDORIA,5);
end
player:tradeComplete();
player:addTitle(dsp.title.BUG_CATCHER);
player:addGil(GIL_RATE*750);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*750)
end
end; | gpl-3.0 |
kidaa/darkstar | scripts/zones/Abyssea-La_Theine/mobs/Lusion.lua | 13 | 1536 | -----------------------------------
-- Area: Abyssea - La Theine
-- NPC: Luison
-----------------------------------
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
setLocalVar("transformTime", os.time())
end;
-----------------------------------
-- onMobRoam Action
-----------------------------------
function onMobRoam(mob)
local spawnTime = mob:getLocalVar("transformTime");
local roamChance = math.random(1,100);
local roamMoonPhase = VanadielMoonPhase();
if(roamChance > 100-roamMoonPhase) then
if(mob:AnimationSub() == 0 and os.time() - transformTime > 300) then
mob:AnimationSub(1);
mob:setLocalVar("transformTime", os.time());
elseif(mob:AnimationSub() == 1 and os.time() - transformTime > 300) then
mob:AnimationSub(0);
mob:setLocalVar("transformTime", os.time());
end
end
end;
-----------------------------------
-- onMobEngaged
-- Change forms every 60 seconds
-----------------------------------
function onMobEngaged(mob,target)
local changeTime = mob:getLocalVar("changeTime");
local chance = math.random(1,100);
local moonPhase = VanadielMoonPhase();
if(chance > 100-moonPhase) then
if(mob:AnimationSub() == 0 and mob:getBattleTime() - changeTime > 45) then
mob:AnimationSub(1);
mob:setLocalVar("changeTime", mob:getBattleTime());
elseif(mob:AnimationSub() == 1 and mob:getBattleTime() - changeTime > 45) then
mob:AnimationSub(0);
mob:setLocalVar("changeTime", mob:getBattleTime());
end
end
end; | gpl-3.0 |
kidaa/darkstar | scripts/zones/Windurst_Waters/npcs/Chyuk-Kochak.lua | 38 | 1048 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Chyuk-Kochak
-- Type: Standard NPC
-- @zone: 238
-- @pos -252.162 -6.319 -307.011
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0298);
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 |
madpilot78/ntopng | scripts/lua/rest/v2/reset/active_monitoring/config.lua | 1 | 1050 | --
-- (C) 2019-21 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
package.path = dirs.installdir .. "/scripts/lua/modules/import_export/?.lua;" .. package.path
require "lua_utils"
local plugins_utils = require("plugins_utils")
local am_import_export = plugins_utils.loadModule("active_monitoring", "am_import_export")
local json = require "dkjson"
local rest_utils = require "rest_utils"
local import_export_rest_utils = require "import_export_rest_utils"
local auth = require "auth"
--
-- Reset Active Monitoring configuration
-- Example: curl -u admin:admin http://localhost:3000/lua/rest/v2/reset/active_monitoring/config.lua
--
-- NOTE: in case of invalid login, no error is returned but redirected to login
--
if not auth.has_capability(auth.capabilities.active_monitoring) then
rest_utils.answer(rest_utils.consts.err.not_granted)
return
end
local instances = {}
instances["active_monitoring"] = am_import_export:create()
import_export_rest_utils.reset(instances)
| gpl-3.0 |
DashingStrike/Automato-ATITD | scripts/barrel_vise.lua | 2 | 7573 | dofile("screen_reader_common.inc");
dofile("ui_utils.inc");
window_w = 200;
window_h = 270;
tol=5000;
taken=0;
made=0;
stop_cooking=0;
mes = '';
per_click_delay = 0;
tick_time = 100;
-- All these coords are offsets from the image used to find the bars.
-- X starts with 0 at the first black pixel in the P of progress. (13 from window 0)
-- Y has 0 as the topmost black pixel in the F of fuel. (156 from window 0)
-- This is towards the end of progress bar, when it detects blue, at this coord, it starts looking
-- for the Take... option
-- It also stops stoking, should be enough heat to finish it the last 2 ticks, save a couple wood.
-- Make this about 2 coords (X coord) from the end of the bar
-- Also prevents a stoke after the barrel completes, which results in a popup.
ProgressOffX = 176
ProgressOffY = 54
-- Max Flame wanted (DANGER), do not have 2 wood in Fuel passed this point. May need to adjust.
-- Set about 24 coords (X coord) from the end of bar
barMaxFlameOffX = 148
bar1WoodOffX = 57 -- Coord for determining if at least 1 wood is in Fuel (+2 coords from left bar (black area/edge bar)
bar2WoodOffX = 63 -- Coord for determining if at least 2 wood is in Fuel (+8 coords from left bar (black area/edge bar)
fuelBarOffY = 5 -- Y Coord for Fuel bar
flameBarOffY = 20 -- Y Coord for Flame bar
function clickAll(image_name, up)
-- Find buttons and click them!
srReadScreen();
xyWindowSize = srGetWindowSize();
local buttons = findAllImages(image_name);
if #buttons == 0 then
-- statusScreen("Could not find specified buttons...");
-- lsSleep(1500);
else
-- statusScreen("Clicking " .. #buttons .. "button(s)...");
if up then
for i=#buttons, 1, -1 do
srClickMouseNoMove(buttons[i][0]+5, buttons[i][1]+3);
lsSleep(per_click_delay);
end
else
for i=1, #buttons do
srClickMouseNoMove(buttons[i][0]+5, buttons[i][1]+3);
lsSleep(per_click_delay);
end
end
-- statusScreen("Done clicking (" .. #buttons .. " clicks).");
-- lsSleep(100);
end
end
function stoke(window_pos)
-- lsPrintln(window_pos[0] .. " " .. window_pos[1] .. " " .. window_w .. " " .. window_h);
local pos = srFindImageInRange("Stoke.png", window_pos[0], window_pos[1], window_w, window_h, tol);
if not pos then
error 'Could not find Stoke button';
end
srClickMouseNoMove(pos[0]+5, pos[1]+2);
end
function ClosePopups()
local OKpopup = srFindImage("OK-popup.png", tol);
if OKpopup then
srClickMouseNoMove(OKpopup[0]+5, OKpopup[1]+2);
lsSleep(100);
end
end;
function FindBlue(X,Y)
-- srSetMousePos(X,Y); lsSleep(250);
local new_px = srReadPixel(X,Y);
local px_R = (math.floor(new_px/256/256/256) % 256);
local px_G = (math.floor(new_px/256/256) % 256);
local px_B = (math.floor(new_px/256) % 256);
local px_A = (new_px % 256);
return ((px_B - px_R) > 0);
end;
function process_vise(window_pos)
-- if we can take anything do that
local take = srFindImageInRange("Take.png", window_pos[0], window_pos[1], window_w, window_h, tol);
if take then
srClickMouseNoMove(take[0], take[1]);
lsSleep(200);
srClickMouseNoMove(take[0]+20, take[1]+7);
taken = taken+1;
return 'Take Everything'
end;
-- else if we can start a barrel do that
-- ClosePopups();
local makeabarrel = srFindImageInRange("Makeabarrel.png", window_pos[0], window_pos[1], window_w, window_h, tol);
if makeabarrel then
if (made>=num_barrels) or (taken >=num_barrels) or (stop_cooking>0) then
return nil;
else
made = made+1;
srClickMouseNoMove(makeabarrel[0], makeabarrel[1]);
return 'Starting New Barrel'
end;
end;
-- else
-- read bars
--
local FuelStatus = 0;
local cooldown = 0;
local pos = srFindImageInRange("Vise_bars.png", window_pos[0]-5, window_pos[1], window_w, window_h, tol);
if not pos then
error 'Could not find Vise bars';
end;
local curFuel1 = FindBlue(pos[0]+bar1WoodOffX, pos[1]+fuelBarOffY);
local curFuel2 = FindBlue(pos[0]+bar2WoodOffX, pos[1]+fuelBarOffY);
local curFlame = FindBlue(pos[0]+barMaxFlameOffX, pos[1]+flameBarOffY);
local curProgress = FindBlue(pos[0]+ProgressOffX, pos[1]+ProgressOffY);
if curFuel2 then
FuelStatus = 2
elseif curFuel1 then
FuelStatus = 1
else
FuelStatus = 0
end;
if curProgress then
cooldown = 1
end
if cooldown > 0 then --Stop Stoking, should be enough heat to finish
return('waiting for finish');
elseif not curFlame then
if FuelStatus < 1 then -- Add 2 wood
stoke(window_pos);
stoke(window_pos);
return "Flame: OK; Stoke (2 Wood)";
elseif FuelStatus < 2 then -- Add 1 wood
stoke(window_pos);
return "Flame: OK; Stoke (1 Wood)";
end;
else
return "DANGER; No Stoke (0 Wood)";
end;
return 'Flame: OK; Fuel OK';
end
function refresh(window_pos)
srClickMouseNoMove(window_pos[0], window_pos[1]);
end
function doit()
-- testReorder();
num_barrels = promptNumber("How many barrels?", 1);
askForWindow("Have 100 Boards, 2 Copper Straps, and 80 Wood in your inventory for every barrel you want to make.\n \nFor large numbers of barrels you can get away with less wood, the average used is 60.\n \nPin as many vises as you want, put the cursor over the ATITD window, press Shift.");
srReadScreen();
local vise_windows = findAllImages("ThisIs.png");
if #vise_windows == 0 then
error 'Could not find \'Barrel Vise\' windows.';
end
local last_ret = {};
local should_continue = 1;
while should_continue > 0 do
-- Tick
clickAll("This.png", 1);
ClosePopups();
lsSleep(200);
srReadScreen();
local vise_windows2 = findAllImages("ThisIs.png");
if #vise_windows == #vise_windows2 then
for window_index=1, #vise_windows do
local r = process_vise(vise_windows[window_index]);
last_ret[window_index] = r;
end
end
-- Display status and sleep
should_continue = 0;
checkBreak();
local start_time = lsGetTimer();
while tick_time - (lsGetTimer() - start_time) > 0 do
time_left = tick_time - (lsGetTimer() - start_time);
lsPrint(10, 6, 0, 0.7, 0.7, 0xB0B0B0ff, "Hold Ctrl+Shift to end this script.");
lsPrint(10, 18, 0, 0.7, 0.7, 0xB0B0B0ff, "Hold Alt+Shift to pause this script.");
lsPrint(10, 30, 0, 0.7, 0.7, 0xFFFFFFff, "Waiting " .. time_left .. "ms...");
if not (#vise_windows == #vise_windows2) then
lsPrintWrapped(10, 45, 5, lsScreenX-15, 1, 1, 0xFF7070ff, "Expected " .. #vise_windows .. " windows, found " .. #vise_windows2 .. ", not ticking.");
elseif (made>=num_barrels) or (taken >= num_barrels) or (stop_cooking>0) then
lsPrint(10, 45, 5, 0.8, 0.8, 0x70FF70ff, "Finishing up.");
elseif (taken > made) then
lsPrint(10, 45, 5, 0.8, 0.8, 0xFFFFFFff, taken .. "/" .. num_barrels .. " finished");
else
lsPrint(10, 45, 5, 0.8, 0.8, 0xFFFFFFff, made .. "/" .. num_barrels .. " started");
end
for window_index=1, #vise_windows do
if last_ret[window_index] then
should_continue = 1;
lsPrint(10, 80 + 15*window_index, 0, 0.7, 0.7, 0xFFFFFFff, "#" .. window_index .. " - " .. last_ret[window_index]);
else
lsPrint(10, 80 + 15*window_index, 0, 0.7, 0.7, 0xFFFFFFff, "#" .. window_index .. " - Finished");
end
end
if lsButtonText(lsScreenX - 110, lsScreenY - 60, z, 100, 0xFFFFFFff, "Finish up") then
stop_cooking = 1;
end
if lsButtonText(lsScreenX - 110, lsScreenY - 30, z, 100, 0xFFFFFFff, "End script") then
error "Clicked End Script button";
end
checkBreak();
lsDoFrame();
lsSleep(25);
end
checkBreak();
-- error 'done';
end
lsPlaySound("Complete.wav");
end | mit |
pakoito/ToME---t-engine4 | game/modules/tome/data/texts/tutorial/stats-scale/scale11.lua | 3 | 1080 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- 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/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
return [[
It simply costs more to increase scores that are in higher tiers.
For each tier, here's the cost of increasing your score by one:
#B4B4B4#Tier 1#WHITE#: 1 point
#FFFFFF#Tier 2#WHITE#: 2 points
#00FF80#Tier 3#WHITE#: 3 points
#0080FF#Tier 4#WHITE#: 4 points
#8d55ff#Tier 5#WHITE#: 5 points
]]
| gpl-3.0 |
vince06fr/prosody-modules | mod_storage_multi/mod_storage_multi.lua | 32 | 2258 | -- mod_storage_multi
local storagemanager = require"core.storagemanager";
local backends = module:get_option_array(module.name); -- TODO better name?
-- TODO migrate data "upwards"
-- one → one successful write is success
-- all → all backends must report success
-- majority → majority of backends must report success
local policy = module:get_option_string(module.name.."_policy", "all");
local keyval_store = {};
keyval_store.__index = keyval_store;
function keyval_store:get(username)
local backends = self.backends;
local data, err;
for i = 1, #backends do
module:log("debug", "%s:%s:get(%q)", tostring(backends[i].get), backends[i]._store, username);
data, err = backends[i]:get(username);
if err then
module:log("error", tostring(err));
elseif not data then
module:log("debug", "No data returned");
else
module:log("debug", "Data returned");
return data, err;
end
end
end
-- This is where it gets complicated
function keyval_store:set(username, data)
local backends = self.backends;
local ok, err, backend;
local all, one, oks = true, false, 0;
for i = 1, #backends do
backend = backends[i];
module:log("debug", "%s:%s:set(%q)", tostring(backends[i].get), backends[i].store, username);
ok, err = backend:set(username, data);
if not ok then
module:log("error", "Error in storage driver %s: %s", backend.name, tostring(err));
else
oks = oks + 1;
end
one = one or ok; -- At least one successful write
all = all and ok; -- All successful
end
if policy == "all" then
return all, err
elseif policy == "majority" then
return oks > (#backends/2), err;
end
-- elseif policy == "one" then
return one, err;
end
local stores = {
keyval = keyval_store;
}
local driver = {};
function driver:open(store, typ)
local store_mt = stores[typ or "keyval"];
if store_mt then
local my_backends = {};
local driver, opened
for i = 1, #backends do
driver = storagemanager.load_driver(module.host, backends[i]);
opened = driver:open(store, typ);
my_backends[i] = assert(driver:open(store, typ));
my_backends[i]._store = store;
end
return setmetatable({ backends = my_backends }, store_mt);
end
return nil, "unsupported-store";
end
module:provides("storage", driver);
| mit |
pakoito/ToME---t-engine4 | game/modules/tome/data/chats/undead-start-game.lua | 3 | 1865 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- 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/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
newChat{ id="welcome",
text = [[#LIGHT_GREEN#*Before you stands a Human clothed in black robes. He seems to be ignoring you.*#WHITE#
#LIGHT_GREEN#*You stand inside some kind of summoning circle, which prevents you from moving.*#WHITE#
Oh yes! YES, one more for my collection. My collection, yes. A powerful one indeed!]],
answers = {
{"[listen]", jump="welcome2"},
}
}
newChat{ id="welcome2",
text = [[A powerful tool against my enemies. Yes, yes. They all hate me, but I will show them my power!
I will show them! SHOW THEM!]],
answers = {
{"I am not a tool! RELEASE ME!", jump="welcome3"},
}
}
newChat{ id="welcome3",
text = [[You cannot talk. You cannot talk! You are a slave, a tool!
You are mine! Be quiet!
#LIGHT_GREEN#*As his mind drifts off you notice part of the summoning circle is fading. You can probably escape!*#WHITE#
]],
answers = {
{"[attack]", action=function(npc, player)
local floor = game.zone:makeEntityByName(game.level, "terrain", "SUMMON_CIRCLE_BROKEN")
game.zone:addEntity(game.level, floor, "terrain", 22, 3)
end},
}
}
return "welcome"
| gpl-3.0 |
eriche2016/nn | MaskedSelect.lua | 17 | 2507 | local unpack = unpack or table.unpack
local MaskedSelect, parent = torch.class('nn.MaskedSelect', 'nn.Module')
--[[ Sets the provided mask value for the module. ]]
function MaskedSelect:__init()
parent.__init(self)
self._maskIndices = torch.LongTensor()
self._maskIndexBuffer = torch.LongTensor()
self._maskIndexBufferCPU = torch.FloatTensor()
self._gradBuffer = torch.Tensor()
self._gradMask = torch.ByteTensor()
end
--[[ Performs maskedSelect operation. ]]
function MaskedSelect:updateOutput(input)
local input, mask = unpack(input)
self.output:maskedSelect(input, mask)
return self.output
end
--[[ Reverse maps unmasked gradOutput back to gradInput. ]]
function MaskedSelect:updateGradInput(input, gradOutput)
local input, mask = unpack(input)
if input:type() == 'torch.CudaTensor' then
self._maskIndexBufferCPU:range(1, mask:nElement()):resize(mask:size())
self._maskIndexBuffer:resize(
self._maskIndexBufferCPU:size()):copy(self._maskIndexBufferCPU)
else
self._maskIndexBuffer:range(1, mask:nElement()):resize(mask:size())
end
self._maskIndices:maskedSelect(self._maskIndexBuffer, mask)
self._gradBuffer:resize(input:nElement()):zero()
self._gradBuffer:scatter(1, self._maskIndices, gradOutput)
self._gradBuffer:resize(input:size())
self.gradInput = {self._gradBuffer,
self._gradMask:resize(mask:size()):fill(0)}
return self.gradInput
end
function MaskedSelect:type(type, tensorCache)
if not type then
return self._type
end
self._gradBuffer = self._gradBuffer:type(type)
self.gradInput = self.gradInput:type(type)
self.output = self.output:type(type)
-- These casts apply when switching between cuda/non-cuda types
if type ~= 'torch.CudaTensor' then
self._maskIndexBuffer = self._maskIndexBuffer:long()
self._maskIndices = self._maskIndices:long()
self._gradMask = self._gradMask:byte()
elseif type == 'torch.CudaTensor' then
self._maskIndexBuffer = self._maskIndexBuffer:cuda()
self._maskIndices = self._maskIndices:cuda()
self._gradMask = self._gradMask:cuda()
end
self._type = type
return self
end
function MaskedSelect:clearState()
return nn.utils.clear(self, {'output',
'gradInput',
'_maskIndexBuffer',
'_maskIndexBufferCPU',
'_maskIndices',
'_gradBuffer',
'_gradMask'})
end
| bsd-3-clause |
fmassa/nn | Reshape.lua | 42 | 1801 | local Reshape, parent = torch.class('nn.Reshape', 'nn.Module')
function Reshape:__init(...)
parent.__init(self)
local arg = {...}
self.size = torch.LongStorage()
self.batchsize = torch.LongStorage()
if torch.type(arg[#arg]) == 'boolean' then
self.batchMode = arg[#arg]
table.remove(arg, #arg)
end
local n = #arg
if n == 1 and torch.typename(arg[1]) == 'torch.LongStorage' then
self.size:resize(#arg[1]):copy(arg[1])
else
self.size:resize(n)
for i=1,n do
self.size[i] = arg[i]
end
end
self.nelement = 1
self.batchsize:resize(#self.size+1)
for i=1,#self.size do
self.nelement = self.nelement * self.size[i]
self.batchsize[i+1] = self.size[i]
end
-- only used for non-contiguous input or gradOutput
self._input = torch.Tensor()
self._gradOutput = torch.Tensor()
end
function Reshape:updateOutput(input)
if not input:isContiguous() then
self._input:resizeAs(input)
self._input:copy(input)
input = self._input
end
if (self.batchMode == false) or (
(self.batchMode == nil) and
(input:nElement() == self.nelement and input:size(1) ~= 1)
) then
self.output:view(input, self.size)
else
self.batchsize[1] = input:size(1)
self.output:view(input, self.batchsize)
end
return self.output
end
function Reshape:updateGradInput(input, gradOutput)
if not gradOutput:isContiguous() then
self._gradOutput:resizeAs(gradOutput)
self._gradOutput:copy(gradOutput)
gradOutput = self._gradOutput
end
self.gradInput:viewAs(gradOutput, input)
return self.gradInput
end
function Reshape:__tostring__()
return torch.type(self) .. '(' ..
table.concat(self.size:totable(), 'x') .. ')'
end
| bsd-3-clause |
Ferk/Dungeontest | mods/unified_inventory/api.lua | 1 | 6159 | local S = unified_inventory.gettext
-- Create detached creative inventory after loading all mods
minetest.after(0.01, function()
local rev_aliases = {}
for source, target in pairs(minetest.registered_aliases) do
if not rev_aliases[target] then rev_aliases[target] = {} end
table.insert(rev_aliases[target], source)
end
unified_inventory.items_list = {}
for name, def in pairs(minetest.registered_items) do
if (not def.groups.not_in_creative_inventory or
def.groups.not_in_creative_inventory == 0) and
def.description and def.description ~= "" then
table.insert(unified_inventory.items_list, name)
local all_names = rev_aliases[name] or {}
table.insert(all_names, name)
for _, name in ipairs(all_names) do
local recipes = minetest.get_all_craft_recipes(name)
if recipes then
for _, recipe in ipairs(recipes) do
local unknowns
for _,chk in pairs(recipe.items) do
local groupchk = string.find(chk, "group:")
if (not groupchk and not minetest.registered_items[chk])
or (groupchk and not unified_inventory.get_group_item(string.gsub(chk, "group:", "")).item) then
unknowns = true
end
end
if not unknowns then
unified_inventory.register_craft(recipe)
end
end
end
end
end
end
table.sort(unified_inventory.items_list)
unified_inventory.items_list_size = #unified_inventory.items_list
print("Unified Inventory. inventory size: "..unified_inventory.items_list_size)
for _, name in ipairs(unified_inventory.items_list) do
local def = minetest.registered_items[name]
if type(def.drop) == "string" then
local dstack = ItemStack(def.drop)
if not dstack:is_empty() and dstack:get_name() ~= name then
unified_inventory.register_craft({
type = "digging",
items = {name},
output = def.drop,
width = 0,
})
end
end
end
for _, recipes in pairs(unified_inventory.crafts_for.recipe) do
for _, recipe in ipairs(recipes) do
local ingredient_items = {}
for _, spec in ipairs(recipe.items) do
local matches_spec = unified_inventory.canonical_item_spec_matcher(spec)
for _, name in ipairs(unified_inventory.items_list) do
if matches_spec(name) then
ingredient_items[name] = true
end
end
end
for name, _ in pairs(ingredient_items) do
if unified_inventory.crafts_for.usage[name] == nil then
unified_inventory.crafts_for.usage[name] = {}
end
table.insert(unified_inventory.crafts_for.usage[name], recipe)
end
end
end
end)
-- load_home
local function load_home()
local input = io.open(unified_inventory.home_filename, "r")
if not input then
unified_inventory.home_pos = {}
return
end
while true do
local x = input:read("*n")
if not x then break end
local y = input:read("*n")
local z = input:read("*n")
local name = input:read("*l")
unified_inventory.home_pos[name:sub(2)] = {x = x, y = y, z = z}
end
io.close(input)
end
load_home()
function unified_inventory.set_home(player, pos)
local player_name = player:get_player_name()
unified_inventory.home_pos[player_name] = vector.round(pos)
-- save the home data from the table to the file
local output = io.open(unified_inventory.home_filename, "w")
for k, v in pairs(unified_inventory.home_pos) do
output:write(v.x.." "..v.y.." "..v.z.." "..k.."\n")
end
io.close(output)
end
function unified_inventory.go_home(player)
local pos = unified_inventory.home_pos[player:get_player_name()]
if pos then
player:setpos(pos)
end
end
-- register_craft
function unified_inventory.register_craft(options)
if not options.output then
return
end
local itemstack = ItemStack(options.output)
if itemstack:is_empty() then
return
end
if options.type == "normal" and options.width == 0 then
options = { type = "shapeless", items = options.items, output = options.output, width = 0 }
end
if not unified_inventory.crafts_for.recipe[itemstack:get_name()] then
unified_inventory.crafts_for.recipe[itemstack:get_name()] = {}
end
table.insert(unified_inventory.crafts_for.recipe[itemstack:get_name()],options)
end
local craft_type_defaults = {
width = 3,
height = 3,
uses_crafting_grid = false,
}
function unified_inventory.craft_type_defaults(name, options)
if not options.description then
options.description = name
end
setmetatable(options, {__index = craft_type_defaults})
return options
end
function unified_inventory.register_craft_type(name, options)
unified_inventory.registered_craft_types[name] =
unified_inventory.craft_type_defaults(name, options)
end
unified_inventory.register_craft_type("normal", {
description = "Crafting",
icon = "ui_craftgrid_icon.png",
width = 3,
height = 3,
get_shaped_craft_width = function (craft) return craft.width end,
dynamic_display_size = function (craft)
local w = craft.width
local h = math.ceil(table.maxn(craft.items) / craft.width)
local g = w < h and h or w
return { width = g, height = g }
end,
uses_crafting_grid = true,
})
unified_inventory.register_craft_type("shapeless", {
description = "Mixing",
icon = "ui_craftgrid_icon.png",
width = 3,
height = 3,
dynamic_display_size = function (craft)
local maxn = table.maxn(craft.items)
local g = 1
while g*g < maxn do g = g + 1 end
return { width = g, height = g }
end,
uses_crafting_grid = true,
})
unified_inventory.register_craft_type("cooking", {
description = "Cooking",
icon = "default_furnace_front.png",
width = 1,
height = 1,
})
unified_inventory.register_craft_type("digging", {
description = "Digging",
icon = "default_tool_steelpick.png",
width = 1,
height = 1,
})
function unified_inventory.register_page(name, def)
unified_inventory.pages[name] = def
end
function unified_inventory.register_button(name, def)
if not def.action then
def.action = function(player)
unified_inventory.set_inventory_formspec(player, name)
end
end
def.name = name
table.insert(unified_inventory.buttons, def)
end
function unified_inventory.is_creative(playername)
return minetest.check_player_privs(playername, {creative=true})
or minetest.settings:get_bool("creative_mode")
end
| gpl-3.0 |
eriche2016/nn | Dropout.lua | 10 | 1762 | local Dropout, Parent = torch.class('nn.Dropout', 'nn.Module')
function Dropout:__init(p,v1,inplace,stochasticInference)
Parent.__init(self)
self.p = p or 0.5
self.train = true
self.inplace = inplace
self.stochastic_inference = stochasticInference or false
-- version 2 scales output during training instead of evaluation
self.v2 = not v1
if self.p >= 1 or self.p < 0 then
error('<Dropout> illegal percentage, must be 0 <= p < 1')
end
self.noise = torch.Tensor()
end
function Dropout:updateOutput(input)
if self.inplace then
self.output:set(input)
else
self.output:resizeAs(input):copy(input)
end
if self.p > 0 then
if self.train or self.stochastic_inference then
self.noise:resizeAs(input)
self.noise:bernoulli(1-self.p)
if self.v2 then
self.noise:div(1-self.p)
end
self.output:cmul(self.noise)
elseif not self.v2 then
self.output:mul(1-self.p)
end
end
return self.output
end
function Dropout:updateGradInput(input, gradOutput)
if self.inplace then
self.gradInput:set(gradOutput)
else
self.gradInput:resizeAs(gradOutput):copy(gradOutput)
end
if self.train then
if self.p > 0 then
self.gradInput:cmul(self.noise) -- simply mask the gradients with the noise vector
end
else
if not self.v2 and self.p > 0 then
self.gradInput:mul(1-self.p)
end
end
return self.gradInput
end
function Dropout:setp(p)
self.p = p
end
function Dropout:__tostring__()
return string.format('%s(%f)', torch.type(self), self.p)
end
function Dropout:clearState()
if self.noise then
self.noise:set()
end
return Parent.clearState(self)
end
| bsd-3-clause |
rigeirani/sss | plugins/google.lua | 722 | 1037 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
| gpl-2.0 |
hfjgjfg/sss25 | plugins/google.lua | 722 | 1037 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
| gpl-2.0 |
osamaalbsraoy/osama_albsraoy1989 | tg/test.lua | 210 | 2571 | started = 0
our_id = 0
function vardump(value, depth, key)
local linePrefix = ""
local spaces = ""
if key ~= nil then
linePrefix = "["..key.."] = "
end
if depth == nil then
depth = 0
else
depth = depth + 1
for i=1, depth do spaces = spaces .. " " end
end
if type(value) == 'table' then
mTable = getmetatable(value)
if mTable == nil then
print(spaces ..linePrefix.."(table) ")
else
print(spaces .."(metatable) ")
value = mTable
end
for tableKey, tableValue in pairs(value) do
vardump(tableValue, depth, tableKey)
end
elseif type(value) == 'function' or
type(value) == 'thread' or
type(value) == 'userdata' or
value == nil
then
print(spaces..tostring(value))
else
print(spaces..linePrefix.."("..type(value)..") "..tostring(value))
end
end
print ("HI, this is lua script")
function ok_cb(extra, success, result)
end
-- Notification code {{{
function get_title (P, Q)
if (Q.type == 'user') then
return P.first_name .. " " .. P.last_name
elseif (Q.type == 'chat') then
return Q.title
elseif (Q.type == 'encr_chat') then
return 'Secret chat with ' .. P.first_name .. ' ' .. P.last_name
else
return ''
end
end
local lgi = require ('lgi')
local notify = lgi.require('Notify')
notify.init ("Telegram updates")
local icon = os.getenv("HOME") .. "/.telegram-cli/telegram-pics/telegram_64.png"
function do_notify (user, msg)
local n = notify.Notification.new(user, msg, icon)
n:show ()
end
-- }}}
function on_msg_receive (msg)
if started == 0 then
return
end
if msg.out then
return
end
do_notify (get_title (msg.from, msg.to), msg.text)
if (msg.text == 'ping') then
if (msg.to.id == our_id) then
send_msg (msg.from.print_name, 'pong', ok_cb, false)
else
send_msg (msg.to.print_name, 'pong', ok_cb, false)
end
return
end
if (msg.text == 'PING') then
if (msg.to.id == our_id) then
fwd_msg (msg.from.print_name, msg.id, ok_cb, false)
else
fwd_msg (msg.to.print_name, msg.id, ok_cb, false)
end
return
end
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
function cron()
-- do something
postpone (cron, false, 1.0)
end
function on_binlog_replay_end ()
started = 1
postpone (cron, false, 1.0)
end
| gpl-2.0 |
james2doyle/lit | libs/import.lua | 5 | 3761 | --[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local pathJoin = require('luvi').path.join
local isAllowed = require('rules').isAllowed
local compileFilter = require('rules').compileFilter
local modes = require('git').modes
-- Import a fs path into the database
return function (db, fs, rootpath, rules, nativeOnly)
if nativeOnly == nil then nativeOnly = false end
local filters = {}
if rules then
filters[#filters + 1] = compileFilter(rootpath, rules, nativeOnly)
end
local importEntry, importTree
function importEntry(path, stat)
if stat.type == "directory" then
local hash, err = importTree(path)
if not hash and err then
return nil, err
end
return modes.tree, hash
end
if stat.type == "file" then
if not stat.mode then
stat = fs.stat(path)
end
local mode = bit.band(stat.mode, 73) > 0 and modes.exec or modes.file
local data, hash, err
data, err = fs.readFile(path)
if not data then
return nil, err or "Problem reading file: " .. path
end
hash, err = db.saveAs("blob", data)
if not hash then
return nil, err or "Problem saving blob: " .. path
end
return mode, hash
end
if stat.type == "link" then
local data, hash, err
data, err = fs.readlink(path)
if not data then
return nil, err or "Problem reading symlink: " .. path
end
hash, err = db.saveAs("blob", data)
if not hash then
return nil, err or "Problem saving symlink: " .. path
end
return modes.sym, hash
end
return nil, "Unsupported entry type at " .. path .. ": " .. tostring(stat.type)
end
function importTree(path)
assert(type(fs) == "table")
local items = {}
local meta = fs.readFile(pathJoin(path, "package.lua"))
if meta then meta = loadstring(meta)() end
if meta and meta.files then
filters[#filters + 1] = compileFilter(path, meta.files, nativeOnly)
end
local iter, err = fs.scandir(path)
if not iter then
return nil, err or "Problem scanning directory: " .. path
end
for entry in iter do
local fullPath = pathJoin(path, entry.name)
if not entry.type then
local stat, e = fs.stat(fullPath)
if not (stat and stat.type) then
return nil, e or "Cannot determine entry type: " .. fullPath
end
entry.type = stat.type
end
if isAllowed(fullPath, entry, filters) then
local mode, hash = importEntry(fullPath, entry)
if not mode then
return nil, hash or "Problem importing entry: " .. fullPath
end
entry.mode, entry.hash = mode, hash
if entry.hash then
items[#items + 1] = entry
end
end
end
if #items > 0 then
return db.saveAs("tree", items)
end
end
local stat, err = fs.stat(rootpath)
if not stat then
return nil, err or "Problem statting: " .. rootpath
end
local mode, hash = importEntry(rootpath, stat)
if not mode then
return nil, hash or "Problem importing: " .. rootpath
end
if not hash then
return nil, "Nothing to import"
end
return modes.toType(mode), hash
end
| apache-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Env/TerrainBrush.lua | 1 | 2941 | --[[
Title: TerrainBrush
Author(s): LiXizhi
Date: 2009/1/31
Desc: terrain form brush data structure only. Keeping the dafault brush settings.
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Env/TerrainBrush.lua");
brush = MyCompany.Aries.Creator.TerrainBrush:new({})
-- well known brushes
brush = MyCompany.Aries.Creator.TerrainBrush.Brushes["GaussionHill"]
brush = MyCompany.Aries.Creator.TerrainBrush.Brushes["Flatten"]
brush = MyCompany.Aries.Creator.TerrainBrush.Brushes["RadialScale"]
brush = MyCompany.Aries.Creator.TerrainBrush.Brushes["Roughen_Smooth"]
brush = MyCompany.Aries.Creator.TerrainBrush.Brushes["SetHole"]
brush = MyCompany.Aries.Creator.TerrainBrush.Brushes["Ramp"]
------------------------------------------------------------
]]
NPL.load("(gl)script/apps/Aries/Creator/Env/TerrainBrushMarker.lua");
local TerrainBrushMarker = commonlib.gettable("MyCompany.Aries.Creator.TerrainBrushMarker");
local TerrainBrush = {
filtername = nil,
BrushSize = 10,
BrushStrength = 0.1,
BrushSoftness = 0.5,
FlattenOperation = 2,
Elevation = 0,
gaussian_deviation = 0.9,
HeightScale = 3,
};
commonlib.setfield("MyCompany.Aries.Creator.TerrainBrush", TerrainBrush)
function TerrainBrush:new (o)
o = o or {} -- create object if user does not provide one
setmetatable(o, self)
self.__index = self
return o
end
-- refresh the terrain marker
function TerrainBrush:RefreshMarker()
if(self.filtername ~= nil) then
TerrainBrushMarker.DrawBrush({x=self.x,y=self.y,z=self.z,radius=self.BrushSize});
end
end
-- clear the terrain marker
function TerrainBrush:ClearMarker()
TerrainBrushMarker.Clear();
end
-- some known brushes
TerrainBrush.Brushes= {
["GaussionHill"] = TerrainBrush:new({
filtername = "GaussianHill",
BrushSize = 10,
BrushStrength = 0.1,
BrushSoftness = 0.5,
gaussian_deviation = 0.9,
HeightScale = 3,
}),
["Flatten"] = TerrainBrush:new({
filtername = "Flatten",
BrushSize = 5,
BrushStrength = 0.1,
BrushSoftness = 0.5,
FlattenOperation = 2,
Elevation = 0,
}),
["Roughen_Smooth"] = TerrainBrush:new({
filtername = "Roughen_Smooth",
BrushSize = 4,
BrushStrength = 0.1,
BrushSoftness = 0.5,
}),
["RadialScale"] = TerrainBrush:new({
filtername = "RadialScale",
BrushSize = 20,
BrushStrength = 0.1,
BrushSoftness = 0.5,
HeightScale = 3,
}),
["SetHole"] = TerrainBrush:new({
filtername = "SetHole",
BrushSize = 2,
BrushStrength = 0.1,
BrushSoftness = 0.5,
}),
["Ramp"] = TerrainBrush:new({
filtername = "SetHole",
filtername = "Ramp",
BrushSize = 5,
BrushStrength = 0.3,
BrushSoftness = 0.1,
}),
}
-- overwrite the marker function
function TerrainBrush.Brushes.Ramp:RefreshMarker()
if(self.filtername ~= nil) then
TerrainBrushMarker.DrawRamp({x1=self.x1,z1=self.z1,x=self.x,z=self.z,radius=self.BrushSize});
end
end
| gpl-2.0 |
pixeljetstream/luajit_gfx_sandbox | runtime/lua/jit/dis_ppc.lua | 2 | 20301 | ----------------------------------------------------------------------------
-- LuaJIT PPC disassembler module.
--
-- Copyright (C) 2005-2016 Mike Pall. All rights reserved.
-- Released under the MIT/X license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
-- This is a helper module used by the LuaJIT machine code dumper module.
--
-- It disassembles all common, non-privileged 32/64 bit PowerPC instructions
-- plus the e500 SPE instructions and some Cell/Xenon extensions.
--
-- NYI: VMX, VMX128
------------------------------------------------------------------------------
local type = type
local byte, format = string.byte, string.format
local match, gmatch, gsub = string.match, string.gmatch, string.gsub
local concat = table.concat
local bit = require("bit")
local band, bor, tohex = bit.band, bit.bor, bit.tohex
local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift
------------------------------------------------------------------------------
-- Primary and extended opcode maps
------------------------------------------------------------------------------
local map_crops = {
shift = 1, mask = 1023,
[0] = "mcrfXX",
[33] = "crnor|crnotCCC=", [129] = "crandcCCC",
[193] = "crxor|crclrCCC%", [225] = "crnandCCC",
[257] = "crandCCC", [289] = "creqv|crsetCCC%",
[417] = "crorcCCC", [449] = "cror|crmoveCCC=",
[16] = "b_lrKB", [528] = "b_ctrKB",
[150] = "isync",
}
local map_rlwinm = setmetatable({
shift = 0, mask = -1,
},
{ __index = function(t, x)
local rot = band(rshift(x, 11), 31)
local mb = band(rshift(x, 6), 31)
local me = band(rshift(x, 1), 31)
if mb == 0 and me == 31-rot then
return "slwiRR~A."
elseif me == 31 and mb == 32-rot then
return "srwiRR~-A."
else
return "rlwinmRR~AAA."
end
end
})
local map_rld = {
shift = 2, mask = 7,
[0] = "rldiclRR~HM.", "rldicrRR~HM.", "rldicRR~HM.", "rldimiRR~HM.",
{
shift = 1, mask = 1,
[0] = "rldclRR~RM.", "rldcrRR~RM.",
},
}
local map_ext = setmetatable({
shift = 1, mask = 1023,
[0] = "cmp_YLRR", [32] = "cmpl_YLRR",
[4] = "twARR", [68] = "tdARR",
[8] = "subfcRRR.", [40] = "subfRRR.",
[104] = "negRR.", [136] = "subfeRRR.",
[200] = "subfzeRR.", [232] = "subfmeRR.",
[520] = "subfcoRRR.", [552] = "subfoRRR.",
[616] = "negoRR.", [648] = "subfeoRRR.",
[712] = "subfzeoRR.", [744] = "subfmeoRR.",
[9] = "mulhduRRR.", [73] = "mulhdRRR.", [233] = "mulldRRR.",
[457] = "divduRRR.", [489] = "divdRRR.",
[745] = "mulldoRRR.",
[969] = "divduoRRR.", [1001] = "divdoRRR.",
[10] = "addcRRR.", [138] = "addeRRR.",
[202] = "addzeRR.", [234] = "addmeRR.", [266] = "addRRR.",
[522] = "addcoRRR.", [650] = "addeoRRR.",
[714] = "addzeoRR.", [746] = "addmeoRR.", [778] = "addoRRR.",
[11] = "mulhwuRRR.", [75] = "mulhwRRR.", [235] = "mullwRRR.",
[459] = "divwuRRR.", [491] = "divwRRR.",
[747] = "mullwoRRR.",
[971] = "divwouRRR.", [1003] = "divwoRRR.",
[15] = "iselltRRR", [47] = "iselgtRRR", [79] = "iseleqRRR",
[144] = { shift = 20, mask = 1, [0] = "mtcrfRZ~", "mtocrfRZ~", },
[19] = { shift = 20, mask = 1, [0] = "mfcrR", "mfocrfRZ", },
[371] = { shift = 11, mask = 1023, [392] = "mftbR", [424] = "mftbuR", },
[339] = {
shift = 11, mask = 1023,
[32] = "mferR", [256] = "mflrR", [288] = "mfctrR", [16] = "mfspefscrR",
},
[467] = {
shift = 11, mask = 1023,
[32] = "mtxerR", [256] = "mtlrR", [288] = "mtctrR", [16] = "mtspefscrR",
},
[20] = "lwarxRR0R", [84] = "ldarxRR0R",
[21] = "ldxRR0R", [53] = "lduxRRR",
[149] = "stdxRR0R", [181] = "stduxRRR",
[341] = "lwaxRR0R", [373] = "lwauxRRR",
[23] = "lwzxRR0R", [55] = "lwzuxRRR",
[87] = "lbzxRR0R", [119] = "lbzuxRRR",
[151] = "stwxRR0R", [183] = "stwuxRRR",
[215] = "stbxRR0R", [247] = "stbuxRRR",
[279] = "lhzxRR0R", [311] = "lhzuxRRR",
[343] = "lhaxRR0R", [375] = "lhauxRRR",
[407] = "sthxRR0R", [439] = "sthuxRRR",
[54] = "dcbst-R0R", [86] = "dcbf-R0R",
[150] = "stwcxRR0R.", [214] = "stdcxRR0R.",
[246] = "dcbtst-R0R", [278] = "dcbt-R0R",
[310] = "eciwxRR0R", [438] = "ecowxRR0R",
[470] = "dcbi-RR",
[598] = {
shift = 21, mask = 3,
[0] = "sync", "lwsync", "ptesync",
},
[758] = "dcba-RR",
[854] = "eieio", [982] = "icbi-R0R", [1014] = "dcbz-R0R",
[26] = "cntlzwRR~", [58] = "cntlzdRR~",
[122] = "popcntbRR~",
[154] = "prtywRR~", [186] = "prtydRR~",
[28] = "andRR~R.", [60] = "andcRR~R.", [124] = "nor|notRR~R=.",
[284] = "eqvRR~R.", [316] = "xorRR~R.",
[412] = "orcRR~R.", [444] = "or|mrRR~R=.", [476] = "nandRR~R.",
[508] = "cmpbRR~R",
[512] = "mcrxrX",
[532] = "ldbrxRR0R", [660] = "stdbrxRR0R",
[533] = "lswxRR0R", [597] = "lswiRR0A",
[661] = "stswxRR0R", [725] = "stswiRR0A",
[534] = "lwbrxRR0R", [662] = "stwbrxRR0R",
[790] = "lhbrxRR0R", [918] = "sthbrxRR0R",
[535] = "lfsxFR0R", [567] = "lfsuxFRR",
[599] = "lfdxFR0R", [631] = "lfduxFRR",
[663] = "stfsxFR0R", [695] = "stfsuxFRR",
[727] = "stfdxFR0R", [759] = "stfduxFR0R",
[855] = "lfiwaxFR0R",
[983] = "stfiwxFR0R",
[24] = "slwRR~R.",
[27] = "sldRR~R.", [536] = "srwRR~R.",
[792] = "srawRR~R.", [824] = "srawiRR~A.",
[794] = "sradRR~R.", [826] = "sradiRR~H.", [827] = "sradiRR~H.",
[922] = "extshRR~.", [954] = "extsbRR~.", [986] = "extswRR~.",
[539] = "srdRR~R.",
},
{ __index = function(t, x)
if band(x, 31) == 15 then return "iselRRRC" end
end
})
local map_ld = {
shift = 0, mask = 3,
[0] = "ldRRE", "lduRRE", "lwaRRE",
}
local map_std = {
shift = 0, mask = 3,
[0] = "stdRRE", "stduRRE",
}
local map_fps = {
shift = 5, mask = 1,
{
shift = 1, mask = 15,
[0] = false, false, "fdivsFFF.", false,
"fsubsFFF.", "faddsFFF.", "fsqrtsF-F.", false,
"fresF-F.", "fmulsFF-F.", "frsqrtesF-F.", false,
"fmsubsFFFF~.", "fmaddsFFFF~.", "fnmsubsFFFF~.", "fnmaddsFFFF~.",
}
}
local map_fpd = {
shift = 5, mask = 1,
[0] = {
shift = 1, mask = 1023,
[0] = "fcmpuXFF", [32] = "fcmpoXFF", [64] = "mcrfsXX",
[38] = "mtfsb1A.", [70] = "mtfsb0A.", [134] = "mtfsfiA>>-A>",
[8] = "fcpsgnFFF.", [40] = "fnegF-F.", [72] = "fmrF-F.",
[136] = "fnabsF-F.", [264] = "fabsF-F.",
[12] = "frspF-F.",
[14] = "fctiwF-F.", [15] = "fctiwzF-F.",
[583] = "mffsF.", [711] = "mtfsfZF.",
[392] = "frinF-F.", [424] = "frizF-F.",
[456] = "fripF-F.", [488] = "frimF-F.",
[814] = "fctidF-F.", [815] = "fctidzF-F.", [846] = "fcfidF-F.",
},
{
shift = 1, mask = 15,
[0] = false, false, "fdivFFF.", false,
"fsubFFF.", "faddFFF.", "fsqrtF-F.", "fselFFFF~.",
"freF-F.", "fmulFF-F.", "frsqrteF-F.", false,
"fmsubFFFF~.", "fmaddFFFF~.", "fnmsubFFFF~.", "fnmaddFFFF~.",
}
}
local map_spe = {
shift = 0, mask = 2047,
[512] = "evaddwRRR", [514] = "evaddiwRAR~",
[516] = "evsubwRRR~", [518] = "evsubiwRAR~",
[520] = "evabsRR", [521] = "evnegRR",
[522] = "evextsbRR", [523] = "evextshRR", [524] = "evrndwRR",
[525] = "evcntlzwRR", [526] = "evcntlswRR",
[527] = "brincRRR",
[529] = "evandRRR", [530] = "evandcRRR", [534] = "evxorRRR",
[535] = "evor|evmrRRR=", [536] = "evnor|evnotRRR=",
[537] = "eveqvRRR", [539] = "evorcRRR", [542] = "evnandRRR",
[544] = "evsrwuRRR", [545] = "evsrwsRRR",
[546] = "evsrwiuRRA", [547] = "evsrwisRRA",
[548] = "evslwRRR", [550] = "evslwiRRA",
[552] = "evrlwRRR", [553] = "evsplatiRS",
[554] = "evrlwiRRA", [555] = "evsplatfiRS",
[556] = "evmergehiRRR", [557] = "evmergeloRRR",
[558] = "evmergehiloRRR", [559] = "evmergelohiRRR",
[560] = "evcmpgtuYRR", [561] = "evcmpgtsYRR",
[562] = "evcmpltuYRR", [563] = "evcmpltsYRR",
[564] = "evcmpeqYRR",
[632] = "evselRRR", [633] = "evselRRRW",
[634] = "evselRRRW", [635] = "evselRRRW",
[636] = "evselRRRW", [637] = "evselRRRW",
[638] = "evselRRRW", [639] = "evselRRRW",
[640] = "evfsaddRRR", [641] = "evfssubRRR",
[644] = "evfsabsRR", [645] = "evfsnabsRR", [646] = "evfsnegRR",
[648] = "evfsmulRRR", [649] = "evfsdivRRR",
[652] = "evfscmpgtYRR", [653] = "evfscmpltYRR", [654] = "evfscmpeqYRR",
[656] = "evfscfuiR-R", [657] = "evfscfsiR-R",
[658] = "evfscfufR-R", [659] = "evfscfsfR-R",
[660] = "evfsctuiR-R", [661] = "evfsctsiR-R",
[662] = "evfsctufR-R", [663] = "evfsctsfR-R",
[664] = "evfsctuizR-R", [666] = "evfsctsizR-R",
[668] = "evfststgtYRR", [669] = "evfststltYRR", [670] = "evfststeqYRR",
[704] = "efsaddRRR", [705] = "efssubRRR",
[708] = "efsabsRR", [709] = "efsnabsRR", [710] = "efsnegRR",
[712] = "efsmulRRR", [713] = "efsdivRRR",
[716] = "efscmpgtYRR", [717] = "efscmpltYRR", [718] = "efscmpeqYRR",
[719] = "efscfdR-R",
[720] = "efscfuiR-R", [721] = "efscfsiR-R",
[722] = "efscfufR-R", [723] = "efscfsfR-R",
[724] = "efsctuiR-R", [725] = "efsctsiR-R",
[726] = "efsctufR-R", [727] = "efsctsfR-R",
[728] = "efsctuizR-R", [730] = "efsctsizR-R",
[732] = "efststgtYRR", [733] = "efststltYRR", [734] = "efststeqYRR",
[736] = "efdaddRRR", [737] = "efdsubRRR",
[738] = "efdcfuidR-R", [739] = "efdcfsidR-R",
[740] = "efdabsRR", [741] = "efdnabsRR", [742] = "efdnegRR",
[744] = "efdmulRRR", [745] = "efddivRRR",
[746] = "efdctuidzR-R", [747] = "efdctsidzR-R",
[748] = "efdcmpgtYRR", [749] = "efdcmpltYRR", [750] = "efdcmpeqYRR",
[751] = "efdcfsR-R",
[752] = "efdcfuiR-R", [753] = "efdcfsiR-R",
[754] = "efdcfufR-R", [755] = "efdcfsfR-R",
[756] = "efdctuiR-R", [757] = "efdctsiR-R",
[758] = "efdctufR-R", [759] = "efdctsfR-R",
[760] = "efdctuizR-R", [762] = "efdctsizR-R",
[764] = "efdtstgtYRR", [765] = "efdtstltYRR", [766] = "efdtsteqYRR",
[768] = "evlddxRR0R", [769] = "evlddRR8",
[770] = "evldwxRR0R", [771] = "evldwRR8",
[772] = "evldhxRR0R", [773] = "evldhRR8",
[776] = "evlhhesplatxRR0R", [777] = "evlhhesplatRR2",
[780] = "evlhhousplatxRR0R", [781] = "evlhhousplatRR2",
[782] = "evlhhossplatxRR0R", [783] = "evlhhossplatRR2",
[784] = "evlwhexRR0R", [785] = "evlwheRR4",
[788] = "evlwhouxRR0R", [789] = "evlwhouRR4",
[790] = "evlwhosxRR0R", [791] = "evlwhosRR4",
[792] = "evlwwsplatxRR0R", [793] = "evlwwsplatRR4",
[796] = "evlwhsplatxRR0R", [797] = "evlwhsplatRR4",
[800] = "evstddxRR0R", [801] = "evstddRR8",
[802] = "evstdwxRR0R", [803] = "evstdwRR8",
[804] = "evstdhxRR0R", [805] = "evstdhRR8",
[816] = "evstwhexRR0R", [817] = "evstwheRR4",
[820] = "evstwhoxRR0R", [821] = "evstwhoRR4",
[824] = "evstwwexRR0R", [825] = "evstwweRR4",
[828] = "evstwwoxRR0R", [829] = "evstwwoRR4",
[1027] = "evmhessfRRR", [1031] = "evmhossfRRR", [1032] = "evmheumiRRR",
[1033] = "evmhesmiRRR", [1035] = "evmhesmfRRR", [1036] = "evmhoumiRRR",
[1037] = "evmhosmiRRR", [1039] = "evmhosmfRRR", [1059] = "evmhessfaRRR",
[1063] = "evmhossfaRRR", [1064] = "evmheumiaRRR", [1065] = "evmhesmiaRRR",
[1067] = "evmhesmfaRRR", [1068] = "evmhoumiaRRR", [1069] = "evmhosmiaRRR",
[1071] = "evmhosmfaRRR", [1095] = "evmwhssfRRR", [1096] = "evmwlumiRRR",
[1100] = "evmwhumiRRR", [1101] = "evmwhsmiRRR", [1103] = "evmwhsmfRRR",
[1107] = "evmwssfRRR", [1112] = "evmwumiRRR", [1113] = "evmwsmiRRR",
[1115] = "evmwsmfRRR", [1127] = "evmwhssfaRRR", [1128] = "evmwlumiaRRR",
[1132] = "evmwhumiaRRR", [1133] = "evmwhsmiaRRR", [1135] = "evmwhsmfaRRR",
[1139] = "evmwssfaRRR", [1144] = "evmwumiaRRR", [1145] = "evmwsmiaRRR",
[1147] = "evmwsmfaRRR",
[1216] = "evaddusiaawRR", [1217] = "evaddssiaawRR",
[1218] = "evsubfusiaawRR", [1219] = "evsubfssiaawRR",
[1220] = "evmraRR",
[1222] = "evdivwsRRR", [1223] = "evdivwuRRR",
[1224] = "evaddumiaawRR", [1225] = "evaddsmiaawRR",
[1226] = "evsubfumiaawRR", [1227] = "evsubfsmiaawRR",
[1280] = "evmheusiaawRRR", [1281] = "evmhessiaawRRR",
[1283] = "evmhessfaawRRR", [1284] = "evmhousiaawRRR",
[1285] = "evmhossiaawRRR", [1287] = "evmhossfaawRRR",
[1288] = "evmheumiaawRRR", [1289] = "evmhesmiaawRRR",
[1291] = "evmhesmfaawRRR", [1292] = "evmhoumiaawRRR",
[1293] = "evmhosmiaawRRR", [1295] = "evmhosmfaawRRR",
[1320] = "evmhegumiaaRRR", [1321] = "evmhegsmiaaRRR",
[1323] = "evmhegsmfaaRRR", [1324] = "evmhogumiaaRRR",
[1325] = "evmhogsmiaaRRR", [1327] = "evmhogsmfaaRRR",
[1344] = "evmwlusiaawRRR", [1345] = "evmwlssiaawRRR",
[1352] = "evmwlumiaawRRR", [1353] = "evmwlsmiaawRRR",
[1363] = "evmwssfaaRRR", [1368] = "evmwumiaaRRR",
[1369] = "evmwsmiaaRRR", [1371] = "evmwsmfaaRRR",
[1408] = "evmheusianwRRR", [1409] = "evmhessianwRRR",
[1411] = "evmhessfanwRRR", [1412] = "evmhousianwRRR",
[1413] = "evmhossianwRRR", [1415] = "evmhossfanwRRR",
[1416] = "evmheumianwRRR", [1417] = "evmhesmianwRRR",
[1419] = "evmhesmfanwRRR", [1420] = "evmhoumianwRRR",
[1421] = "evmhosmianwRRR", [1423] = "evmhosmfanwRRR",
[1448] = "evmhegumianRRR", [1449] = "evmhegsmianRRR",
[1451] = "evmhegsmfanRRR", [1452] = "evmhogumianRRR",
[1453] = "evmhogsmianRRR", [1455] = "evmhogsmfanRRR",
[1472] = "evmwlusianwRRR", [1473] = "evmwlssianwRRR",
[1480] = "evmwlumianwRRR", [1481] = "evmwlsmianwRRR",
[1491] = "evmwssfanRRR", [1496] = "evmwumianRRR",
[1497] = "evmwsmianRRR", [1499] = "evmwsmfanRRR",
}
local map_pri = {
[0] = false, false, "tdiARI", "twiARI",
map_spe, false, false, "mulliRRI",
"subficRRI", false, "cmpl_iYLRU", "cmp_iYLRI",
"addicRRI", "addic.RRI", "addi|liRR0I", "addis|lisRR0I",
"b_KBJ", "sc", "bKJ", map_crops,
"rlwimiRR~AAA.", map_rlwinm, false, "rlwnmRR~RAA.",
"oriNRR~U", "orisRR~U", "xoriRR~U", "xorisRR~U",
"andi.RR~U", "andis.RR~U", map_rld, map_ext,
"lwzRRD", "lwzuRRD", "lbzRRD", "lbzuRRD",
"stwRRD", "stwuRRD", "stbRRD", "stbuRRD",
"lhzRRD", "lhzuRRD", "lhaRRD", "lhauRRD",
"sthRRD", "sthuRRD", "lmwRRD", "stmwRRD",
"lfsFRD", "lfsuFRD", "lfdFRD", "lfduFRD",
"stfsFRD", "stfsuFRD", "stfdFRD", "stfduFRD",
false, false, map_ld, map_fps,
false, false, map_std, map_fpd,
}
------------------------------------------------------------------------------
local map_gpr = {
[0] = "r0", "sp", "r2", "r3", "r4", "r5", "r6", "r7",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
"r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31",
}
local map_cond = { [0] = "lt", "gt", "eq", "so", "ge", "le", "ne", "ns", }
-- Format a condition bit.
local function condfmt(cond)
if cond <= 3 then
return map_cond[band(cond, 3)]
else
return format("4*cr%d+%s", rshift(cond, 2), map_cond[band(cond, 3)])
end
end
------------------------------------------------------------------------------
-- Output a nicely formatted line with an opcode and operands.
local function putop(ctx, text, operands)
local pos = ctx.pos
local extra = ""
if ctx.rel then
local sym = ctx.symtab[ctx.rel]
if sym then extra = "\t->"..sym end
end
if ctx.hexdump > 0 then
ctx.out(format("%08x %s %-7s %s%s\n",
ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra))
else
ctx.out(format("%08x %-7s %s%s\n",
ctx.addr+pos, text, concat(operands, ", "), extra))
end
ctx.pos = pos + 4
end
-- Fallback for unknown opcodes.
local function unknown(ctx)
return putop(ctx, ".long", { "0x"..tohex(ctx.op) })
end
-- Disassemble a single instruction.
local function disass_ins(ctx)
local pos = ctx.pos
local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4)
local op = bor(lshift(b0, 24), lshift(b1, 16), lshift(b2, 8), b3)
local operands = {}
local last = nil
local rs = 21
ctx.op = op
ctx.rel = nil
local opat = map_pri[rshift(b0, 2)]
while type(opat) ~= "string" do
if not opat then return unknown(ctx) end
opat = opat[band(rshift(op, opat.shift), opat.mask)]
end
local name, pat = match(opat, "^([a-z0-9_.]*)(.*)")
local altname, pat2 = match(pat, "|([a-z0-9_.]*)(.*)")
if altname then pat = pat2 end
for p in gmatch(pat, ".") do
local x = nil
if p == "R" then
x = map_gpr[band(rshift(op, rs), 31)]
rs = rs - 5
elseif p == "F" then
x = "f"..band(rshift(op, rs), 31)
rs = rs - 5
elseif p == "A" then
x = band(rshift(op, rs), 31)
rs = rs - 5
elseif p == "S" then
x = arshift(lshift(op, 27-rs), 27)
rs = rs - 5
elseif p == "I" then
x = arshift(lshift(op, 16), 16)
elseif p == "U" then
x = band(op, 0xffff)
elseif p == "D" or p == "E" then
local disp = arshift(lshift(op, 16), 16)
if p == "E" then disp = band(disp, -4) end
if last == "r0" then last = "0" end
operands[#operands] = format("%d(%s)", disp, last)
elseif p >= "2" and p <= "8" then
local disp = band(rshift(op, rs), 31) * p
if last == "r0" then last = "0" end
operands[#operands] = format("%d(%s)", disp, last)
elseif p == "H" then
x = band(rshift(op, rs), 31) + lshift(band(op, 2), 4)
rs = rs - 5
elseif p == "M" then
x = band(rshift(op, rs), 31) + band(op, 0x20)
elseif p == "C" then
x = condfmt(band(rshift(op, rs), 31))
rs = rs - 5
elseif p == "B" then
local bo = rshift(op, 21)
local cond = band(rshift(op, 16), 31)
local cn = ""
rs = rs - 10
if band(bo, 4) == 0 then
cn = band(bo, 2) == 0 and "dnz" or "dz"
if band(bo, 0x10) == 0 then
cn = cn..(band(bo, 8) == 0 and "f" or "t")
end
if band(bo, 0x10) == 0 then x = condfmt(cond) end
name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+")
elseif band(bo, 0x10) == 0 then
cn = map_cond[band(cond, 3) + (band(bo, 8) == 0 and 4 or 0)]
if cond > 3 then x = "cr"..rshift(cond, 2) end
name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+")
end
name = gsub(name, "_", cn)
elseif p == "J" then
x = arshift(lshift(op, 27-rs), 29-rs)*4
if band(op, 2) == 0 then x = ctx.addr + pos + x end
ctx.rel = x
x = "0x"..tohex(x)
elseif p == "K" then
if band(op, 1) ~= 0 then name = name.."l" end
if band(op, 2) ~= 0 then name = name.."a" end
elseif p == "X" or p == "Y" then
x = band(rshift(op, rs+2), 7)
if x == 0 and p == "Y" then x = nil else x = "cr"..x end
rs = rs - 5
elseif p == "W" then
x = "cr"..band(op, 7)
elseif p == "Z" then
x = band(rshift(op, rs-4), 255)
rs = rs - 10
elseif p == ">" then
operands[#operands] = rshift(operands[#operands], 1)
elseif p == "0" then
if last == "r0" then
operands[#operands] = nil
if altname then name = altname end
end
elseif p == "L" then
name = gsub(name, "_", band(op, 0x00200000) ~= 0 and "d" or "w")
elseif p == "." then
if band(op, 1) == 1 then name = name.."." end
elseif p == "N" then
if op == 0x60000000 then name = "nop"; break end
elseif p == "~" then
local n = #operands
operands[n-1], operands[n] = operands[n], operands[n-1]
elseif p == "=" then
local n = #operands
if last == operands[n-1] then
operands[n] = nil
name = altname
end
elseif p == "%" then
local n = #operands
if last == operands[n-1] and last == operands[n-2] then
operands[n] = nil
operands[n-1] = nil
name = altname
end
elseif p == "-" then
rs = rs - 5
else
assert(false)
end
if x then operands[#operands+1] = x; last = x end
end
return putop(ctx, name, operands)
end
------------------------------------------------------------------------------
-- Disassemble a block of code.
local function disass_block(ctx, ofs, len)
if not ofs then ofs = 0 end
local stop = len and ofs+len or #ctx.code
stop = stop - stop % 4
ctx.pos = ofs - ofs % 4
ctx.rel = nil
while ctx.pos < stop do disass_ins(ctx) end
end
-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
local function create(code, addr, out)
local ctx = {}
ctx.code = code
ctx.addr = addr or 0
ctx.out = out or io.write
ctx.symtab = {}
ctx.disass = disass_block
ctx.hexdump = 8
return ctx
end
-- Simple API: disassemble code (a string) at address and output via out.
local function disass(code, addr, out)
create(code, addr, out):disass()
end
-- Return register name for RID.
local function regname(r)
if r < 32 then return map_gpr[r] end
return "f"..(r-32)
end
-- Public module functions.
return {
create = create,
disass = disass,
regname = regname
}
| mit |
pakoito/ToME---t-engine4 | game/modules/tome/data/talents/gifts/summon-advanced.lua | 3 | 5788 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- 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/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
newTalent{
name = "Master Summoner",
type = {"wild-gift/summon-advanced", 1},
require = gifts_req_high1,
mode = "sustained",
points = 5,
sustain_equilibrium = 20,
cooldown = 10,
range = 10,
tactical = { BUFF = 2 },
getCooldownReduction = function(self, t) return util.bound(self:getTalentLevelRaw(t) / 15, 0.05, 0.3) end,
activate = function(self, t)
game:playSoundNear(self, "talents/heal")
local particle
if self:addShaderAura("master_summoner", "awesomeaura", {time_factor=6200, alpha=0.7, flame_scale=0.8}, "particles_images/naturewings.png") then
--
elseif core.shader.active(4) then
particle = self:addParticles(Particles.new("shader_ring_rotating", 1, {radius=1.1}, {type="flames", zoom=2, npow=4, time_factor=4000, color1={0.2,0.7,0,1}, color2={0,1,0.3,1}, hide_center=0, xy={self.x, self.y}}))
else
particle = self:addParticles(Particles.new("master_summoner", 1))
end
return {
cd = self:addTemporaryValue("summon_cooldown_reduction", t.getCooldownReduction(self, t)),
particle = particle,
}
end,
deactivate = function(self, t, p)
self:removeShaderAura("master_summoner")
self:removeParticles(p.particle)
self:removeTemporaryValue("summon_cooldown_reduction", p.cd)
return true
end,
info = function(self, t)
local cooldownred = t.getCooldownReduction(self, t)
return ([[Reduces the cooldown of all summons by %d%%.]]):
format(cooldownred * 100)
end,
}
newTalent{
name = "Grand Arrival",
type = {"wild-gift/summon-advanced", 2},
require = gifts_req_high2,
points = 5,
mode = "passive",
radius = function(self, t) return math.floor(self:combatTalentScale(t, 1.3, 3.7, "log")) end,
effectDuration = function(self, t) return math.floor(self:combatTalentScale(t, 5, 9)) end,
nbEscorts = function(self, t) return math.max(1,math.floor(self:combatTalentScale(t, 0.3, 2.7, "log"))) end,
info = function(self, t)
local radius = self:getTalentRadius(t)
return ([[While Master Summoner is active, when a creature you summon appears in the world, it will trigger a wild effect:
- Ritch Flamespitter: Reduce fire resistance of all foes in a radius
- Hydra: Generates a cloud of lingering poison
- Rimebark: Reduce cold resistance of all foes in a radius
- Fire Drake: Appears with %d fire drake hatchling(s)
- War Hound: Reduce physical resistance of all foes in a radius
- Jelly: Reduce nature resistance of all foes in a radius
- Minotaur: Reduces movement speed of all foes in a radius
- Stone Golem: Dazes all foes in a radius
- Turtle: Heals all friendly targets in a radius
- Spider: The spider is so hideous that foes around it are repelled
Radius for effects is %d, and the duration of each lasting effect is %d turns.
The effects improve with your Willpower.]]):format(t.nbEscorts(self, t), radius, t.effectDuration(self, t))
end,
}
newTalent{
name = "Nature's Cycle", short_name = "NATURE_CYCLE",
type = {"wild-gift/summon-advanced", 3},
require = gifts_req_high3,
mode = "passive",
points = 5,
getChance = function(self, t) return math.min(100, 30 + self:getTalentLevel(t) * 15) end,
getReduction = function(self, t) return math.floor(self:combatTalentLimit(t, 5, 1, 3.1)) end, -- Limit < 5
info = function(self, t)
return ([[While Master Summoner is active, each new summon will reduce the remaining cooldown of Rage, Detonate and Wild Summon.
%d%% chance to reduce them by %d.]]):format(t.getChance(self, t), t.getReduction(self, t))
end,
}
newTalent{
name = "Wild Summon",
type = {"wild-gift/summon-advanced", 4},
require = gifts_req_high4,
points = 5,
equilibrium = 9,
cooldown = 25,
range = 10,
tactical = { BUFF = 5 },
no_energy = true,
on_pre_use = function(self, t, silent)
return self:isTalentActive(self.T_MASTER_SUMMONER)
end,
duration = function(self, t) return math.floor(self:combatTalentLimit(t, 25, 1, 5)) end, -- Limit <25
action = function(self, t)
self:setEffect(self.EFF_WILD_SUMMON, t.duration(self,t), {chance=100})
game:playSoundNear(self, "talents/teleport")
return true
end,
info = function(self, t)
return ([[For %d turn(s), you have 100%% chance that your summons appear as a wild version.
Each turn the chance disminishes.
Wild creatures have one more talent/power than the base versions:
- Ritch Flamespitter: sends a blast of flames around it, knocking foes away
- Hydra: Can disengage from melee range
- Rimebark: Becomes more resistant to magic damage
- Fire Drake: Can emit a powerful roar to silence its foes
- War Hound: Can rage, inreasing its critical chance and armour penetration
- Jelly: Can swallow foes that are low on life, regenerating your equilibrium
- Minotaur: Can rush toward its target
- Stone Golem: Melee blows can deal a small area of effect damage
- Turtle: Can force all foes in a radius into melee range
- Spider: Can project an insidious poison at its foes, reducing their healing
This talent requires Master Summoner to be active to be used.]]):format(t.duration(self,t))
end,
}
| gpl-3.0 |
RyMarq/Zero-K | LuaRules/Gadgets/start_unit_setup.lua | 1 | 24876 | function gadget:GetInfo()
return {
name = "StartSetup",
desc = "Implements initial setup: start units, resources, and plop for construction",
author = "Licho, CarRepairer, Google Frog, SirMaverick",
date = "2008-2010",
license = "GNU GPL, v2 or later",
layer = -1, -- Before terraforming gadget (for facplop terraforming)
enabled = true -- loaded by default?
}
end
-- partially based on Spring's unit spawn gadget
include("LuaRules/Configs/start_setup.lua")
include("LuaRules/Configs/constants.lua")
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spGetTeamInfo = Spring.GetTeamInfo
local spGetPlayerInfo = Spring.GetPlayerInfo
local spGetSpectatingState = Spring.GetSpectatingState
local spGetPlayerList = Spring.GetPlayerList
local modOptions = Spring.GetModOptions()
local DELAYED_AFK_SPAWN = false
local COOP_MODE = false
local playerChickens = Spring.Utilities.tobool(Spring.GetModOption("playerchickens", false, false))
local campaignBattleID = modOptions.singleplayercampaignbattleid
local setAiStartPos = (modOptions.setaispawns == "1")
local CAMPAIGN_SPAWN_DEBUG = (Spring.GetModOptions().campaign_spawn_debug == "1")
local gaiateam = Spring.GetGaiaTeamID()
local gaiaally = select(6, spGetTeamInfo(gaiateam, false))
local SAVE_FILE = "Gadgets/start_unit_setup.lua"
local fixedStartPos = (modOptions.fixedstartpos == "1")
local ordersToRemove
local storageUnits = {
{
unitDefID = UnitDefNames["staticstorage"].id,
storeAmount = UnitDefNames["staticstorage"].metalStorage
}
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if (gadgetHandler:IsSyncedCode()) then
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Functions shared between missions and non-missions
local function CheckOrderRemoval() -- FIXME: maybe we can remove polling every frame and just remove the orders directly
if not ordersToRemove then
return
end
for unitID, factoryDefID in pairs(ordersToRemove) do
local cmdID, _, cmdTag = Spring.GetUnitCurrentCommand(unitID)
if cmdID == -factoryDefID then
Spring.GiveOrderToUnit(unitID, CMD.REMOVE, cmdTag, CMD.OPT_ALT)
end
end
ordersToRemove = nil
end
local function CheckFacplopUse(unitID, unitDefID, teamID, builderID)
if ploppableDefs[unitDefID] and (select(5, Spring.GetUnitHealth(unitID)) < 0.1) and (builderID and Spring.GetUnitRulesParam(builderID, "facplop") == 1) then
-- (select(5, Spring.GetUnitHealth(unitID)) < 0.1) to prevent ressurect from spending facplop.
Spring.SetUnitRulesParam(builderID,"facplop",0, {inlos = true})
Spring.SetUnitRulesParam(unitID,"ploppee",1, {private = true})
ordersToRemove = ordersToRemove or {}
ordersToRemove[builderID] = unitDefID
-- Instantly complete factory
local maxHealth = select(2,Spring.GetUnitHealth(unitID))
Spring.SetUnitHealth(unitID, {health = maxHealth, build = 1})
local x,y,z = Spring.GetUnitPosition(unitID)
Spring.SpawnCEG("gate", x, y, z)
-- Stats collection (acuelly not, see below)
if GG.mod_stats_AddFactoryPlop then
GG.mod_stats_AddFactoryPlop(teamID, unitDefID)
end
-- FIXME: temporary hack because I'm in a hurry
-- proper way: get rid of all the useless shit in modstats, reenable and collect plop stats that way (see above)
local str = "SPRINGIE:facplop," .. UnitDefs[unitDefID].name .. "," .. teamID .. "," .. select(6, Spring.GetTeamInfo(teamID, false)) .. ","
local _, playerID, _, isAI = Spring.GetTeamInfo(teamID, false)
if isAI then
str = str .. "Nightwatch" -- existing account just in case infra explodes otherwise
else
str = str .. (Spring.GetPlayerInfo(playerID, false) or "ChanServ") -- ditto, different acc to differentiate
end
str = str .. ",END_PLOP"
Spring.SendCommands("wbynum 255 " .. str)
-- Spring.PlaySoundFile("sounds/misc/teleport2.wav", 10, x, y, z) -- FIXME: performance loss, possibly preload?
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Mission Handling
if VFS.FileExists("mission.lua") then -- this is a mission, we just want to set starting storage (and enable facplopping)
function gadget:Initialize()
for _, teamID in ipairs(Spring.GetTeamList()) do
Spring.SetTeamResource(teamID, "es", START_STORAGE + HIDDEN_STORAGE)
Spring.SetTeamResource(teamID, "ms", START_STORAGE + HIDDEN_STORAGE)
end
end
function GG.SetStartLocation()
end
function gadget:GameFrame(n)
CheckOrderRemoval()
end
function GG.GiveFacplop(unitID) -- deprecated, use rulesparam directly
Spring.SetUnitRulesParam(unitID, "facplop", 1, {inlos = true})
end
function gadget:UnitCreated(unitID, unitDefID, teamID, builderID)
CheckFacplopUse(unitID, unitDefID, teamID, builderID)
end
return
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local gamestart = false
--local createBeforeGameStart = {} -- no longer used
local scheduledSpawn = {}
local luaSetStartPositions = {}
local playerSides = {} -- sides selected ingame from widget - per players
local teamSides = {} -- sides selected ingame from widgets - per teams
local playerIDsByName = {}
local commChoice = {}
--local prespawnedCommIDs = {} -- [teamID] = unitID
GG.startUnits = {} -- WARNING: this is liable to break with new dyncomms (entries will likely not be an actual unitDefID)
GG.CommanderSpawnLocation = {}
local waitingForComm = {}
GG.waitingForComm = waitingForComm
-- overlaps with the rulesparam
local commSpawnedTeam = {}
local commSpawnedPlayer = {}
-- allow gadget:Save (unsynced) to reach them
local function UpdateSaveReferences()
_G.waitingForComm = waitingForComm
_G.scheduledSpawn = scheduledSpawn
_G.playerSides = playerSides
_G.teamSides = teamSides
_G.commSpawnedTeam = commSpawnedTeam
_G.commSpawnedPlayer = commSpawnedPlayer
end
UpdateSaveReferences()
local loadGame = false -- was this loaded from a savegame?
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:UnitCreated(unitID, unitDefID, teamID, builderID)
CheckFacplopUse(unitID, unitDefID, teamID, builderID)
end
local function InitUnsafe()
end
function gadget:Initialize()
-- needed if you reload luarules
local frame = Spring.GetGameFrame()
if frame and frame > 0 then
gamestart = true
end
InitUnsafe()
local allUnits = Spring.GetAllUnits()
for _, unitID in pairs(allUnits) do
local udid = Spring.GetUnitDefID(unitID)
if udid then
gadget:UnitCreated(unitID, udid, Spring.GetUnitTeam(unitID))
end
end
end
local function GetStartUnit(teamID, playerID, isAI)
local teamInfo = teamID and select(7, Spring.GetTeamInfo(teamID, true))
if teamInfo and teamInfo.staticcomm then
local commanderName = teamInfo.staticcomm
local commanderLevel = teamInfo.staticcomm_level or 1
local commanderProfile = GG.ModularCommAPI.GetCommProfileInfo(commanderName)
return commanderProfile.baseUnitDefID
end
local startUnit
local commProfileID = nil
if isAI then -- AI that didn't pick comm type gets default comm
return UnitDefNames[Spring.GetTeamRulesParam(teamID, "start_unit") or "dyntrainer_assault_base"].id
end
if (teamID and teamSides[teamID]) then
startUnit = DEFAULT_UNIT
end
if (playerID and playerSides[playerID]) then
startUnit = DEFAULT_UNIT
end
-- if a player-selected comm is available, use it
playerID = playerID or (teamID and select(2, spGetTeamInfo(teamID, false)) )
if (playerID and commChoice[playerID]) then
--Spring.Echo("Attempting to load alternate comm")
local playerCommProfiles = GG.ModularCommAPI.GetPlayerCommProfiles(playerID, true)
local altComm = playerCommProfiles[commChoice[playerID]]
if altComm then
startUnit = playerCommProfiles[commChoice[playerID]].baseUnitDefID
commProfileID = commChoice[playerID]
end
end
if (not startUnit) and (not DELAYED_AFK_SPAWN) then
startUnit = DEFAULT_UNIT
end
-- hack workaround for chicken
--local luaAI = Spring.GetTeamLuaAI(teamID)
--if luaAI and string.find(string.lower(luaAI), "chicken") then startUnit = nil end
--if didn't pick a comm, wait for user to pick
return (startUnit or nil)
end
local function GetFacingDirection(x, z, teamID)
return (math.abs(Game.mapSizeX/2 - x) > math.abs(Game.mapSizeZ/2 - z))
and ((x>Game.mapSizeX/2) and "west" or "east")
or ((z>Game.mapSizeZ/2) and "north" or "south")
end
local function getMiddleOfStartBox(teamID)
local x = Game.mapSizeX / 2
local z = Game.mapSizeZ / 2
local boxID = Spring.GetTeamRulesParam(teamID, "start_box_id")
if boxID then
local startposList = GG.startBoxConfig[boxID] and GG.startBoxConfig[boxID].startpoints
if startposList then
local startpos = startposList[1] -- todo: distribute afkers over them all instead of always using the 1st
x = startpos[1]
z = startpos[2]
end
end
return x, Spring.GetGroundHeight(x,z), z
end
local function GetStartPos(teamID, teamInfo, isAI)
if luaSetStartPositions[teamID] then
return luaSetStartPositions[teamID].x, luaSetStartPositions[teamID].y, luaSetStartPositions[teamID].z
end
if fixedStartPos then
local x, y, z
if teamInfo then
x, z = tonumber(teamInfo.start_x), tonumber(teamInfo.start_z)
end
if x then
y = Spring.GetGroundHeight(x, z)
else
x, y, z = Spring.GetTeamStartPosition(teamID)
end
return x, y, z
end
if not (Spring.GetTeamRulesParam(teamID, "valid_startpos") or isAI) then
local x, y, z = getMiddleOfStartBox(teamID)
return x, y, z
end
local x, y, z = Spring.GetTeamStartPosition(teamID)
-- clamp invalid positions
-- AIs can place them -- remove this once AIs are able to be filtered through AllowStartPosition
local boxID = isAI and Spring.GetTeamRulesParam(teamID, "start_box_id")
if boxID and not GG.CheckStartbox(boxID, x, z) then
x,y,z = getMiddleOfStartBox(teamID)
end
return x, y, z
end
local function SpawnStartUnit(teamID, playerID, isAI, bonusSpawn, notAtTheStartOfTheGame)
if not teamID then
return
end
local _,_,_,_,_,allyTeamID,teamInfo = Spring.GetTeamInfo(teamID, true)
if teamInfo and teamInfo.nocommander then
waitingForComm[teamID] = nil
return
end
local luaAI = Spring.GetTeamLuaAI(teamID)
if luaAI and string.find(string.lower(luaAI), "chicken") then
return false
elseif playerChickens then
-- allied to latest chicken team? no com for you
local chickenTeamID = -1
for _,t in pairs(Spring.GetTeamList()) do
local teamLuaAI = Spring.GetTeamLuaAI(t)
if teamLuaAI and string.find(string.lower(teamLuaAI), "chicken") then
chickenTeamID = t
end
end
if (chickenTeamID > -1) and (Spring.AreTeamsAllied(teamID,chickenTeamID)) then
--Spring.Echo("chicken_control detected no com for "..playerID)
return false
end
end
-- get start unit
local startUnit = GetStartUnit(teamID, playerID, isAI)
if ((COOP_MODE and playerID and commSpawnedPlayer[playerID]) or (not COOP_MODE and commSpawnedTeam[teamID])) and not bonusSpawn then
return false
end
if startUnit then
-- replace with shuffled position
local x,y,z = GetStartPos(teamID, teamInfo, isAI)
-- get facing direction
local facing = GetFacingDirection(x, z, teamID)
if CAMPAIGN_SPAWN_DEBUG then
local _, aiName = Spring.GetAIInfo(teamID)
Spring.MarkerAddPoint(x, y, z, "Commander " .. (aiName or "Player"))
return -- Do not spawn commander
end
GG.startUnits[teamID] = startUnit
GG.CommanderSpawnLocation[teamID] = {x = x, y = y, z = z, facing = facing}
if GG.GalaxyCampaignHandler then
facing = GG.GalaxyCampaignHandler.OverrideCommFacing(teamID) or facing
end
-- CREATE UNIT
local unitID = GG.DropUnit(startUnit, x, y, z, facing, teamID, _, _, _, _, _, GG.ModularCommAPI.GetProfileIDByBaseDefID(startUnit), teamInfo and tonumber(teamInfo.static_level), true)
if not unitID then
return
end
if GG.GalaxyCampaignHandler then
GG.GalaxyCampaignHandler.DeployRetinue(unitID, x, z, facing, teamID)
end
if Spring.GetGameFrame() <= 1 then
Spring.SpawnCEG("gate", x, y, z)
-- Spring.PlaySoundFile("sounds/misc/teleport2.wav", 10, x, y, z) -- performance loss
end
if not bonusSpawn then
Spring.SetTeamRulesParam(teamID, "commSpawned", 1, {allied = true})
commSpawnedTeam[teamID] = true
if playerID then
Spring.SetGameRulesParam("commSpawnedPlayer"..playerID, 1, {allied = true})
commSpawnedPlayer[playerID] = true
end
waitingForComm[teamID] = nil
end
-- add facplop
local teamLuaAI = Spring.GetTeamLuaAI(teamID)
local udef = UnitDefs[Spring.GetUnitDefID(unitID)]
local metal, metalStore = Spring.GetTeamResources(teamID, "metal")
local energy, energyStore = Spring.GetTeamResources(teamID, "energy")
Spring.SetTeamResource(teamID, "energy", teamInfo.start_energy or (START_ENERGY + energy))
Spring.SetTeamResource(teamID, "metal", teamInfo.start_metal or (START_METAL + metal))
if GG.Overdrive then
GG.Overdrive.AddInnateIncome(allyTeamID, INNATE_INC_METAL, INNATE_INC_ENERGY)
end
if (udef.customParams.level and udef.name ~= "chickenbroodqueen") and
((not campaignBattleID) or GG.GalaxyCampaignHandler.HasFactoryPlop(teamID)) then
Spring.SetUnitRulesParam(unitID, "facplop", 1, {inlos = true})
end
local name = "noname" -- Backup for when player does not choose a commander and then resigns.
if isAI then
name = select(2, Spring.GetAIInfo(teamID))
else
name = Spring.GetPlayerInfo(playerID, false)
end
Spring.SetUnitRulesParam(unitID, "commander_owner", name, {inlos = true})
return true
end
return false
end
local function StartUnitPicked(playerID, name)
local _,_,spec,teamID = spGetPlayerInfo(playerID, false)
if spec then
return
end
teamSides[teamID] = name
local startUnit = GetStartUnit(teamID, playerID)
if startUnit then
SendToUnsynced("CommSelection",playerID, startUnit) --activate an event called "CommSelection" that can be detected in unsynced part
if UnitDefNames[startUnit] then
Spring.SetTeamRulesParam(teamID, "commChoice", UnitDefNames[startUnit].id)
else
Spring.SetTeamRulesParam(teamID, "commChoice", startUnit)
end
end
if gamestart then
-- picked commander after game start, prep for orbital drop
-- can't do it directly because that's an unsafe change
local frame = Spring.GetGameFrame() + 3
if not scheduledSpawn[frame] then scheduledSpawn[frame] = {} end
scheduledSpawn[frame][#scheduledSpawn[frame] + 1] = {teamID, playerID}
else
--[[
if startPosition[teamID] then
local oldCommID = prespawnedCommIDs[teamID]
local pos = startPosition[teamID]
local startUnit = GetStartUnit(teamID, playerID, isAI)
if startUnit then
local newCommID = Spring.CreateUnit(startUnit, pos.x, pos.y, pos.z , "s", 0)
if oldCommID then
local cmds = Spring.GetCommandQueue(oldCommID, -1)
--//transfer command queue
for i = 1, #cmds do
local cmd = cmds[i]
Spring.GiveOrderToUnit(newUnit, cmd.id, cmd.params, cmd.options.coded)
end
Spring.DestroyUnit(oldCommID, false, true)
end
prespawnedCommIDs[teamID] = newCommID
end
end
]]
end
GG.startUnits[teamID] = GetStartUnit(teamID) -- ctf compatibility
end
local function workAroundSpecsInTeamZero(playerlist, team)
if team == 0 then
local players = #playerlist
local specs = 0
-- count specs
for i=1,#playerlist do
local _,_,spec = spGetPlayerInfo(playerlist[i], false)
if spec then
specs = specs + 1
end
end
if players == specs then
return nil
end
end
return playerlist
end
--[[
This function return true if everyone in the team resigned.
This function is alternative to "isDead" from: "_,_,isDead,isAI = spGetTeamInfo(team, false)"
because "isDead" failed to return true when human team resigned before GameStart() event.
--]]
local function IsTeamResigned(team)
local playersInTeam = spGetPlayerList(team)
for j=1,#playersInTeam do
local spec = select(3,spGetPlayerInfo(playersInTeam[j], false))
if not spec then
return false
end
end
return true
end
local function GetPregameUnitStorage(teamID)
local storage = 0
for i = 1, #storageUnits do
storage = storage + Spring.GetTeamUnitDefCount(teamID, storageUnits[i].unitDefID) * storageUnits[i].storeAmount
end
return storage
end
function gadget:GameStart()
if Spring.Utilities.tobool(Spring.GetGameRulesParam("loadedGame")) then
return
end
gamestart = true
-- spawn units
for teamNum,team in ipairs(Spring.GetTeamList()) do
-- clear resources
-- actual resources are set depending on spawned unit and setup
if not loadGame then
local pregameUnitStorage = (campaignBattleID and GetPregameUnitStorage(team)) or 0
Spring.SetTeamResource(team, "es", pregameUnitStorage + HIDDEN_STORAGE)
Spring.SetTeamResource(team, "ms", pregameUnitStorage + HIDDEN_STORAGE)
Spring.SetTeamResource(team, "energy", 0)
Spring.SetTeamResource(team, "metal", 0)
end
--check if player resigned before game started
local _,playerID,_,isAI = spGetTeamInfo(team, false)
local deadPlayer = (not isAI) and IsTeamResigned(team)
if team ~= gaiateam and not deadPlayer then
local luaAI = Spring.GetTeamLuaAI(team)
if DELAYED_AFK_SPAWN then
if not (luaAI and string.find(string.lower(luaAI), "chicken")) then
waitingForComm[team] = true
end
end
if COOP_MODE then
-- 1 start unit per player
local playerlist = Spring.GetPlayerList(team, true)
playerlist = workAroundSpecsInTeamZero(playerlist, team)
if playerlist and (#playerlist > 0) then
for i=1,#playerlist do
local _,_,spec = spGetPlayerInfo(playerlist[i], false)
if (not spec) then
SpawnStartUnit(team, playerlist[i])
end
end
else
-- AI etc.
SpawnStartUnit(team, nil, true)
end
else -- no COOP_MODE
if (playerID) then
local _,_,spec,teamID = spGetPlayerInfo(playerID, false)
if (teamID == team and not spec) then
isAI = false
else
playerID = nil
end
end
SpawnStartUnit(team, playerID, isAI)
end
-- extra comms
local playerlist = Spring.GetPlayerList(team, true)
playerlist = workAroundSpecsInTeamZero(playerlist, team)
if playerlist then
for i = 1, #playerlist do
local customKeys = select(10, Spring.GetPlayerInfo(playerlist[i]))
if customKeys and customKeys.extracomm then
for j = 1, tonumber(customKeys.extracomm) do
Spring.Echo("Spawing a commander")
SpawnStartUnit(team, playerlist[i], false, true)
end
end
end
end
end
end
end
function gadget:RecvSkirmishAIMessage(aiTeam, dataStr)
-- perhaps this should be a global relay mode somewhere instead
local command = "ai_commander:";
if dataStr:find(command,1,true) then
local name = dataStr:sub(command:len()+1);
CallAsTeam(aiTeam, function()
Spring.SendLuaRulesMsg(command..aiTeam..":"..name);
end)
end
end
local function SetStartLocation(teamID, x, z)
luaSetStartPositions[teamID] = {x = x, y = Spring.GetGroundHeight(x,z), z = z}
end
GG.SetStartLocation = SetStartLocation
function gadget:RecvLuaMsg(msg, playerID)
if msg:find("faction:",1,true) then
local side = msg:sub(9)
playerSides[playerID] = side
commChoice[playerID] = nil -- unselect existing custom comm, if any
StartUnitPicked(playerID, side)
elseif msg:find("customcomm:",1,true) then
local name = msg:sub(12)
commChoice[playerID] = name
StartUnitPicked(playerID, name)
elseif msg:find("ai_commander:",1,true) then
local command = "ai_commander:";
local offset = msg:find(":",command:len()+1,true);
local teamID = msg:sub(command:len()+1,offset-1);
local name = msg:sub(offset+1);
teamID = tonumber(teamID);
local _,_,_,isAI = Spring.GetTeamInfo(teamID, false)
if(isAI) then -- this is actually an AI
local aiid, ainame, aihost = Spring.GetAIInfo(teamID)
if (aihost == playerID) then -- it's actually controlled by the local host
local unitDef = UnitDefNames[name];
if unitDef then -- the requested unit actually exists
if aiCommanders[unitDef.id] then
Spring.SetTeamRulesParam(teamID, "start_unit", name);
end
end
end
end
elseif (msg:find("ai_start_pos:",1,true) and setAiStartPos) then
local msg_table = Spring.Utilities.ExplodeString(':', msg)
if msg_table then
local teamID, x, z = tonumber(msg_table[2]), tonumber(msg_table[3]), tonumber(msg_table[4])
if teamID then
local _,_,_,isAI = Spring.GetTeamInfo(teamID, false)
if isAI and x and z then
SetStartLocation(teamID, x, z)
Spring.MarkerAddPoint(x, 0, z, "AI " .. teamID .. " start")
end
end
end
end
end
function gadget:GameFrame(n)
CheckOrderRemoval()
if n == (COMM_SELECT_TIMEOUT) then
for team in pairs(waitingForComm) do
local _,playerID = spGetTeamInfo(team, false)
teamSides[team] = DEFAULT_UNIT_NAME
--playerSides[playerID] = "basiccomm"
scheduledSpawn[n] = scheduledSpawn[n] or {}
scheduledSpawn[n][#scheduledSpawn[n] + 1] = {team, playerID} -- playerID is needed here so the player can't spawn coms 2 times in COOP_MODE mode
end
end
if scheduledSpawn[n] then
for _, spawnData in pairs(scheduledSpawn[n]) do
local teamID, playerID = spawnData[1], spawnData[2]
local canSpawn = SpawnStartUnit(teamID, playerID, false, false, true)
if (canSpawn) then
-- extra comms
local customKeys = select(10, playerID)
if playerID and customKeys and customKeys.extracomm then
for j=1, tonumber(customKeys.extracomm) do
SpawnStartUnit(teamID, playerID, false, true, true)
end
end
end
end
scheduledSpawn[n] = nil
end
end
function gadget:Shutdown()
--Spring.Echo("<Start Unit Setup> Going to sleep...")
end
function gadget:Load(zip)
if not (GG.SaveLoad and GG.SaveLoad.ReadFile) then
Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Start Unit Setup failed to access save/load API")
return
end
loadGame = true
local data = GG.SaveLoad.ReadFile(zip, "Start Unit Setup", SAVE_FILE) or {}
-- load data wholesale
waitingForComm = data.waitingForComm or {}
scheduledSpawn = data.scheduledSpawn or {}
playerSides = data.playerSides or {}
teamSides = data.teamSides or {}
commSpawnedPlayer = data.commSpawnedPlayer or {}
commSpawnedTeam = data.commSpawnedTeam or {}
UpdateSaveReferences()
end
--------------------------------------------------------------------
-- unsynced code
--------------------------------------------------------------------
else
local teamID = Spring.GetLocalTeamID()
local spGetUnitDefID = Spring.GetUnitDefID
local spValidUnitID = Spring.ValidUnitID
local spAreTeamsAllied = Spring.AreTeamsAllied
local spGetUnitTeam = Spring.GetUnitTeam
function gadget:Initialize()
gadgetHandler:AddSyncAction('CommSelection',CommSelection) --Associate "CommSelected" event to "WrapToLuaUI". Reference: http://springrts.com/phpbb/viewtopic.php?f=23&t=24781 "Gadget and Widget Cross Communication"
end
function CommSelection(_,playerID, startUnit)
if (Script.LuaUI('CommSelection')) then --if there is widgets subscribing to "CommSelection" function then:
local isSpec = Spring.GetSpectatingState() --receiver player is spectator?
local myAllyID = Spring.GetMyAllyTeamID() --receiver player's alliance?
local _,_,_,_, eventAllyID = Spring.GetPlayerInfo(playerID, false) --source alliance?
if isSpec or myAllyID == eventAllyID then
Script.LuaUI.CommSelection(playerID, startUnit) --send to widgets as event
end
end
end
local MakeRealTable = Spring.Utilities.MakeRealTable
function gadget:Save(zip)
if VFS.FileExists("mission.lua") then -- nothing to do
return
end
if not GG.SaveLoad then
Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Start Unit Setup failed to access save/load API")
return
end
local toSave = {
waitingForComm = MakeRealTable(SYNCED.waitingForComm, "Start setup (waitingForComm)"),
scheduledSpawn = MakeRealTable(SYNCED.scheduledSpawn, "Start setup (scheduledSpawn)"),
playerSides = MakeRealTable(SYNCED.playerSides, "Start setup (playerSides)"),
teamSides = MakeRealTable(SYNCED.teamSides, "Start setup (teamSides)"),
commSpawnedPlayer = MakeRealTable(SYNCED.commSpawnedPlayer, "Start setup (commSpawnedPlayer)"),
commSpawnedTeam = MakeRealTable(SYNCED.commSpawnedTeam, "Start setup (commSpawnedTeam)"),
}
GG.SaveLoad.WriteSaveData(zip, SAVE_FILE, toSave)
end
end
| gpl-2.0 |
TerminalShell/zombiesurvival | entities/effects/spithit.lua | 1 | 1490 | function EFFECT:Think()
return false
end
function EFFECT:Render()
end
local function CollideCallback(particle, hitpos, hitnormal)
if particle:GetDieTime() == 0 then return end
particle:SetDieTime(0)
if math.random(3) == 3 then
sound.Play("physics/flesh/flesh_squishy_impact_hard"..math.random(4)..".wav", hitpos, 50, math.Rand(95, 105))
end
if math.random(3) == 3 then
util.Decal("Impact.AlienFlesh", hitpos + hitnormal, hitpos - hitnormal)
end
end
function EFFECT:Init(data)
local pos = data:GetOrigin()
local hitnormal = data:GetNormal() * -1
local emitter = ParticleEmitter(pos)
emitter:SetNearClip(24, 48)
local grav = Vector(0, 0, -500)
for i = 1, math.random(60, 85) do
local particle = emitter:Add("particles/smokey", pos)
particle:SetVelocity(VectorRand():GetNormalized() * math.Rand(32, 72) + hitnormal * math.Rand(48, 198))
particle:SetDieTime(math.Rand(0.9, 2))
particle:SetStartAlpha(200)
particle:SetEndAlpha(0)
particle:SetStartSize(math.Rand(1, 5))
particle:SetEndSize(0)
particle:SetRoll(math.Rand(0, 360))
particle:SetRollDelta(math.Rand(-15, 15))
particle:SetColor(math.Rand(25, 30), math.Rand(200, 240), math.Rand(25, 30))
particle:SetLighting(true)
particle:SetGravity(grav)
particle:SetCollide(true)
particle:SetCollideCallback(CollideCallback)
end
emitter:Finish()
util.Decal("Impact.AlienFlesh", pos + hitnormal, pos - hitnormal)
sound.Play("npc/antlion_grub/squashed.wav", pos, 74, math.random(95, 110))
end
| gpl-3.0 |
NPLPackages/paracraft | script/kids/3DMapSystemData/Item_AppCommand.lua | 1 | 2086 | --[[
Title: an unknown item
Author(s): LiXizhi
Date: 2009/2/3
Desc:
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/kids/3DMapSystemData/Item_AppCommand.lua");
local dummyItem = Map3DSystem.Item.Item_AppCommand:new({AppCommand="File.Exit", params=nil});
Map3DSystem.Item.ItemManager:AddItem(dummyItem);
------------------------------------------------------------
]]
NPL.load("(gl)script/kids/3DMapSystemData/ItemBase.lua");
local Item_AppCommand = commonlib.inherit(Map3DSystem.Item.ItemBase, {type=Map3DSystem.Item.Types.AppCommand});
commonlib.setfield("Map3DSystem.Item.Item_AppCommand", Item_AppCommand)
---------------------------------
-- functions
---------------------------------
-- Get the Icon of this object
-- @param callbackFunc: function (filename) end. if nil, it will return the icon texture path. otherwise it will use the callback,since the icon may not be immediately available at call time.
function Item_AppCommand:GetIcon(callbackFunc)
if(self.icon) then
return self.icon;
elseif(self.AppCommand or self.cmd) then
self.cmd = self.cmd or Map3DSystem.App.Commands.GetCommand(self.AppCommand)
if(self.cmd) then
self.icon = self.cmd.icon;
return self.icon;
end
else
return ItemBase:GetIcon(callbackFunc);
end
end
-- When this item is clicked
function Item_AppCommand:OnClick(mouseButton)
if(self.AppCommand) then
Map3DSystem.App.Commands.Call(self.AppCommand, self.params);
end
end
-- Get the tooltip of this object
-- @param callbackFunc: function (text) end. if nil, it will return the text. otherwise it will use the callback,since the icon may not be immediately available at call time.
function Item_AppCommand:GetTooltip(callbackFunc)
if(self.tooltip) then
return self.tooltip;
elseif(self.AppCommand or self.cmd) then
self.cmd = self.cmd or Map3DSystem.App.Commands.GetCommand(self.AppCommand)
if(self.cmd) then
self.tooltip = self.cmd.ButtonText or self.cmd.tooltip;
return self.tooltip;
end
else
return ItemBase:GetTooltip(callbackFunc);
end
end | gpl-2.0 |
zcaliptium/Serious-Engine | Sources/luajit/src/jit/v.lua | 88 | 5614 | ----------------------------------------------------------------------------
-- Verbose mode of the LuaJIT compiler.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module shows verbose information about the progress of the
-- JIT compiler. It prints one line for each generated trace. This module
-- is useful to see which code has been compiled or where the compiler
-- punts and falls back to the interpreter.
--
-- Example usage:
--
-- luajit -jv -e "for i=1,1000 do for j=1,1000 do end end"
-- luajit -jv=myapp.out myapp.lua
--
-- Default output is to stderr. To redirect the output to a file, pass a
-- filename as an argument (use '-' for stdout) or set the environment
-- variable LUAJIT_VERBOSEFILE. The file is overwritten every time the
-- module is started.
--
-- The output from the first example should look like this:
--
-- [TRACE 1 (command line):1 loop]
-- [TRACE 2 (1/3) (command line):1 -> 1]
--
-- The first number in each line is the internal trace number. Next are
-- the file name ('(command line)') and the line number (':1') where the
-- trace has started. Side traces also show the parent trace number and
-- the exit number where they are attached to in parentheses ('(1/3)').
-- An arrow at the end shows where the trace links to ('-> 1'), unless
-- it loops to itself.
--
-- In this case the inner loop gets hot and is traced first, generating
-- a root trace. Then the last exit from the 1st trace gets hot, too,
-- and triggers generation of the 2nd trace. The side trace follows the
-- path along the outer loop and *around* the inner loop, back to its
-- start, and then links to the 1st trace. Yes, this may seem unusual,
-- if you know how traditional compilers work. Trace compilers are full
-- of surprises like this -- have fun! :-)
--
-- Aborted traces are shown like this:
--
-- [TRACE --- foo.lua:44 -- leaving loop in root trace at foo:lua:50]
--
-- Don't worry -- trace aborts are quite common, even in programs which
-- can be fully compiled. The compiler may retry several times until it
-- finds a suitable trace.
--
-- Of course this doesn't work with features that are not-yet-implemented
-- (NYI error messages). The VM simply falls back to the interpreter. This
-- may not matter at all if the particular trace is not very high up in
-- the CPU usage profile. Oh, and the interpreter is quite fast, too.
--
-- Also check out the -jdump module, which prints all the gory details.
--
------------------------------------------------------------------------------
-- Cache some library functions and objects.
local jit = require("jit")
assert(jit.version_num == 20004, "LuaJIT core/library version mismatch")
local jutil = require("jit.util")
local vmdef = require("jit.vmdef")
local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo
local type, format = type, string.format
local stdout, stderr = io.stdout, io.stderr
-- Active flag and output file handle.
local active, out
------------------------------------------------------------------------------
local startloc, startex
local function fmtfunc(func, pc)
local fi = funcinfo(func, pc)
if fi.loc then
return fi.loc
elseif fi.ffid then
return vmdef.ffnames[fi.ffid]
elseif fi.addr then
return format("C:%x", fi.addr)
else
return "(?)"
end
end
-- Format trace error message.
local function fmterr(err, info)
if type(err) == "number" then
if type(info) == "function" then info = fmtfunc(info) end
err = format(vmdef.traceerr[err], info)
end
return err
end
-- Dump trace states.
local function dump_trace(what, tr, func, pc, otr, oex)
if what == "start" then
startloc = fmtfunc(func, pc)
startex = otr and "("..otr.."/"..oex..") " or ""
else
if what == "abort" then
local loc = fmtfunc(func, pc)
if loc ~= startloc then
out:write(format("[TRACE --- %s%s -- %s at %s]\n",
startex, startloc, fmterr(otr, oex), loc))
else
out:write(format("[TRACE --- %s%s -- %s]\n",
startex, startloc, fmterr(otr, oex)))
end
elseif what == "stop" then
local info = traceinfo(tr)
local link, ltype = info.link, info.linktype
if ltype == "interpreter" then
out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n",
tr, startex, startloc))
elseif link == tr or link == 0 then
out:write(format("[TRACE %3s %s%s %s]\n",
tr, startex, startloc, ltype))
elseif ltype == "root" then
out:write(format("[TRACE %3s %s%s -> %d]\n",
tr, startex, startloc, link))
else
out:write(format("[TRACE %3s %s%s -> %d %s]\n",
tr, startex, startloc, link, ltype))
end
else
out:write(format("[TRACE %s]\n", what))
end
out:flush()
end
end
------------------------------------------------------------------------------
-- Detach dump handlers.
local function dumpoff()
if active then
active = false
jit.attach(dump_trace)
if out and out ~= stdout and out ~= stderr then out:close() end
out = nil
end
end
-- Open the output file and attach dump handlers.
local function dumpon(outfile)
if active then dumpoff() end
if not outfile then outfile = os.getenv("LUAJIT_VERBOSEFILE") end
if outfile then
out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
else
out = stderr
end
jit.attach(dump_trace, "trace")
active = true
end
-- Public module functions.
module(...)
on = dumpon
off = dumpoff
start = dumpon -- For -j command line option.
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/talents/chronomancy/fate-weaving.lua | 2 | 5325 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- 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/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
-- EDGE TODO: Particles, Timed Effect Particles
newTalent{
name = "Spin Fate",
type = {"chronomancy/fate-weaving", 1},
require = chrono_req1,
mode = "passive",
points = 5,
getSaveBonus = function(self, t) return math.ceil(self:combatTalentScale(t, 2, 8, 0.75)) end,
doSpinFate = function(self, t)
local save_bonus = t.getSaveBonus(self, t)
local resists = self:knowTalent(self.T_FATEWEAVER) and self:callTalent(self.T_FATEWEAVER, "getResist") or 0
self:setEffect(self.EFF_SPIN_FATE, 3, {save_bonus=save_bonus, resists=resists, spin=1, max_spin=3})
return true
end,
info = function(self, t)
local save = t.getSaveBonus(self, t)
return ([[Each time you take damage from someone else you gain one spin, increasing your defense and saves by %d for three turns.
This effect may occur once per turn and stacks up to three spin (for a maximum bonus of %d).]]):
format(save, save * 3)
end,
}
newTalent{
name = "Webs of Fate",
type = {"chronomancy/fate-weaving", 2},
require = chrono_req2,
points = 5,
paradox = function (self, t) return getParadoxCost(self, t, 10) end,
cooldown = 12,
tactical = { BUFF = 2, CLOSEIN = 2, ESCAPE = 2 },
getPower = function(self, t) return self:combatTalentSpellDamage(t, 20, 100, getParadoxSpellpower(self))/100 end,
getDuration = function(self, t) return 5 end,
action = function(self, t)
local effs = {}
-- Find all pins
for eff_id, p in pairs(self.tmp) do
local e = self.tempeffect_def[eff_id]
if e.subtype.pin then
effs[#effs+1] = {"effect", eff_id}
end
end
-- And remove them
while #effs > 0 do
local eff = rng.tableRemove(effs)
if eff[1] == "effect" then
self:removeEffect(eff[2])
end
end
-- Set our power based on current spin
local move = t.getPower(self, t)
local pin = t.getPower(self, t)/2
local eff = self:hasEffect(self.EFF_SPIN_FATE)
if eff then
move = move * (1 + eff.spin/3)
pin = pin * (1 + eff.spin/3)
end
pin = math.min(1, pin) -- Limit 100%
self:setEffect(self.EFF_WEBS_OF_FATE, t.getDuration(self, t), {move=move, pin=pin})
return true
end,
info = function(self, t)
local power = t.getPower(self, t) * 100
local duration = t.getDuration(self, t)
return ([[Activate to remove pins. You also gain %d%% movement speed and %d%% pin immunity for %d turns.
If you have Spin Fate active these bonuses will be increased by 33%% per spin (up to a maximum of %d%% and %d%% respectively).
This spell will automatically cast when you're hit by most anomalies. This will not consume a turn or put the spell on cooldown.
While Webs of Fate is active you may gain one additional spin per turn.
These bonuses will scale with your Spellpower.]]):format(power, math.min(100, power/2), duration, power * 2, math.min(100, power/2 * 2))
end,
}
newTalent{
name = "Fateweaver",
type = {"chronomancy/fate-weaving", 3},
require = chrono_req3,
mode = "passive",
points = 5,
getResist = function(self, t) return self:combatTalentScale(t, 2, 8, 0.75) end,
info = function(self, t)
local resist = t.getResist(self, t)
return ([[You now gain %0.1f%% resist all when you gain spin with Spin Fate (up to a maximum of %0.1f%% resist all at three spin).]]):
format(resist, resist*3)
end,
}
newTalent{
name = "Seal Fate",
type = {"chronomancy/fate-weaving", 4},
require = chrono_req4,
points = 5,
paradox = function (self, t) return getParadoxCost(self, t, 20) end,
cooldown = 24,
tactical = { BUFF = 2 },
getPower = function(self, t) return self:combatTalentSpellDamage(t, 10, 25, getParadoxSpellpower(self)) end,
getDuration = function(self, t) return 5 end,
action = function(self, t)
-- Set our power based on current spin
local crits = t.getPower(self, t)
local eff = self:hasEffect(self.EFF_SPIN_FATE)
if eff then
crits = crits * (1 + eff.spin/3)
end
self:setEffect(self.EFF_SEAL_FATE, t.getDuration(self, t), {crit=crits})
return true
end,
info = function(self, t)
local power = t.getPower(self, t)
local duration = t.getDuration(self, t)
return ([[Activate to increase critical hit chance and critical damage by %d%% for five turns.
If you have Spin Fate active these bonuses will be increased by 33%% per spin (up to a maximum of %d%%).
This spell will automatically cast when you're hit by most anomalies. This will not consume a turn or put the spell on cooldown.
While Seal Fate is active you may gain one additional spin per turn.
These bonuses will scale with your Spellpower.]]):format(power, power * 2)
end,
} | gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Den_of_Rancor/Zone.lua | 1 | 1120 | -----------------------------------
--
-- Zone: Den_of_Rancor
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Den_of_Rancor/TextIDs"] = nil;
require("scripts/zones/Den_of_Rancor/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
| gpl-3.0 |
madpilot78/ntopng | scripts/lua/http_servers_stats.lua | 1 | 3085 | --
-- (C) 2013-21 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
local page_utils = require("page_utils")
sendHTTPContentTypeHeader('text/html')
page_utils.set_active_menu_entry(page_utils.menu_entries.http_servers)
dofile(dirs.installdir .. "/scripts/lua/inc/menu.lua")
page_utils.print_page_title(i18n("http_servers_stats.local_http_servers"))
print [[
<div id="table-http"></div>
<script>
var url_update = "]]
print (ntop.getHttpPrefix())
print [[/lua/get_http_hosts_data.lua]]
print ('";')
ntop.dumpFile(dirs.installdir .. "/httpdocs/inc/http_servers_stats_id.inc")
print [[
$("#table-http").datatable({
title: "Local HTTP Servers",
url: url_update ,
]]
print('title: "",\n')
print ('rowCallback: function ( row ) { return http_table_setID(row); },')
-- Set the preference table
preference = tablePreferences("rows_number",_GET["perPage"])
if (preference ~= "") then print ('perPage: '..preference.. ",\n") end
-- Automatic default sorted. NB: the column must exist.
print ('sort: [ ["' .. getDefaultTableSort("http") ..'","' .. getDefaultTableSortOrder("http").. '"] ],')
print [[
showPagination: true,
columns: [
{
title: "Key",
field: "key",
hidden: true,
css: {
textAlign: 'center'
}
},
{
title: "]] print(i18n("http_servers_stats.http_virtual_host")) print[[",
field: "column_http_virtual_host",
sortable: true,
css: {
textAlign: 'left'
}
},
{
title: "]] print(i18n("http_servers_stats.http_server_ip")) print[[",
field: "column_server_ip",
sortable: true,
css: {
textAlign: 'center'
}
},
]]
print [[
{
title: "]] print(i18n("http_servers_stats.bytes_sent")) print[[",
field: "column_bytes_sent",
sortable: true,
css: {
textAlign: 'center'
}
},
{
title: "]] print(i18n("http_servers_stats.bytes_received")) print[[",
field: "column_bytes_rcvd",
sortable: true,
css: {
textAlign: 'center'
}
},
{
title: "]] print(i18n("http_servers_stats.total_requests")) print[[",
field: "column_http_requests",
sortable: true,
css: {
textAlign: 'center'
}
},
{
title: "]] print(i18n("http_servers_stats.actual_requests")) print[[",
field: "column_act_num_http_requests",
sortable: true,
css: {
textAlign: 'center'
}
},
]]
print [[
]
});
</script>
]]
dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
| gpl-3.0 |
Ferk/Dungeontest | mods/dungeon_decor/fake_fire/init.lua | 1 | 6635 | screwdriver = screwdriver or {}
local function start_smoke(pos, node, clicker, chimney)
local this_spawner_meta = minetest.get_meta(pos)
local id = this_spawner_meta:get_int("smoky")
local s_handle = this_spawner_meta:get_int("sound")
local above = minetest.get_node({x=pos.x, y=pos.y+1, z=pos.z}).name
if id ~= 0 then
if s_handle then
minetest.after(0, function(s_handle)
minetest.sound_stop(s_handle)
end, s_handle)
end
minetest.delete_particlespawner(id)
this_spawner_meta:set_int("smoky", nil)
this_spawner_meta:set_int("sound", nil)
return
end
if above == "air" and (not id or id == 0) then
id = minetest.add_particlespawner({
amount = 4, time = 0, collisiondetection = true,
minpos = {x=pos.x-0.25, y=pos.y+0.4, z=pos.z-0.25},
maxpos = {x=pos.x+0.25, y=pos.y+5, z=pos.z+0.25},
minvel = {x=-0.2, y=0.3, z=-0.2}, maxvel = {x=0.2, y=1, z=0.2},
minacc = {x=0,y=0,z=0}, maxacc = {x=0,y=0.5,z=0},
minexptime = 1, maxexptime = 3,
minsize = 4, maxsize = 8,
texture = "smoke_particle.png",
})
if chimney == 1 then
s_handle = nil
this_spawner_meta:set_int("smoky", id)
this_spawner_meta:set_int("sound", nil)
else
s_handle = minetest.sound_play("fire_small", {
pos = pos,
max_hear_distance = 5,
loop = true
})
this_spawner_meta:set_int("smoky", id)
this_spawner_meta:set_int("sound", s_handle)
end
return end
end
local function stop_smoke(pos)
local this_spawner_meta = minetest.get_meta(pos)
local id = this_spawner_meta:get_int("smoky")
local s_handle = this_spawner_meta:get_int("sound")
if id ~= 0 then
minetest.delete_particlespawner(id)
end
if s_handle then
minetest.after(0, function(s_handle)
minetest.sound_stop(s_handle)
end, s_handle)
end
this_spawner_meta:set_int("smoky", nil)
this_spawner_meta:set_int("sound", nil)
end
-- FLAME TYPES
local flame_types = {"fake", "ice"}
for _, f in ipairs(flame_types) do
minetest.register_node("fake_fire:"..f.."_fire", {
inventory_image = f.."_fire_inv.png",
description = f.." fire",
drawtype = "plantlike",
paramtype = "light",
paramtype2 = "facedir",
groups = {dig_immediate=3, not_in_creative_inventory=1},
use_texture_alpha = "clip",
sunlight_propagates = true,
buildable_to = true,
walkable = false,
light_source = 14,
waving = 1,
tiles = {
{name=f.."_fire_animated.png", animation={type="vertical_frames",
aspect_w=16, aspect_h=16, length=1.5}},
},
on_rightclick = function (pos, node, clicker)
start_smoke(pos, node, clicker)
end,
on_destruct = function (pos)
stop_smoke(pos)
minetest.sound_play("fire_extinguish", {
pos = pos, max_hear_distance = 5
})
end,
drop = ""
})
end
minetest.register_node("fake_fire:fancy_fire", {
inventory_image = "fancy_fire_inv.png",
description = "Fancy Fire",
drawtype = "mesh",
mesh = "fancy_fire.obj",
paramtype = "light",
paramtype2 = "facedir",
groups = {dig_immediate=3},
use_texture_alpha = "clip",
sunlight_propagates = true,
light_source = 14,
walkable = false,
damage_per_second = 4,
on_rotate = screwdriver.rotate_simple,
tiles = {
{name="fake_fire_animated.png",
animation={type='vertical_frames', aspect_w=16, aspect_h=16, length=1}}, {name='fake_fire_logs.png'}},
on_rightclick = function (pos, node, clicker)
start_smoke(pos, node, clicker)
end,
on_destruct = function (pos)
stop_smoke(pos)
minetest.sound_play("fire_extinguish", {
pos = pos, max_hear_distance = 5
})
end,
drop = {
max_items = 3,
items = {
{
items = { "default:torch", "default:torch", "building_blocks:sticks" },
rarity = 1,
}
}
}
})
-- EMBERS
minetest.register_node("fake_fire:embers", {
description = "Glowing Embers",
tiles = {
{name="embers_animated.png", animation={type="vertical_frames",
aspect_w=16, aspect_h=16, length=2}},
},
light_source = 9,
groups = {crumbly=3},
paramtype = "light",
sounds = default.node_sound_dirt_defaults(),
})
-- CHIMNEYS
local materials = {"stone", "sandstone"}
for _, m in ipairs(materials) do
minetest.register_node("fake_fire:chimney_top_"..m, {
description = "Chimney Top - "..m,
tiles = {"default_"..m..".png^chimney_top.png", "default_"..m..".png"},
groups = {snappy=3},
paramtype = "light",
sounds = default.node_sound_stone_defaults(),
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5},
},
on_rightclick = function (pos, node, clicker)
local chimney = 1
start_smoke(pos, node, clicker, chimney)
end,
on_destruct = function (pos)
stop_smoke(pos)
end
})
minetest.register_craft({
type = "shapeless",
output = 'fake_fire:chimney_top_'..m,
recipe = {"default:torch", "stairs:slab_"..m}
})
end
-- FLINT and STEEL
minetest.register_tool("fake_fire:flint_and_steel", {
description = "Flint and steel",
inventory_image = "flint_and_steel.png",
liquids_pointable = false,
stack_max = 1,
tool_capabilities = {
full_punch_interval = 1.0,
max_drop_level=0,
groupcaps={flamable = {uses=65, maxlevel=1}}
},
on_use = function(itemstack, user, pointed_thing)
if pointed_thing.type == "node" and minetest.get_node(pointed_thing.above).name == "air" then
if not minetest.is_protected(pointed_thing.above, user:get_player_name()) then
if string.find(minetest.get_node(pointed_thing.under).name, "ice") then
minetest.set_node(pointed_thing.above, {name="fake_fire:ice_fire"})
else
minetest.set_node(pointed_thing.above, {name="fake_fire:fake_fire"})
end
else
minetest.chat_send_player(user:get_player_name(), "This area is protected!")
end
else
return
end
itemstack:add_wear(65535/65)
return itemstack
end
})
-- CRAFTS
minetest.register_craft({
type = "shapeless",
output = 'fake_fire:flint_and_steel',
recipe = {"default:obsidian_shard", "default:steel_ingot"}
})
minetest.register_craft({
type = "shapeless",
output = 'fake_fire:embers',
recipe = {"default:torch", "group:wood", "default:torch"}
})
minetest.register_craft({
type = "shapeless",
output = 'fake_fire:fancy_fire',
recipe = {"default:torch", "building_blocks:sticks", "default:torch" }
})
-- ALIASES
minetest.register_alias("fake_fire:smokeless_fire", "fake_fire:fake_fire")
minetest.register_alias("fake_fire:smokeless_ice_fire", "fake_fire:ice_fire")
minetest.register_alias("fake_fire:smokeless_chimney_top_stone", "fake_fire:chimney_top_stone")
minetest.register_alias("fake_fire:smokeless_chimney_top_sandstone", "fake_fire:chimney_top_sandstone")
minetest.register_alias("fake_fire:flint", "fake_fire:flint_and_steel")
| gpl-3.0 |
mysql/mysql-proxy | tests/suite/base/t/bug_41991-mock.lua | 4 | 1290 | --[[ $%BEGINLICENSE%$
Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
local proto = require("mysql.proto")
function connect_server()
proxy.response = {
type = proxy.MYSQLD_PACKET_RAW,
packets = {
proto.to_challenge_packet({})
}
}
return proxy.PROXY_SEND_RESULT
end
function read_query(packet)
if packet:byte() ~= proxy.COM_QUERY then
proxy.response = {
type = proxy.MYSQLD_PACKET_OK
}
return proxy.PROXY_SEND_RESULT
end
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
errmsg = "(bug_41991-mock) >" .. packet:sub(2) .. "<"
}
return proxy.PROXY_SEND_RESULT
end
| gpl-2.0 |
Joshalexjacobs/fantastic-guacamole | tiled/matrix.lua | 1 | 9928 | return {
version = "1.1",
luaversion = "5.1",
tiledversion = "0.16.1",
orientation = "orthogonal",
renderorder = "right-down",
width = 77,
height = 6,
tilewidth = 32,
tileheight = 32,
nextobjectid = 18,
properties = {},
tilesets = {
{
name = "matrix",
firstgid = 1,
tilewidth = 32,
tileheight = 32,
spacing = 0,
margin = 0,
image = "../img/background/matrix.png",
imagewidth = 128,
imageheight = 96,
tileoffset = {
x = 0,
y = 0
},
properties = {},
terrains = {},
tilecount = 12,
tiles = {}
},
{
name = "Black",
firstgid = 13,
tilewidth = 32,
tileheight = 32,
spacing = 0,
margin = 0,
image = "../img/background/Black.png",
imagewidth = 32,
imageheight = 32,
tileoffset = {
x = 0,
y = 0
},
properties = {},
terrains = {},
tilecount = 1,
tiles = {}
},
{
name = "matrix2",
firstgid = 14,
tilewidth = 32,
tileheight = 32,
spacing = 0,
margin = 0,
image = "../img/background/matrix2.png",
imagewidth = 96,
imageheight = 32,
tileoffset = {
x = 0,
y = 0
},
properties = {},
terrains = {},
tilecount = 3,
tiles = {}
}
},
layers = {
{
type = "tilelayer",
name = "Black",
x = 0,
y = 0,
width = 77,
height = 6,
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13
}
},
{
type = "tilelayer",
name = "Background",
x = 0,
y = 0,
width = 77,
height = 6,
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 10, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 9, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 0, 5, 6, 0, 0, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 0, 0, 0, 9
}
},
{
type = "tilelayer",
name = "Foreground",
x = 0,
y = 0,
width = 77,
height = 6,
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
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, 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, 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, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0
}
},
{
type = "objectgroup",
name = "Objects",
visible = true,
opacity = 0,
offsetx = 0,
offsety = 0,
properties = {},
objects = {
{
id = 1,
name = "Ground",
type = "ground",
shape = "rectangle",
x = 0,
y = 170.67,
width = 479.795,
height = 21.3333,
rotation = 0,
visible = true,
properties = {
["collidable"] = true
}
},
{
id = 2,
name = "Ground",
type = "ground",
shape = "rectangle",
x = 511.967,
y = 170.67,
width = 63.6717,
height = 21.33,
rotation = 0,
visible = true,
properties = {
["collidable"] = true
}
},
{
id = 3,
name = "Ground",
type = "ground",
shape = "rectangle",
x = 640.098,
y = 170.67,
width = 1695.75,
height = 21.33,
rotation = 0,
visible = true,
properties = {
["collidable"] = true
}
},
{
id = 4,
name = "wall",
type = "block",
shape = "rectangle",
x = 480.078,
y = 172.042,
width = 0.929835,
height = 19.6606,
rotation = 0,
visible = true,
properties = {
["collidable"] = true
}
},
{
id = 5,
name = "wall",
type = "block",
shape = "rectangle",
x = 510.983,
y = 172.434,
width = 0.929835,
height = 19.6606,
rotation = 0,
visible = true,
properties = {
["collidable"] = true
}
},
{
id = 6,
name = "wall",
type = "block",
shape = "rectangle",
x = 575.867,
y = 172.347,
width = 0.929835,
height = 19.6606,
rotation = 0,
visible = true,
properties = {
["collidable"] = true
}
},
{
id = 7,
name = "wall",
type = "block",
shape = "rectangle",
x = 639.105,
y = 172.347,
width = 0.929835,
height = 19.6606,
rotation = 0,
visible = true,
properties = {
["collidable"] = true
}
},
{
id = 8,
name = "portal",
type = "portal",
shape = "rectangle",
x = 2247.06,
y = 124.04,
width = 17.2378,
height = 50,
rotation = 0,
visible = true,
properties = {
["collidable"] = true
}
}
}
}
}
}
| mit |
pakoito/ToME---t-engine4 | game/modules/tome/data/talents/psionic/psionic.lua | 2 | 11878 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Nicolas Casalini
--
-- 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/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
-- Talent trees
newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/absorption", name = "absorption", description = "Absorb damage and gain energy." }
newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/projection", name = "projection", description = "Project energy to damage foes." }
newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/psi-fighting", name = "psi-fighting", description = "Wield melee weapons with mentally-manipulated forces." }
newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/focus", name = "focus", description = "Use gems to focus your energies." }
newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/augmented-mobility", generic = true, name = "augmented mobility", description = "Use energy to move yourself and others." }
newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/augmented-striking", name = "augmented striking", description = "Augment melee attacks with psionic enegies." }
newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/voracity", name = "voracity", description = "Pull energy from your surroundings." }
newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/finer-energy-manipulations", generic = true, name = "finer energy manipulations", description = "Subtle applications of the psionic arts." }
--newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/mental-discipline", generic = true, name = "mental discipline", description = "Increase mental capacity, endurance, and flexibility." }
newTalentType{ is_mind=true, type="psionic/other", name = "other", description = "Various psionic talents." }
-- Advanced Talent Trees
--newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/grip", name = "grip", min_lev = 10, description = "Augment your telekinetic grip." }
newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/kinetic-mastery", name = "kinetic mastery", min_lev = 10, description = "Mastery of telekinetic forces." }
newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/thermal-mastery", name = "thermal mastery", min_lev = 10, description = "Mastery of pyrokinetic forces." }
newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/charged-mastery", name = "charged mastery", min_lev = 10, description = "Mastery of electrokinetic forces." }
--newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/psi-archery", name = "psi-archery", min_lev = 10, description = "Use your telekinetic powers to wield bows with deadly effectiveness." }
--newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/greater-psi-fighting", name = "greater psi-fighting", description = "Elevate psi-fighting prowess to epic levels." }
--newTalentType{ allow_random=true, is_mind=true, autolearn_mindslayer=true, type="psionic/brainstorm", name = "brainstorm", description = "Focus your telekinetic powers in ways undreamed of by most mindslayers." }
-- Solipsist Talent Trees
newTalentType{ allow_random=true, is_mind=true, type="psionic/discharge", name = "discharge", description = "Project feedback on the world around you." }
newTalentType{ allow_random=true, is_mind=true, type="psionic/distortion", name = "distortion", description = "Distort reality with your mental energy." }
newTalentType{ allow_random=true, is_mind=true, type="psionic/dream-forge", generic = true, name = "Dream Forge", description = "Master the dream forge to create powerful armor and effects." }
newTalentType{ allow_random=true, is_mind=true, type="psionic/dream-smith", name = "Dream Smith", description = "Call the dream-forge hammer to smite your foes." }
newTalentType{ allow_random=true, is_mind=true, type="psionic/nightmare", name = "nightmare", description = "Manifest your enemies nightmares." }
newTalentType{ allow_random=true, is_mind=true, type="psionic/psychic-assault", name = "Psychic Assault", description = "Directly attack your opponents minds." }
newTalentType{ allow_random=true, is_mind=true, type="psionic/slumber", name = "slumber", description = "Force enemies into a deep sleep." }
newTalentType{ allow_random=true, is_mind=true, type="psionic/solipsism", name = "solipsism", description = "Nothing exists outside the minds ability to perceive it." }
newTalentType{ allow_random=true, is_mind=true, type="psionic/thought-forms", name = "Thought-Forms", description = "Manifest your thoughts as psionic summons." }
-- Generic Solipsist Trees
newTalentType{ allow_random=true, is_mind=true, type="psionic/dreaming", generic = true, name = "dreaming", description = "Manipulate the sleep cycles of yourself and your enemies." }
newTalentType{ allow_random=true, is_mind=true, type="psionic/mentalism", generic = true, name = "mentalism", description = "Various mind based effects." }
newTalentType{ allow_random=true, is_mind=true, type="psionic/feedback", generic = true, name = "feedback", description = "Store feedback as you get damaged and use it to protect and heal your body." }
newTalentType{ allow_random=true, is_mind=true, type="psionic/trance", generic = true, name = "trance", description = "Put your mind into a deep trance." }
newTalentType{ allow_random=true, is_mind=true, type="psionic/possession", name = "possession", description = "You have learnt to shed away your body, allowing you to possess any other." }
-- Level 0 wil tree requirements:
psi_absorb = {
stat = { wil=function(level) return 12 + (level-1) * 8 end },
level = function(level) return 0 + 5*(level-1) end,
}
psi_wil_req1 = {
stat = { wil=function(level) return 12 + (level-1) * 2 end },
level = function(level) return 0 + (level-1) end,
}
psi_wil_req2 = {
stat = { wil=function(level) return 20 + (level-1) * 2 end },
level = function(level) return 4 + (level-1) end,
}
psi_wil_req3 = {
stat = { wil=function(level) return 28 + (level-1) * 2 end },
level = function(level) return 8 + (level-1) end,
}
psi_wil_req4 = {
stat = { wil=function(level) return 36 + (level-1) * 2 end },
level = function(level) return 12 + (level-1) end,
}
--Level 10 wil tree requirements:
psi_wil_high1 = {
stat = { wil=function(level) return 22 + (level-1) * 2 end },
level = function(level) return 10 + (level-1) end,
}
psi_wil_high2 = {
stat = { wil=function(level) return 30 + (level-1) * 2 end },
level = function(level) return 14 + (level-1) end,
}
psi_wil_high3 = {
stat = { wil=function(level) return 38 + (level-1) * 2 end },
level = function(level) return 18 + (level-1) end,
}
psi_wil_high4 = {
stat = { wil=function(level) return 46 + (level-1) * 2 end },
level = function(level) return 22 + (level-1) end,
}
--Level 20 wil tree requirements:
psi_wil_20_1 = {
stat = { wil=function(level) return 32 + (level-1) * 2 end },
level = function(level) return 20 + (level-1) end,
}
psi_wil_20_2 = {
stat = { wil=function(level) return 36 + (level-1) * 2 end },
level = function(level) return 24 + (level-1) end,
}
psi_wil_20_3 = {
stat = { wil=function(level) return 42 + (level-1) * 2 end },
level = function(level) return 28 + (level-1) end,
}
psi_wil_20_4 = {
stat = { wil=function(level) return 48 + (level-1) * 2 end },
level = function(level) return 32 + (level-1) end,
}
-- Level 0 cun tree requirements:
psi_cun_req1 = {
stat = { cun=function(level) return 12 + (level-1) * 2 end },
level = function(level) return 0 + (level-1) end,
}
psi_cun_req2 = {
stat = { cun=function(level) return 20 + (level-1) * 2 end },
level = function(level) return 4 + (level-1) end,
}
psi_cun_req3 = {
stat = { cun=function(level) return 28 + (level-1) * 2 end },
level = function(level) return 8 + (level-1) end,
}
psi_cun_req4 = {
stat = { cun=function(level) return 36 + (level-1) * 2 end },
level = function(level) return 12 + (level-1) end,
}
-- Level 10 cun tree requirements:
psi_cun_high1 = {
stat = { cun=function(level) return 22 + (level-1) * 2 end },
level = function(level) return 10 + (level-1) end,
}
psi_cun_high2 = {
stat = { cun=function(level) return 30 + (level-1) * 2 end },
level = function(level) return 14 + (level-1) end,
}
psi_cun_high3 = {
stat = { cun=function(level) return 38 + (level-1) * 2 end },
level = function(level) return 18 + (level-1) end,
}
psi_cun_high4 = {
stat = { cun=function(level) return 46 + (level-1) * 2 end },
level = function(level) return 22 + (level-1) end,
}
-- Useful definitions for psionic talents
function getGemLevel(self)
local gem_level = 0
if self:getInven("PSIONIC_FOCUS") then
local tk_item = self:getInven("PSIONIC_FOCUS")[1]
if tk_item and ((tk_item.type == "gem") or (tk_item.subtype == "mindstar") or tk_item.combat.is_psionic_focus == true) then
gem_level = tk_item.material_level or 5
end
end
return gem_level
end
-- Cancel Thought Forms, we do this here because we use it for dreamscape and projection as well as thought-forms
function cancelThoughtForms(self, id)
local forms = {self.T_TF_DEFENDER, self.T_TF_WARRIOR, self.T_TF_BOWMAN}
for i, t in ipairs(forms) do
if self:isTalentActive(t) then
self:forceUseTalent(t, {ignore_energy=true})
end
-- Put other thought-forms on cooldown; checks for id to prevent dreamscape putting all thought-forms on cooldown
if id and id ~= t then
if self:knowTalent(t) then
local t = self:getTalentFromId(t)
self:startTalentCooldown(t)
end
end
end
end
load("/data/talents/psionic/absorption.lua")
load("/data/talents/psionic/finer-energy-manipulations.lua")
--load("/data/talents/psionic/mental-discipline.lua")
load("/data/talents/psionic/projection.lua")
load("/data/talents/psionic/psi-fighting.lua")
load("/data/talents/psionic/voracity.lua")
load("/data/talents/psionic/augmented-mobility.lua")
load("/data/talents/psionic/augmented-striking.lua")
load("/data/talents/psionic/focus.lua")
load("/data/talents/psionic/other.lua")
load("/data/talents/psionic/kinetic-mastery.lua")
load("/data/talents/psionic/thermal-mastery.lua")
load("/data/talents/psionic/charged-mastery.lua")
--load("/data/talents/psionic/psi-archery.lua")
--load("/data/talents/psionic/grip.lua")
-- Solipsist
load("/data/talents/psionic/discharge.lua")
load("/data/talents/psionic/distortion.lua")
load("/data/talents/psionic/dream-forge.lua")
load("/data/talents/psionic/dream-smith.lua")
load("/data/talents/psionic/dreaming.lua")
load("/data/talents/psionic/mentalism.lua")
load("/data/talents/psionic/feedback.lua")
load("/data/talents/psionic/nightmare.lua")
load("/data/talents/psionic/psychic-assault.lua")
load("/data/talents/psionic/slumber.lua")
load("/data/talents/psionic/solipsism.lua")
load("/data/talents/psionic/thought-forms.lua")
--load("/data/talents/psionic/trance.lua")
load("/data/talents/psionic/possession.lua")
| gpl-3.0 |
zhutaorun/2DPlatformer-SLua | Assets/StreamingAssets/Lua/Logic/LgRemover.lua | 1 | 2541 | --
-- The remover class.
--
-- @filename LgRemover.lua
-- @copyright Copyright (c) 2015 Yaukey/yaukeywang/WangYaoqi (yaukeywang@gmail.com) all rights reserved.
-- @license The MIT License (MIT)
-- @author Yaukey
-- @date 2015-09-05
--
local YwDeclare = YwDeclare
local YwClass = YwClass
local DLog = YwDebug.Log
local DLogWarn = YwDebug.LogWarning
local DLogError = YwDebug.LogError
-- Register new class LgRemover.
local strClassName = "LgRemover"
local LgRemover = YwDeclare(strClassName, YwClass(strClassName))
-- Member variables.
-- The c# class object.
LgRemover.this = false
-- The transform.
LgRemover.transform = false
-- The c# gameObject.
LgRemover.gameObject = false
-- Awake method.
function LgRemover:Awake()
--print("LgRemover:Awake")
-- Check variable.
if (not self.this) or (not self.transform) or (not self.gameObject) then
DLogError("Init error in LgRemover!")
return
end
end
-- OnTriggerEnter2D method.
function LgRemover:OnTriggerEnter2D(cOtherCollider2D)
--print("LgRemover:OnTriggerEnter2D")
local this = self.this
-- If the player hits the trigger...
if "Player" == cOtherCollider2D.gameObject.tag then
-- .. stop the camera tracking the player
GameObject.FindGameObjectWithTag("MainCamera"):GetComponent(CameraFollow).enabled = false
-- .. stop the Health Bar following the player.
local cHealthBarObj = GameObject.FindGameObjectWithTag("HealthBar")
if cHealthBarObj.activeSelf then
cHealthBarObj:SetActive(false)
end
-- ... instantiate the splash where the player falls in.
GameObject.Instantiate(this.m_splash, cOtherCollider2D.transform.position, self.transform.rotation)
-- ... destroy the player.
GameObject.Destroy(cOtherCollider2D.gameObject)
-- ... reload the level.
self:ReloadGame()
else
-- ... instantiate the splash where the enemy falls in.
GameObject.Instantiate(this.m_splash, cOtherCollider2D.transform.position, self.transform.rotation)
-- Destroy the enemy.
GameObject.Destroy(cOtherCollider2D.gameObject)
end
end
function LgRemover:ReloadGame()
--print("LgRemover:ReloadGame")
local cCol = coroutine.create(function ()
-- ... pause briefly.
Yield(WaitForSeconds(2.0))
-- ... and then reload the level.
Application.LoadLevel(Application.loadedLevel)
end)
coroutine.resume(cCol)
end
-- Return this class.
return LgRemover
| mit |
pakoito/ToME---t-engine4 | game/modules/tome/data/gfx/particles/dismayed.lua | 3 | 1467 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- 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/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
base_size = 32
local toggle = false
return { generator = function()
local ad = rng.range(0, 15) * 360 / 16
local a = math.rad(ad)
local dir = -math.rad(ad)
local r = rng.range(5, 25)
local dirchance = rng.chance(2)
return {
life = 10,
size = 6, sizev = -0.3, sizea = 0,
x = r * math.cos(a), xv = 0, xa = 0,
y = r * math.sin(a), yv = 0, ya = 0,
dir = dir, dirv = 0, dira = 0,
vel = -0.4, velv = 0, vela = dirchance and -0.02 or 0.02,
r = 100 / 255, rv = 0, ra = 0,
g = 120 / 255, gv = 0, ga = 0,
b = rng.percent(5) and 80 / 255 or 160 / 255, bv = 0, ba = 0,
a = rng.range(120, 200) / 255, av = 0, aa = 0,
}
end, },
function(self)
self.ps:emit(1)
end,
100
| gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Code/CodeBlockWindow.lua | 1 | 53075 | --[[
Title: CodeBlockWindow
Author(s): LiXizhi
Date: 2018/5/22
Desc:
use the lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeBlockWindow.lua");
local CodeBlockWindow = commonlib.gettable("MyCompany.Aries.Game.Code.CodeBlockWindow");
CodeBlockWindow.Show(true)
CodeBlockWindow.SetCodeEntity(entityCode);
-------------------------------------------------------
]]
NPL.load("(gl)script/ide/System/Windows/Window.lua")
NPL.load("(gl)script/ide/System/Scene/Viewports/ViewportManager.lua");
NPL.load("(gl)script/ide/System/Windows/Mouse.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/SceneContext/AllContext.lua");
NPL.load("(gl)script/ide/System/Windows/Screen.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeHelpWindow.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/EditCodeActor/EditCodeActor.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/NplBrowser/NplBrowserLoaderPage.lua");
NPL.load("(gl)script/apps/WebServer/WebServer.lua");
NPL.load("(gl)script/ide/System/Windows/Keyboard.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeIntelliSense.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/ChatSystem/ChatWindow.lua");
NPL.load("(gl)script/apps/Aries/BBSChat/ChatSystem/ChatChannel.lua");
local ChatChannel = commonlib.gettable("MyCompany.Aries.ChatSystem.ChatChannel");
local ChatWindow = commonlib.gettable("MyCompany.Aries.ChatSystem.ChatWindow");
local FocusPolicy = commonlib.gettable("System.Core.Namespace.FocusPolicy");
local CameraController = commonlib.gettable("MyCompany.Aries.Game.CameraController")
local CodeIntelliSense = commonlib.gettable("MyCompany.Aries.Game.Code.CodeIntelliSense");
local Keyboard = commonlib.gettable("System.Windows.Keyboard");
local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager");
local EditCodeActor = commonlib.gettable("MyCompany.Aries.Game.Tasks.EditCodeActor");
local CodeHelpWindow = commonlib.gettable("MyCompany.Aries.Game.Code.CodeHelpWindow");
local Files = commonlib.gettable("MyCompany.Aries.Game.Common.Files");
local Screen = commonlib.gettable("System.Windows.Screen");
local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine")
local AllContext = commonlib.gettable("MyCompany.Aries.Game.AllContext");
local Mouse = commonlib.gettable("System.Windows.Mouse");
local ViewportManager = commonlib.gettable("System.Scene.Viewports.ViewportManager");
local NplBrowserLoaderPage = commonlib.gettable("NplBrowser.NplBrowserLoaderPage");
local CodeBlockWindow = commonlib.inherit(commonlib.gettable("System.Core.ToolBase"), commonlib.gettable("MyCompany.Aries.Game.Code.CodeBlockWindow"));
-- whether we are using big code window size
CodeBlockWindow:Property({"BigCodeWindowSize", false, "IsBigCodeWindowSize", "SetBigCodeWindowSize"});
-- code text size
CodeBlockWindow:Property({"fontSize", 13, "GetFontSize", "SetFontSize"});
-- when entity being edited is changed.
CodeBlockWindow:Signal("entityChanged", function(entity) end)
local code_block_window_name = "code_block_window_";
local page;
local groupindex_hint = 3;
-- this is singleton class
local self = CodeBlockWindow;
local NplBlocklyEditorPage = nil;
CodeBlockWindow.defaultCodeUIUrl = "script/apps/Aries/Creator/Game/Code/CodeBlockWindow.html";
-- show code block window at the right side of the screen
-- @param bShow:
function CodeBlockWindow.Show(bShow)
if(not bShow) then
CodeBlockWindow.Close();
else
GameLogic.GetFilters():add_filter("OnShowEscFrame", CodeBlockWindow.OnShowEscFrame);
GameLogic.GetFilters():add_filter("ShowExitDialog", CodeBlockWindow.OnShowExitDialog);
GameLogic.GetFilters():add_filter("OnCodeBlockLineStep", CodeBlockWindow.OnCodeBlockLineStep);
GameLogic.GetFilters():add_filter("OnCodeBlockNplBlocklyLineStep", CodeBlockWindow.OnCodeBlockNplBlocklyLineStep);
GameLogic.GetFilters():add_filter("ChatLogWindowShowAndHide", CodeBlockWindow.OnChatLogWindowShowAndHide);
GameLogic:desktopLayoutRequested("CodeBlockWindow");
GameLogic:Connect("desktopLayoutRequested", CodeBlockWindow, CodeBlockWindow.OnLayoutRequested, "UniqueConnection");
GameLogic.GetCodeGlobal():Connect("logAdded", CodeBlockWindow, CodeBlockWindow.AddConsoleText, "UniqueConnection");
local _this = ParaUI.GetUIObject(code_block_window_name);
if(not _this:IsValid()) then
self.width, self.height, self.margin_right, self.bottom, self.top, sceneMarginBottom = self:CalculateMargins();
_this = ParaUI.CreateUIObject("container", code_block_window_name, "_mr", 0, self.top, self.width, self.bottom);
_this.zorder = -2;
_this.background="";
_this:SetScript("onsize", function()
CodeBlockWindow:OnViewportChange();
end)
local viewport = ViewportManager:GetSceneViewport();
viewport:SetMarginRight(self.margin_right);
viewport:SetMarginRightHandler(self);
if(sceneMarginBottom~=0) then
if(viewport:GetMarginBottomHandler() == nil or viewport:GetMarginBottomHandler() == self) then
viewport:SetMarginBottom(sceneMarginBottom);
viewport:SetMarginBottomHandler(self);
end
end
viewport:Connect("sizeChanged", CodeBlockWindow, CodeBlockWindow.OnViewportChange, "UniqueConnection");
_this:SetScript("onclick", function() end); -- just disable click through
_guihelper.SetFontColor(_this, "#ffffff");
_this:AttachToRoot();
page = System.mcml.PageCtrl:new({url=CodeBlockWindow.GetDefaultCodeUIUrl()});
page:Create(code_block_window_name.."page", _this, "_fi", 0, 0, 0, 0);
end
_this.visible = true;
CodeBlockWindow.isTextCtrlHasFocus = false;
CodeBlockWindow:OnViewportChange();
local viewport = ViewportManager:GetSceneViewport();
viewport:SetMarginRight(self.margin_right);
viewport:SetMarginRightHandler(self);
GameLogic:Connect("beforeWorldSaved", CodeBlockWindow, CodeBlockWindow.OnWorldSave, "UniqueConnection");
GameLogic:Connect("WorldUnloaded", CodeBlockWindow, CodeBlockWindow.OnWorldUnload, "UniqueConnection")
CodeBlockWindow:LoadSceneContext();
if(self.entity) then
EntityManager.SetLastTriggerEntity(self.entity)
local langConfig = CodeHelpWindow.GetLanguageConfigByEntity(self.entity)
if(langConfig and langConfig.OnOpenCodeEditor) then
langConfig.OnOpenCodeEditor(self.entity)
end
end
if (self.IsSupportNplBlockly()) then
self.OpenBlocklyEditor();
end
GameLogic.GetEvents():DispatchEvent({type = "CodeBlockWindowShow" , bShow = true, width = self.width});
end
end
function CodeBlockWindow.GetPageCtrl()
return page;
end
function CodeBlockWindow.GetDefaultCodeUIUrl()
local codeUIUrl = GameLogic.GetFilters():apply_filters("CodeBlockUIUrl", CodeBlockWindow.defaultCodeUIUrl)
return codeUIUrl;
end
-- @param locationInfo: in format of "filename:line:"
function CodeBlockWindow.OnCodeBlockLineStep(locationInfo)
if(locationInfo) then
local filename, lineNumber = locationInfo:match("^([^:]+):(%d+)")
if(filename) then
lineNumber = tonumber(lineNumber);
local codeblock = self.GetCodeBlock();
if(codeblock and codeblock:GetFilename() == filename) then
-- flash the line for 1000 ms
if(not CodeBlockWindow.IsBlocklyEditMode()) then
local ctrl = CodeBlockWindow.GetTextControl();
if(ctrl) then
ctrl:FlashLine(lineNumber, 1000);
end
else
-- TODO for WXA: flash line in blockly editor
end
end
end
end
return locationInfo;
end
function CodeBlockWindow.OnCodeBlockNplBlocklyLineStep(blockid)
if (not NplBlocklyEditorPage) then return end
local G = NplBlocklyEditorPage:GetG();
if (type(G.SetRunBlockId) ~= "function") then return end
G.SetRunBlockId(blockid);
end
function CodeBlockWindow.OnShowEscFrame(bShow)
if(bShow or bShow == nil) then
CodeBlockWindow.SetNplBrowserVisible(false)
end
return bShow;
end
function CodeBlockWindow.OnShowExitDialog(p1)
CodeBlockWindow.SetNplBrowserVisible(false);
return p1;
end
function CodeBlockWindow:OnLayoutRequested(requesterName)
if(requesterName ~= "CodeBlockWindow") then
if(CodeBlockWindow.IsVisible()) then
CodeBlockWindow.Show(false);
end
end
end
function CodeBlockWindow:IsBigCodeWindowSize()
return self.BigCodeWindowSize;
end
function CodeBlockWindow:SetBigCodeWindowSize(enabled)
if(self.BigCodeWindowSize ~= enabled) then
self.BigCodeWindowSize = enabled;
self:OnViewportChange();
end
end
function CodeBlockWindow.ToggleSize()
local self = CodeBlockWindow;
self:SetBigCodeWindowSize(not self:IsBigCodeWindowSize());
end
-- @return width, height, margin_right, margin_bottom, margin_top
function CodeBlockWindow:CalculateMargins()
-- local MAX_3DCANVAS_WIDTH = 800;
local MAX_3DCANVAS_WIDTH = 600;
local MIN_CODEWINDOW_WIDTH = 200+350;
local viewport = ViewportManager:GetSceneViewport();
local width = math.max(math.floor(Screen:GetWidth() * 1/3), MIN_CODEWINDOW_WIDTH);
local halfScreenWidth = math.floor(Screen:GetWidth() * 11 / 20); -- 50% 55%
if(halfScreenWidth > MAX_3DCANVAS_WIDTH) then
width = halfScreenWidth;
elseif((Screen:GetWidth() - width) > MAX_3DCANVAS_WIDTH) then
width = Screen:GetWidth() - MAX_3DCANVAS_WIDTH;
end
local bottom, sceneMarginBottom = 0, 0;
if(viewport:GetMarginBottomHandler() == nil or viewport:GetMarginBottomHandler() == self) then
bottom = 0;
if(self:IsBigCodeWindowSize()) then
local sceneWidth = 300;
width = math.max(Screen:GetWidth() - sceneWidth, MIN_CODEWINDOW_WIDTH);
local sceneBottom = Screen:GetHeight() - math.floor(sceneWidth / 4 * 3);
sceneMarginBottom = math.floor(sceneBottom * (Screen:GetUIScaling()[2]))
end
else
bottom = math.floor(viewport:GetMarginBottom() / Screen:GetUIScaling()[2]);
end
local margin_right = math.floor(width * Screen:GetUIScaling()[1]);
local margin_top = math.floor(viewport:GetTop() / Screen:GetUIScaling()[2]);
return width, Screen:GetHeight()-bottom-margin_top, margin_right, bottom, margin_top, sceneMarginBottom;
end
function CodeBlockWindow:OnViewportChange()
if(CodeBlockWindow.IsVisible()) then
local viewport = ViewportManager:GetSceneViewport();
-- TODO: use a scene/ui layout manager here
local width, height, margin_right, bottom, top, sceneMarginBottom = self:CalculateMargins();
if(self.width ~= width or self.height ~= height) then
self.width = width;
self.height = height;
self.margin_right = margin_right;
self.bottom = bottom;
self.top = top;
viewport:SetMarginRight(self.margin_right);
viewport:SetMarginRightHandler(self);
local _this = ParaUI.GetUIObject(code_block_window_name);
_this:Reposition("_mr", 0, self.top, self.width, self.bottom);
if(page) then
local ctrl = CodeBlockWindow.GetTextControl();
if(ctrl) then
CodeBlockWindow.isTextCtrlHasFocus = ctrl:hasFocus()
end
CodeBlockWindow.UpdateCodeToEntity();
CodeBlockWindow.RestoreCursorPosition()
page:Rebuild();
GameLogic.GetEvents():DispatchEvent({type = "CodeBlockWindowShow" , bShow = true, width = self.width});
end
CodeBlockWindow.ShowNplBlocklyEditorPage();
end
if(sceneMarginBottom ~= viewport:GetMarginBottom())then
if(viewport:GetMarginBottomHandler() == nil or viewport:GetMarginBottomHandler() == self) then
viewport:SetMarginBottom(sceneMarginBottom);
viewport:SetMarginBottomHandler(self);
end
end
if(not CodeBlockWindow.IsBlocklyEditMode() and CodeBlockWindow.isTextCtrlHasFocus) then
CodeBlockWindow.SetFocusToTextControl();
end
end
end
function CodeBlockWindow.OnWorldUnload()
self.lastBlocklyUrl = nil;
self.recentOpenFiles = nil;
end
function CodeBlockWindow.OnWorldSave()
CodeBlockWindow.UpdateCodeToEntity();
CodeBlockWindow.UpdateNplBlocklyCode();
GameLogic.RunCommand("/compile")
end
function CodeBlockWindow.HighlightCodeEntity(entity)
if(self.entity) then
local x, y, z = self.entity:GetBlockPos();
ParaTerrain.SelectBlock(x,y,z, false, groupindex_hint);
end
if(entity) then
local x, y, z = entity:GetBlockPos();
ParaTerrain.SelectBlock(x,y,z, true, groupindex_hint);
end
end
function CodeBlockWindow:OnEntityRemoved()
CodeBlockWindow.SetCodeEntity(nil, nil, true);
end
function CodeBlockWindow:OnCodeChange()
if(not CodeBlockWindow.IsVisible()) then
if(CodeBlockWindow.SetCodeEntity(nil, true, true)) then
return
end
end
if(page) then
page:Refresh(0.01);
commonlib.TimerManager.SetTimeout(CodeBlockWindow.UpdateNPLBlocklyUIFromCode, 200, "CodeBlockWindow_OnCodeChangeTimer")
end
end
function CodeBlockWindow.UpdateNPLBlocklyUIFromCode()
CodeBlockWindow.isUpdatingNPLBlocklyUIFromCode = true;
CodeBlockWindow.ShowNplBlocklyEditorPage();
CodeBlockWindow.isUpdatingNPLBlocklyUIFromCode = false;
end
function CodeBlockWindow.SetFocusToTextControl()
commonlib.TimerManager.SetTimeout(function()
local ctrl = CodeBlockWindow.GetTextControl();
if(ctrl) then
local window = ctrl:GetWindow()
if(window) then
if(not GameLogic.Macros:IsPlaying()) then
window:SetFocus_sys(FocusPolicy.StrongFocus)
window:handleActivateEvent(true);
else
window.isEmulatedFocus = true;
window:handleActivateEvent(true);
window.isEmulatedFocus = nil;
end
end
ctrl:setFocus("OtherFocusReason")
end
end, 400);
end
function CodeBlockWindow.RestoreCursorPositionImp()
commonlib.TimerManager.SetTimeout(function()
local ctrl = CodeBlockWindow.GetTextControl();
if(ctrl) then
if(self.entity and self.entity.cursorPos) then
local cursorPos = self.entity.cursorPos;
ctrl:moveCursor(cursorPos.line, cursorPos.pos, false, true);
if(cursorPos.fromLine) then
ctrl:SetFromLine(cursorPos.fromLine)
else
ctrl:SetFromLine(math.max(1, cursorPos.line-10))
end
end
end
end, 10);
end
function CodeBlockWindow.RestoreCursorPosition(bImmediate)
CodeBlockWindow.RequestRestoreCursor = true;
if(bImmediate) then
if(page) then
page:Refresh(0.01);
end
end
end
function CodeBlockWindow.AddToRecentFiles(entity)
if(entity) then
local bx, by, bz = entity:GetBlockPos()
self.recentOpenFiles = self.recentOpenFiles or {};
local items = self.recentOpenFiles
for i, item in ipairs(items) do
if(item.bx == bx and item.by == by and item.bz==bz) then
-- already exist, shuffle it to the first item
for k=i, 2, -1 do
items[k] = items[k-1]
end
items[1] = item;
return
end
end
for k=#items+1, 2, -1 do
items[k] = items[k-1]
end
items[1] = {bx=bx, by=by, bz=bz};
end
end
-- @return nil or array of recently opened files in format {bx, by, bz}
function CodeBlockWindow.GetRecentOpenFiles()
return self.recentOpenFiles
end
function CodeBlockWindow.SetCodeEntity(entity, bNoCodeUpdate, bDelayRefresh)
CodeBlockWindow.AddToRecentFiles(entity)
CodeBlockWindow.HighlightCodeEntity(entity);
local isEntityChanged = false;
if(self.entity ~= entity) then
if(entity) then
EntityManager.SetLastTriggerEntity(entity);
entity:Connect("beforeRemoved", self, self.OnEntityRemoved, "UniqueConnection");
entity:Connect("editModeChanged", self, self.UpdateEditModeUI, "UniqueConnection");
entity:Connect("remotelyUpdated", self, self.OnCodeChange, "UniqueConnection");
end
if(self.entity) then
local codeBlock = self.entity:GetCodeBlock();
if(not self.entity:IsPowered() and (codeBlock and (codeBlock:IsLoaded() or codeBlock:HasRunningTempCode()))) then
if(not self.entity:IsEntitySameGroup(entity)) then
self.entity:Stop();
end
end
self.entity:Disconnect("beforeRemoved", self, self.OnEntityRemoved);
self.entity:Disconnect("editModeChanged", self, self.UpdateEditModeUI);
self.entity:Disconnect("remotelyUpdated", self, self.OnCodeChange);
if(not bNoCodeUpdate) then
CodeBlockWindow.UpdateCodeToEntity();
end
end
-- 先关闭NPL blockly, 关闭会冲刷代码, 所以一定要在entity切换前关闭
CodeBlockWindow.CloseNplBlocklyEditorPage();
self.entity = entity;
-- 切换实体, 若为blockly编辑模式则重新打开 (npl blocly 已经存在就继续存在)
if (CodeBlockWindow.IsSupportNplBlockly()) then
CodeBlockWindow.OpenBlocklyEditor()
end
CodeBlockWindow.OnTryOpenMicrobit();
CodeBlockWindow.RestoreCursorPosition();
isEntityChanged = true;
end
local codeBlock = self.GetCodeBlock();
if(codeBlock) then
local text = codeBlock:GetLastMessage() or "";
if(text == "" and not CodeBlockWindow.GetMovieEntity()) then
if(self.entity and self.entity:IsCodeEmpty() and self.entity.AutoCreateMovieEntity) then
if(self.entity:AutoCreateMovieEntity()) then
text = L"我们在代码方块旁边自动创建了一个电影方块! 你现在可以用代码控制电影方块中的演员了!";
else
text = L"没有找到电影方块! 请将一个包含演员的电影方块放到代码方块的旁边,就可以用代码控制演员了!";
end
end
end
self.SetConsoleText(text);
codeBlock:Connect("message", self, self.OnMessage, "UniqueConnection");
end
if(isEntityChanged) then
CodeBlockWindow.UpdateCodeEditorStatus()
if(EditCodeActor.GetInstance() and EditCodeActor.GetInstance():GetEntityCode() ~= entity and entity) then
local task = EditCodeActor:new():Init(CodeBlockWindow.GetCodeEntity());
task:Run();
end
self:entityChanged(self.entity);
end
if(not entity) then
CodeBlockWindow.CloseEditorWindow()
end
if(isEntityChanged) then
if(page) then
page:Refresh(bDelayRefresh and 0.01 or 0);
end
end
return isEntityChanged
end
function CodeBlockWindow:OnMessage(msg)
self.SetConsoleText(msg or "");
end
function CodeBlockWindow.GetCodeFromEntity()
if (self.IsSupportNplBlockly()) then
return self.entity:GetNPLBlocklyNPLCode();
end
if(self.entity) then
return self.entity:GetCommand();
end
end
function CodeBlockWindow.GetCodeEntity(bx, by, bz)
if(bx) then
local codeEntity = BlockEngine:GetBlockEntity(bx, by, bz)
if(codeEntity and (codeEntity.class_name == "EntityCode"
or codeEntity.class_name == "EntitySign"
or codeEntity.class_name == "EntityCommandBlock"
or codeEntity.class_name == "EntityCollisionSensor")) then
return codeEntity;
end
else
return CodeBlockWindow.entity;
end
end
function CodeBlockWindow.GetCodeBlock()
if(self.entity) then
return self.entity:GetCodeBlock(true);
end
end
function CodeBlockWindow.GetMovieEntity()
local codeBlock = CodeBlockWindow.GetCodeBlock();
if(codeBlock) then
return codeBlock:GetMovieEntity();
end
end
function CodeBlockWindow.IsVisible()
return page and page:IsVisible();
end
function CodeBlockWindow.Close()
GameLogic.GetCodeGlobal():Disconnect("logAdded", CodeBlockWindow, CodeBlockWindow.AddConsoleText);
CodeBlockWindow:UnloadSceneContext();
CodeBlockWindow.CloseEditorWindow();
CodeBlockWindow.CloseNplBlocklyEditorPage();
CodeBlockWindow.lastBlocklyUrl = nil;
EntityManager.SetLastTriggerEntity(nil);
CodeIntelliSense.Close()
GameLogic.GetEvents():DispatchEvent({type = "CodeBlockWindowShow" , bShow = false});
end
function CodeBlockWindow.CloseEditorWindow()
CodeBlockWindow.RestoreWindowLayout()
CodeBlockWindow.UpdateCodeToEntity();
CodeBlockWindow.HighlightCodeEntity(nil);
local codeBlock = CodeBlockWindow.GetCodeBlock();
if(codeBlock and codeBlock:GetEntity()) then
local entity = codeBlock:GetEntity();
if(entity:IsPowered() and (not codeBlock:IsLoaded() or codeBlock:HasRunningTempCode())) then
entity:Restart();
elseif(not entity:IsPowered() and (codeBlock:IsLoaded() or codeBlock:HasRunningTempCode())) then
entity:Stop();
end
local langConfig = CodeHelpWindow.GetLanguageConfigByEntity(entity)
if(langConfig and langConfig.OnCloseCodeEditor) then
langConfig.OnCloseCodeEditor(entity)
end
end
CodeBlockWindow.SetNplBrowserVisible(false);
end
function CodeBlockWindow.RestoreWindowLayout()
local _this = ParaUI.GetUIObject(code_block_window_name)
if(_this:IsValid()) then
_this.visible = false;
_this:LostFocus();
end
local viewport = ViewportManager:GetSceneViewport();
if(viewport:GetMarginBottomHandler() == self) then
viewport:SetMarginBottomHandler(nil);
viewport:SetMarginBottom(0);
end
if(viewport:GetMarginRightHandler() == self) then
viewport:SetMarginRightHandler(nil);
viewport:SetMarginRight(0);
end
end
function CodeBlockWindow.UpdateCodeToEntity()
if(CodeBlockWindow.updateCodeTimer) then
CodeBlockWindow.updateCodeTimer:Change();
end
local entity = CodeBlockWindow.GetCodeEntity()
if(page and entity) then
local code = page:GetUIValue("code");
if(not entity:IsBlocklyEditMode()) then
if(entity:GetNPLCode() ~= code) then
entity:BeginEdit()
entity:SetNPLCode(code);
entity:EndEdit()
end
local ctl = CodeBlockWindow.GetTextControl();
if(ctl) then
entity.cursorPos = ctl:CursorPos();
if(entity.cursorPos) then
entity.cursorPos.fromLine = ctl:GetFromLine()
end
end
end
end
end
function CodeBlockWindow.DoTextLineWrap(text)
local lines = {};
for line in string.gmatch(text or "", "([^\r\n]*)\r?\n?") do
while (line) do
local remaining_text;
line, remaining_text = _guihelper.TrimUtf8TextByWidth(line, self.width or 300, "System;12;norm");
lines[#lines+1] = line;
line = remaining_text
end
end
return table.concat(lines, "\n");
end
function CodeBlockWindow.SetConsoleText(text)
if(self.console_text ~= text) then
self.console_text = text;
self.console_text_linewrapped = CodeBlockWindow.DoTextLineWrap(self.console_text) or "";
if(page) then
page:SetValue("console", self.console_text_linewrapped);
end
end
end
function CodeBlockWindow:AddConsoleText(text)
if(page) then
local textAreaCtrl = page:FindControl("console");
local textCtrl = textAreaCtrl and textAreaCtrl.ctrlEditbox;
if(textCtrl) then
textCtrl = textCtrl:ViewPort();
if(textCtrl) then
for line in text:gmatch("[^\r\n]+") do
textCtrl:AddItem(line)
end
textCtrl:DocEnd();
end
end
end
end
function CodeBlockWindow.GetConsoleText()
return self.console_text_linewrapped or self.console_text;
end
function CodeBlockWindow.OnClickStart()
GameLogic.RunCommand("/sendevent start");
end
function CodeBlockWindow.OnClickPause()
local codeBlock = CodeBlockWindow.GetCodeBlock();
if(codeBlock) then
codeBlock:Pause();
end
end
function CodeBlockWindow.OnClickStop()
local codeBlock = CodeBlockWindow.GetCodeBlock();
if(codeBlock) then
codeBlock:StopAll();
end
end
function CodeBlockWindow.OnClickCompileAndRun(onFinishedCallback)
ParaUI.GetUIObject("root"):Focus();
local codeEntity = CodeBlockWindow.GetCodeEntity();
if(codeEntity) then
if(codeEntity:GetCodeLanguageType() == "python") then
GameLogic.IsVip("PythonCodeBlock", false, function(result)
if (result) then
CodeBlockWindow.UpdateCodeToEntity();
codeEntity:Restart();
else
GameLogic.AddBBS(nil, L"非VIP用户只能免费运行3次Python语言代码", 15000, "255 0 0")
CodeBlockWindow.python_run_times = (CodeBlockWindow.python_run_times or 0) + 1;
end
end);
else
-- GameLogic.GetFilters():apply_filters("user_event_stat", "code", "execute", nil, nil);
CodeBlockWindow.UpdateCodeToEntity();
CodeBlockWindow.UpdateNplBlocklyCode();
codeEntity:Restart(onFinishedCallback);
end
end
end
function CodeBlockWindow.OnClickCodeActor()
local movieEntity = CodeBlockWindow.GetMovieEntity();
if(movieEntity) then
if(mouse_button=="left") then
local codeBlock = CodeBlockWindow.GetCodeBlock();
if(codeBlock) then
codeBlock:HighlightActors();
local task = EditCodeActor:new():Init(CodeBlockWindow.GetCodeEntity());
task:Run();
end
else
movieEntity:OpenEditor("entity");
end
else
_guihelper.MessageBox(L"没有找到电影方块! 请将一个包含演员的电影方块放到代码方块的旁边,就可以用代码控制演员了!")
end
end
function CodeBlockWindow.OnChangeFilename()
if(self.entity) then
if(page) then
local filename = page:GetValue("filename");
self.entity:SetDisplayName(filename);
local codeBlock = CodeBlockWindow.GetCodeBlock();
if(codeBlock) then
codeBlock:SetModified(true);
end
end
end
end
function CodeBlockWindow.GetFilename()
if(self.entity) then
return self.entity:GetFilename();
end
end
function CodeBlockWindow.RunTempCode(code, filename)
local codeBlock = CodeBlockWindow.GetCodeBlock();
if(codeBlock) then
codeBlock:RunTempCode(code, filename);
end
end
function CodeBlockWindow.ShowHelpWndForCodeName(name)
CodeBlockWindow.ShowHelpWnd("script/apps/Aries/Creator/Game/Code/CodeHelpItemTooltip.html?showclose=true&name="..name);
end
function CodeBlockWindow.RefreshPage(time)
CodeBlockWindow.UpdateCodeToEntity()
if(page) then
page:Refresh(time or 0.01);
end
end
function CodeBlockWindow.ShowHelpWnd(url)
if(url and url~="") then
self.helpWndUrl = url;
self.isShowHelpWnd = true;
if(page) then
page:SetValue("helpWnd", url);
CodeBlockWindow.RefreshPage();
end
else
self.isShowHelpWnd = false;
CodeBlockWindow.RefreshPage();
end
end
function CodeBlockWindow.GetHelpWndUrl()
return self.helpWndUrl;
end
function CodeBlockWindow.IsShowHelpWnd()
return self.isShowHelpWnd;
end
function CodeBlockWindow.OnPreviewPyConversionPage()
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodePyToNplPage.lua");
local CodePyToNplPage = commonlib.gettable("MyCompany.Aries.Game.Code.CodePyToNplPage");
local txt;
if(CodeBlockWindow.IsBlocklyEditMode()) then
txt = CodeBlockWindow.GetCodeFromEntity()
else
local textCtrl = CodeBlockWindow.GetTextControl();
if(textCtrl)then
txt = textCtrl:GetText();
end
end
CodePyToNplPage.ShowPage(txt,function(codes)
end);
end
function CodeBlockWindow.OnChangeModel()
local codeBlock = CodeBlockWindow.GetCodeBlock()
if(codeBlock) then
local actor;
local movieEntity = self.entity:FindNearByMovieEntity()
if(movieEntity and not movieEntity:GetFirstActorStack()) then
movieEntity:CreateNPC();
CodeBlockWindow:GetSceneContext():UpdateCodeBlock();
end
local sceneContext = CodeBlockWindow:GetSceneContext();
if(sceneContext) then
actor = sceneContext:GetActor()
end
actor = actor or codeBlock:GetActor();
if(not actor) then
-- auto create movie block and an NPC entity if no movie actor is found
if(self.entity) then
local movieEntity = self.entity:FindNearByMovieEntity()
if(not movieEntity) then
self.entity:AutoCreateMovieEntity()
movieEntity = self.entity:FindNearByMovieEntity()
end
if(movieEntity and not movieEntity:GetFirstActorStack()) then
movieEntity:CreateNPC();
CodeBlockWindow:GetSceneContext():UpdateCodeBlock();
actor = sceneContext:GetActor();
end
end
end
if(actor) then
actor:SetTime(0);
actor:CreateKeyFromUI("assetfile", function(bIsAdded)
if(bIsAdded) then
-- do something?
end
local movieEntity = self.entity and self.entity:FindNearByMovieEntity()
if(movieEntity) then
movieEntity:MarkForUpdate();
end
if(codeBlock:IsLoaded()) then
CodeBlockWindow.OnClickCompileAndRun();
else
CodeBlockWindow:GetSceneContext():UpdateCodeBlock();
end
end);
end
CodeBlockWindow.SetNplBrowserVisible(false)
end
end
function CodeBlockWindow.OnDragEnd(name)
end
function CodeBlockWindow.IsMousePointerInCodeEditor()
if(page) then
local x, y = Mouse:GetMousePosition()
local textAreaCtrl = page:FindControl("code");
if(textAreaCtrl.window) then
local ctrlX, ctrlY = textAreaCtrl.window:GetScreenPos();
if(ctrlX and x > ctrlX and y>ctrlY) then
return true;
end
end
end
end
-- @return textcontrol, multilineEditBox control.
function CodeBlockWindow.GetTextControl()
if(page) then
local textAreaCtrl = page:FindControl("code");
local textCtrl = textAreaCtrl and textAreaCtrl.ctrlEditbox;
if(textCtrl) then
return textCtrl:ViewPort(), textCtrl;
end
end
end
-- @param bx, by, bz: if not nil, we will only insert when they match the current code block.
function CodeBlockWindow.ReplaceCode(code, bx, by, bz)
if(CodeBlockWindow.IsSameBlock(bx, by, bz)) then
local textCtrl = CodeBlockWindow.GetTextControl();
if(textCtrl) then
textCtrl:SetText(code or "");
return true;
end
else
if(bx and by and bz) then
local codeEntity = CodeBlockWindow.GetCodeEntity(bx, by, bz)
if(codeEntity) then
if(not codeEntity:IsBlocklyEditMode()) then
codeEntity:SetNPLCode(code);
end
return true;
end
end
return false;
end
end
-- @param bx, by, bz: we will return false if they do not match the current block.
-- @return it will also return true if input are nil
function CodeBlockWindow.IsSameBlock(bx, by, bz)
if(bx and by and bz) then
local entity = CodeBlockWindow.GetCodeEntity();
if(entity) then
local cur_bx, cur_by, cur_bz = entity:GetBlockPos();
if(cur_bx==bx and cur_by == by and cur_bz==bz) then
-- same block ready to go
else
return false;
end
end
end
return true;
end
-- @param blockly_xmlcode: xml text for blockly
-- @param code: this is the generated NPL code, should be readonly until we have two way binding.
-- @param bx, by, bz: if not nil, we will only insert when they match the current code block.
function CodeBlockWindow.UpdateBlocklyCode(blockly_xmlcode, code, bx, by, bz)
local codeEntity = CodeBlockWindow.GetCodeEntity(bx, by, bz);
if(codeEntity) then
codeEntity:BeginEdit()
codeEntity:SetBlocklyEditMode(true);
codeEntity:SetBlocklyXMLCode(blockly_xmlcode);
codeEntity:SetBlocklyNPLCode(code);
codeEntity:EndEdit()
if(CodeBlockWindow.IsSameBlock(bx, by, bz)) then
CodeBlockWindow.ReplaceCode(code, bx, by, bz)
end
end
end
-- @param bx, by, bz: if not nil, we will only insert when they match the current code block.
function CodeBlockWindow.InsertCodeAtCurrentLine(code, forceOnNewLine, bx, by, bz)
if(not CodeBlockWindow.IsSameBlock(bx, by, bz) or CodeBlockWindow.IsBlocklyEditMode()) then
return false;
end
if(code and page) then
local textAreaCtrl = page:FindControl("code");
local textCtrl = textAreaCtrl and textAreaCtrl.ctrlEditbox;
if(textCtrl) then
textCtrl = textCtrl:ViewPort();
if(textCtrl) then
local text = textCtrl:GetLineText(textCtrl.cursorLine);
if(text) then
text = tostring(text);
if(forceOnNewLine) then
local newText = "";
if(text:match("%S")) then
-- always start a new line if current line is not empty
textCtrl:LineEnd(false);
textCtrl:InsertTextInCursorPos("\n");
textCtrl:InsertTextInCursorPos(code);
else
textCtrl:InsertTextInCursorPos(code);
end
else
textCtrl:InsertTextInCursorPos(code);
end
-- set focus to control.
if(textAreaCtrl and textAreaCtrl.window) then
textAreaCtrl.window:SetFocus_sys(FocusPolicy.StrongFocus);
textAreaCtrl.window:handleActivateEvent(true)
end
return true;
end
end
end
end
end
function CodeBlockWindow.IsBlocklyEditMode()
local entity = CodeBlockWindow.GetCodeEntity()
if(entity) then
return entity:IsBlocklyEditMode()
end
end
function CodeBlockWindow.UpdateCodeEditorStatus()
local textCtrl = CodeBlockWindow.GetTextControl();
if(textCtrl) then
local bReadOnly = CodeBlockWindow.IsBlocklyEditMode();
textCtrl:setReadOnly(bReadOnly)
end
local entity = CodeBlockWindow.GetCodeEntity()
if(entity) then
CodeHelpWindow.SetLanguageConfigFile(entity:GetLanguageConfigFile(),entity:GetCodeLanguageType());
if (NplBlocklyEditorPage) then CodeBlockWindow.ShowNplBlocklyEditorPage() end
local sceneContext = self:GetSceneContext();
if(sceneContext) then
local langConfig = CodeHelpWindow.GetLanguageConfigByEntity(entity)
-- whether to show bones
local bShowBones = false;
if(langConfig.IsShowBones) then
bShowBones = langConfig.IsShowBones()
end
sceneContext:SetShowBones(bShowBones);
-- custom code block theme
-- local codeUIUrl = CodeBlockWindow.defaultCodeUIUrl;
local codeUIUrl = CodeBlockWindow.GetDefaultCodeUIUrl();
if(langConfig.GetCustomCodeUIUrl) then
codeUIUrl = langConfig.GetCustomCodeUIUrl() or codeUIUrl;
codeUIUrl = Files.FindFile(codeUIUrl)
end
if(page.url ~= codeUIUrl or langConfig.GetCustomToolbarMCML) then
page:Goto(codeUIUrl);
if(langConfig and langConfig.OnOpenCodeEditor) then
langConfig.OnOpenCodeEditor(entity)
end
end
end
end
end
-- default to standard NPL language. One can create domain specific language configuration files.
function CodeBlockWindow.OnClickSelectLanguageSettings()
local entity = CodeBlockWindow.GetCodeEntity()
if(not entity) then
return
end
local old_value = entity:GetLanguageConfigFile();
NPL.load("(gl)script/apps/Aries/Creator/Game/GUI/OpenFileDialog.lua");
local OpenFileDialog = commonlib.gettable("MyCompany.Aries.Game.GUI.OpenFileDialog");
OpenFileDialog.ShowPage('<a class="linkbutton_yellow" href="https://github.com/nplpackages/paracraft/wiki/languageConfigFile">'..L"点击查看帮助"..'</a>', function(result)
if(result) then
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/LanguageConfigurations.lua");
local LanguageConfigurations = commonlib.gettable("MyCompany.Aries.Game.Code.LanguageConfigurations");
if(not LanguageConfigurations:IsBuildinFilename(result)) then
local filename = Files.GetWorldFilePath(result)
if(not filename) then
filename = result:gsub("%.npl$", "");
filename = filename..".npl";
_guihelper.MessageBox(format("是否要新建语言配置文件:%s", filename), function(res)
if(res and res == _guihelper.DialogResult.Yes) then
local fullPath = Files.WorldPathToFullPath(filename);
ParaIO.CopyFile("script/apps/Aries/Creator/Game/Code/Examples/HelloLanguage.npl", fullPath, false);
entity:SetLanguageConfigFile(filename);
CodeBlockWindow.UpdateCodeEditorStatus()
end
end, _guihelper.MessageBoxButtons.YesNo);
_guihelper.MessageBox(L"文件不存在");
return;
end
end
entity:SetLanguageConfigFile(result);
CodeBlockWindow.UpdateCodeEditorStatus()
end
end, old_value or "", L"选择语言配置文件", "npl");
end
function CodeBlockWindow.GetCustomToolbarMCML()
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/LanguageConfigurations.lua");
local LanguageConfigurations = commonlib.gettable("MyCompany.Aries.Game.Code.LanguageConfigurations");
local entity = CodeBlockWindow.GetCodeEntity()
local mcmlText;
if(entity) then
CodeHelpWindow.SetLanguageConfigFile(entity:GetLanguageConfigFile(),entity:GetCodeLanguageType());
mcmlText = LanguageConfigurations:GetCustomToolbarMCML(entity:GetLanguageConfigFile())
end
if(not mcmlText) then
-- testing python conversion
local b_pytonpl = ParaEngine.GetAppCommandLineByParam("pytonpl", false);
if(b_pytonpl == "true")then
mcmlText = string.format([[<div class="mc_item" style="float: left; margin-top:3px;margin-left:5px;width: 34px; height: 34px;">
<pe:mc_block block_id='CodeActor' style="margin-left: 1px; margin-top: 1px; width:32px;height:32px;" onclick="CodeBlockWindow.OnClickCodeActor" tooltip='<%%="%s"%%>' />
</div>
<input type="button" value='<%%="%s"%%>' tooltip='<%%="%s"%%>' onclick="CodeBlockWindow.OnPreviewPyConversionPage" style="margin-left:5px;min-width:80px;margin-top:7px;color:#ffffff;font-size:12px;height:25px;background:url(Texture/Aries/Creator/Theme/GameCommonIcon_32bits.png#179 89 21 21:8 8 8 8)" />
]],
L"左键查看代码方块中的角色, 右键打开电影方块", L"Python", L"python -> npl");
else
mcmlText = string.format([[<div class="mc_item" style="float: left; margin-top:3px;margin-left:5px;width: 34px; height: 34px;">
<pe:mc_block block_id='CodeActor' style="margin-left: 1px; margin-top: 1px; width:32px;height:32px;" onclick="CodeBlockWindow.OnClickCodeActor" tooltip='<%%="%s"%%>' />
</div>
<input type="button" value='<%%="%s"%%>' tooltip='<%%="%s"%%>' onclick="CodeBlockWindow.OnChangeModel" style="margin-left:5px;min-width:80px;margin-top:7px;color:#ffffff;font-size:12px;height:25px;background:url(Texture/Aries/Creator/Theme/GameCommonIcon_32bits.png#179 89 21 21:8 8 8 8)" />
]],
L"左键查看代码方块中的角色, 右键打开电影方块", L"角色模型", L"也可以通过电影方块编辑");
end
end
return mcmlText;
end
function CodeBlockWindow.OnClickEditMode(name,bForceRefresh)
local entity = CodeBlockWindow.GetCodeEntity()
if(not entity) then
return
end
if(CodeBlockWindow.IsBlocklyEditMode()) then
if(name == "codeMode") then
CodeBlockWindow.CloseNplBlocklyEditorPage();
entity:SetBlocklyEditMode(false);
CodeBlockWindow.UpdateCodeEditorStatus();
end
else
if(name == "blockMode") then
CodeBlockWindow.UpdateCodeToEntity();
if(GameLogic.Macros:IsRecording() or GameLogic.Macros:IsPlaying()) then
entity:SetUseNplBlockly(true);
end
entity:SetBlocklyEditMode(true);
CodeBlockWindow.UpdateCodeEditorStatus();
end
end
if(mouse_button == "right") then
CodeBlockWindow.OnClickSelectLanguageSettings()
end
if(name == "blockMode") then
CodeBlockWindow.OpenBlocklyEditor(bForceRefresh);
end
end
function CodeBlockWindow.UpdateEditModeUI()
local textCtrl, multiLineCtrl = CodeBlockWindow.GetTextControl();
if(page and textCtrl) then
if(CodeBlockWindow.IsBlocklyEditMode()) then
_guihelper.SetUIColor(page:FindControl("blockMode"), "#0b9b3a")
_guihelper.SetUIColor(page:FindControl("codeMode"), "#808080")
if(CodeBlockWindow.IsNPLBrowserVisible()) then
CodeBlockWindow.SetNplBrowserVisible(true);
end
multiLineCtrl:SetBackgroundColor("#cccccc")
local tipCtrl = page:FindControl("blocklyTip");
if(tipCtrl) then
tipCtrl.visible = true;
end
else
_guihelper.SetUIColor(page:FindControl("blockMode"), "#808080")
_guihelper.SetUIColor(page:FindControl("codeMode"), "#0b9b3a")
CodeBlockWindow.SetNplBrowserVisible(false);
multiLineCtrl:SetBackgroundColor("#00000000")
local tipCtrl = page:FindControl("blocklyTip");
if(tipCtrl) then
tipCtrl.visible = false;
end
end
textCtrl:SetText(CodeBlockWindow.GetCodeFromEntity());
textCtrl:Connect("userTyped", CodeBlockWindow, CodeBlockWindow.OnUserTypedCode, "UniqueConnection");
textCtrl:Connect("keyPressed", CodeIntelliSense, CodeIntelliSense.OnUserKeyPress, "UniqueConnection");
CodeIntelliSense.Close()
if(CodeBlockWindow.RequestRestoreCursor) then
CodeBlockWindow.RequestRestoreCursor = false;
CodeBlockWindow.RestoreCursorPositionImp()
end
end
end
-- @param bForceRefresh: whether to refresh the content of the browser according to current blockly code. If nil, it will refresh if url has changed.
function CodeBlockWindow.SetNplBrowserVisible(bVisible, bForceRefresh)
if not System.options.enable_npl_brower then
bVisible = false
end
if(page)then
-- block NPL.activate "cef3/NplCefPlugin.dll" if npl browser isn't loaded
-- so that we can running auto updater normally
if(not CodeBlockWindow.NplBrowserIsLoaded())then
return
end
page.isNPLBrowserVisible = bVisible;
if(bVisible and not CodeBlockWindow.temp_nplbrowser_reload)then
-- tricky: this will create the pe:npl_browser control on first use.
CodeBlockWindow.temp_nplbrowser_reload = true;
page:Rebuild();
end
page:CallMethod("nplbrowser_codeblock","SetVisible",bVisible)
if(bVisible) then
if(bForceRefresh == nil) then
if(self.lastBlocklyUrl ~= CodeBlockWindow.GetBlockEditorUrl()) then
self.lastBlocklyUrl = CodeBlockWindow.GetBlockEditorUrl();
bForceRefresh = true;
end
end
if(bForceRefresh) then
page:CallMethod("nplbrowser_codeblock","Reload",CodeBlockWindow.GetBlockEditorUrl());
end
end
local ctl = page:FindControl("browserLoadingTips")
if(ctl) then
ctl.visible = bVisible
end
local ctl = page:FindControl("helpContainer")
if(ctl) then
ctl.visible = not (bVisible == true)
end
local ctl = page:FindControl("codeContainer")
if(ctl) then
ctl.visible = not (bVisible == true)
end
end
end
function CodeBlockWindow.IsNPLBrowserVisible()
return page and page.isNPLBrowserVisible;
end
function CodeBlockWindow.GetBlockEditorUrl()
local blockpos;
local entity = CodeBlockWindow.GetCodeEntity();
local codeLanguageType;
local codeConfigType;
if(entity) then
local bx, by, bz = entity:GetBlockPos();
local langConfig = CodeHelpWindow.GetLanguageConfigByBlockPos(bx,by,bz)
if(langConfig)then
codeConfigType = langConfig.type;
end
if(bz) then
blockpos = format("%d,%d,%d", bx, by, bz);
end
codeLanguageType = entity:GetCodeLanguageType();
end
local request_url = "npl://blockeditor"
if(blockpos) then
request_url = request_url..format("?blockpos=%s&codeLanguageType=%s&codeConfigType=%s", blockpos, codeLanguageType or "npl", codeConfigType or "");
end
if(codeConfigType == "microbit")then
local Microbit = NPL.load("(gl)script/apps/Aries/Creator/Game/Code/Microbit/Microbit.lua");
request_url = Microbit.GetWebEditorUrl();
end
NPL.load("(gl)script/apps/Aries/Creator/Game/Network/NPLWebServer.lua");
local NPLWebServer = commonlib.gettable("MyCompany.Aries.Game.Network.NPLWebServer");
local bStarted, site_url = NPLWebServer.CheckServerStarted(function(bStarted, site_url) end)
if(bStarted) then
return request_url:gsub("^npl:?/*", site_url);
end
end
function CodeBlockWindow.OpenBlocklyEditor(bForceRefresh)
local blockpos;
local entity = CodeBlockWindow.GetCodeEntity();
local codeLanguageType;
local codeConfigType;
if(entity) then
local bx, by, bz = entity:GetBlockPos();
local langConfig = CodeHelpWindow.GetLanguageConfigByBlockPos(bx,by,bz)
if(langConfig)then
codeConfigType = langConfig.type;
end
if(bz) then
blockpos = format("%d,%d,%d", bx, by, bz);
end
codeLanguageType = entity:GetCodeLanguageType();
end
if (CodeBlockWindow.IsSupportNplBlockly()) then
if (NplBlocklyEditorPage) then
CodeBlockWindow.CloseNplBlocklyEditorPage();
if(page) then page:Refresh(0.01); end
else
CodeBlockWindow.ShowNplBlocklyEditorPage();
end
return ;
end
local request_url = "npl://blockeditor"
if(blockpos) then
request_url = request_url..format("?blockpos=%s&codeLanguageType=%s&codeConfigType=%s", blockpos, codeLanguageType or "npl", codeConfigType or "");
end
local bForceShow;
if(codeConfigType == "microbit")then
local Microbit = NPL.load("(gl)script/apps/Aries/Creator/Game/Code/Microbit/Microbit.lua");
request_url = Microbit.GetWebEditorUrl();
bForceShow = true;
end
local function OpenInternalBrowser_()
if(bForceShow or not CodeBlockWindow.IsNPLBrowserVisible()) then
NPL.load("(gl)script/apps/Aries/Creator/Game/Network/NPLWebServer.lua");
local NPLWebServer = commonlib.gettable("MyCompany.Aries.Game.Network.NPLWebServer");
local bStarted, site_url = NPLWebServer.CheckServerStarted(function(bStarted, site_url)
if(bStarted) then
CodeBlockWindow.SetNplBrowserVisible(true,bForceRefresh)
end
end)
else
CodeBlockWindow.SetNplBrowserVisible(false)
end
end
if(not CodeBlockWindow.NplBrowserIsLoaded() and System.options.enable_npl_brower) then
local isDownloading
isDownloading = NplBrowserLoaderPage.Check(function(result)
if(result) then
if(isDownloading) then
_guihelper.CloseMessageBox();
end
if(CodeBlockWindow.IsVisible()) then
OpenInternalBrowser_()
end
end
end)
if(isDownloading) then
_guihelper.MessageBox(L"正在更新图块编程系统,请等待1-2分钟。<br/>如果有杀毒软件提示安全警告请允许。", function(res)
end, _guihelper.MessageBoxButtons.Nothing);
return;
end
end
if(System.os.GetPlatform() == "mac")then
OpenInternalBrowser_();
return
end
if(CodeBlockWindow.NplBrowserIsLoaded() and not Keyboard:IsCtrlKeyPressed())then
OpenInternalBrowser_()
else
GameLogic.RunCommand("/open "..request_url);
end
end
function CodeBlockWindow.OnOpenBlocklyEditor()
CodeBlockWindow.OpenBlocklyEditor()
end
function CodeBlockWindow.GetBlockList()
local blockList = {};
local entity = self.entity;
if(entity and entity.ForEachNearbyCodeEntity) then
entity:ForEachNearbyCodeEntity(function(codeEntity)
blockList[#blockList+1] = {filename = codeEntity:GetFilename() or L"未命名", entity = codeEntity}
end);
table.sort(blockList, function(a, b)
return a.filename < b.filename;
end)
end
return blockList;
end
function CodeBlockWindow.OnOpenTutorials()
CodeHelpWindow.OnClickLearn()
end
function CodeBlockWindow.OpenExternalFile(filename)
local filepath = Files.WorldPathToFullPath(filename);
if(filepath) then
GameLogic.RunCommand("/open npl://editcode?src="..filepath);
end
end
-- Redirect this object as a scene context, so that it will receive all key/mouse events from the scene.
-- as if this task object is a scene context derived class. One can then overwrite
-- `UpdateManipulators` function to add any manipulators.
function CodeBlockWindow:LoadSceneContext()
local sceneContext = self:GetSceneContext();
if(not sceneContext:IsSelected()) then
sceneContext:activate();
sceneContext:SetCodeEntity(CodeBlockWindow.GetCodeEntity());
CameraController.SetFPSMouseUIMode(true, "codeblockwindow");
end
end
function CodeBlockWindow:UnloadSceneContext()
local sceneContext = self:GetSceneContext();
if(sceneContext) then
sceneContext:SetCodeEntity(nil);
end
GameLogic.ActivateDefaultContext();
CameraController.SetFPSMouseUIMode(false, "codeblockwindow");
end
function CodeBlockWindow:GetSceneContext()
if(not self.sceneContext) then
self.sceneContext = AllContext:GetContext("code");
CodeBlockWindow:Connect("entityChanged", self.sceneContext, "SetCodeEntity")
end
return self.sceneContext;
end
function CodeBlockWindow.NplBrowserIsLoaded()
return NplBrowserLoaderPage.IsLoaded();
end
function CodeBlockWindow.OnClickSettings()
if(mouse_button == "left") then
if(CodeBlockWindow.IsNPLBrowserVisible()) then
CodeBlockWindow.SetNplBrowserVisible(false);
end
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeBlockSettings.lua");
local CodeBlockSettings = commonlib.gettable("MyCompany.Aries.Game.Code.CodeBlockSettings");
CodeBlockSettings.Show(true)
else
CodeBlockWindow.GotoCodeBlock()
end
end
function CodeBlockWindow.GotoCodeBlock()
local codeblock = CodeBlockWindow.GetCodeBlock()
if(codeblock) then
local x, y, z = codeblock:GetBlockPos()
if(x and y and z) then
GameLogic.RunCommand(format("/goto %d %d %d", x, y+1, z));
end
end
end
function CodeBlockWindow.OnMouseOverWordChange(word, line, from, to)
CodeIntelliSense.OnMouseOverWordChange(word, line, from, to)
end
function CodeBlockWindow.OnRightClick(event)
local ctrl = CodeBlockWindow.GetTextControl()
if(ctrl) then
local info = ctrl:getMouseOverWordInfo()
if(info and info.word) then
CodeIntelliSense.ShowContextMenuForWord(info.word, info.lineText, info.fromPos, info.toPos)
else
CodeIntelliSense.ShowContextMenuForWord();
end
end
end
function CodeBlockWindow.OnLearnMore()
return CodeIntelliSense.OnLearnMore(CodeBlockWindow.GetTextControl())
end
function CodeBlockWindow.FindTextGlobally()
local ctrl = CodeBlockWindow.GetTextControl()
if(ctrl) then
if(ctrl:hasSelectedText()) then
local text = ctrl:selectedText()
if(text and not text:match("\n")) then
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/FindBlockTask.lua");
local FindBlockTask = commonlib.gettable("MyCompany.Aries.Game.Tasks.FindBlockTask");
local task = MyCompany.Aries.Game.Tasks.FindBlockTask:new()
task:ShowFindFile(text, function(lastGotoItemIndex)
if(not lastGotoItemIndex) then
CodeBlockWindow.SetFocusToTextControl();
end
end)
return true;
end
end
end
end
function CodeBlockWindow:OnUserTypedCode(textCtrl, newChar)
CodeIntelliSense:OnUserTypedCode(textCtrl, newChar)
CodeBlockWindow.updateCodeTimer = CodeBlockWindow.updateCodeTimer or commonlib.Timer:new({callbackFunc = function(timer)
CodeBlockWindow.UpdateCodeToEntity();
end})
CodeBlockWindow.updateCodeTimer:Change(1000, nil);
end
function CodeBlockWindow.IsSupportNplBlockly()
local entity = CodeBlockWindow.GetCodeEntity();
local language = entity and entity:GetCodeLanguageType();
return language ~= "python" and not CodeBlockWindow.IsMicrobitEntity() and entity and type(entity.IsBlocklyEditMode) and type(entity.IsUseNplBlockly) == "function" and entity:IsBlocklyEditMode() and entity:IsUseNplBlockly();
end
function CodeBlockWindow.OnTryOpenMicrobit()
if(CodeBlockWindow.IsMicrobitEntity() and CodeBlockWindow.IsVisible())then
local entity = CodeBlockWindow.GetCodeEntity();
entity:SetBlocklyEditMode(true);
CodeBlockWindow.OpenBlocklyEditor(true);
end
end
function CodeBlockWindow.IsMicrobitEntity()
local entity = CodeBlockWindow.GetCodeEntity();
if(entity)then
local configFile = entity:GetLanguageConfigFile()
if(configFile == "microbit") then
return true;
end
end
end
function CodeBlockWindow.UpdateNplBlocklyCode()
local codeEntity = CodeBlockWindow.GetCodeEntity();
if (not NplBlocklyEditorPage or not codeEntity or CodeBlockWindow.isUpdatingNPLBlocklyUIFromCode) then return end
if (not CodeBlockWindow.IsSupportNplBlockly()) then return end
if (not CodeBlockWindow.IsBlocklyEditMode()) then return print("---------------------------NOT IsBlocklyEditMode---------------------------") end
local G = NplBlocklyEditorPage:GetG();
local code = type(G.GetCode) == "function" and G.GetCode() or "";
local xml = type(G.GetXml) == "function" and G.GetXml() or "";
local hasCodeChanged = codeEntity:GetNPLBlocklyNPLCode() ~= code;
if(hasCodeChanged) then
codeEntity:BeginEdit();
end
codeEntity:SetNPLBlocklyXMLCode(xml);
codeEntity:SetNPLBlocklyNPLCode(code);
if(hasCodeChanged) then
codeEntity:EndEdit();
end
end
function CodeBlockWindow.ShowNplBlocklyEditorPage()
if(CodeBlockWindow.IsNPLBrowserVisible()) then
CodeBlockWindow.SetNplBrowserVisible(false);
end
CodeBlockWindow.CloseNplBlocklyEditorPage();
-- if (NplBlocklyEditorPage) then
-- NplBlocklyEditorPage:CloseWindow();
-- NplBlocklyEditorPage = nil;
-- end
local entity = CodeBlockWindow.GetCodeEntity();
if (not CodeBlockWindow.IsSupportNplBlockly()) then return end
CodeHelpWindow.SetLanguageConfigFile(entity:GetLanguageConfigFile(),entity:GetCodeLanguageType());
local Page = NPL.load("Mod/GeneralGameServerMod/UI/Page.lua", IsDevEnv);
local width, height, margin_right, bottom, top, sceneMarginBottom = self:CalculateMargins();
-- local language = entity:IsUseCustomBlock() and "UserCustomBlock" or entity:GetLanguageConfigFile();
NplBlocklyEditorPage = Page.Show({
-- Language = (language == "npl" or language == "") and "SystemNplBlock" or "npl",
Language = entity:IsUseCustomBlock() and "CustomWorldBlock" or "npl",
xmltext = entity:GetNPLBlocklyXMLCode() or "",
ToolBoxXmlText = entity:GetNplBlocklyToolboxXmlText(),
OnChange = function()
CodeBlockWindow.UpdateNplBlocklyCode();
end,
OnGenerateBlockCodeBefore = function(block)
if (not entity:IsStepMode() or block:IsOutput()) then return end
return "checkstep_nplblockly(" .. block:GetId() ..", true, 0.5)\n";
end,
OnGenerateBlockCodeAfter = function(block)
if (not entity:IsStepMode() or block:IsOutput()) then return end
return "checkstep_nplblockly(0, false, 0)\n";
end,
}, {
url = "%ui%/Blockly/Pages/NplBlockly.html",
alignment="_rt",
x = 0, y = 45 + top,
height = height - 45 - 54,
width = width,
isAutoScale = false,
windowName = "UICodeBlockWindow",
minRootScreenWidth = 0,
minRootScreenHeight = 0,
zorder = -2,
});
end
function CodeBlockWindow.CloseNplBlocklyEditorPage()
if (not NplBlocklyEditorPage) then return end
CodeBlockWindow.UpdateNplBlocklyCode();
NplBlocklyEditorPage:CloseWindow();
NplBlocklyEditorPage = nil;
end
function CodeBlockWindow.SetFontSize(value)
CodeBlockWindow.fontSize = value or 13;
if(page) then
page:Refresh(0.01);
end
end
function CodeBlockWindow.GetFontSize()
return CodeBlockWindow.fontSize or 13;
end
function CodeBlockWindow.OnClickShowConsoleText()
ChatWindow.ShowAllPage();
ChatWindow.HideEdit();
ChatWindow.OnSwitchChannelDisplay(ChatChannel.EnumChannels.NearBy);
end
function CodeBlockWindow.OnClickHideConsoleText()
ChatWindow.HideChatLog();
end
function CodeBlockWindow.OnClickClearConsoleText()
CodeBlockWindow.SetConsoleText("");
ChatChannel.ClearChat(ChatChannel.EnumChannels.NearBy);
ChatWindow.OnSwitchChannelDisplay("0");
end
function CodeBlockWindow.OnChatLogWindowShowAndHide(bShow)
CodeBlockWindow.bShowChatLogWindow = bShow;
if(page) then page:Refresh(0.01) end
end
CodeBlockWindow:InitSingleton();
| gpl-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Tasks/MakeAppTask.lua | 1 | 63527 | --[[
Title: make app Command
Author(s): LiXizhi,big
CreateDate: 2020.4.23
ModifyDate: 2022.3.2
Desc: make current world into a standalone app file (zip)
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/MakeAppTask.lua");
local MakeApp = commonlib.gettable("MyCompany.Aries.Game.Tasks.MakeApp");
local task = MyCompany.Aries.Game.Tasks.MakeApp:new()
task:Run();
-------------------------------------------------------
]]
--------- thread part start ---------
NPL.load("(gl)script/ide/commonlib.lua")
NPL.load("(gl)script/ide/System/Concurrent/rpc.lua")
local rpc = commonlib.gettable("System.Concurrent.Async.rpc")
rpc:new():init(
"MyCompany.Aries.Game.Tasks.MakeAppThread.AndroidSignApk",
function(self, msg)
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/MakeAppTask.lua");
local MakeApp = commonlib.gettable("MyCompany.Aries.Game.Tasks.MakeApp");
MakeApp:AndroidSignApkThread();
return true;
end,
"script/apps/Aries/Creator/Game/Tasks/MakeAppTask.lua"
)
rpc:new():init(
"MyCompany.Aries.Game.Tasks.MakeAppThread.AndroidZipAlignApk",
function(self, msg)
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/MakeAppTask.lua");
local MakeApp = commonlib.gettable("MyCompany.Aries.Game.Tasks.MakeApp");
MakeApp:AndroidZipAlignApkThread();
return true;
end,
"script/apps/Aries/Creator/Game/Tasks/MakeAppTask.lua"
)
rpc:new():init(
"MyCompany.Aries.Game.Tasks.MakeAppThread.AndroidDecodeApk",
function(self, msg)
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/MakeAppTask.lua");
local MakeApp = commonlib.gettable("MyCompany.Aries.Game.Tasks.MakeApp");
MakeApp:AndroidDecodeApkThread();
return true;
end,
"script/apps/Aries/Creator/Game/Tasks/MakeAppTask.lua"
)
rpc:new():init(
"MyCompany.Aries.Game.Tasks.MakeAppThread.AndroidGenerateApk",
function(self, msg)
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/MakeAppTask.lua");
local MakeApp = commonlib.gettable("MyCompany.Aries.Game.Tasks.MakeApp");
MakeApp:AndroidGenerateApkThread();
return true;
end,
"script/apps/Aries/Creator/Game/Tasks/MakeAppTask.lua"
)
--------- thread part end ---------
NPL.load("(gl)script/apps/Aries/Creator/Game/Common/Files.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/API/FileDownloader.lua");
NPL.load("(gl)script/ide/System/Encoding/crc32.lua");
local Encoding = commonlib.gettable("System.Encoding");
local FileDownloader = commonlib.gettable("MyCompany.Aries.Creator.Game.API.FileDownloader");
local Files = commonlib.gettable("MyCompany.Aries.Game.Common.Files");
local WorldCommon = commonlib.gettable("MyCompany.Aries.Creator.WorldCommon")
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local MakeApp = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.Task"), commonlib.gettable("MyCompany.Aries.Game.Tasks.MakeApp"));
MakeApp.mode = {
android = 0,
UI = 1,
}
MakeApp.curAndroidVersion = "2.0.20";
MakeApp.androidBuildRoot = "temp/build_android_resource/";
MakeApp.iOSBuildRoot = "temp/build_ios_resource/";
MakeApp.iOSResourceBaseCDN = "https://cdn.keepwork.com/paracraft/ios/";
MakeApp.xcodePath = ""
function MakeApp:ctor()
end
function MakeApp:Run(...)
local platform = System.os.GetPlatform();
if (platform == "win32" or platform == "mac") then
self:RunImp(...);
else
_guihelper.MessageBox(L"此功能暂不支持该操作系统");
end
end
function MakeApp:RunImp(mode, ...)
local platform = System.os.GetPlatform();
if (mode == self.mode.UI) then
System.App.Commands.Call(
"File.MCMLWindowFrame",
{
url = "script/apps/Aries/Creator/Game/Tasks/MakeApp.html",
name = "Tasks.MakeApp",
isShowTitleBar = false,
DestroyOnClose = true, -- prevent many ViewProfile pages staying in memory
style = CommonCtrl.WindowFrame.ContainerStyle,
zorder = 0,
allowDrag = true,
bShow = nil,
directPosition = true,
align = "_ct",
x = -300,
y = -225,
width = 600,
height = 460,
cancelShowAnimation = true,
bToggleShowHide = true,
enable_esc_key = true
}
)
else
if (platform == "win32") then
if (mode == self.mode.android) then
if (not MakeApp.localAndroidVersion) then
if (ParaIO.DoesFileExist(MakeApp.androidBuildRoot .. "version.txt")) then
local readFile = ParaIO.open(MakeApp.androidBuildRoot .. "version.txt", "r");
if (readFile:IsValid()) then
local version = readFile:GetText(0, -1);
readFile:close();
MakeApp.localAndroidVersion = version;
end
end
end
local method = ...;
GameLogic.IsVip("MakeApk", true, function(result)
if (result) then
self:MakeAndroidApp(method);
end
end)
else
self:MakeWindows();
end
elseif (platform == "mac") then
end
end
end
-- windows
function MakeApp:MakeWindows()
local name = WorldCommon.GetWorldTag("name");
self.name = name;
local dirName = commonlib.Encoding.Utf8ToDefault(name);
self.dirName = dirName;
local output_folder = ParaIO.GetWritablePath() .. "release/" .. dirName .. "/";
self.output_folder = output_folder;
_guihelper.MessageBox(format(L"是否将世界%s 发布为独立应用程序?", self.name), function(res)
if(res and res == _guihelper.DialogResult.Yes) then
self:MakeApp();
end
end, _guihelper.MessageBoxButtons.YesNo);
end
function MakeApp:MakeApp()
if(self:GenerateFiles()) then
if(self:MakeZipInstaller()) then
GameLogic.AddBBS(nil, L"恭喜!成功打包为独立应用程序", 5000, "0 255 0")
System.App.Commands.Call("File.WinExplorer", self:GetOutputDir());
return true;
end
end
end
function MakeApp:GetOutputDir()
return self.output_folder;
end
function MakeApp:GetBinDir()
return self.output_folder .. "bin/"
end
function MakeApp:GenerateFiles()
ParaIO.CreateDirectory(self:GetBinDir())
if(self:MakeStartupExe() and self:CopyWorldFiles() and self:GenerateHelpFile()) then
if(self:CopyParacraftFiles()) then
return true;
end
end
end
function MakeApp:GetBatFile()
return self.output_folder .. "start" .. ".bat";
end
function MakeApp:MakeStartupExe()
local file = ParaIO.open(self:GetBatFile(), "w")
if(file:IsValid()) then
file:WriteString("@echo off\n");
file:WriteString("cd bin\n");
local worldPath = Files.ResolveFilePath(GameLogic.GetWorldDirectory()).relativeToRootPath or GameLogic.GetWorldDirectory()
file:WriteString("start ParaEngineClient.exe noupdate=\"true\" IsAppVersion=\"true\" mc=\"true\" bootstrapper=\"script/apps/Aries/main_loop.lua\" world=\"%~dp0data/\"");
file:close();
return true;
end
end
function MakeApp:GenerateHelpFile()
local file = ParaIO.open(self.output_folder..commonlib.Encoding.Utf8ToDefault(L"使用指南")..".html", "w")
if(file:IsValid()) then
file:WriteString([[<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<META HTTP-EQUIV="Refresh" CONTENT="1; URL=https://keepwork.com/official/docs/tutorials/exe_Instruction">
<title>Paracraft App</title>
</head>
<body>
<p>Powered by NPL and paracraft</p>
<p>Page will be redirected in 3 seconds</p>
</body>
</html>
]]);
file:close();
return true;
end
end
local excluded_files = {
["log.txt"] = true,
["paracraft.exe"] = true,
["haqilauncherkids.exe"] = true,
["haqilauncherkids.mem.exe"] = true,
["auto_update_log.txt"] = true,
["assets.log"] = true,
}
-- minimum paracraft files
local bin_files = {
["ParaEngineClient.exe"] = true,
["ParaEngineClient.dll"] = true,
["physicsbt.dll"] = true,
["ParaEngine.sig"] = true,
["lua.dll"] = true,
["FreeImage.dll"] = true,
["libcurl.dll"] = true,
["sqlite.dll"] = true,
["assets_manifest.txt"] = true,
["config/bootstrapper.xml"] = true,
["config/GameClient.config.xml"] = true,
["config/commands.xml"] = true,
["config/config.txt"] = true,
["caudioengine.dll"] = true,
["config.txt"] = true,
["d3dx9_43.dll"] = true,
["main.pkg"] = true,
["main_mobile_res.pkg"] = true,
["main150727.pkg"] = true,
["openal32.dll"] = true,
["wrap_oal.dll"] = true,
["database/characters.db"] = true,
["database/extendedcost.db.mem"] = true,
["database/globalstore.db.mem"] = true,
["database/apps.db"] = true,
["npl_packages/paracraftbuildinmod.zip"] = true,
}
function MakeApp:CopyParacraftFiles()
local redist_root = self:GetBinDir();
ParaIO.DeleteFile(redist_root)
local sdk_root = ParaIO.GetCurDirectory(0);
for filename, _ in pairs(bin_files) do
ParaIO.CreateDirectory(sdk_root..filename);
ParaIO.CopyFile(sdk_root..filename, redist_root..filename, true)
end
return true;
end
function MakeApp:CopyWorldFiles()
WorldCommon.CopyWorldTo(self.output_folder.."data/")
return true
end
function MakeApp:GetZipFile()
return self.output_folder..self.dirName..".zip"
end
function MakeApp:MakeZipInstaller()
local output_folder = self.output_folder;
local result = commonlib.Files.Find({}, self.output_folder, 10, 5000, function(item)
return true;
--no need to check zipfile
--[[
local ext = commonlib.Files.GetFileExtension(item.filename);
if(ext) then
return (ext ~= "zip")
end
]]
end)
local zipfile = self:GetZipFile();
ParaIO.DeleteFile(zipfile)
local writer = ParaIO.CreateZip(zipfile,"");
local appFolder = "ParacraftApp/";
for i, item in ipairs(result) do
local filename = item.filename;
if(filename) then
-- add all files
local destFolder = (appFolder..filename):gsub("[/\\][^/\\]+$", "");
writer:AddDirectory(destFolder, output_folder..filename, 0);
end
end
writer:close();
LOG.std(nil, "info", "MakeZipInstaller", "successfully generated package to %s", commonlib.Encoding.DefaultToUtf8(zipfile))
return true;
end
-- android
function MakeApp:AndroidDecodeApk(callback)
if not callback or type(callback) ~= "function" then
return
end
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在解压APK,请稍候...", 120000, nil, 350);
MyCompany.Aries.Game.Tasks.MakeAppThread.AndroidDecodeApk(
"(worker_android_decode_apk)",
{},
function(err, msg)
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
ParaIO.DeleteFile("temp/worker_android_decode_apk_temp.bat");
ParaIO.DeleteFile("temp/main_temp.bat");
callback()
end
)
end
function MakeApp:AndroidDecodeApkThread()
System.os.run(
"temp\\build_android_resource\\jre-windows\\bin\\java -jar " ..
self.androidBuildRoot .. "apktool.jar d " ..
self.androidBuildRoot .. "paracraft_ver" .. self.curAndroidVersion .. ".apk -o " ..
self.androidBuildRoot .. "paracraft_ver" .. self.curAndroidVersion
);
end
function MakeApp:AndroidDownloadApk(callback)
local apkUrl = "https://cdn.keepwork.com/paracraft/android/paracraft_" .. self.curAndroidVersion .. ".apk";
local fileDownloader = FileDownloader:new();
fileDownloader.isSilent = true;
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在获取基础文件,请稍候...", 120000, nil, 350);
local apkFile = self.androidBuildRoot .. "paracraft_ver" .. self.curAndroidVersion .. ".apk";
if (not ParaIO.DoesFileExist(apkFile)) then
commonlib.TimerManager.SetTimeout(function()
fileDownloader:Init("paracraft.apk", apkUrl, apkFile, function(result)
if (result) then
fileDownloader:DeleteCacheFile();
ParaIO.DeleteFile(self.androidBuildRoot .. "version.txt");
local writeFile = ParaIO.open(self.androidBuildRoot .. "version.txt", "w");
if (writeFile:IsValid()) then
writeFile:write(self.curAndroidVersion, #self.curAndroidVersion);
writeFile:close();
MakeApp.localAndroidVersion = self.curAndroidVersion;
end
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
if (callback and type(callback) == "function") then
callback();
end
end
end)
end, 500);
else
callback()
end
end
function MakeApp:AndroidUpdateManifest(callback)
if (not callback or type(callback) ~= "function") then
return
end
GameLogic.GetFilters():apply_filters(
"cellar.common.msg_box.show",
L"正在更新Manifest,请稍候...",
120000,
nil,
350
);
local currentEnterWorld = GameLogic.GetFilters():apply_filters("store_get", "world/currentEnterWorld");
local fileRead = ParaIO.open(self.androidBuildRoot .. "paracraft_ver2.0.20/AndroidManifest.xml", "r");
local content = "";
local appName = "";
if (currentEnterWorld.name and type(currentEnterWorld.name) == "string") then
appName = currentEnterWorld.name;
else
appName = currentEnterWorld.foldername;
end
if (fileRead:IsValid()) then
local line = "";
while (line) do
line = fileRead:readline();
if (line) then
if (string.match(line, "(.+package%=)%\"")) then
local packageName = string.match(line, ".+package%=%\"([a-z.]+)%\"")
local newPackageName = "com.paraengine.paracraft.world.c" .. Encoding.crc32(currentEnterWorld.foldername)
if (packageName) then
line = line:gsub(packageName, newPackageName)
end
content = content .. line .. "\n";
elseif (string.match(line, "(.+android:label%=)%\"")) then
local labelName = string.match(line, ".+android%:label%=%\"([a-z.@/_]+)%\"")
local newLabelName = appName
if (labelName) then
line = line:gsub(labelName, newLabelName)
end
content = content .. line .. "\n";
else
content = content .. line .. "\n";
end
end
end
fileRead:close();
end
local writeFile = ParaIO.open(self.androidBuildRoot .. "paracraft_ver2.0.20/AndroidManifest.xml", "w");
if (writeFile:IsValid()) then
writeFile:write(content, #content);
writeFile:close();
end
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
callback();
end
function MakeApp:AndroidGenerateApk(callback)
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在生成APK,请稍候...", 120000, nil, 350);
MyCompany.Aries.Game.Tasks.MakeAppThread.AndroidGenerateApk(
"(worker_android_generate_apk)",
{},
function(err, msg)
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
ParaIO.DeleteFile("temp/worker_android_generate_apk_temp.bat");
ParaIO.DeleteFile("temp/main_temp.bat");
callback();
end
)
end
function MakeApp:AndroidGenerateApkThread()
System.os.run(
"temp\\build_android_resource\\jre-windows\\bin\\java -jar " ..
self.androidBuildRoot .. "apktool.jar b " ..
self.androidBuildRoot .. "paracraft_ver" .. self.curAndroidVersion .. " -o " ..
self.androidBuildRoot .. "paracraft_ver" .. self.curAndroidVersion .. "_build_temp.apk"
);
end
function MakeApp:AndroidCopyWorld(compress, beAutoUpdate, beAutoUpdateWorld, loginEnable, callback)
GameLogic.GetFilters():apply_filters(
"cellar.common.msg_box.show",
L"正在拷贝世界,请稍候...",
120000,
nil,
350
);
local currentEnterWorld = GameLogic.GetFilters():apply_filters("store_get", "world/currentEnterWorld");
if (currentEnterWorld and type(currentEnterWorld) == "table") then
if (compress) then
-- copy world
local fileList = GameLogic.GetFilters():apply_filters("service.local_service.load_files", currentEnterWorld.worldpath, true, true);
if not fileList or type(fileList) ~= "table" or #fileList == 0 then
return;
end
for key, item in ipairs(fileList) do
if item.filename == "icon.png" then
local worldIcon = item.file_path;
ParaIO.CreateDirectory(self.androidBuildRoot .. "backup/");
local drawableHdpiIconPath =
self.androidBuildRoot ..
"paracraft_ver" .. self.curAndroidVersion ..
"/res/drawable-hdpi/ic_launcher.png";
local drawableXhdpiIconPath =
self.androidBuildRoot ..
"paracraft_ver" .. self.curAndroidVersion ..
"/res/drawable-xhdpi/ic_launcher.png";
local drawableXxhdpiIconPath =
self.androidBuildRoot ..
"paracraft_ver" .. self.curAndroidVersion ..
"/res/drawable-xxhdpi/ic_launcher.png";
local drawableHdpiBackupIconPath = self.androidBuildRoot .. "backup/drawable_hdpi_icon.png";
local drawableXhdpiBackupIconPath = self.androidBuildRoot .. "backup/drawable_xhdpi_icon.png";
local drawableXxhdpiBackupIconPath = self.androidBuildRoot .. "backup/drawable_xxhdpi_icon.png";
if (not ParaIO.DoesFileExist(drawableHdpiBackupIconPath)) then
ParaIO.CopyFile(drawableHdpiIconPath, drawableHdpiV4BackupIconPath, true);
end
if (not ParaIO.DoesFileExist(drawableXhdpiBackupIconPath)) then
ParaIO.CopyFile(drawableXhdpiIconPath, drawableXhdpiV4BackupIconPath, true);
end
if (not ParaIO.DoesFileExist(drawableXxhdpiBackupIconPath)) then
ParaIO.CopyFile(drawableXxhdpiIconPath, drawableXxhdpiV4BackupIconPath, true);
end
ParaIO.CopyFile(worldIcon, drawableHdpiIconPath, true);
ParaIO.CopyFile(worldIcon, drawableXhdpiIconPath, true);
ParaIO.CopyFile(worldIcon, drawableXxhdpiIconPath, true);
break;
end
end
local apkWorldPath =
self.androidBuildRoot ..
"paracraft_ver" ..
self.curAndroidVersion ..
"/assets/worlds/DesignHouse/" ..
commonlib.Encoding.Utf8ToDefault(currentEnterWorld.foldername) .. "/" ..
commonlib.Encoding.Utf8ToDefault(currentEnterWorld.foldername) .. "/";
ParaIO.CreateDirectory(apkWorldPath);
for key, item in ipairs(fileList) do
local relativePath = commonlib.Encoding.Utf8ToDefault(item.filename);
if item.filesize == 0 then
local folderPath = apkWorldPath .. relativePath .. "/";
ParaIO.CreateDirectory(folderPath);
else
local filePath = apkWorldPath .. relativePath;
ParaIO.CopyFile(item.file_path, filePath, true);
end
end
local apkWorldPath1 =
self.androidBuildRoot ..
"paracraft_ver" ..
self.curAndroidVersion ..
"/assets/worlds/DesignHouse/" ..
commonlib.Encoding.Utf8ToDefault(currentEnterWorld.foldername) .. "/";
GameLogic.GetFilters():apply_filters(
"service.local_service.move_folder_to_zip",
apkWorldPath1,
self.androidBuildRoot ..
"paracraft_ver" ..
self.curAndroidVersion ..
"/assets/worlds/DesignHouse/" ..
commonlib.Encoding.Utf8ToDefault(currentEnterWorld.foldername) .. ".zip",
function()
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
-- update config.txt file
local writeFile =
ParaIO.open(
self.androidBuildRoot ..
"paracraft_ver" ..
self.curAndroidVersion ..
"/assets/config.txt",
"w"
);
if (writeFile:IsValid()) then
local content =
"cmdline=mc=\"true\" debug=\"main\" IsAppVersion=\"true\" bootstrapper=\"script/apps/Aries/main_loop.lua\" " ..
"world=\"" .. "worlds/DesignHouse/" .. currentEnterWorld.foldername .. ".zip\"";
if (not beAutoUpdate) then
content = content .. " noclientupdate=\"true\"";
end
if (beAutoUpdateWorld) then
content = content .. " auto_update_world=\"true\"";
end
if (loginEnable) then
content = content .. " login_enable=\"true\"";
end
writeFile:write(content, #content);
writeFile:close();
end
ParaIO.DeleteFile(apkWorldPath1);
if (callback and type(callback) == "function") then
callback();
end
end
)
else
-- copy world
local fileList =
GameLogic.GetFilters():apply_filters(
"service.local_service.load_files",
currentEnterWorld.worldpath,
true,
true
);
if not fileList or type(fileList) ~= "table" or #fileList == 0 then
return;
end
for key, item in ipairs(fileList) do
if item.filename == "icon.png" then
local worldIcon = item.file_path;
ParaIO.CreateDirectory(self.androidBuildRoot .. "backup/");
local drawableHdpiIconPath =
self.androidBuildRoot ..
"paracraft_ver" ..
self.curAndroidVersion ..
"/res/drawable-hdpi/ic_launcher.png";
local drawableXhdpiIconPath =
self.androidBuildRoot ..
"paracraft_ver" .. self.curAndroidVersion ..
"/res/drawable-xhdpi/ic_launcher.png";
local drawableXxhdpiIconPath =
self.androidBuildRoot ..
"paracraft_ver" ..
self.curAndroidVersion ..
"/res/drawable-xxhdpi/ic_launcher.png";
local drawableHdpiBackupIconPath = self.androidBuildRoot .. "backup/drawable_hdpi_icon.png";
local drawableXhdpiBackupIconPath = self.androidBuildRoot .. "backup/drawable_xhdpi_icon.png";
local drawableXxhdpiBackupIconPath = self.androidBuildRoot .. "backup/drawable_xxhdpi_icon.png";
if (not ParaIO.DoesFileExist(drawableHdpiBackupIconPath)) then
ParaIO.CopyFile(drawableHdpiIconPath, drawableHdpiBackupIconPath, true);
end
if (not ParaIO.DoesFileExist(drawableXhdpiBackupIconPath)) then
ParaIO.CopyFile(drawableXhdpiIconPath, drawableXhdpiBackupIconPath, true);
end
if (not ParaIO.DoesFileExist(drawableXxhdpiBackupIconPath)) then
ParaIO.CopyFile(drawableXxhdpiIconPath, drawableXxhdpiBackupIconPath, true);
end
ParaIO.CopyFile(worldIcon, drawableHdpiIconPath, true);
ParaIO.CopyFile(worldIcon, drawableXhdpiIconPath, true);
ParaIO.CopyFile(worldIcon, drawableXxhdpiIconPath, true);
break;
end
end
local apkWorldPath =
self.androidBuildRoot ..
"paracraft_ver" ..
self.curAndroidVersion ..
"/assets/worlds/DesignHouse/" ..
commonlib.Encoding.Utf8ToDefault(currentEnterWorld.foldername) .. "/";
ParaIO.CreateDirectory(apkWorldPath);
for key, item in ipairs(fileList) do
local relativePath = commonlib.Encoding.Utf8ToDefault(item.filename);
if item.filesize == 0 then
local folderPath = apkWorldPath .. relativePath .. "/";
ParaIO.CreateDirectory(folderPath);
else
local filePath = apkWorldPath .. relativePath;
ParaIO.CopyFile(item.file_path, filePath, true);
end
end
-- update config.txt file
local writeFile = ParaIO.open(self.androidBuildRoot .. "paracraft_ver" .. self.curAndroidVersion .."/assets/config.txt", "w");
if (writeFile:IsValid()) then
local content =
"cmdline=mc=\"true\" debug=\"main\" IsAppVersion=\"true\" bootstrapper=\"script/apps/Aries/main_loop.lua\" " ..
"world=\"" .. "worlds/DesignHouse/" .. currentEnterWorld.foldername .. "\"";
if (not beAutoUpdate) then
content = content .. " noclientupdate=\"true\"";
end
if (beAutoUpdateWorld) then
content = content .. " auto_update_world=\"true\"";
end
if (loginEnable) then
content = content .. " login_enable=\"true\"";
end
writeFile:write(content, #content);
writeFile:close();
end
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
if (callback and type(callback) == "function") then
callback();
end
end
end
end
function MakeApp:AndroidDownloadTools(callback)
if not callback or type(callback) ~= "function" then
return;
end
local host = "https://cdn.keepwork.com/paracraft/android"
local function downloadJre(callback)
if (not ParaIO.DoesFileExist(self.androidBuildRoot .. "jre-windows/")) then
local jreTool = host .. "/jre-windows.zip";
local fileDownloader = FileDownloader:new();
fileDownloader.isSilent = true;
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在获取Jre Runtime,请稍候...", 120000, nil, 400)
commonlib.TimerManager.SetTimeout(function()
fileDownloader:Init("jre-windows.zip", jreTool, self.androidBuildRoot .. "jre-windows.zip", function(result)
if (result) then
fileDownloader:DeleteCacheFile();
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在解压Jre Runtime,请稍候...", 120000, nil, 400);
GameLogic.GetFilters():apply_filters(
"service.local_service.move_zip_to_folder",
self.androidBuildRoot .. "jre-windows/",
self.androidBuildRoot .. "jre-windows.zip",
function()
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
callback()
end
)
end
end)
end, 500)
else
callback()
end
end
local function downloadApkTool(callback)
if (not ParaIO.DoesFileExist(self.androidBuildRoot .. "apktool.jar")) then
local apkTool = host .. "/apktool.jar"
local fileDownloader = FileDownloader:new();
fileDownloader.isSilent = true;
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在获取ApkTool,请稍候...", 120000, nil, 400)
commonlib.TimerManager.SetTimeout(function()
fileDownloader:Init("apktool.jar", apkTool, self.androidBuildRoot .. "apktool.jar", function(result)
if (result) then
fileDownloader:DeleteCacheFile();
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
callback()
end
end)
end, 500)
else
callback()
end
end
local function downloadAndroidSDKBuildTool(callback)
if (not ParaIO.DoesFileExist(self.androidBuildRoot .. "android-sdk-build-tools-32.0.0/")) then
local androidSDKBuildTool = host .. "/android-sdk-build-tools-32.0.0.zip"
local fileDownloader = FileDownloader:new();
fileDownloader.isSilent = true;
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在获取Android SDK Build Tool,请稍候...", 120000, nil, 400)
commonlib.TimerManager.SetTimeout(function()
fileDownloader:Init("android-sdk-build-tools-32.0.0.zip", androidSDKBuildTool, self.androidBuildRoot .. "android-sdk-build-tools-32.0.0.zip", function(result)
if (result) then
fileDownloader:DeleteCacheFile();
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在解压Android SDK Build Tool,请稍候...", 120000, nil, 400);
GameLogic.GetFilters():apply_filters(
"service.local_service.move_zip_to_folder",
self.androidBuildRoot .. "android-sdk-build-tools-32.0.0/",
self.androidBuildRoot .. "android-sdk-build-tools-32.0.0.zip",
function()
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
callback()
end
)
end
end)
end, 500)
else
callback()
end
end
downloadJre(function()
downloadApkTool(function()
downloadAndroidSDKBuildTool(function()
callback()
end)
end)
end)
end
function MakeApp:AndroidSignApkWrapper(callback)
if (not ParaIO.DoesFileExist(self.androidBuildRoot .. "personal-key.keystore")) then
local function downloadLicense(downloadCallback)
local keystore = "https://cdn.keepwork.com/paracraft/android/personal-key.keystore";
local fileDownloader = FileDownloader:new();
fileDownloader.isSilent = true;
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在获取Certification,请稍候...", 120000, nil, 400);
commonlib.TimerManager.SetTimeout(function()
fileDownloader:Init("personal-key.keystore", keystore, self.androidBuildRoot .. "personal-key.keystore", function(result)
if (result) then
fileDownloader:DeleteCacheFile();
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
if downloadCallback and type(downloadCallback) == "function" then
downloadCallback();
end
end
end)
end, 500)
end
downloadLicense(function()
self:AndroidZipAlignApk(function()
self:AndroidSignApk(callback)
end)
end)
else
self:AndroidZipAlignApk(function()
self:AndroidSignApk(callback)
end)
end
end
function MakeApp:AndroidZipAlignApk(callback)
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在对齐APK,请稍候...", 120000, nil, 350);
MyCompany.Aries.Game.Tasks.MakeAppThread.AndroidZipAlignApk(
"(worker_android_zip_align_apk)",
{},
function(err, msg)
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
ParaIO.DeleteFile("temp/worker_android_zip_align_apk_temp.bat");
ParaIO.DeleteFile("temp/main_temp.bat");
if callback and type(callback) == "function" then
callback();
end
end
)
end
function MakeApp:AndroidZipAlignApkThread()
System.os.run(
"temp\\build_android_resource\\android-sdk-build-tools-32.0.0\\32.0.0\\zipalign.exe -p -f -v 4 " ..
self.androidBuildRoot .. "paracraft_ver" .. self.curAndroidVersion .. "_build_temp.apk " ..
self.androidBuildRoot .. "paracraft_ver" .. self.curAndroidVersion .. "_align_temp.apk"
);
ParaIO.DeleteFile(self.androidBuildRoot .. "paracraft_ver" .. self.curAndroidVersion .. "_build_temp.apk");
end
function MakeApp:AndroidSignApk(callback)
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在签名APK,请稍候...", 120000, nil, 350);
MyCompany.Aries.Game.Tasks.MakeAppThread.AndroidSignApk(
"(worker_android_sign_apk)",
{},
function(err, msg)
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
_guihelper.MessageBox(L"APK已生成(" .. self.androidBuildRoot .. "paracraft_ver" .. self.curAndroidVersion .. "_pack.apk)");
ParaIO.DeleteFile("temp/worker_android_sign_apk_temp.bat");
ParaIO.DeleteFile("temp/main_temp.bat");
Map3DSystem.App.Commands.Call("File.WinExplorer", {filepath = self.androidBuildRoot, silentmode = true});
if callback and type(callback) == "function" then
callback();
end
end
)
end
function MakeApp:AndroidSignApkThread()
System.os.run(
"temp\\build_android_resource\\jre-windows\\bin\\java -jar " ..
"temp\\build_android_resource\\android-sdk-build-tools-32.0.0\\32.0.0\\lib\\apksigner.jar sign -ks " ..
self.androidBuildRoot .. "personal-key.keystore " ..
"--ks-key-alias paracraft " ..
"--ks-pass pass:paracraft " ..
"--out " .. self.androidBuildRoot .. "paracraft_ver" .. self.curAndroidVersion .. "_pack.apk " ..
self.androidBuildRoot .. "paracraft_ver" .. self.curAndroidVersion .. "_align_temp.apk"
);
ParaIO.DeleteFile(self.androidBuildRoot .. "paracraft_ver" .. self.curAndroidVersion .. "_align_temp.apk");
end
function MakeApp:AndroidClean(callback)
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在清理,请稍候...", 120000, nil, 400);
commonlib.TimerManager.SetTimeout(function()
ParaIO.DeleteFile(self.androidBuildRoot);
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
if (callback and type(callback) == "function") then
callback();
end
end, 1000)
end
function MakeApp:AndroidZip()
ParaIO.CreateDirectory(self.androidBuildRoot);
if ParaIO.DoesFileExist(self.androidBuildRoot .. "paracraft_android_ver" .. self.curAndroidVersion .. "/") then
self:AndroidDownloadTools(function()
self:AndroidDecodeApk(function()
self:AndroidUpdateManifest(function()
self:AndroidCopyWorld(false, false, false, false, function()
self:AndroidGenerateApk(function()
self:AndroidSignApk()
end)
end)
end)
end)
end)
else
self:AndroidDownloadApk(function()
self:AndroidDownloadTools(function()
self:AndroidDecodeApk(function()
self:AndroidUpdateManifest(function()
self:AndroidCopyWorld(false, false, false, false, function()
self:AndroidGenerateApk(function()
self:AndroidSignApk()
end)
end)
end)
end)
end)
end)
end
end
function MakeApp:MakeAndroidApp(method)
if (method == "zip") then
self:AndroidZip()
return
end
if (method == "clean") then
self:AndroidClean()
return
end
self:AndroidClean(function()
commonlib.TimerManager.SetTimeout(function()
self:AndroidZip()
end, 5000)
end)
end
-- ios
function MakeApp:iOSCheckENV(callback)
if (not callback or type(callback) ~= "function") then
return;
end
if (not self:iOSCheckXcode()) then
return;
end
if (not ParaIO.DoesFileExist("/usr/bin/tar")) then
_guihelper.MessageBox(L"请先安装tar");
return;
end
self:iOSCheckCmake(function(result)
if (result) then
self:iOSCheckNPLRuntime(function(result)
if (result) then
self:iOSCheckBoost(function(result)
if (result) then
callback(true);
else
_guihelper.MessageBox(L"安装Boost失败!");
callback(false);
end
end);
else
_guihelper.MessageBox(L"安装NPLRuntime失败!");
callback(false);
end
end);
else
_guihelper.MessageBox(L"安装Cmake失败!");
callback(false);
end
end)
end
function MakeApp:iOSCheckXcode()
if not ParaIO.DoesFileExist("/Applications/Xcode.app") then
_guihelper.MessageBox(L"请先安装Xcode");
return false;
else
return true;
end
end
function MakeApp:iOSCheckCmake(callback)
if (not callback or type(callback) ~= "function") then
return;
end
if (not ParaIO.DoesFileExist(self.iOSBuildRoot)) then
ParaIO.CreateDirectory(self.iOSBuildRoot);
end
if (not ParaIO.DoesFileExist(self.iOSBuildRoot .. "/Cmake.app")) then
local url = self.iOSResourceBaseCDN .. "cmake-3.21.3-macos-universal.tar.gz";
local fileDownloader = FileDownloader:new();
fileDownloader.isSilent = true;
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在获取Cmake,请稍候...", 120000, nil, 400)
local tarGzFile = self.iOSBuildRoot .. "cmake-3.21.3-macos-universal.tar.gz";
if (ParaIO.DoesFileExist(tarGzFile)) then
ParaIO.DeleteFile(tarGzFile);
end
commonlib.TimerManager.SetTimeout(function()
fileDownloader:Init("cmake-3.21.3-macos-universal.tar.gz", url, tarGzFile, function(result)
if (result) then
local tarGzAbsPath = ParaIO.GetWritablePath() .. tarGzFile;
os.execute("tar -xzf " .. tarGzAbsPath .. " -C " .. ParaIO.GetWritablePath() .. self.iOSBuildRoot .. " --strip-components 1");
if (ParaIO.DoesFileExist(self.iOSBuildRoot .. "/Cmake.app")) then
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
callback(true);
else
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
_guihelper.MessageBox(L"安装Cmake失败!");
callback(false);
end
else
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
_guihelper.MessageBox(L"下载Cmake失败!");
callback(false);
end
end)
end, 500)
else
callback(true);
end
end
function MakeApp:iOSCheckNPLRuntime(callback)
if (not callback or type(callback) ~= "function") then
return;
end
if (not ParaIO.DoesFileExist(self.iOSBuildRoot)) then
ParaIO.CreateDirectory(self.iOSBuildRoot);
end
if (not ParaIO.DoesFileExist(self.iOSBuildRoot .. "NPLRuntime/")) then
local version = '2.3'
local url = "http://code.kp-para.cn/root/NPLRuntime/-/archive/v" .. version .. "/NPLRuntime-v" .. version .. ".tar.bz2";
local fileDownloader = FileDownloader:new();
fileDownloader.isSilent = true;
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在获取NPLRuntime,请稍候...", 120000, nil, 400)
local tarGzFile = self.iOSBuildRoot .. "NPLRuntime.tar.gz";
if (ParaIO.DoesFileExist(tarGzFile)) then
ParaIO.DeleteFile(tarGzFile);
end
commonlib.TimerManager.SetTimeout(function()
fileDownloader:Init("NPLRuntime.tar.gz", url, tarGzFile, function(result)
if (result) then
local tarGzAbsPath = ParaIO.GetWritablePath() .. tarGzFile;
os.execute("mkdir " ..
ParaIO.GetWritablePath() ..
self.iOSBuildRoot ..
"NPLRuntime/ && tar -xzf " ..
tarGzAbsPath ..
" -C " ..
ParaIO.GetWritablePath() ..
self.iOSBuildRoot ..
"NPLRuntime/ --strip-components 1");
if (ParaIO.DoesFileExist(self.iOSBuildRoot .. "NPLRuntime/")) then
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
callback(true);
else
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
_guihelper.MessageBox(L"安装NPLRuntime失败!");
callback(false);
end
else
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
_guihelper.MessageBox(L"下载NPLRuntime失败!");
callback(false);
end
end)
end, 500)
else
callback(true);
end
end
function MakeApp:iOSCheckBoost(callback)
if (not callback or type(callback) ~= "function") then
return;
end
if (not ParaIO.DoesFileExist(self.iOSBuildRoot)) then
ParaIO.CreateDirectory(self.iOSBuildRoot);
end
if (not ParaIO.DoesFileExist(self.iOSBuildRoot .. "Boost/")) then
ParaIO.CreateDirectory(self.iOSBuildRoot .. "Boost/");
end
if (not ParaIO.DoesFileExist(self.iOSBuildRoot .. "Boost/src/boost_1_74_0")) then
local url = self.iOSResourceBaseCDN .. "boost_1_74_0.tar.bz2";
local fileDownloader = FileDownloader:new();
fileDownloader.isSilent = true;
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在获取Boost,请稍候...", 120000, nil, 400)
local tarGzFile = self.iOSBuildRoot .. "Boost/boost_1_74_0.tar.bz2";
if (ParaIO.DoesFileExist(tarGzFile)) then
ParaIO.DeleteFile(tarGzFile);
end
commonlib.TimerManager.SetTimeout(function()
fileDownloader:Init("boost_1_74_0.tar.bz2", url, tarGzFile, function(result)
if (result) then
local tarGzAbsPath = ParaIO.GetWritablePath() .. tarGzFile;
os.execute("mkdir -p " ..
ParaIO.GetWritablePath() ..
self.iOSBuildRoot ..
"Boost/src/boost_1_74_0/ && tar -xjf " ..
tarGzAbsPath ..
" -C " ..
ParaIO.GetWritablePath() ..
self.iOSBuildRoot ..
"Boost/src/boost_1_74_0/ --strip-components 1");
if (ParaIO.DoesFileExist(self.iOSBuildRoot .. "Boost/src/boost_1_74_0/")) then
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
callback(true);
else
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
_guihelper.MessageBox(L"安装Boost失败!");
callback(false);
end
else
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
_guihelper.MessageBox(L"下载Boost失败!");
callback(false);
end
end)
end, 500)
else
callback(true);
end
end
function MakeApp:iOSBuildProject(callback)
if (not callback or type(callback) ~= "function") then
return;
end
-- copy assets files
local assetsDir = 'apps/haqi/';
if (ParaIO.DoesFileExist(assetsDir)) then
commonlib.Files.CopyFolder("apps/haqi", self.iOSBuildRoot .. "NPLRuntime/NPLRuntime/Platform/iOS/assets");
commonlib.Files.CopyFolder(
"/Applications/Paracraft.app/Contents/Resources/assets/fonts",
self.iOSBuildRoot .. "NPLRuntime/NPLRuntime/Platform/iOS/assets/fonts"
)
else
commonlib.Files.CopyFolder(
"/Applications/Paracraft.app/Contents/Resources/assets",
self.iOSBuildRoot .. "NPLRuntime/NPLRuntime/Platform/iOS/assets"
)
end
local guideFolder = "⚠️请输入sh空格build.sh回车,命令执行完毕后请关闭窗口/"
if (not ParaIO.DoesFileExist(self.iOSBuildRoot .. guideFolder)) then
ParaIO.CreateDirectory(self.iOSBuildRoot .. guideFolder);
end
local shFilePath = ParaIO.GetWritablePath() .. self.iOSBuildRoot .. guideFolder .. "build.sh"
if (not ParaIO.DoesFileExist(shFilePath)) then
local shFile = [[
#!/bin/sh
# Author: big
# CreateDate: 2022.2.11
# ModifyDate: 2022.2.21
echo "开始构建iOS工程"
cd ../
if [ ! -f "./Boost/src/boost_1_74_0/b2" ]; then
xattr -d com.apple.quarantine ./Boost/src/boost_1_74_0/tools/build/src/engine/build.sh
xattr -d com.apple.quarantine ./Boost/src/boost_1_74_0/bootstrap.sh
pushd ./Boost/src/boost_1_74_0/ && ./bootstrap.sh && popd
fi
xattr -d com.apple.quarantine ]] ..
ParaIO.GetWritablePath() ..
self.iOSBuildRoot ..
"NPLRuntime/NPLRuntime/externals/EmbedResource/prebuild/osx/embed-resource" ..
[[
if [ ! -d "./Boost/build" ]; then
pushd ./Boost/
sh ../NPLRuntime/NPLRuntime/externals/boost/scripts/boost.sh \
-ios -macos --no-framework --boost-version 1.74.0 \
--boost-libs "thread date_time filesystem system chrono regex serialization iostreams log"
popd
fi
xattr -d com.apple.quarantine ./Cmake.app
xattr -dr com.apple.quarantine ./Cmake.app/*
if [ ! -d "./build/" ]; then
mkdir build
fi
echo "Building NPLRuntime..."
pushd ./build/
cmake=../CMake.app/Contents/bin/cmake
export BOOST_ROOT=]] ..
ParaIO.GetWritablePath() ..
[[temp/build_ios_resource/Boost/src/boost_1_74_0/
$cmake -G Xcode -S ../NPLRuntime/NPLRuntime \
-DCMAKE_TOOLCHAIN_FILE=../NPLRuntime/NPLRuntime/cmake/ios.toolchain.cmake \
-DIOS_PLATFORM=OS -DENABLE_BITCODE=0 -DIOS_DEPLOYMENT_TARGET=10.0
popd
echo "构建结束,请关闭此窗口"
if [ -f "./build/lock" ]; then
rm ./build/lock
fi
exit 0;
]];
local writeFile = ParaIO.open(shFilePath, "w");
if (writeFile:IsValid()) then
writeFile:write(shFile, #shFile);
writeFile:close();
os.execute("tr -d \"\\r\" < " .. shFilePath .. " > " .. shFilePath .. ".tmp && mv " .. shFilePath .. ".tmp " .. shFilePath);
end
end
if (ParaIO.DoesFileExist(self.iOSBuildRoot .. "build/lock")) then
ParaIO.DeleteFile(self.iOSBuildRoot .. "build/lock");
end
if (not ParaIO.DoesFileExist(self.iOSBuildRoot .. "build/")) then
ParaIO.CreateDirectory(self.iOSBuildRoot .. "build/");
local writeFile = ParaIO.open(self.iOSBuildRoot .. "build/lock", "w");
if (writeFile:IsValid()) then
writeFile:write("lock", 4);
writeFile:close();
end
os.execute("open -a Terminal " ..
ParaIO.GetWritablePath() ..
self.iOSBuildRoot ..
guideFolder);
local checkTimer
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在处理中,请看Terminal提示...", 60000 * 120, nil, 350);
checkTimer = commonlib.Timer:new({callbackFunc = function()
if (not ParaIO.DoesFileExist(self.iOSBuildRoot .. "build/lock")) then
ParaIO.DeleteFile(self.iOSBuildRoot .. guideFolder);
ParaIO.DeleteFile(self.iOSBuildRoot .. "build/lock");
checkTimer:Change(nil, nil);
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
callback();
end
end});
checkTimer:Change(100, 100);
else
callback();
end
end
function MakeApp:iOSCopyCurWorldToProject(compress, beAutoUpdate, beAutoUpdateWorld, loginEnable, callback)
local currentEnterWorld = Mod.WorldShare.Store:Get("world/currentEnterWorld");
if (not currentEnterWorld or type(currentEnterWorld) ~= "table") then
return;
end
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.show", L"正在拷贝世界,请稍候...", 120000, nil, 350);
local worldPath = currentEnterWorld.worldpath;
local worldsPath = self.iOSBuildRoot .. "NPLRuntime/NPLRuntime/Platform/iOS/assets/worlds/DesignHouse/";
if (not ParaIO.DoesFileExist(worldsPath)) then
commonlib.Files.CreateDirectory(worldsPath);
end
if (compress) then
ParaIO.DeleteFile("temp/" .. currentEnterWorld.foldername .. "/");
local tempWorldPath =
"temp/" ..
currentEnterWorld.foldername ..
"/" ..
currentEnterWorld.foldername ..
"/";
commonlib.Files.CopyFolder(worldPath, tempWorldPath);
GameLogic.GetFilters():apply_filters(
"service.local_service.move_folder_to_zip",
"temp/" .. currentEnterWorld.foldername .. "/",
worldsPath .. currentEnterWorld.foldername .. ".zip"
);
else
commonlib.Files.CopyFolder(worldPath, worldsPath .. currentEnterWorld.foldername);
end
-- update config.txt file
local configPath = self.iOSBuildRoot .. "NPLRuntime/NPLRuntime/Platform/iOS/assets/config.txt";
if (ParaIO.DoesFileExist(configPath)) then
ParaIO.DeleteFile(configPath);
end
local writeFile = ParaIO.open(configPath, "w");
if (writeFile:IsValid()) then
local foldername = currentEnterWorld.foldername;
if (compress) then
foldername = foldername .. ".zip";
end
local content =
"cmdline=mc=\"true\" debug=\"main\" IsAppVersion=\"true\" bootstrapper=\"script/apps/Aries/main_loop.lua\" " ..
"world=\"" .. "worlds/DesignHouse/" .. foldername .. "\"";
if (not beAutoUpdate) then
content = content .. " noclientupdate=\"true\"";
end
if (beAutoUpdateWorld) then
content = content .. " auto_update_world=\"true\"";
end
if (loginEnable) then
content = content .. " login_enable=\"true\"";
end
writeFile:write(content, #content);
writeFile:close();
end
GameLogic.GetFilters():apply_filters("cellar.common.msg_box.close");
if (callback and type(callback) == "function") then
callback();
end
end
function MakeApp:CopyIconToProject(callback)
local currentEnterWorld = Mod.WorldShare.Store:Get("world/currentEnterWorld");
if (not currentEnterWorld or type(currentEnterWorld) ~= "table") then
return;
end
local size = {
{
dimensions = {
width = 20,
height = 20,
},
idiom = "",
scale = 1,
},
{
dimensions = {
width = 20,
height = 20,
},
scale = 2,
},
{
dimensions = {
width = 20,
height = 20,
},
scale = 3,
},
{
dimensions = {
width = 29,
height = 29,
},
scale = 1,
},
{
dimensions = {
width = 29,
height = 29,
},
scale = 2,
},
{
dimensions = {
width = 29,
height = 29,
},
scale = 3,
},
{
dimensions = {
width = 40,
height = 40,
},
scale = 1,
},
{
dimensions = {
width = 40,
height = 40,
},
scale = 2,
},
{
dimensions = {
width = 40,
height = 40,
},
scale = 3,
},
{
dimensions = {
width = 57,
height = 57,
},
scale = 1,
},
{
dimensions = {
width = 57,
height = 57,
},
scale = 2,
},
{
dimensions = {
width = 60,
height = 60,
},
scale = 2,
},
{
dimensions = {
width = 60,
height = 60,
},
scale = 3,
},
{
dimensions = {
width = 72,
height = 72,
},
scale = 1,
},
{
dimensions = {
width = 72,
height = 72,
},
scale = 2,
},
{
dimensions = {
width = 76,
height = 76,
},
scale = 1,
},
{
dimensions = {
width = 76,
height = 76,
},
scale = 2,
},
{
dimensions = {
width = 83.5,
height = 83.5,
},
scale = 2,
},
{
dimensions = {
width = 50,
height = 50,
},
scale = 1,
name = "Icon-Small-50x50@1x",
},
{
dimensions = {
width = 50,
height = 50,
},
scale = 2,
name = "Icon-Small-50x50@2x",
},
{
dimensions = {
width = 512,
height = 512,
},
scale = 2,
name = "ItunesArtwork@2x",
},
}
local appIconFolder = ParaIO.GetWritablePath() .. self.iOSBuildRoot .. "NPLRuntime/NPLRuntime/Platform/iOS/Images.xcassets/AppIcon.appiconset";
local iconPath;
ParaIO.DeleteFile(appIconFolder .. "/");
ParaIO.CreateDirectory(appIconFolder .. "/");
if (ParaIO.DoesFileExist(currentEnterWorld.worldpath .. "/icon.png")) then
iconPath = currentEnterWorld.worldpath .. "/icon.png"
else
ParaIO.CopyFile(
"Texture/Aries/Creator/paracraft/default_icon_32bits.png",
"temp/default_icon_32bits.png",
true
);
iconPath = ParaIO.GetWritablePath() .. "temp/default_icon_32bits.png";
end
for key, item in ipairs(size) do
local dest
if (item.name) then
dest = appIconFolder .. "/" .. item.name;
else
dest = appIconFolder .. "/" .. format("Icon-App-%sx%s@%dx",
tostring(item.dimensions.width),
tostring(item.dimensions.height),
item.scale
);
end
os.execute(format("sips -Z %d %s --out %s.png",
item.dimensions.width * item.scale,
iconPath,
dest));
end
local contents = [[
{
"images" : [
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "Icon-App-20x20@2x.png",
"scale" : "2x"
},
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "Icon-App-20x20@3x.png",
"scale" : "3x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@1x.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@2x.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@3x.png",
"scale" : "3x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "Icon-App-40x40@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "Icon-App-40x40@3x.png",
"scale" : "3x"
},
{
"size" : "57x57",
"idiom" : "iphone",
"filename" : "Icon-App-57x57@1x.png",
"scale" : "1x"
},
{
"size" : "57x57",
"idiom" : "iphone",
"filename" : "Icon-App-57x57@2x.png",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-App-60x60@2x.png",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-App-60x60@3x.png",
"scale" : "3x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "Icon-App-20x20@1x.png",
"scale" : "1x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "Icon-App-20x20@2x.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "Icon-App-29x29@1x.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "Icon-App-29x29@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "Icon-App-40x40@1x.png",
"scale" : "1x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "Icon-App-40x40@2x.png",
"scale" : "2x"
},
{
"size" : "50x50",
"idiom" : "ipad",
"filename" : "Icon-Small-50x50@1x.png",
"scale" : "1x"
},
{
"size" : "50x50",
"idiom" : "ipad",
"filename" : "Icon-Small-50x50@2x.png",
"scale" : "2x"
},
{
"size" : "72x72",
"idiom" : "ipad",
"filename" : "Icon-App-72x72@1x.png",
"scale" : "1x"
},
{
"size" : "72x72",
"idiom" : "ipad",
"filename" : "Icon-App-72x72@2x.png",
"scale" : "2x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "Icon-App-76x76@1x.png",
"scale" : "1x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "Icon-App-76x76@2x.png",
"scale" : "2x"
},
{
"size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "Icon-App-83.5x83.5@2x.png",
"scale" : "2x"
},
{
"size" : "1024x1024",
"idiom" : "ios-marketing",
"filename" : "ItunesArtwork@2x.png",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
]];
local writeFile = ParaIO.open(appIconFolder .. "/Contents.json", "w");
if (writeFile:IsValid()) then
writeFile:write(contents, #contents);
writeFile:close();
end
if (callback and type(callback) == "function") then
callback();
end
end
function MakeApp:iOSOpenProject()
os.execute("open -a Xcode " ..
ParaIO.GetWritablePath() ..
self.iOSBuildRoot ..
"build/NPLRuntime.xcodeproj");
end
| gpl-2.0 |
mysql/mysql-proxy | examples/tutorial-monitor.lua | 6 | 5362 | --[[ $%BEGINLICENSE%$
Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
--[[
--]]
local function str2hex(str)
local raw_len = string.len(str)
local i = 1
local o = ""
while i <= raw_len do
o = o .. string.format(" %02x", string.byte(str, i))
i = i + 1
end
return o
end
--
-- map the constants to strings
-- lua starts at 1
local command_names = {
"COM_SLEEP",
"COM_QUIT",
"COM_INIT_DB",
"COM_QUERY",
"COM_FIELD_LIST",
"COM_CREATE_DB",
"COM_DROP_DB",
"COM_REFRESH",
"COM_SHUTDOWN",
"COM_STATISTICS",
"COM_PROCESS_INFO",
"COM_CONNECT",
"COM_PROCESS_KILL",
"COM_DEBUG",
"COM_PING",
"COM_TIME",
"COM_DELAYED_INSERT",
"COM_CHANGE_USER",
"COM_BINLOG_DUMP",
"COM_TABLE_DUMP",
"COM_CONNECT_OUT",
"COM_REGISTER_SLAVE",
"COM_STMT_PREPARE",
"COM_STMT_EXECUTE",
"COM_STMT_SEND_LONG_DATA",
"COM_STMT_CLOSE",
"COM_STMT_RESET",
"COM_SET_OPTION",
"COM_STMT_FETCH",
"COM_DAEMON"
}
--- dump the result-set to stdout
--
-- @param inj "packet.injection"
local function dump_query_result( inj )
local field_count = 1
local fields = inj.resultset.fields
while fields[field_count] do
local field = fields[field_count]
print("| | field[" .. field_count .. "] = { type = " ..
field.type .. ", name = " .. field.name .. " }" )
field_count = field_count + 1
end
local row_count = 0
for row in inj.resultset.rows do
local cols = {}
local o
for i = 1, field_count do
if not o then
o = ""
else
o = o .. ", "
end
if not row[i] then
o = o .. "(nul)"
else
o = o .. row[i]
end
end
print("| | row["..row_count.."] = { " .. o .. " }")
row_count = row_count + 1
end
end
local function decode_query_packet( packet )
-- we don't have the packet header in the
packet_len = string.len(packet)
print("| query.len = " .. packet_len)
print("| query.packet =" .. str2hex(packet))
-- print("(decode_query) " .. "| packet-id = " .. "(unknown)")
print("| .--- query")
print("| | command = " .. command_names[string.byte(packet) + 1])
if string.byte(packet) == proxy.COM_QUERY then
-- after the COM_QUERY comes the query
print("| | query = " .. string.format("%q", string.sub(packet, 2)))
elseif string.byte(packet) == proxy.COM_INIT_DB then
print("| | db = " .. string.format("%q", string.sub(packet, 2)))
elseif string.byte(packet) == proxy.COM_STMT_PREPARE then
print("| | query = " .. string.format("%q", string.sub(packet, 2)))
elseif string.byte(packet) == proxy.COM_STMT_EXECUTE then
local stmt_handler_id = string.byte(packet, 2) + (string.byte(packet, 3) * 256) + (string.byte(packet, 4) * 256 * 256) + (string.byte(packet, 5) * 256 * 256 * 256)
local flags = string.byte(packet, 6)
local iteration_count = string.byte(packet, 7) + (string.byte(packet, 8) * 256) + (string.byte(packet, 9) * 256 * 256) + (string.byte(packet, 10) * 256 * 256 * 256)
print("| | stmt-id = " .. stmt_handler_id )
print("| | flags = " .. string.format("%02x", flags) )
print("| | iteration_count = " .. iteration_count )
if packet_len > 10 then
-- if we don't have any place-holders, no for NUL and friends
local nul_bitmap = string.byte(packet, 11)
local new_param = string.byte(packet, 12)
print("| | nul_bitmap = " .. string.format("%02x", nul_bitmap ))
print("| | new_param = " .. new_param )
else
print("| | (no params)")
end
print("| | prepared-query = " .. prepared_queries[stmt_handler_id] )
else
print("| | packet =" .. str2hex(packet))
end
print("| '---")
end
function read_query()
--[[ for i = 1, #proxy.global.backends do
local s = proxy.global.backends[i]
local pool = s.pool -- we don't have a username yet, try to find a connections which is idling
local cur_idle = pool.users[""].cur_idle_connections
print(" [".. i .."].connected_clients = " .. s.connected_clients)
print(" [".. i .."].idling_connections = " .. cur_idle)
print(" [".. i .."].type = " .. s.type)
print(" [".. i .."].state = " .. s.state)
end
--]]
proxy.queries:append(1, string.char(proxy.COM_QUERY) .. "SELECT NOW()", { resultset_is_needed = true } )
if proxy.connection then
print ("inject monitor query into backend # " .. proxy.connection.backend_ndx)
else
print ("inject monitor query")
end
end
function read_query_result ( inj )
local res = assert(inj.resultset)
local packet = assert(inj.query)
decode_query_packet(packet)
print "read query result, dumping"
dump_query_result(inj)
end
| gpl-2.0 |
flyzjhz/witi-openwrt | package/ramips/ui/luci-mtk/src/libs/json/luasrc/json.lua | 50 | 13333 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
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$
Decoder:
Info:
null will be decoded to luci.json.null if first parameter of Decoder() is true
Example:
decoder = luci.json.Decoder()
luci.ltn12.pump.all(luci.ltn12.source.string("decodableJSON"), decoder:sink())
luci.util.dumptable(decoder:get())
Known issues:
does not support unicode conversion \uXXYY with XX != 00 will be ignored
Encoder:
Info:
Accepts numbers, strings, nil, booleans as they are
Accepts luci.json.null as replacement for nil
Accepts full associative and full numerically indexed tables
Mixed tables will loose their associative values during conversion
Iterator functions will be encoded as an array of their return values
Non-iterator functions will probably corrupt the encoder
Example:
encoder = luci.json.Encoder(encodableData)
luci.ltn12.pump.all(encoder:source(), luci.ltn12.sink.file(io.open("someFile", w)))
]]--
local nixio = require "nixio"
local util = require "luci.util"
local table = require "table"
local string = require "string"
local coroutine = require "coroutine"
local assert = assert
local tonumber = tonumber
local tostring = tostring
local error = error
local type = type
local pairs = pairs
local ipairs = ipairs
local next = next
local pcall = pcall
local band = nixio.bit.band
local bor = nixio.bit.bor
local rshift = nixio.bit.rshift
local char = string.char
local getmetatable = getmetatable
--- LuCI JSON-Library
-- @cstyle instance
module "luci.json"
--- Directly decode a JSON string
-- @param json JSON-String
-- @return Lua object
function decode(json, ...)
local a = ActiveDecoder(function() return nil end, ...)
a.chunk = json
local s, obj = pcall(a.get, a)
return s and obj or nil
end
--- Direcly encode a Lua object into a JSON string.
-- @param obj Lua Object
-- @return JSON string
function encode(obj, ...)
local out = {}
local e = Encoder(obj, 1, ...):source()
local chnk, err
repeat
chnk, err = e()
out[#out+1] = chnk
until not chnk
return not err and table.concat(out) or nil
end
--- Null replacement function
-- @return null
function null()
return null
end
--- Create a new JSON-Encoder.
-- @class function
-- @name Encoder
-- @param data Lua-Object to be encoded.
-- @param buffersize Blocksize of returned data source.
-- @param fastescape Use non-standard escaping (don't escape control chars)
-- @return JSON-Encoder
Encoder = util.class()
function Encoder.__init__(self, data, buffersize, fastescape)
self.data = data
self.buffersize = buffersize or 512
self.buffer = ""
self.fastescape = fastescape
getmetatable(self).__call = Encoder.source
end
--- Create an LTN12 source providing the encoded JSON-Data.
-- @return LTN12 source
function Encoder.source(self)
local source = coroutine.create(self.dispatch)
return function()
local res, data = coroutine.resume(source, self, self.data, true)
if res then
return data
else
return nil, data
end
end
end
function Encoder.dispatch(self, data, start)
local parser = self.parsers[type(data)]
parser(self, data)
if start then
if #self.buffer > 0 then
coroutine.yield(self.buffer)
end
coroutine.yield()
end
end
function Encoder.put(self, chunk)
if self.buffersize < 2 then
coroutine.yield(chunk)
else
if #self.buffer + #chunk > self.buffersize then
local written = 0
local fbuffer = self.buffersize - #self.buffer
coroutine.yield(self.buffer .. chunk:sub(written + 1, fbuffer))
written = fbuffer
while #chunk - written > self.buffersize do
fbuffer = written + self.buffersize
coroutine.yield(chunk:sub(written + 1, fbuffer))
written = fbuffer
end
self.buffer = chunk:sub(written + 1)
else
self.buffer = self.buffer .. chunk
end
end
end
function Encoder.parse_nil(self)
self:put("null")
end
function Encoder.parse_bool(self, obj)
self:put(obj and "true" or "false")
end
function Encoder.parse_number(self, obj)
self:put(tostring(obj))
end
function Encoder.parse_string(self, obj)
if self.fastescape then
self:put('"' .. obj:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"')
else
self:put('"' ..
obj:gsub('[%c\\"]',
function(char)
return '\\u00%02x' % char:byte()
end
)
.. '"')
end
end
function Encoder.parse_iter(self, obj)
if obj == null then
return self:put("null")
end
if type(obj) == "table" and (#obj == 0 and next(obj)) then
self:put("{")
local first = true
for key, entry in pairs(obj) do
first = first or self:put(",")
first = first and false
self:parse_string(tostring(key))
self:put(":")
self:dispatch(entry)
end
self:put("}")
else
self:put("[")
local first = true
if type(obj) == "table" then
for i=1, #obj do
first = first or self:put(",")
first = first and nil
self:dispatch(obj[i])
end
else
for entry in obj do
first = first or self:put(",")
first = first and nil
self:dispatch(entry)
end
end
self:put("]")
end
end
Encoder.parsers = {
['nil'] = Encoder.parse_nil,
['table'] = Encoder.parse_iter,
['number'] = Encoder.parse_number,
['string'] = Encoder.parse_string,
['boolean'] = Encoder.parse_bool,
['function'] = Encoder.parse_iter
}
--- Create a new JSON-Decoder.
-- @class function
-- @name Decoder
-- @param customnull Use luci.json.null instead of nil for decoding null
-- @return JSON-Decoder
Decoder = util.class()
function Decoder.__init__(self, customnull)
self.cnull = customnull
getmetatable(self).__call = Decoder.sink
end
--- Create an LTN12 sink from the decoder object which accepts the JSON-Data.
-- @return LTN12 sink
function Decoder.sink(self)
local sink = coroutine.create(self.dispatch)
return function(...)
return coroutine.resume(sink, self, ...)
end
end
--- Get the decoded data packets after the rawdata has been sent to the sink.
-- @return Decoded data
function Decoder.get(self)
return self.data
end
function Decoder.dispatch(self, chunk, src_err, strict)
local robject, object
local oset = false
while chunk do
while chunk and #chunk < 1 do
chunk = self:fetch()
end
assert(not strict or chunk, "Unexpected EOS")
if not chunk then break end
local char = chunk:sub(1, 1)
local parser = self.parsers[char]
or (char:match("%s") and self.parse_space)
or (char:match("[0-9-]") and self.parse_number)
or error("Unexpected char '%s'" % char)
chunk, robject = parser(self, chunk)
if parser ~= self.parse_space then
assert(not oset, "Scope violation: Too many objects")
object = robject
oset = true
if strict then
return chunk, object
end
end
end
assert(not src_err, src_err)
assert(oset, "Unexpected EOS")
self.data = object
end
function Decoder.fetch(self)
local tself, chunk, src_err = coroutine.yield()
assert(chunk or not src_err, src_err)
return chunk
end
function Decoder.fetch_atleast(self, chunk, bytes)
while #chunk < bytes do
local nchunk = self:fetch()
assert(nchunk, "Unexpected EOS")
chunk = chunk .. nchunk
end
return chunk
end
function Decoder.fetch_until(self, chunk, pattern)
local start = chunk:find(pattern)
while not start do
local nchunk = self:fetch()
assert(nchunk, "Unexpected EOS")
chunk = chunk .. nchunk
start = chunk:find(pattern)
end
return chunk, start
end
function Decoder.parse_space(self, chunk)
local start = chunk:find("[^%s]")
while not start do
chunk = self:fetch()
if not chunk then
return nil
end
start = chunk:find("[^%s]")
end
return chunk:sub(start)
end
function Decoder.parse_literal(self, chunk, literal, value)
chunk = self:fetch_atleast(chunk, #literal)
assert(chunk:sub(1, #literal) == literal, "Invalid character sequence")
return chunk:sub(#literal + 1), value
end
function Decoder.parse_null(self, chunk)
return self:parse_literal(chunk, "null", self.cnull and null)
end
function Decoder.parse_true(self, chunk)
return self:parse_literal(chunk, "true", true)
end
function Decoder.parse_false(self, chunk)
return self:parse_literal(chunk, "false", false)
end
function Decoder.parse_number(self, chunk)
local chunk, start = self:fetch_until(chunk, "[^0-9eE.+-]")
local number = tonumber(chunk:sub(1, start - 1))
assert(number, "Invalid number specification")
return chunk:sub(start), number
end
function Decoder.parse_string(self, chunk)
local str = ""
local object = nil
assert(chunk:sub(1, 1) == '"', 'Expected "')
chunk = chunk:sub(2)
while true do
local spos = chunk:find('[\\"]')
if spos then
str = str .. chunk:sub(1, spos - 1)
local char = chunk:sub(spos, spos)
if char == '"' then -- String end
chunk = chunk:sub(spos + 1)
break
elseif char == "\\" then -- Escape sequence
chunk, object = self:parse_escape(chunk:sub(spos))
str = str .. object
end
else
str = str .. chunk
chunk = self:fetch()
assert(chunk, "Unexpected EOS while parsing a string")
end
end
return chunk, str
end
function Decoder.utf8_encode(self, s1, s2)
local n = s1 * 256 + s2
if n >= 0 and n <= 0x7F then
return char(n)
elseif n >= 0 and n <= 0x7FF then
return char(
bor(band(rshift(n, 6), 0x1F), 0xC0),
bor(band(n, 0x3F), 0x80)
)
elseif n >= 0 and n <= 0xFFFF then
return char(
bor(band(rshift(n, 12), 0x0F), 0xE0),
bor(band(rshift(n, 6), 0x3F), 0x80),
bor(band(n, 0x3F), 0x80)
)
elseif n >= 0 and n <= 0x10FFFF then
return char(
bor(band(rshift(n, 18), 0x07), 0xF0),
bor(band(rshift(n, 12), 0x3F), 0x80),
bor(band(rshift(n, 6), 0x3F), 0x80),
bor(band(n, 0x3F), 0x80)
)
else
return "?"
end
end
function Decoder.parse_escape(self, chunk)
local str = ""
chunk = self:fetch_atleast(chunk:sub(2), 1)
local char = chunk:sub(1, 1)
chunk = chunk:sub(2)
if char == '"' then
return chunk, '"'
elseif char == "\\" then
return chunk, "\\"
elseif char == "u" then
chunk = self:fetch_atleast(chunk, 4)
local s1, s2 = chunk:sub(1, 2), chunk:sub(3, 4)
s1, s2 = tonumber(s1, 16), tonumber(s2, 16)
assert(s1 and s2, "Invalid Unicode character")
return chunk:sub(5), self:utf8_encode(s1, s2)
elseif char == "/" then
return chunk, "/"
elseif char == "b" then
return chunk, "\b"
elseif char == "f" then
return chunk, "\f"
elseif char == "n" then
return chunk, "\n"
elseif char == "r" then
return chunk, "\r"
elseif char == "t" then
return chunk, "\t"
else
error("Unexpected escaping sequence '\\%s'" % char)
end
end
function Decoder.parse_array(self, chunk)
chunk = chunk:sub(2)
local array = {}
local nextp = 1
local chunk, object = self:parse_delimiter(chunk, "%]")
if object then
return chunk, array
end
repeat
chunk, object = self:dispatch(chunk, nil, true)
table.insert(array, nextp, object)
nextp = nextp + 1
chunk, object = self:parse_delimiter(chunk, ",%]")
assert(object, "Delimiter expected")
until object == "]"
return chunk, array
end
function Decoder.parse_object(self, chunk)
chunk = chunk:sub(2)
local array = {}
local name
local chunk, object = self:parse_delimiter(chunk, "}")
if object then
return chunk, array
end
repeat
chunk = self:parse_space(chunk)
assert(chunk, "Unexpected EOS")
chunk, name = self:parse_string(chunk)
chunk, object = self:parse_delimiter(chunk, ":")
assert(object, "Separator expected")
chunk, object = self:dispatch(chunk, nil, true)
array[name] = object
chunk, object = self:parse_delimiter(chunk, ",}")
assert(object, "Delimiter expected")
until object == "}"
return chunk, array
end
function Decoder.parse_delimiter(self, chunk, delimiter)
while true do
chunk = self:fetch_atleast(chunk, 1)
local char = chunk:sub(1, 1)
if char:match("%s") then
chunk = self:parse_space(chunk)
assert(chunk, "Unexpected EOS")
elseif char:match("[%s]" % delimiter) then
return chunk:sub(2), char
else
return chunk, nil
end
end
end
Decoder.parsers = {
['"'] = Decoder.parse_string,
['t'] = Decoder.parse_true,
['f'] = Decoder.parse_false,
['n'] = Decoder.parse_null,
['['] = Decoder.parse_array,
['{'] = Decoder.parse_object
}
--- Create a new Active JSON-Decoder.
-- @class function
-- @name ActiveDecoder
-- @param customnull Use luci.json.null instead of nil for decoding null
-- @return Active JSON-Decoder
ActiveDecoder = util.class(Decoder)
function ActiveDecoder.__init__(self, source, customnull)
Decoder.__init__(self, customnull)
self.source = source
self.chunk = nil
getmetatable(self).__call = self.get
end
--- Fetches one JSON-object from given source
-- @return Decoded object
function ActiveDecoder.get(self)
local chunk, src_err, object
if not self.chunk then
chunk, src_err = self.source()
else
chunk = self.chunk
end
self.chunk, object = self:dispatch(chunk, src_err, true)
return object
end
function ActiveDecoder.fetch(self)
local chunk, src_err = self.source()
assert(chunk or not src_err, src_err)
return chunk
end
| gpl-2.0 |
pyxenium/EasyAutoLoot | Libs/AceGUI-3.0/widgets/AceGUIContainer-TabGroup.lua | 50 | 10384 | --[[-----------------------------------------------------------------------------
TabGroup Container
Container that uses tabs on top to switch between groups.
-------------------------------------------------------------------------------]]
local Type, Version = "TabGroup", 35
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local pairs, ipairs, assert, type, wipe = pairs, ipairs, assert, type, wipe
-- WoW APIs
local PlaySound = PlaySound
local CreateFrame, UIParent = CreateFrame, UIParent
local _G = _G
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: PanelTemplates_TabResize, PanelTemplates_SetDisabledTabState, PanelTemplates_SelectTab, PanelTemplates_DeselectTab
-- local upvalue storage used by BuildTabs
local widths = {}
local rowwidths = {}
local rowends = {}
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function UpdateTabLook(frame)
if frame.disabled then
PanelTemplates_SetDisabledTabState(frame)
elseif frame.selected then
PanelTemplates_SelectTab(frame)
else
PanelTemplates_DeselectTab(frame)
end
end
local function Tab_SetText(frame, text)
frame:_SetText(text)
local width = frame.obj.frame.width or frame.obj.frame:GetWidth() or 0
PanelTemplates_TabResize(frame, 0, nil, nil, width, frame:GetFontString():GetStringWidth())
end
local function Tab_SetSelected(frame, selected)
frame.selected = selected
UpdateTabLook(frame)
end
local function Tab_SetDisabled(frame, disabled)
frame.disabled = disabled
UpdateTabLook(frame)
end
local function BuildTabsOnUpdate(frame)
local self = frame.obj
self:BuildTabs()
frame:SetScript("OnUpdate", nil)
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Tab_OnClick(frame)
if not (frame.selected or frame.disabled) then
PlaySound("igCharacterInfoTab")
frame.obj:SelectTab(frame.value)
end
end
local function Tab_OnEnter(frame)
local self = frame.obj
self:Fire("OnTabEnter", self.tabs[frame.id].value, frame)
end
local function Tab_OnLeave(frame)
local self = frame.obj
self:Fire("OnTabLeave", self.tabs[frame.id].value, frame)
end
local function Tab_OnShow(frame)
_G[frame:GetName().."HighlightTexture"]:SetWidth(frame:GetTextWidth() + 30)
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetTitle()
end,
["OnRelease"] = function(self)
self.status = nil
for k in pairs(self.localstatus) do
self.localstatus[k] = nil
end
self.tablist = nil
for _, tab in pairs(self.tabs) do
tab:Hide()
end
end,
["CreateTab"] = function(self, id)
local tabname = ("AceGUITabGroup%dTab%d"):format(self.num, id)
local tab = CreateFrame("Button", tabname, self.border, "OptionsFrameTabButtonTemplate")
tab.obj = self
tab.id = id
tab.text = _G[tabname .. "Text"]
tab.text:ClearAllPoints()
tab.text:SetPoint("LEFT", 14, -3)
tab.text:SetPoint("RIGHT", -12, -3)
tab:SetScript("OnClick", Tab_OnClick)
tab:SetScript("OnEnter", Tab_OnEnter)
tab:SetScript("OnLeave", Tab_OnLeave)
tab:SetScript("OnShow", Tab_OnShow)
tab._SetText = tab.SetText
tab.SetText = Tab_SetText
tab.SetSelected = Tab_SetSelected
tab.SetDisabled = Tab_SetDisabled
return tab
end,
["SetTitle"] = function(self, text)
self.titletext:SetText(text or "")
if text and text ~= "" then
self.alignoffset = 25
else
self.alignoffset = 18
end
self:BuildTabs()
end,
["SetStatusTable"] = function(self, status)
assert(type(status) == "table")
self.status = status
end,
["SelectTab"] = function(self, value)
local status = self.status or self.localstatus
local found
for i, v in ipairs(self.tabs) do
if v.value == value then
v:SetSelected(true)
found = true
else
v:SetSelected(false)
end
end
status.selected = value
if found then
self:Fire("OnGroupSelected",value)
end
end,
["SetTabs"] = function(self, tabs)
self.tablist = tabs
self:BuildTabs()
end,
["BuildTabs"] = function(self)
local hastitle = (self.titletext:GetText() and self.titletext:GetText() ~= "")
local status = self.status or self.localstatus
local tablist = self.tablist
local tabs = self.tabs
if not tablist then return end
local width = self.frame.width or self.frame:GetWidth() or 0
wipe(widths)
wipe(rowwidths)
wipe(rowends)
--Place Text into tabs and get thier initial width
for i, v in ipairs(tablist) do
local tab = tabs[i]
if not tab then
tab = self:CreateTab(i)
tabs[i] = tab
end
tab:Show()
tab:SetText(v.text)
tab:SetDisabled(v.disabled)
tab.value = v.value
widths[i] = tab:GetWidth() - 6 --tabs are anchored 10 pixels from the right side of the previous one to reduce spacing, but add a fixed 4px padding for the text
end
for i = (#tablist)+1, #tabs, 1 do
tabs[i]:Hide()
end
--First pass, find the minimum number of rows needed to hold all tabs and the initial tab layout
local numtabs = #tablist
local numrows = 1
local usedwidth = 0
for i = 1, #tablist do
--If this is not the first tab of a row and there isn't room for it
if usedwidth ~= 0 and (width - usedwidth - widths[i]) < 0 then
rowwidths[numrows] = usedwidth + 10 --first tab in each row takes up an extra 10px
rowends[numrows] = i - 1
numrows = numrows + 1
usedwidth = 0
end
usedwidth = usedwidth + widths[i]
end
rowwidths[numrows] = usedwidth + 10 --first tab in each row takes up an extra 10px
rowends[numrows] = #tablist
--Fix for single tabs being left on the last row, move a tab from the row above if applicable
if numrows > 1 then
--if the last row has only one tab
if rowends[numrows-1] == numtabs-1 then
--if there are more than 2 tabs in the 2nd last row
if (numrows == 2 and rowends[numrows-1] > 2) or (rowends[numrows] - rowends[numrows-1] > 2) then
--move 1 tab from the second last row to the last, if there is enough space
if (rowwidths[numrows] + widths[numtabs-1]) <= width then
rowends[numrows-1] = rowends[numrows-1] - 1
rowwidths[numrows] = rowwidths[numrows] + widths[numtabs-1]
rowwidths[numrows-1] = rowwidths[numrows-1] - widths[numtabs-1]
end
end
end
end
--anchor the rows as defined and resize tabs to fill thier row
local starttab = 1
for row, endtab in ipairs(rowends) do
local first = true
for tabno = starttab, endtab do
local tab = tabs[tabno]
tab:ClearAllPoints()
if first then
tab:SetPoint("TOPLEFT", self.frame, "TOPLEFT", 0, -(hastitle and 14 or 7)-(row-1)*20 )
first = false
else
tab:SetPoint("LEFT", tabs[tabno-1], "RIGHT", -10, 0)
end
end
-- equal padding for each tab to fill the available width,
-- if the used space is above 75% already
-- the 18 pixel is the typical width of a scrollbar, so we can have a tab group inside a scrolling frame,
-- and not have the tabs jump around funny when switching between tabs that need scrolling and those that don't
local padding = 0
if not (numrows == 1 and rowwidths[1] < width*0.75 - 18) then
padding = (width - rowwidths[row]) / (endtab - starttab+1)
end
for i = starttab, endtab do
PanelTemplates_TabResize(tabs[i], padding + 4, nil, nil, width, tabs[i]:GetFontString():GetStringWidth())
end
starttab = endtab + 1
end
self.borderoffset = (hastitle and 17 or 10)+((numrows)*20)
self.border:SetPoint("TOPLEFT", 1, -self.borderoffset)
end,
["OnWidthSet"] = function(self, width)
local content = self.content
local contentwidth = width - 60
if contentwidth < 0 then
contentwidth = 0
end
content:SetWidth(contentwidth)
content.width = contentwidth
self:BuildTabs(self)
self.frame:SetScript("OnUpdate", BuildTabsOnUpdate)
end,
["OnHeightSet"] = function(self, height)
local content = self.content
local contentheight = height - (self.borderoffset + 23)
if contentheight < 0 then
contentheight = 0
end
content:SetHeight(contentheight)
content.height = contentheight
end,
["LayoutFinished"] = function(self, width, height)
if self.noAutoHeight then return end
self:SetHeight((height or 0) + (self.borderoffset + 23))
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local PaneBackdrop = {
bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 3, right = 3, top = 5, bottom = 3 }
}
local function Constructor()
local num = AceGUI:GetNextWidgetNum(Type)
local frame = CreateFrame("Frame",nil,UIParent)
frame:SetHeight(100)
frame:SetWidth(100)
frame:SetFrameStrata("FULLSCREEN_DIALOG")
local titletext = frame:CreateFontString(nil,"OVERLAY","GameFontNormal")
titletext:SetPoint("TOPLEFT", 14, 0)
titletext:SetPoint("TOPRIGHT", -14, 0)
titletext:SetJustifyH("LEFT")
titletext:SetHeight(18)
titletext:SetText("")
local border = CreateFrame("Frame", nil, frame)
border:SetPoint("TOPLEFT", 1, -27)
border:SetPoint("BOTTOMRIGHT", -1, 3)
border:SetBackdrop(PaneBackdrop)
border:SetBackdropColor(0.1, 0.1, 0.1, 0.5)
border:SetBackdropBorderColor(0.4, 0.4, 0.4)
local content = CreateFrame("Frame", nil, border)
content:SetPoint("TOPLEFT", 10, -7)
content:SetPoint("BOTTOMRIGHT", -10, 7)
local widget = {
num = num,
frame = frame,
localstatus = {},
alignoffset = 18,
titletext = titletext,
border = border,
borderoffset = 27,
tabs = {},
content = content,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
return AceGUI:RegisterAsContainer(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| mit |
pakoito/ToME---t-engine4 | game/modules/tome/data/general/objects/egos/scrolls.lua | 3 | 1026 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- 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/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
newEntity{
name = "fire-proof ", prefix=true,
level_range = {1, 50},
rarity = 4,
cost = 0.5,
fire_proof = true,
}
newEntity{
name = "long ", prefix=true,
level_range = {1, 50},
rarity = 5,
cost = 2,
multicharge = resolvers.mbonus(4, 2),
}
| gpl-3.0 |
padrinoo1/teleunity | plugins/banhammer.lua | 106 | 11894 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^([Bb]anall) (.*)$",
"^([Bb]anall)$",
"^([Bb]anlist) (.*)$",
"^([Bb]anlist)$",
"^([Gg]banlist)$",
"^([Bb]an) (.*)$",
"^([Kk]ick)$",
"^([Uu]nban) (.*)$",
"^([Uu]nbanall) (.*)$",
"^([Uu]nbanall)$",
"^([Kk]ick) (.*)$",
"^([Kk]ickme)$",
"^([Bb]an)$",
"^([Uu]nban)$",
"^([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
devFRIND/M.F.I_BOT | libs/fakeredis.lua | 650 | 40405 | local unpack = table.unpack or unpack
--- Bit operations
local ok,bit
if _VERSION == "Lua 5.3" then
bit = (load [[ return {
band = function(x, y) return x & y end,
bor = function(x, y) return x | y end,
bxor = function(x, y) return x ~ y end,
bnot = function(x) return ~x end,
rshift = function(x, n) return x >> n end,
lshift = function(x, n) return x << n end,
} ]])()
else
ok,bit = pcall(require,"bit")
if not ok then bit = bit32 end
end
assert(type(bit) == "table", "module for bitops not found")
--- default sleep
local default_sleep
do
local ok, mod = pcall(require, "socket")
if ok and type(mod) == "table" then
default_sleep = mod.sleep
else
default_sleep = function(n)
local t0 = os.clock()
while true do
local delta = os.clock() - t0
if (delta < 0) or (delta > n) then break end
end
end
end
end
--- Helpers
local xdefv = function(ktype)
if ktype == "list" then
return {head = 0, tail = 0}
elseif ktype == "zset" then
return {
list = {},
set = {},
}
else return {} end
end
local xgetr = function(self, k, ktype)
if self.data[k] then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
assert(self.data[k].value)
return self.data[k].value
else return xdefv(ktype) end
end
local xgetw = function(self, k, ktype)
if self.data[k] and self.data[k].value then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
else
self.data[k] = {ktype = ktype, value = xdefv(ktype)}
end
return self.data[k].value
end
local empty = function(self, k)
local v, t = self.data[k].value, self.data[k].ktype
if t == nil then
return true
elseif t == "string" then
return not v[1]
elseif (t == "hash") or (t == "set") then
for _,_ in pairs(v) do return false end
return true
elseif t == "list" then
return v.head == v.tail
elseif t == "zset" then
if #v.list == 0 then
for _,_ in pairs(v.set) do error("incoherent") end
return true
else
for _,_ in pairs(v.set) do return(false) end
error("incoherent")
end
else error("unsupported") end
end
local cleanup = function(self, k)
if empty(self, k) then self.data[k] = nil end
end
local is_integer = function(x)
return (type(x) == "number") and (math.floor(x) == x)
end
local overflows = function(n)
return (n > 2^53-1) or (n < -2^53+1)
end
local is_bounded_integer = function(x)
return (is_integer(x) and (not overflows(x)))
end
local is_finite_number = function(x)
return (type(x) == "number") and (x > -math.huge) and (x < math.huge)
end
local toint = function(x)
if type(x) == "string" then x = tonumber(x) end
return is_bounded_integer(x) and x or nil
end
local tofloat = function(x)
if type(x) == "number" then return x end
if type(x) ~= "string" then return nil end
local r = tonumber(x)
if r then return r end
if x == "inf" or x == "+inf" then
return math.huge
elseif x == "-inf" then
return -math.huge
else return nil end
end
local tostr = function(x)
if is_bounded_integer(x) then
return string.format("%d", x)
else return tostring(x) end
end
local char_bitcount = function(x)
assert(
(type(x) == "number") and
(math.floor(x) == x) and
(x >= 0) and (x < 256)
)
local n = 0
while x ~= 0 do
x = bit.band(x, x-1)
n = n+1
end
return n
end
local chkarg = function(x)
if type(x) == "number" then x = tostr(x) end
assert(type(x) == "string")
return x
end
local chkargs = function(n, ...)
local arg = {...}
assert(#arg == n)
for i=1,n do arg[i] = chkarg(arg[i]) end
return unpack(arg)
end
local getargs = function(...)
local arg = {...}
local n = #arg; assert(n > 0)
for i=1,n do arg[i] = chkarg(arg[i]) end
return arg
end
local getargs_as_map = function(...)
local arg, r = getargs(...), {}
assert(#arg%2 == 0)
for i=1,#arg,2 do r[arg[i]] = arg[i+1] end
return r
end
local chkargs_wrap = function(f, n)
assert( (type(f) == "function") and (type(n) == "number") )
return function(self, ...) return f(self, chkargs(n, ...)) end
end
local lset_to_list = function(s)
local r = {}
for v,_ in pairs(s) do r[#r+1] = v end
return r
end
local nkeys = function(x)
local r = 0
for _,_ in pairs(x) do r = r + 1 end
return r
end
--- Commands
-- keys
local del = function(self, ...)
local arg = getargs(...)
local r = 0
for i=1,#arg do
if self.data[arg[i]] then r = r + 1 end
self.data[arg[i]] = nil
end
return r
end
local exists = function(self, k)
return not not self.data[k]
end
local keys = function(self, pattern)
assert(type(pattern) == "string")
-- We want to convert the Redis pattern to a Lua pattern.
-- Start by escaping dashes *outside* character classes.
-- We also need to escape percents here.
local t, p, n = {}, 1, #pattern
local p1, p2
while true do
p1, p2 = pattern:find("%[.+%]", p)
if p1 then
if p1 > p then
t[#t+1] = {true, pattern:sub(p, p1-1)}
end
t[#t+1] = {false, pattern:sub(p1, p2)}
p = p2+1
if p > n then break end
else
t[#t+1] = {true, pattern:sub(p, n)}
break
end
end
for i=1,#t do
if t[i][1] then
t[i] = t[i][2]:gsub("[%%%-]", "%%%0")
else t[i] = t[i][2]:gsub("%%", "%%%%") end
end
-- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]'
-- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is.
-- Wrap in '^$' to enforce bounds.
local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0")
:gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$"
local r = {}
for k,_ in pairs(self.data) do
if k:match(lp) then r[#r+1] = k end
end
return r
end
local _type = function(self, k)
return self.data[k] and self.data[k].ktype or "none"
end
local randomkey = function(self)
local ks = lset_to_list(self.data)
local n = #ks
if n > 0 then
return ks[math.random(1, n)]
else return nil end
end
local rename = function(self, k, k2)
assert((k ~= k2) and self.data[k])
self.data[k2] = self.data[k]
self.data[k] = nil
return true
end
local renamenx = function(self, k, k2)
if self.data[k2] then
return false
else
return rename(self, k, k2)
end
end
-- strings
local getrange, incrby, set
local append = function(self, k, v)
local x = xgetw(self, k, "string")
x[1] = (x[1] or "") .. v
return #x[1]
end
local bitcount = function(self, k, i1, i2)
k = chkarg(k)
local s
if i1 or i2 then
assert(i1 and i2, "ERR syntax error")
s = getrange(self, k, i1, i2)
else
s = xgetr(self, k, "string")[1] or ""
end
local r, bytes = 0,{s:byte(1, -1)}
for i=1,#bytes do
r = r + char_bitcount(bytes[i])
end
return r
end
local bitop = function(self, op, k, ...)
assert(type(op) == "string")
op = op:lower()
assert(
(op == "and") or
(op == "or") or
(op == "xor") or
(op == "not"),
"ERR syntax error"
)
k = chkarg(k)
local arg = {...}
local good_arity = (op == "not") and (#arg == 1) or (#arg > 0)
assert(good_arity, "ERR wrong number of arguments for 'bitop' command")
local l, vals = 0, {}
local s
for i=1,#arg do
s = xgetr(self, arg[i], "string")[1] or ""
if #s > l then l = #s end
vals[i] = s
end
if l == 0 then
del(self, k)
return 0
end
local vector_mt = {__index=function() return 0 end}
for i=1,#vals do
vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt)
end
local r = {}
if op == "not" then
assert(#vals[1] == l)
for i=1,l do
r[i] = bit.band(bit.bnot(vals[1][i]), 0xff)
end
else
local _op = bit["b" .. op]
for i=1,l do
local t = {}
for j=1,#vals do t[j] = vals[j][i] end
r[i] = _op(unpack(t))
end
end
set(self, k, string.char(unpack(r)))
return l
end
local decr = function(self, k)
return incrby(self, k, -1)
end
local decrby = function(self, k, n)
n = toint(n)
assert(n, "ERR value is not an integer or out of range")
return incrby(self, k, -n)
end
local get = function(self, k)
local x = xgetr(self, k, "string")
return x[1]
end
local getbit = function(self, k, offset)
k = chkarg(k)
offset = toint(offset)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
if bytepos >= #s then return 0 end
local char = s:sub(bytepos+1, bytepos+1):byte()
return bit.band(bit.rshift(char, 7-bitpos), 1)
end
getrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetr(self, k, "string")
x = x[1] or ""
if i1 >= 0 then i1 = i1 + 1 end
if i2 >= 0 then i2 = i2 + 1 end
return x:sub(i1, i2)
end
local getset = function(self, k, v)
local r = get(self, k)
set(self, k, v)
return r
end
local incr = function(self, k)
return incrby(self, k, 1)
end
incrby = function(self, k, n)
k, n = chkarg(k), toint(n)
assert(n, "ERR value is not an integer or out of range")
local x = xgetw(self, k, "string")
local i = toint(x[1] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[1] = tostr(i)
return i
end
local incrbyfloat = function(self, k, n)
k, n = chkarg(k), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "string")
local i = tofloat(x[1] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[1] = tostr(i)
return i
end
local mget = function(self, ...)
local arg, r = getargs(...), {}
for i=1,#arg do r[i] = get(self, arg[i]) end
return r
end
local mset = function(self, ...)
local argmap = getargs_as_map(...)
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
local msetnx = function(self, ...)
local argmap = getargs_as_map(...)
for k,_ in pairs(argmap) do
if self.data[k] then return false end
end
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
set = function(self, k, v)
self.data[k] = {ktype = "string", value = {v}}
return true
end
local setbit = function(self, k, offset, b)
k = chkarg(k)
offset, b = toint(offset), toint(b)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
assert(
(b == 0) or (b == 1),
"ERR bit is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
local pad = {s}
for i=2,bytepos+2-#s do pad[i] = "\0" end
s = table.concat(pad)
assert(#s >= bytepos+1)
local before = s:sub(1, bytepos)
local char = s:sub(bytepos+1, bytepos+1):byte()
local after = s:sub(bytepos+2, -1)
local old = bit.band(bit.rshift(char, 7-bitpos), 1)
if b == 1 then
char = bit.bor(bit.lshift(1, 7-bitpos), char)
else
char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char)
end
local r = before .. string.char(char) .. after
set(self, k, r)
return old
end
local setnx = function(self, k, v)
if self.data[k] then
return false
else
return set(self, k, v)
end
end
local setrange = function(self, k, i, s)
local k, s = chkargs(2, k, s)
i = toint(i)
assert(i and (i >= 0))
local x = xgetw(self, k, "string")
local y = x[1] or ""
local ly, ls = #y, #s
if i > ly then -- zero padding
local t = {}
for i=1, i-ly do t[i] = "\0" end
y = y .. table.concat(t) .. s
else
y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly)
end
x[1] = y
return #y
end
local strlen = function(self, k)
local x = xgetr(self, k, "string")
return x[1] and #x[1] or 0
end
-- hashes
local hdel = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local r = 0
local x = xgetw(self, k, "hash")
for i=1,#arg do
if x[arg[i]] then r = r + 1 end
x[arg[i]] = nil
end
cleanup(self, k)
return r
end
local hget
local hexists = function(self, k, k2)
return not not hget(self, k, k2)
end
hget = function(self, k, k2)
local x = xgetr(self, k, "hash")
return x[k2]
end
local hgetall = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,v in pairs(x) do r[_k] = v end
return r
end
local hincrby = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), toint(n)
assert(n, "ERR value is not an integer or out of range")
assert(type(n) == "number")
local x = xgetw(self, k, "hash")
local i = toint(x[k2] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[k2] = tostr(i)
return i
end
local hincrbyfloat = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "hash")
local i = tofloat(x[k2] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[k2] = tostr(i)
return i
end
local hkeys = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,_ in pairs(x) do r[#r+1] = _k end
return r
end
local hlen = function(self, k)
local x = xgetr(self, k, "hash")
return nkeys(x)
end
local hmget = function(self, k, k2s)
k = chkarg(k)
assert((type(k2s) == "table"))
local r = {}
local x = xgetr(self, k, "hash")
for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end
return r
end
local hmset = function(self, k, ...)
k = chkarg(k)
local arg = {...}
if type(arg[1]) == "table" then
assert(#arg == 1)
local x = xgetw(self, k, "hash")
for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end
else
assert(#arg % 2 == 0)
local x = xgetw(self, k, "hash")
local t = getargs(...)
for i=1,#t,2 do x[t[i]] = t[i+1] end
end
return true
end
local hset = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
local r = not x[k2]
x[k2] = v
return r
end
local hsetnx = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
if x[k2] == nil then
x[k2] = v
return true
else
return false
end
end
local hvals = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _,v in pairs(x) do r[#r+1] = v end
return r
end
-- lists (head = left, tail = right)
local _l_real_i = function(x, i)
if i < 0 then
return x.tail+i+1
else
return x.head+i+1
end
end
local _l_len = function(x)
return x.tail - x.head
end
local _block_for = function(self, timeout)
if timeout > 0 then
local sleep = self.sleep or default_sleep
if type(sleep) == "function" then
sleep(timeout)
else
error("sleep function unavailable", 0)
end
else
error("operation would block", 0)
end
end
local rpoplpush
local blpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpoplpush = function(self, k1, k2, timeout)
k1, k2 = chkargs(2, k1, k2)
timeout = toint(timeout)
if not self.data[k1] then _block_for(self, timeout) end
return rpoplpush(self, k1, k2)
end
local lindex = function(self, k, i)
k = chkarg(k)
i = assert(toint(i))
local x = xgetr(self, k, "list")
return x[_l_real_i(x, i)]
end
local linsert = function(self, k, mode, pivot, v)
mode = mode:lower()
assert((mode == "before") or (mode == "after"))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local p = nil
for i=x.head+1, x.tail do
if x[i] == pivot then
p = i
break
end
end
if not p then return -1 end
if mode == "after" then
for i=x.head+1, p do x[i-1] = x[i] end
x.head = x.head - 1
else
for i=x.tail, p, -1 do x[i+1] = x[i] end
x.tail = x.tail + 1
end
x[p] = v
return _l_len(x)
end
local llen = function(self, k)
local x = xgetr(self, k, "list")
return _l_len(x)
end
local lpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return r
end
local lpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x[x.head] = vs[i]
x.head = x.head - 1
end
return _l_len(x)
end
local lpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x[x.head] = v
x.head = x.head - 1
return _l_len(x)
end
local lrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x, r = xgetr(self, k, "list"), {}
i1 = math.max(_l_real_i(x, i1), x.head+1)
i2 = math.min(_l_real_i(x, i2), x.tail)
for i=i1,i2 do r[#r+1] = x[i] end
return r
end
local _lrem_i = function(x, p)
for i=p,x.tail do
x[i] = x[i+1]
end
x.tail = x.tail - 1
end
local _lrem_l = function(x, v, s)
assert(v)
if not s then s = x.head+1 end
for i=s,x.tail do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local _lrem_r = function(x, v, s)
assert(v)
if not s then s = x.tail end
for i=s,x.head+1,-1 do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local lrem = function(self, k, count, v)
k, v = chkarg(k), chkarg(v)
count = assert(toint(count))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local n, last = 0, nil
local op = (count < 0) and _lrem_r or _lrem_l
local limited = (count ~= 0)
count = math.abs(count)
while true do
last = op(x, v, last)
if last then
n = n+1
if limited then
count = count - 1
if count == 0 then break end
end
else break end
end
return n
end
local lset = function(self, k, i, v)
k, v = chkarg(k), chkarg(v)
i = assert(toint(i))
if not self.data[k] then
error("ERR no such key")
end
local x = xgetw(self, k, "list")
local l = _l_len(x)
if i >= l or i < -l then
error("ERR index out of range")
end
x[_l_real_i(x, i)] = v
return true
end
local ltrim = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetw(self, k, "list")
i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2)
for i=x.head+1,i1-1 do x[i] = nil end
for i=i2+1,x.tail do x[i] = nil end
x.head = math.max(i1-1, x.head)
x.tail = math.min(i2, x.tail)
assert(
(x[x.head] == nil) and
(x[x.tail+1] == nil)
)
cleanup(self, k)
return true
end
local rpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return r
end
rpoplpush = function(self, k1, k2)
local v = rpop(self, k1)
if not v then return nil end
lpush(self, k2, v)
return v
end
local rpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x.tail = x.tail + 1
x[x.tail] = vs[i]
end
return _l_len(x)
end
local rpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x.tail = x.tail + 1
x[x.tail] = v
return _l_len(x)
end
-- sets
local sadd = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if not x[arg[i]] then
x[arg[i]] = true
r = r + 1
end
end
return r
end
local scard = function(self, k)
local x = xgetr(self, k, "set")
return nkeys(x)
end
local _sdiff = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
for v,_ in pairs(x) do r[v] = true end
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = nil end
end
return r
end
local sdiff = function(self, k, ...)
return lset_to_list(_sdiff(self, k, ...))
end
local sdiffstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sdiff(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local _sinter = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
local y
for v,_ in pairs(x) do
r[v] = true
for i=1,#arg do
y = xgetr(self, arg[i], "set")
if not y[v] then r[v] = nil; break end
end
end
return r
end
local sinter = function(self, k, ...)
return lset_to_list(_sinter(self, k, ...))
end
local sinterstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sinter(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local sismember = function(self, k, v)
local x = xgetr(self, k, "set")
return not not x[v]
end
local smembers = function(self, k)
local x = xgetr(self, k, "set")
return lset_to_list(x)
end
local smove = function(self, k, k2, v)
local x = xgetr(self, k, "set")
if x[v] then
local y = xgetw(self, k2, "set")
x[v] = nil
y[v] = true
return true
else return false end
end
local spop = function(self, k)
local x, r = xgetw(self, k, "set"), nil
local l = lset_to_list(x)
local n = #l
if n > 0 then
r = l[math.random(1, n)]
x[r] = nil
end
cleanup(self, k)
return r
end
local srandmember = function(self, k, count)
k = chkarg(k)
local x = xgetr(self, k, "set")
local l = lset_to_list(x)
local n = #l
if not count then
if n > 0 then
return l[math.random(1, n)]
else return nil end
end
count = toint(count)
if (count == 0) or (n == 0) then return {} end
if count >= n then return l end
local r = {}
if count > 0 then -- distinct elements
for i=0,count-1 do
r[#r+1] = table.remove(l, math.random(1, n-i))
end
else -- allow repetition
for i=1,-count do
r[#r+1] = l[math.random(1, n)]
end
end
return r
end
local srem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if x[arg[i]] then
x[arg[i]] = nil
r = r + 1
end
end
cleanup(self, k)
return r
end
local _sunion = function(self, ...)
local arg = getargs(...)
local r = {}
local x
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = true end
end
return r
end
local sunion = function(self, k, ...)
return lset_to_list(_sunion(self, k, ...))
end
local sunionstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sunion(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
-- zsets
local _z_p_mt = {
__eq = function(a, b)
if a.v == b.v then
assert(a.s == b.s)
return true
else return false end
end,
__lt = function(a, b)
if a.s == b.s then
return (a.v < b.v)
else
return (a.s < b.s)
end
end,
}
local _z_pair = function(s, v)
assert(
(type(s) == "number") and
(type(v) == "string")
)
local r = {s = s, v = v}
return setmetatable(r, _z_p_mt)
end
local _z_pairs = function(...)
local arg = {...}
assert((#arg > 0) and (#arg % 2 == 0))
local ps = {}
for i=1,#arg,2 do
ps[#ps+1] = _z_pair(
assert(tofloat(arg[i])),
chkarg(arg[i+1])
)
end
return ps
end
local _z_insert = function(x, ix, p)
assert(
(type(x) == "table") and
(type(ix) == "number") and
(type(p) == "table")
)
local l = x.list
table.insert(l, ix, p)
for i=ix+1,#l do
x.set[l[i].v] = x.set[l[i].v] + 1
end
x.set[p.v] = ix
end
local _z_remove = function(x, v)
if not x.set[v] then return false end
local l, ix = x.list, x.set[v]
assert(l[ix].v == v)
table.remove(l, ix)
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - 1
end
x.set[v] = nil
return true
end
local _z_remove_range = function(x, i1, i2)
local l = x.list
i2 = i2 or i1
assert(
(i1 > 0) and
(i2 >= i1) and
(i2 <= #l)
)
local ix, n = i1, i2-i1+1
for i=1,n do
x.set[l[ix].v] = nil
table.remove(l, ix)
end
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - n
end
return n
end
local _z_update = function(x, p)
local l = x.list
local found = _z_remove(x, p.v)
local ix = nil
for i=1,#l do
if l[i] > p then
ix = i; break
end
end
if not ix then ix = #l+1 end
_z_insert(x, ix, p)
return found
end
local _z_coherence = function(x)
local l, s = x.list, x.set
local found, n = {}, 0
for val,pos in pairs(s) do
if found[pos] then return false end
found[pos] = true
n = n + 1
if not (l[pos] and (l[pos].v == val)) then
return false
end
end
if #l ~= n then return false end
for i=1, n-1 do
if l[i].s > l[i+1].s then return false end
end
return true
end
local _z_normrange = function(l, i1, i2)
i1, i2 = assert(toint(i1)), assert(toint(i2))
if i1 < 0 then i1 = #l+i1 end
if i2 < 0 then i2 = #l+i2 end
i1, i2 = math.max(i1+1, 1), i2+1
if (i2 < i1) or (i1 > #l) then return nil end
i2 = math.min(i2, #l)
return i1, i2
end
local _zrbs_opts = function(...)
local arg = {...}
if #arg == 0 then return {} end
local ix, opts = 1, {}
while type(arg[ix]) == "string" do
if arg[ix] == "withscores" then
opts.withscores = true
ix = ix + 1
elseif arg[ix] == "limit" then
opts.limit = {
offset = assert(toint(arg[ix+1])),
count = assert(toint(arg[ix+2])),
}
ix = ix + 3
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.withscores = opts.withscores or _o.withscores
if _o.limit then
opts.limit = {
offset = assert(toint(_o.limit.offset or _o.limit[1])),
count = assert(toint(_o.limit.count or _o.limit[2])),
}
end
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.limit then
assert(
(opts.limit.count >= 0) and
(opts.limit.offset >= 0)
)
end
return opts
end
local _z_store_params = function(dest, numkeys, ...)
dest = chkarg(dest)
numkeys = assert(toint(numkeys))
assert(numkeys > 0)
local arg = {...}
assert(#arg >= numkeys)
local ks = {}
for i=1, numkeys do ks[i] = chkarg(arg[i]) end
local ix, opts = numkeys+1,{}
while type(arg[ix]) == "string" do
if arg[ix] == "weights" then
opts.weights = {}
ix = ix + 1
for i=1, numkeys do
opts.weights[i] = assert(toint(arg[ix]))
ix = ix + 1
end
elseif arg[ix] == "aggregate" then
opts.aggregate = assert(chkarg(arg[ix+1]))
ix = ix + 2
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.weights = opts.weights or _o.weights
opts.aggregate = opts.aggregate or _o.aggregate
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.aggregate then
assert(
(opts.aggregate == "sum") or
(opts.aggregate == "min") or
(opts.aggregate == "max")
)
else opts.aggregate = "sum" end
if opts.weights then
assert(#opts.weights == numkeys)
for i=1,#opts.weights do
assert(type(opts.weights[i]) == "number")
end
else
opts.weights = {}
for i=1, numkeys do opts.weights[i] = 1 end
end
opts.keys = ks
opts.dest = dest
return opts
end
local _zrbs_limits = function(x, s1, s2, descending)
local s1_incl, s2_incl = true, true
if s1:sub(1, 1) == "(" then
s1, s1_incl = s1:sub(2, -1), false
end
s1 = assert(tofloat(s1))
if s2:sub(1, 1) == "(" then
s2, s2_incl = s2:sub(2, -1), false
end
s2 = assert(tofloat(s2))
if descending then
s1, s2 = s2, s1
s1_incl, s2_incl = s2_incl, s1_incl
end
if s2 < s1 then return nil end
local l = x.list
local i1, i2
local fst, lst = l[1].s, l[#l].s
if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end
if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end
if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end
if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end
for i=1,#l do
if (i1 and i2) then break end
if (not i1) then
if l[i].s > s1 then i1 = i end
if s1_incl and l[i].s == s1 then i1 = i end
end
if (not i2) then
if l[i].s > s2 then i2 = i-1 end
if (not s2_incl) and l[i].s == s2 then i2 = i-1 end
end
end
assert(i1 and i2)
if descending then
return #l-i2, #l-i1
else
return i1-1, i2-1
end
end
local dbg_zcoherence = function(self, k)
local x = xgetr(self, k, "zset")
return _z_coherence(x)
end
local zadd = function(self, k, ...)
k = chkarg(k)
local ps = _z_pairs(...)
local x = xgetw(self, k, "zset")
local n = 0
for i=1,#ps do
if not _z_update(x, ps[i]) then n = n+1 end
end
return n
end
local zcard = function(self, k)
local x = xgetr(self, k, "zset")
return #x.list
end
local zcount = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return i2 - i1 + 1
end
local zincrby = function(self, k, n, v)
k,v = chkargs(2, k, v)
n = assert(tofloat(n))
local x = xgetw(self, k, "zset")
local p = x.list[x.set[v]]
local s = p and (p.s + n) or n
_z_update(x, _z_pair(s, v))
return s
end
local zinterstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local aggregate
if params.aggregate == "sum" then
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
aggregate = math.min
elseif params.aggregate == "max" then
aggregate = math.max
else error() end
local y = xgetr(self, params.keys[1], "zset")
local p1, p2
for j=1,#y.list do
p1 = _z_pair(y.list[j].s, y.list[j].v)
_z_update(x, p1)
end
for i=2,#params.keys do
y = xgetr(self, params.keys[i], "zset")
local to_remove, to_update = {}, {}
for j=1,#x.list do
p1 = x.list[j]
if y.set[p1.v] then
p2 = _z_pair(
aggregate(
p1.s,
params.weights[i] * y.list[y.set[p1.v]].s
),
p1.v
)
to_update[#to_update+1] = p2
else
to_remove[#to_remove+1] = p1.v
end
end
for j=1,#to_remove do _z_remove(x, to_remove[j]) end
for j=1,#to_update do _z_update(x, to_update[j]) end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
local _zranger = function(descending)
return function(self, k, i1, i2, opts)
k = chkarg(k)
local withscores = false
if type(opts) == "table" then
withscores = opts.withscores
elseif type(opts) == "string" then
assert(opts:lower() == "withscores")
withscores = true
else assert(opts == nil) end
local x = xgetr(self, k, "zset")
local l = x.list
i1, i2 = _z_normrange(l, i1, i2)
if not i1 then return {} end
local inc = 1
if descending then
i1 = #l - i1 + 1
i2 = #l - i2 + 1
inc = -1
end
local r = {}
if withscores then
for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end
else
for i=i1, i2, inc do r[#r+1] = l[i].v end
end
return r
end
end
local zrange = _zranger(false)
local zrevrange = _zranger(true)
local _zrangerbyscore = function(descending)
return function(self, k, s1, s2, ...)
k, s1, s2 = chkargs(3, k, s1, s2)
local opts = _zrbs_opts(...)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, descending)
if not (i1 and i2) then return {} end
if opts.limit then
if opts.limit.count == 0 then return {} end
i1 = i1 + opts.limit.offset
if i1 > i2 then return {} end
i2 = math.min(i2, i1+opts.limit.count-1)
end
if descending then
return zrevrange(self, k, i1, i2, opts)
else
return zrange(self, k, i1, i2, opts)
end
end
end
local zrangebyscore = _zrangerbyscore(false)
local zrevrangebyscore = _zrangerbyscore(true)
local zrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return r-1
else return nil end
end
local zrem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "zset"), 0
for i=1,#arg do
if _z_remove(x, arg[i]) then r = r + 1 end
end
cleanup(self, k)
return r
end
local zremrangebyrank = function(self, k, i1, i2)
k = chkarg(k)
local x = xgetw(self, k, "zset")
i1, i2 = _z_normrange(x.list, i1, i2)
if not i1 then
cleanup(self, k)
return 0
end
local n = _z_remove_range(x, i1, i2)
cleanup(self, k)
return n
end
local zremrangebyscore = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return zremrangebyrank(self, k, i1, i2)
end
local zrevrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return #x.list-r
else return nil end
end
local zscore = function(self, k, v)
local x = xgetr(self, k, "zset")
local p = x.list[x.set[v]]
if p then
return p.s
else return nil end
end
local zunionstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local default_score, aggregate
if params.aggregate == "sum" then
default_score = 0
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
default_score = math.huge
aggregate = math.min
elseif params.aggregate == "max" then
default_score = -math.huge
aggregate = math.max
else error() end
local y, p1, p2
for i=1,#params.keys do
y = xgetr(self, params.keys[i], "zset")
for j=1,#y.list do
p1 = y.list[j]
p2 = _z_pair(
aggregate(
params.weights[i] * p1.s,
x.set[p1.v] and x.list[x.set[p1.v]].s or default_score
),
p1.v
)
_z_update(x, p2)
end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
-- connection
local echo = function(self, v)
return v
end
local ping = function(self)
return true
end
-- server
local flushdb = function(self)
self.data = {}
return true
end
--- Class
local methods = {
-- keys
del = del, -- (...) -> #removed
exists = chkargs_wrap(exists, 1), -- (k) -> exists?
keys = keys, -- (pattern) -> list of keys
["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none]
randomkey = randomkey, -- () -> [k|nil]
rename = chkargs_wrap(rename, 2), -- (k,k2) -> true
renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2
-- strings
append = chkargs_wrap(append, 2), -- (k,v) -> #new
bitcount = bitcount, -- (k,[start,end]) -> n
bitop = bitop, -- ([and|or|xor|not],k,...)
decr = chkargs_wrap(decr, 1), -- (k) -> new
decrby = decrby, -- (k,n) -> new
get = chkargs_wrap(get, 1), -- (k) -> [v|nil]
getbit = getbit, -- (k,offset) -> b
getrange = getrange, -- (k,start,end) -> string
getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil]
incr = chkargs_wrap(incr, 1), -- (k) -> new
incrby = incrby, -- (k,n) -> new
incrbyfloat = incrbyfloat, -- (k,n) -> new
mget = mget, -- (k1,...) -> {v1,...}
mset = mset, -- (k1,v1,...) -> true
msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k)
set = chkargs_wrap(set, 2), -- (k,v) -> true
setbit = setbit, -- (k,offset,b) -> old
setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?)
setrange = setrange, -- (k,offset,val) -> #new
strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0]
-- hashes
hdel = hdel, -- (k,sk1,...) -> #removed
hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists?
hget = chkargs_wrap(hget,2), -- (k,sk) -> v
hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map
hincrby = hincrby, -- (k,sk,n) -> new
hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new
hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys
hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0]
hmget = hmget, -- (k,{sk1,...}) -> {v1,...}
hmset = hmset, -- (k,{sk1=v1,...}) -> true
hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed?
hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?)
hvals = chkargs_wrap(hvals, 1), -- (k) -> values
-- lists
blpop = blpop, -- (k1,...) -> k,v
brpop = brpop, -- (k1,...) -> k,v
brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v
lindex = lindex, -- (k,i) -> v
linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after)
llen = chkargs_wrap(llen, 1), -- (k) -> #list
lpop = chkargs_wrap(lpop, 1), -- (k) -> v
lpush = lpush, -- (k,v1,...) -> #list (after)
lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after)
lrange = lrange, -- (k,start,stop) -> list
lrem = lrem, -- (k,count,v) -> #removed
lset = lset, -- (k,i,v) -> true
ltrim = ltrim, -- (k,start,stop) -> true
rpop = chkargs_wrap(rpop, 1), -- (k) -> v
rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v
rpush = rpush, -- (k,v1,...) -> #list (after)
rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after)
-- sets
sadd = sadd, -- (k,v1,...) -> #added
scard = chkargs_wrap(scard, 1), -- (k) -> [n|0]
sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...)
sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0
sinter = sinter, -- (k1,...) -> set
sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0
sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member?
smembers = chkargs_wrap(smembers, 1), -- (k) -> set
smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1)
spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil]
srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...]
srem = srem, -- (k,v1,...) -> #removed
sunion = sunion, -- (k1,...) -> set
sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0
-- zsets
zadd = zadd, -- (k,score,member,[score,member,...])
zcard = chkargs_wrap(zcard, 1), -- (k) -> n
zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count
zincrby = zincrby, -- (k,score,v) -> score
zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card
zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts
zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank
zrem = zrem, -- (k,v1,...) -> #removed
zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed
zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed
zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts
zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank
zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score
zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card
-- connection
echo = chkargs_wrap(echo, 1), -- (v) -> v
ping = ping, -- () -> true
-- server
flushall = flushdb, -- () -> true
flushdb = flushdb, -- () -> true
-- debug
dbg_zcoherence = dbg_zcoherence,
}
local new = function()
local r = {data = {}}
return setmetatable(r,{__index = methods})
end
return {
new = new,
}
| gpl-2.0 |
madpilot78/ntopng | scripts/lua/rest/v2/acknowledge/flow/alerts.lua | 1 | 1074 | --
-- (C) 2013-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
package.path = dirs.installdir .. "/scripts/lua/modules/alert_store/?.lua;" .. package.path
local alert_utils = require "alert_utils"
local alert_consts = require "alert_consts"
local alert_entities = require "alert_entities"
local rest_utils = require("rest_utils")
local flow_alert_store = require "flow_alert_store".new()
--
-- Read alerts data
-- Example: curl -u admin:admin -H "Content-Type: application/json" -d '{"ifid": "1"}' http://localhost:3000/lua/rest/v2/acknowledge/flow/alerts.lua
--
-- NOTE: in case of invalid login, no error is returned but redirected to login
--
local rc = rest_utils.consts.success.ok
local res = {}
local ifid = _GET["ifid"]
if isEmptyString(ifid) then
rc = rest_utils.consts.err.invalid_interface
rest_utils.answer(rc)
return
end
interface.select(ifid)
-- Add filters
flow_alert_store:add_request_filters()
flow_alert_store:acknowledge(_GET["label"])
rest_utils.answer(rc)
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/example/class/Player.lua | 3 | 6384 | -- ToME - Tales of Middle-Earth
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- 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/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
require "mod.class.Actor"
require "engine.interface.PlayerRest"
require "engine.interface.PlayerRun"
require "engine.interface.PlayerMouse"
require "engine.interface.PlayerHotkeys"
local Map = require "engine.Map"
local Dialog = require "engine.Dialog"
local ActorTalents = require "engine.interface.ActorTalents"
local DeathDialog = require "mod.dialogs.DeathDialog"
local Astar = require"engine.Astar"
local DirectPath = require"engine.DirectPath"
--- Defines the player
-- It is a normal actor, with some redefined methods to handle user interaction.<br/>
-- It is also able to run and rest and use hotkeys
module(..., package.seeall, class.inherit(
mod.class.Actor,
engine.interface.PlayerRest,
engine.interface.PlayerRun,
engine.interface.PlayerMouse,
engine.interface.PlayerHotkeys
))
function _M:init(t, no_default)
t.display=t.display or '@'
t.color_r=t.color_r or 230
t.color_g=t.color_g or 230
t.color_b=t.color_b or 230
t.player = true
t.type = t.type or "humanoid"
t.subtype = t.subtype or "player"
t.faction = t.faction or "players"
t.lite = t.lite or 0
mod.class.Actor.init(self, t, no_default)
engine.interface.PlayerHotkeys.init(self, t)
self.descriptor = {}
end
function _M:move(x, y, force)
local moved = mod.class.Actor.move(self, x, y, force)
if moved then
game.level.map:moveViewSurround(self.x, self.y, 8, 8)
end
return moved
end
function _M:act()
if not mod.class.Actor.act(self) then return end
-- Clean log flasher
game.flash:empty()
-- Resting ? Running ? Otherwise pause
if not self:restStep() and not self:runStep() and self.player then
game.paused = true
end
end
-- Precompute FOV form, for speed
local fovdist = {}
for i = 0, 30 * 30 do
fovdist[i] = math.max((20 - math.sqrt(i)) / 14, 0.6)
end
function _M:playerFOV()
-- Clean FOV before computing it
game.level.map:cleanFOV()
-- Compute both the normal and the lite FOV, using cache
self:computeFOV(self.sight or 20, "block_sight", function(x, y, dx, dy, sqdist)
game.level.map:apply(x, y, fovdist[sqdist])
end, true, false, true)
self:computeFOV(self.lite, "block_sight", function(x, y, dx, dy, sqdist) game.level.map:applyLite(x, y) end, true, true, true)
end
--- Called before taking a hit, overload mod.class.Actor:onTakeHit() to stop resting and running
function _M:onTakeHit(value, src)
self:runStop("taken damage")
self:restStop("taken damage")
local ret = mod.class.Actor.onTakeHit(self, value, src)
if self.life < self.max_life * 0.3 then
local sx, sy = game.level.map:getTileToScreen(self.x, self.y)
game.flyers:add(sx, sy, 30, (rng.range(0,2)-1) * 0.5, 2, "LOW HEALTH!", {255,0,0}, true)
end
return ret
end
function _M:die(src)
if self.game_ender then
engine.interface.ActorLife.die(self, src)
game.paused = true
self.energy.value = game.energy_to_act
game:registerDialog(DeathDialog.new(self))
else
mod.class.Actor.die(self, src)
end
end
function _M:setName(name)
self.name = name
game.save_name = name
end
--- Notify the player of available cooldowns
function _M:onTalentCooledDown(tid)
local t = self:getTalentFromId(tid)
local x, y = game.level.map:getTileToScreen(self.x, self.y)
game.flyers:add(x, y, 30, -0.3, -3.5, ("%s available"):format(t.name:capitalize()), {0,255,00})
game.log("#00ff00#Talent %s is ready to use.", t.name)
end
function _M:levelup()
mod.class.Actor.levelup(self)
local x, y = game.level.map:getTileToScreen(self.x, self.y)
game.flyers:add(x, y, 80, 0.5, -2, "LEVEL UP!", {0,255,255})
game.log("#00ffff#Welcome to level %d.", self.level)
end
--- Tries to get a target from the user
function _M:getTarget(typ)
return game:targetGetForPlayer(typ)
end
--- Sets the current target
function _M:setTarget(target)
return game:targetSetForPlayer(target)
end
local function spotHostiles(self)
local seen = false
-- Check for visible monsters, only see LOS actors, so telepathy wont prevent resting
core.fov.calc_circle(self.x, self.y, game.level.map.w, game.level.map.h, 20, function(_, x, y) return game.level.map:opaque(x, y) end, function(_, x, y)
local actor = game.level.map(x, y, game.level.map.ACTOR)
if actor and self:reactionToward(actor) < 0 and self:canSee(actor) and game.level.map.seens(x, y) then seen = true end
end, nil)
return seen
end
--- Can we continue resting ?
-- We can rest if no hostiles are in sight, and if we need life/mana/stamina (and their regen rates allows them to fully regen)
function _M:restCheck()
if spotHostiles(self) then return false, "hostile spotted" end
-- Check resources, make sure they CAN go up, otherwise we will never stop
if self:getPower() < self:getMaxPower() and self.power_regen > 0 then return true end
if self.life < self.max_life and self.life_regen> 0 then return true end
return false, "all resources and life at maximum"
end
--- Can we continue running?
-- We can run if no hostiles are in sight, and if we no interesting terrains are next to us
function _M:runCheck()
if spotHostiles(self) then return false, "hostile spotted" end
-- Notice any noticeable terrain
local noticed = false
self:runScan(function(x, y)
-- Only notice interesting terrains
local grid = game.level.map(x, y, Map.TERRAIN)
if grid and grid.notice then noticed = "interesting terrain" end
end)
if noticed then return false, noticed end
self:playerFOV()
return engine.interface.PlayerRun.runCheck(self)
end
--- Move with the mouse
-- We just feed our spotHostile to the interface mouseMove
function _M:mouseMove(tmx, tmy)
return engine.interface.PlayerMouse.mouseMove(self, tmx, tmy, spotHostiles)
end
| gpl-3.0 |
RyMarq/Zero-K | scripts/tankriot.lua | 7 | 5747 | include "constants.lua"
include "rockPiece.lua"
include "trackControl.lua"
include "pieceControl.lua"
local dynamicRockData
local scriptReload = include("scriptReload.lua")
local base, turret, sleeve = piece ('base', 'turret', 'sleeve')
local missiles = {
piece ('dummy1'),
piece ('dummy2'),
}
local isLoaded = {
true,
true,
}
local RELOAD_TIME = 2.3 * 30
local SIG_AIM = 1
local SIG_MOVE = 2
local SIG_ROCK_X = 4
local SIG_ROCK_Z = 8
local ROCK_FIRE_FORCE = 0.06
local ROCK_SPEED = 18 --Number of half-cycles per second around x-axis.
local ROCK_DECAY = -0.25 --Rocking around axis is reduced by this factor each time = piece 'to rock.
local ROCK_PIECE = base -- should be negative to alternate rocking direction.
local ROCK_MIN = 0.001 --If around axis rock is not greater than this amount, rocking will stop after returning to center.
local ROCK_MAX = 1.5
local hpi = math.pi*0.5
local rockData = {
[x_axis] = {
piece = ROCK_PIECE,
speed = ROCK_SPEED,
decay = ROCK_DECAY,
minPos = ROCK_MIN,
maxPos = ROCK_MAX,
signal = SIG_ROCK_X,
axis = x_axis,
},
[z_axis] = {
piece = ROCK_PIECE,
speed = ROCK_SPEED,
decay = ROCK_DECAY,
minPos = ROCK_MIN,
maxPos = ROCK_MAX,
signal = SIG_ROCK_Z,
axis = z_axis,
},
}
local trackData = {
wheels = {
large = {piece('wheels1'), piece('wheels8')},
small = {},
},
tracks = {},
signal = SIG_MOVE,
smallSpeed = math.rad(540),
smallAccel = math.rad(15),
smallDecel = math.rad(45),
largeSpeed = math.rad(360),
largeAccel = math.rad(10),
largeDecel = math.rad(30),
trackPeriod = 66,
}
for i = 2, 7 do
trackData.wheels.small[i-1] = piece('wheels' .. i)
end
for i = 1, 4 do
trackData.tracks[i] = piece ('tracks' .. i)
end
local gunHeading = 0
local disarmed = false
local stuns = {false, false, false}
local isAiming = false
local currentMissile = 1
local smokePiece = {base, turret}
local function RestoreAfterDelay()
SetSignalMask (SIG_AIM)
Sleep (5000)
Turn (turret, y_axis, 0, math.rad (50))
Turn (sleeve, x_axis, 0, math.rad (50))
WaitForTurn (turret, y_axis)
WaitForTurn (sleeve, x_axis)
isAiming = false
end
function StunThread()
disarmed = true
Signal (SIG_AIM)
GG.PieceControl.StopTurn(turret, y_axis)
GG.PieceControl.StopTurn(sleeve, x_axis)
end
function UnstunThread()
disarmed = false
if isAiming then
StartThread(RestoreAfterDelay)
end
end
function Stunned(stun_type)
-- since only the turret is animated, treat all types the same since they all disable weaponry
stuns[stun_type] = true
StartThread (StunThread)
end
function Unstunned(stun_type)
stuns[stun_type] = false
if not stuns[1] and not stuns[2] and not stuns[3] then
StartThread (UnstunThread)
end
end
function script.StartMoving()
StartThread(TrackControlStartMoving)
end
function script.StopMoving()
TrackControlStopMoving()
end
function script.AimFromWeapon()
return sleeve
end
function script.QueryWeapon()
return missiles[currentMissile]
end
function script.AimWeapon(num, heading, pitch)
Signal (SIG_AIM)
SetSignalMask (SIG_AIM)
isAiming = true
while disarmed do
Sleep (34)
end
local slowMult = (Spring.GetUnitRulesParam (unitID, "baseSpeedMult") or 1)
Turn (turret, y_axis, heading, math.rad(200)*slowMult)
Turn (sleeve, x_axis, -pitch, math.rad(200)*slowMult)
WaitForTurn (turret, y_axis)
WaitForTurn (sleeve, x_axis)
StartThread (RestoreAfterDelay)
gunHeading = heading
return true
end
local SleepAndUpdateReload = scriptReload.SleepAndUpdateReload
local function reload(num)
scriptReload.GunStartReload(num)
isLoaded[num] = false
SleepAndUpdateReload(num, RELOAD_TIME)
isLoaded[num] = true
end
local function ReloadThread(missile)
Hide (missiles[missile])
Move (missiles[missile], z_axis, -5)
Sleep (1000)
Show (missiles[missile])
Move (missiles[missile], z_axis, 0.8, 5.5)
end
function script.FireWeapon()
StartThread(ReloadThread, currentMissile)
StartThread(GG.ScriptRock.Rock, dynamicRockData[z_axis], gunHeading, ROCK_FIRE_FORCE)
StartThread(GG.ScriptRock.Rock, dynamicRockData[x_axis], gunHeading - hpi, ROCK_FIRE_FORCE)
end
function script.EndBurst()
StartThread(reload, currentMissile)
currentMissile = 3 - currentMissile
end
function script.BlockShot(num, targetID)
if isLoaded[currentMissile] then
if not targetID then
return false
end
local distMult = (Spring.GetUnitSeparation(unitID, targetID) or 0) * 0.083
return GG.OverkillPrevention_CheckBlock(unitID, targetID, 240.5, distMult)
end
return true
end
function script.Create()
scriptReload.SetupScriptReload(2, RELOAD_TIME)
dynamicRockData = GG.ScriptRock.InitializeRock(rockData)
InitiailizeTrackControl(trackData)
while (select(5, Spring.GetUnitHealth(unitID)) < 1) do
Sleep (250)
end
Move(missiles[1], z_axis, 0.8)
Move(missiles[2], z_axis, 0.8)
StartThread (GG.Script.SmokeUnit, unitID, smokePiece)
end
function script.Killed (recentDamage, maxHealth)
local severity = recentDamage / maxHealth
if (severity < 0.5) then
if (math.random() < 2*severity) then Explode (missiles[1], SFX.FALL + SFX.FIRE) end
if (math.random() < 2*severity) then Explode (missiles[2], SFX.FALL + SFX.SMOKE) end
return 1
elseif (severity < 0.75) then
if (math.random() < severity) then
Explode (turret, SFX.FALL)
end
Explode(sleeve, SFX.FALL)
Explode(trackData.tracks[1], SFX.SHATTER)
Explode(missiles[1], SFX.FALL + SFX.SMOKE)
Explode(missiles[2], SFX.FALL + SFX.SMOKE + SFX.FIRE)
return 2
else
Explode(base, SFX.SHATTER)
Explode(turret, SFX.FALL + SFX.SMOKE + SFX.FIRE)
Explode(sleeve, SFX.FALL + SFX.SMOKE + SFX.FIRE)
Explode(trackData.tracks[1], SFX.SHATTER)
Explode(missiles[1], SFX.FALL + SFX.SMOKE)
Explode(missiles[2], SFX.FALL + SFX.SMOKE + SFX.FIRE)
return 2
end
end
| gpl-2.0 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/metropolis_torso_knife_secd_3.meta.lua | 2 | 2618 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 0.43000000715255737,
amplification = 140,
light_colors = {
"89 31 168 255",
"48 42 88 255",
"61 16 123 0"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shell_spawn = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shoulder_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
non_standard_shape = {
convex_partition = {},
original_poly = {}
},
torso = {
back = {
pos = {
x = -12,
y = 1
},
rotation = -2.1610796451568604
},
head = {
pos = {
x = 5,
y = 0
},
rotation = -2.385944128036499
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 33,
y = 15
},
rotation = -40
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_shoulder = {
pos = {
x = 9,
y = 23
},
rotation = -178.36341857910156
},
shoulder = {
pos = {
x = 6,
y = -19
},
rotation = 170.27243041992188
},
strafe_facing_offset = 0
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Tasks/ShareBlocksPage.lua | 1 | 12737 | --[[
Title:
Author(s): yangguiyi
Date: 2021/11/24
Desc:
------------------------------------------------------------
local ShareBlocksPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/ShareBlocksPage.lua");
ShareBlocksPage.ShowPage()
-------------------------------------------------------
]]
local SelectBlocks = commonlib.gettable("MyCompany.Aries.Game.Tasks.SelectBlocks");
local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine")
local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager");
local ShareBlocksPage = NPL.export();
local page;
function ShareBlocksPage.OnInit()
page = document:GetPageCtrl();
page.OnClose = ShareBlocksPage.OnClose
end
function ShareBlocksPage.ShowPage(bShow)
if not GameLogic.GetFilters():apply_filters('is_signed_in') then
GameLogic.GetFilters():apply_filters('check_signed_in', "请先登录", function(result)
if result == true then
ShareBlocksPage.ShowPage(bShow)
end
end)
return
end
ShareBlocksPage.selected_count = SelectBlocks.selected_count or 0
ShareBlocksPage.selected_range = 16
SelectBlocks.ClosePage();
-- display a page containing all operations that can apply to current selection, like deletion, extruding, coloring, etc.
local x, y, width, height = 0, 160, 140, 330;
System.App.Commands.Call("File.MCMLWindowFrame", {
url = "script/apps/Aries/Creator/Game/Tasks/ShareBlocksPage.html",
name = "ShareBlocksPage.ShowPage",
app_key = MyCompany.Aries.Creator.Game.Desktop.App.app_key,
isShowTitleBar = false,
DestroyOnClose = true, -- prevent many ViewProfile pages staying in memory
style = CommonCtrl.WindowFrame.ContainerStyle,
zorder = 1,
allowDrag = true,
click_through = true,
directPosition = true,
align = "_lt",
x = x,
y = y,
width = width,
height = height,
});
if ShareBlocksPage.selected_count == 0 then
commonlib.TimerManager.SetTimeout(function()
ShareBlocksPage.AutoSelect()
end, 100);
end
end
function ShareBlocksPage.OnClose()
page = nil
ShareBlocksPage.LastCenterPos = nil
SelectBlocks.CancelSelection()
end
function ShareBlocksPage.Close()
if page then
page:CloseWindow()
page = nil
end
end
function ShareBlocksPage.IsOpen()
return page ~= nil and page:IsVisible()
end
function ShareBlocksPage.UpdateBlockNumber(count)
if(page) then
if(ShareBlocksPage.selected_count ~= count) then
if( not (count > 1 and ShareBlocksPage.selected_count>1) ) then
ShareBlocksPage.selected_count = count;
page:Refresh(0.01);
else
ShareBlocksPage.selected_count = count;
page:SetUIValue("title", format(L"选中了%d块",count or 1));
end
end
end
local cur_select_task = SelectBlocks.GetCurrentInstance()
if cur_select_task then
local x,y,z = cur_select_task:GetSelectionPivot()
ShareBlocksPage.LastCenterPos = {x,y,z}
end
end
function ShareBlocksPage.CancelSelection()
ShareBlocksPage.selected_count = 0
page:Refresh(0.01);
end
function ShareBlocksPage.AutoSelect()
local player = EntityManager.GetPlayer();
if not player then
return
end
ShareBlocksPage.SelectBlockPosList = {}
local x, y, z = player:GetBlockPos();
local radius = math.floor(ShareBlocksPage.selected_range/2)
local start_x = x - radius
local start_z = z - radius
ShareBlocksPage.SelectBlock(start_x, start_z, y, ShareBlocksPage.selected_range)
end
function ShareBlocksPage.SelectBlock(start_x, start_z, search_y, range1, range2)
range2 = range2 or range1
local is_need_find_next_layer = false
for index_x = 1, range1 do
local select_x = start_x + index_x
for index_z = 1, range2 do
local select_z = start_z + index_z
local cur_layer_block_id = BlockEngine:GetBlockId(select_x,search_y,select_z)
local next_layer_block_id = BlockEngine:GetBlockId(select_x,search_y + 1,select_z)
if next_layer_block_id and next_layer_block_id ~= 0 then
is_need_find_next_layer = true
end
if cur_layer_block_id and cur_layer_block_id ~= 0 then
ShareBlocksPage.SelectBlockPosList[#ShareBlocksPage.SelectBlockPosList + 1] = {select_x, search_y, select_z}
end
end
end
if is_need_find_next_layer then
ShareBlocksPage.SelectBlock(start_x, start_z, search_y + 1,range1, range2)
else
if #ShareBlocksPage.SelectBlockPosList > 0 then
local task = MyCompany.Aries.Game.Tasks.SelectBlocks:new({blocks=ShareBlocksPage.SelectBlockPosList})
task:Run();
ShareBlocksPage.SelectBlockPosList = {}
end
end
end
function ShareBlocksPage.ChangeRange(name)
local cur_select_task = SelectBlocks.GetCurrentInstance()
if not cur_select_task then
if name == "add" then
if ShareBlocksPage.LastCenterPos then
local task = MyCompany.Aries.Game.Tasks.SelectBlocks:new({blocks={ShareBlocksPage.LastCenterPos}})
task:Run();
else
ShareBlocksPage.AutoSelect()
end
end
return
end
local center_x, center_y, center_z = cur_select_task:GetSelectionPivot()
-- if cur_select_task then
-- center_x, center_y, center_z = cur_select_task:GetSelectionPivot()
-- elseif ShareBlocksPage.LastCenterPos then
-- local last_center_pos = ShareBlocksPage.LastCenterPos
-- center_x, center_y, center_z = last_center_pos[1],last_center_pos[2],last_center_pos[3]
-- end
if nil == center_x then
return
end
-- 取出距离最远的坐标
local max_dis = -1
local max_dis_pos
for key, v in pairs(cur_select_task.blocks) do
local dis = (v[1] - center_x)^2 + (v[2] - center_y)^2 + (v[3] - center_z)^2;
if dis > max_dis then
max_dis = dis
max_dis_pos = v
end
end
if not max_dis_pos then
return
end
local direct_x = 0
if max_dis_pos[1] > center_x then
direct_x = 1
elseif max_dis_pos[1] < center_x then
direct_x = -1
end
local direct_z = 0
if max_dis_pos[3] > center_z then
direct_z = 1
elseif max_dis_pos[3] < center_z then
direct_z = -1
end
local target_pos_list = {}
if name == "add" then
if #cur_select_task.blocks == 1 then
direct_x = 1
direct_z = 1
end
max_dis_pos[1] = max_dis_pos[1] + direct_x
max_dis_pos[3] = max_dis_pos[3] + direct_z
else
max_dis_pos[1] = max_dis_pos[1] - direct_x
max_dis_pos[3] = max_dis_pos[3] - direct_z
end
local x_times = math.abs(max_dis_pos[1] - center_x) * 2 + 1
local z_times = math.abs(max_dis_pos[3] - center_z) * 2 + 1
if #cur_select_task.blocks == 1 then
if name == "add" then
direct_x = 1
direct_z = 1
else
x_times = 0
z_times = 0
end
end
local function auto_select(select_y)
local is_need_find_next_layer = false
for x_index = 1, x_times do
local target_x = max_dis_pos[1] - (x_index - 1) * direct_x
for z_index = 1, z_times do
local target_z = max_dis_pos[3] - (z_index - 1) * direct_z
local block_id = BlockEngine:GetBlockId(target_x, select_y, target_z)
local next_layer_block_id = BlockEngine:GetBlockId(target_x,select_y + 1,target_z)
if block_id ~= 0 then
target_pos_list[#target_pos_list + 1] = {target_x, select_y, target_z}
end
if next_layer_block_id ~= 0 then
is_need_find_next_layer = true
end
-- ShareBlocksPage.AutoSelectY(target_x, center_y, target_z)
end
end
if is_need_find_next_layer then
auto_select(select_y + 1)
else
SelectBlocks.CancelSelection();
if #target_pos_list > 0 then
commonlib.TimerManager.SetTimeout(function()
local task = MyCompany.Aries.Game.Tasks.SelectBlocks:new({blocks=target_pos_list})
task:Run();
end, 100);
end
end
end
auto_select(center_y)
end
function ShareBlocksPage.AutoSelectY(x_times, z_times, max_dis_pos, direct_x, direct_z, target_pos_list)
for x_index = 1, x_times do
local target_x = max_dis_pos[1] - (x_index - 1) * direct_x
for z_index = 1, z_times do
local target_z = max_dis_pos[3] - (z_index - 1) * direct_z
local block_id = BlockEngine:GetBlockId(target_x, targer_y, targer_z)
local next_layer_block_id = BlockEngine:GetBlockId(select_x,targer_y + 1,select_z)
if block_id ~= 0 then
-- body
end
-- ShareBlocksPage.AutoSelectY(target_x, center_y, target_z)
end
end
-- local block_id = BlockEngine:GetBlockId(target_x, targer_y, targer_z)
-- if block_id ~= 0 then
-- -- target_pos_list[#target_pos_list + 1] = {target_x, center_y, target_z}
-- local block_data = ParaTerrain.GetBlockUserDataByIdx(target_x, targer_y, targer_z);
-- local cur_select_task = SelectBlocks.GetCurrentInstance()
-- cur_select_task:SelectSingleBlock(target_x, targer_y, targer_z, block_id, block_data);
-- ShareBlocksPage.AutoSelectY(target_x, targer_y + 1, targer_z)
-- else
-- end
end
function ShareBlocksPage.GetSelectCount()
local cur_select_task = SelectBlocks.GetCurrentInstance()
if cur_select_task then
return #cur_select_task.blocks
end
return 0
end
function ShareBlocksPage.ShareBlcok()
-- 先保存templete到temp目录下
ShareBlocksPage.SaveBlockAndShare()
end
function ShareBlocksPage.SaveBlockAndShare()
local cur_select_task = SelectBlocks.GetCurrentInstance()
if not cur_select_task then
_guihelper.MessageBox("请先选择方块");
return
end
local pivot_x, pivot_y, pivot_z = cur_select_task:GetSelectionPivot();
if(cur_select_task.UsePlayerPivotY) then
local x,y,z = ParaScene.GetPlayer():GetPosition();
local _, by, _ = BlockEngine:block(0,y+0.1,0);
pivot_y = by;
end
local pivot = {pivot_x, pivot_y, pivot_z};
local blocks = cur_select_task:GetCopyOfBlocks(pivot);
-- NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/BlockTemplatePage.lua");
-- local BlockTemplatePage = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.BlockTemplatePage");
-- BlockTemplatePage.ShowPage(true, blocks, pivot);
local name = "share_file_" .. os.time()
local name_normalized = commonlib.Encoding.Utf8ToDefault(name);
local template_dir = "temp/ShareBlock/"
-- local isThemedTemplate = template_dir and template_dir ~= "";
local bSaveSnapshot = false;
local filename, taskfilename;
ParaIO.CreateDirectory(template_dir);
filename = format("%s%s.blocks.xml", template_dir, name_normalized);
taskfilename = format("%s%s.xml", template_dir, name_normalized);
local function doSave_()
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/BlockTemplatePage.lua");
local BlockTemplatePage = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.BlockTemplatePage");
local x, y, z = ParaScene.GetPlayer():GetPosition();
local bx, by, bz = BlockEngine:block(x,y,z)
local player_pos = string.format("%d,%d,%d",bx,by,bz);
-- replace cob web block with air 0, if it is a task file.
if(taskfilename) then
local cobWebBlock = 118; -- id for cob web block.
for _, b in ipairs(blocks) do
if(b[4] == cobWebBlock) then
b[4] = 0;
end
end
end
local isSilenceSave = true
pivot = string.format("%d,%d,%d",pivot[1],pivot[2],pivot[3]);
BlockTemplatePage.SaveToTemplate(filename, blocks, {
name = name,
author_nid = System.User.nid,
creation_date = ParaGlobal.GetDateFormat("yyyy-MM-dd").."_"..ParaGlobal.GetTimeFormat("HHmmss"),
player_pos = player_pos,
pivot = pivot,
relative_motion = false,
hollow = false,
exportReferencedFiles = false,
},function ()
ShareBlocksPage.UpLoadFile(filename)
end, bSaveSnapshot, isSilenceSave);
end
doSave_();
end
function ShareBlocksPage.UpLoadFile(filename)
local KeepWorkItemManager = NPL.load("(gl)script/apps/Aries/Creator/HttpAPI/KeepWorkItemManager.lua");
local profile = KeepWorkItemManager.GetProfile()
if not profile.id then
return
end
local key = string.format("model-share-%s-%s", profile.id, ParaMisc.md5(filename))
keepwork.shareBlock.getToken({
router_params = {
id = key,
}
},function(err, msg, data)
if err == 200 then
local token = data.data.token
local file_name = commonlib.Encoding.DefaultToUtf8(ParaIO.GetFileName(filename));
local file = ParaIO.open(filename, "rb");
if (not file:IsValid()) then
file:close();
return;
end
local content = file:GetText(0, -1);
file:close();
GameLogic.GetFilters():apply_filters(
'qiniu_upload_file',
token,
key,
file_name,
content,
function(result, err)
-- print("pppppppppppppppeeee", err)
-- echo(result, true)
-- print("qiniu-public-temporary-dev.keepwork.com/" .. key)
-- print("qiniu-public-temporary.keepwork.com/" .. key)
-- local key = "model-share-162199-97f741d183885f245c4534661cd0c2a7"
ShareBlocksPage.Close()
local FriendsPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/Friend/FriendsPage.lua");
FriendsPage.Show(2, {msg_type = 2, content = "qiniu-public-temporary.keepwork.com/" .. key})
if err ~= 200 then
return;
end
end
)
end
end)
end | gpl-2.0 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/electric_missile.meta.lua | 2 | 2022 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"255 255 255 255",
"255 0 0 255",
"255 0 255 255",
"0 255 174 255",
"255 0 228 255",
"0 198 255 255"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
torso = {
back = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Windurst_Waters/npcs/Funpo-Shipo.lua | 5 | 1043 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Funpo-Shipo
-- Type: Standard NPC
-- @zone: 238
-- @pos: -44.091 -4.499 41.728
--
-- Auto-Script: Requires Verification (Verfied By Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0240);
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 |
hfjgjfg/eli25 | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
hfjgjfg/sss25 | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
hfjgjfg/PERSIANGUARD10 | plugins/feedback.lua | 1 | 1030 | do
function run(msg, matches)
local fuse = '#feedback \n\n🌐آیدی : `' .. msg.from.id .. '`\n\n🅿یوزر نیم: @' .. msg.from.username .. '\n️\nⓂ️اسم : `' .. msg.from.print_name ..'`\n\n🔰متن پیام :\n\n\n' .. matches[1]
local fuses = '!printf user#id' .. msg.from.id
local text = matches[1]
bannedidone = string.find(msg.from.id, '000000000')
bannedidtwo =string.find(msg.from.id, '000000000')
bannedidthree =string.find(msg.from.id, '000000000')
print(msg.to.id)
if bannedidone or bannedidtwo or bannedidthree then --for banned people
return 'You are banned to send a feedback'
else
local sends0 = send_msg('chat#id75744575', fuse, ok_cb, false)
return ' ✅فرستاده شد '
end
end
return {
description = "Feedback",
usage = "!feedback message",
patterns = {
"^[!/$&-=+:*.%#?@][Ff]eedback (.*)$",
"^[Ff]eedback (.*)$"
},
run = run
}
end
| gpl-2.0 |
RyMarq/Zero-K | scripts/pw_techlab.lua | 8 | 2577 | include 'constants.lua'
local base = piece "base"
local wheel1 = piece "wheel1"
local wheel2 = piece "wheel2"
local slider = piece "slider"
local sliderturret = piece "sliderturret"
local armabase = piece "armabase"
local armbbase = piece "armbbase"
local armcbase = piece "armcbase"
local armdbase = piece "armdbase"
local armebase = piece "armebase"
local armfbase = piece "armfbase"
local arma = piece "arma"
local armb = piece "armb"
local armc = piece "armc"
local armd = piece "armd"
local arme = piece "arme"
local armf = piece "armf"
local armapick = piece "armapick"
local armbpick = piece "armdpick"
local armcpick = piece "armcpick"
local armdpick = piece "armdpick"
local armepick = piece "armepick"
local armfpick = piece "armfpick"
local anglea = -0.05
local angleb = -0.08
local anglec = -0.1
local speeda = 0.3
local speedb = 0.5
local function armmove(piece1, piece2, piece3)
while(true) do
Turn(piece1, z_axis, anglea, speeda)
Turn(piece2, z_axis, angleb, speeda)
Turn(piece3, z_axis, anglec, speeda)
WaitForTurn(piece1, z_axis)
WaitForTurn(piece2, z_axis)
WaitForTurn(piece3, z_axis)
Turn(piece1, z_axis, anglea, speedb)
Turn(piece2, z_axis, angleb, speedb)
Turn(piece3, z_axis, anglec, speedb)
WaitForTurn(piece1, z_axis)
WaitForTurn(piece2, z_axis)
WaitForTurn(piece3, z_axis)
Turn(piece1, z_axis, 0, speedb)
Turn(piece2, z_axis, 0, speedb)
Turn(piece3, z_axis, 0, speedb)
Sleep (math.random(200,2000))
end
end
local function moveslider()
while(true) do
Move(slider, z_axis, math.random(-5.8,5.8)*5.8, 10)
WaitForMove(slider, z_axis)
Sleep (50)
end
end
function script.Create()
if Spring.GetUnitRulesParam(unitID, "planetwarsDisable") == 1 or GG.applyPlanetwarsDisable then
return
end
StartThread(armmove, armabase, arma, armapick)
StartThread(armmove, armbbase, armb, armbpick)
StartThread(armmove, armcbase, armc, armcpick)
StartThread(armmove, armdbase, armd, armdpick)
StartThread(armmove, armebase, arme, armepick)
StartThread(armmove, armfbase, armf, armfpick)
StartThread(moveslider)
Spin(sliderturret, y_axis, 2, 0.2)
Spin(wheel1, x_axis, 0.5, 0.01)
Spin(wheel2, x_axis, -0.5, 0.01)
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity < .5 then
Explode(base, SFX.NONE)
Explode(sliderturret, SFX.NONE)
Explode(slider, SFX.NONE)
return 1
else
Explode(base, SFX.SHATTER)
--Explode(sliderturret, SFX.FALL + SFX.SMOKE + SFX.FIRE)
Explode(sliderturret, SFX.SHATTER)
Explode(slider, SFX.FALL)
return 2
end
end
| gpl-2.0 |
NPLPackages/paracraft | script/kids/3DMapSystemItem/Item_QuestReward.lua | 1 | 4665 | --[[
Title: quest rewards
Author(s): WangTian
Date: 2009/9/21
Desc: Item_QuestReward type of item is a special item type that can be used for rewards
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/kids/3DMapSystemItem/Item_QuestReward.lua");
------------------------------------------------------------
]]
local Item_QuestReward = {};
commonlib.setfield("Map3DSystem.Item.Item_QuestReward", Item_QuestReward)
---------------------------------
-- functions
---------------------------------
function Item_QuestReward:new(o)
o = o or {} -- create object if user does not provide one
setmetatable(o, self)
self.__index = self
return o
end
-- When item is clicked through pe:slot
function Item_QuestReward:OnClick(mouse_button, callbackFunc)
local ItemManager = Map3DSystem.Item.ItemManager;
if(mouse_button == "left") then
--MyCompany.Aries.Pet.DoFeed(nid,item,function(msg)
----MyCompany.Aries.Inventory.ShowMainWnd(false);
--MyCompany.Aries.Inventory.RefreshMainWnd(2);
--if(msg.issuccess)then
--self:UpdateBag(bagfamily,bag)
------ call hook for pet feed
----local msg = { aries_type = "PetFeed", gsid = self.gsid, wndName = "main"};
----CommonCtrl.os.hook.Invoke(CommonCtrl.os.hook.HookType.WH_CALLWNDPROCRET, 0, "Aries", msg);
--MyCompany.Aries.Pet.DoRefreshPetsInHomeland();
--end
--end);
local ItemManager = System.Item.ItemManager;
local stats = {};
local gsItem = ItemManager.GetGlobalStoreItemInMemory(self.gsid)
if(gsItem) then
stats = gsItem.template.stats;
end
local pet_item = ItemManager.GetMyMountPetItem();
if(not pet_item or pet_item.guid <= 0) then
log("error: invalid pet item got in Item_QuestReward:OnClick()\n")
return;
end
local msg = {
nid = System.App.profiles.ProfileManager.GetNID(),
itemguid = self.guid,
petid = pet_item.guid,
bag = self.bag,
--------------- for local server optimization -------------
gsid = self.gsid,
add_strong = stats[3] or 0, -- strong
add_cleanness = stats[4] or 0, -- cleanness
add_mood = stats[5] or 0, -- mood
add_friendliness = stats[7] or 0, -- friendliness
heal_pet = stats[8] or 0,
revive_pet = stats[9] or 0,
add_kindness = stats[17] or 0, -- kindness
add_intelligence = stats[18] or 0, -- intelligence
add_agility = stats[19] or 0, -- agility
add_strength = stats[20] or 0, -- strength
add_archskillpts = stats[21] or 0, -- archskillpts
--------------- for local server optimization -------------
}
paraworld.homeland.petevolved.UseItem(msg, "QuestReward", function(msg)
if(msg.issuccess == true) then
-- update the item bag
if(gsItem) then
-- automatically update the items in the homeland bag
ItemManager.GetItemsInBag(gsItem.template.bagfamily, "UpdateHomeBagAfterGetQuestReward_", function(msg)
-- update all page controls containing the pe:slot tag
-- TODO: update only the PageCtrl with the same bag
Map3DSystem.mcml_controls.GetClassByTagName("pe:slot").RefreshContainingPageCtrls();
end, "access plus 3 minutes");
end
if(callbackFunc and type(callbackFunc) == "function")then
callbackFunc(msg);
end
--local bean = msg;
--commonlib.echo("after reward with item gsid:"..tostring(self.gsid).." :");
--commonlib.echo(bean);
--if(bean) then
--MyCompany.Aries.Pet.SetBean(nil, bean);
--MyCompany.Aries.Pet.Update();
--
---- Product BUG:
---- 1. don't open any inventory window
---- 2. complete quest with friendliness reward
---- [string "script/kids/3DMapSystemItem/Item_QuestReward.lua"]:79: attempt to call field 'RefreshMainWnd' (a nil value) <Runtime error>
---- this don't bothers user experience though, the window will be refreshed on the next show
--MyCompany.Aries.Inventory.RefreshMainWnd(2);
--msg.issuccess = true;
--if(callbackFunc and type(callbackFunc) == "function")then
--callbackFunc(msg);
--end
--end
end
end);
elseif(mouse_button == "right") then
---- destroy the item
--_guihelper.MessageBox("你确定要销毁 #"..tostring(self.guid).." 物品么?", function(result)
--if(_guihelper.DialogResult.Yes == result) then
--Map3DSystem.Item.ItemManager.DestroyItem(self.guid, 1, function(msg)
--if(msg) then
--log("+++++++Destroy item return: #"..tostring(self.guid).." +++++++\n")
--commonlib.echo(msg);
--end
--end);
--elseif(_guihelper.DialogResult.No == result) then
---- doing nothing if the user cancel the add as friend
--end
--end, _guihelper.MessageBoxButtons.YesNo);
end
end | gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/texts/intro-infinite-dungeon.lua | 3 | 1114 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- 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/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
return [[Welcome #LIGHT_GREEN#@name@#WHITE#.
You have arrived in the Infinite Dungeon.
Your life outside did not satisfy you, so you came here looking for adventure.
While you know this is a one way trip, you hope to go in a blaze of glory!
Go forth, venture into the depths of the dungeon and see how far you can get before the end.
]]
| gpl-3.0 |
matin-igdery/og | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
RyMarq/Zero-K | LuaUI/Widgets/gui_replay_controls.lua | 2 | 11792 | function widget:GetInfo()
return {
name = "Replay control buttons",
desc = "Graphical buttons for controlling replay speed, " ..
"pausing and skipping pregame chatter",
author = "knorke",
date = "August 2012", --updated on 20 May 2015
license = "stackable",
layer = 1,
enabled = true -- loaded by my horse?
}
end
-- 5 May 2015 added progress bar, by xponen
--Speedup
local widgetName = widget:GetInfo().name
local modf = math.modf
local format = string.format
local Chili
local Button
local Label
local Window
local Panel
local TextBox
local Image
local Progressbar
local Control
local Font
-- elements
local window
local button_setspeed = {}
local button_skipPreGame
local button_startStop
local progress_speed
local progress_target
local label_hoverTime
---------------------------------
-- Globals
---------------------------------
local speeds = {0.5, 1, 2, 3, 4, 5,10}
local isPaused = false
-- local wantedSpeed = nil
local skipped = false
local fastForwardTo = -1
local currentFrameTime = 0
local demoStarted = false
local showProgress = true
local SELECT_BUTTON_COLOR = {0.98, 0.48, 0.26, 0.85}
local SELECT_BUTTON_FOCUS_COLOR = {0.98, 0.48, 0.26, 0.85}
-- Defined upon learning the appropriate colors
local BUTTON_COLOR
local BUTTON_FOCUS_COLOR
local BUTTON_BORDER_COLOR
---------------------------------
-- Epic Menu
---------------------------------
options_path = 'Settings/HUD Panels/Replay Controls'
options_order = { 'visibleprogress'}
options = {
visibleprogress = {
name = 'Progress Bar',
desc = 'Enables a clickable progress bar for the replay.',
type = 'bool',
value = true,
noHotkey = true,
OnChange = function(self)
if (not Spring.IsReplay()) then
return
end
local replayLen = Spring.GetReplayLength and Spring.GetReplayLength()
if replayLen == 0 then --replay info broken
replayLen = false
self.value = false
end
local frame = Spring.GetGameFrame()
if self.value then
progress_speed:SetValue(frame)
progress_speed:SetCaption(math.modf(frame/progress_speed.max*100) .. "%")
else
progress_speed:SetValue(0)
progress_speed:SetCaption("")
end
showProgress = self.value
end,
},
}
---------------------------------
---------------------------------
function widget:Initialize()
if (not Spring.IsReplay()) then
Spring.Echo ("<" .. widgetName .. "> Live mode. Widget removed.")
widgetHandler:RemoveWidget(self)
return
end
-- setup Chili
Chili = WG.Chili
Button = Chili.Button
Label = Chili.Label
Window = Chili.Window
StackPanel = Chili.StackPanel
Image = Chili.Image
Progressbar = Chili.Progressbar
Control = Chili.Control
screen0 = Chili.Screen0
CreateTheUI()
end
function CreateTheUI()
--create main Chili elements
local screenWidth,screenHeight = Spring.GetWindowGeometry()
local height = tostring(math.floor(screenWidth/screenHeight*0.35*0.35*100)) .. "%"
local windowY = math.floor(screenWidth*2/11 + 32)
local labelHeight = 24
local fontSize = 16
local currSpeed = 2 --default button setting
if window then
currSpeed = window.currSpeed
screen0:RemoveChild(window)
window:Dispose()
end
local replayLen = Spring.GetReplayLength and Spring.GetReplayLength()
if replayLen == 0 then --replay info broken
replayLen = false
showProgress = false
end
local frame = Spring.GetGameFrame()
window = Window:New{
--parent = screen0,
name = 'replaycontroller3';
width = 310;
height = 86;
right = 10;
y = windowY;
classname = "main_window_small_flat",
dockable = false;
draggable = true,
resizable = false,
tweakDraggable = true,
tweakResizable = false,
--informational tag:
currSpeed = currSpeed,
lastClick = Spring.GetTimer(),
--end info tag
--itemMargin = {0, 0, 0, 0},
--caption = "replay control"
OnMouseDown = {function(self, x, y, mouse)
--clickable bar, reference: "Chili Economy Panel Default"'s Reserve bar
if not showProgress then
return
end
if x>progress_speed.x and y>progress_speed.y and x<progress_speed.x2 and y<progress_speed.y2 then
local target = (x-progress_speed.x) / (progress_speed.width)
if target > progress_speed.value/progress_speed.max then
progress_target:SetValue(target)
snapButton(#speeds)
setReplaySpeed (speeds[#speeds], #speeds)
fastForwardTo = modf(target*progress_speed.max)
label_hoverTime:SetCaption("> >")
else
snapButton(2)
progress_target:SetValue(0)
setReplaySpeed (speeds[2],2)
end
end
return
end},
OnMouseMove = {function(self, x, y, mouse)
--clickable bar, reference: "Chili Economy Panel Default"'s Reserve bar
if not showProgress then
return
end
if x>progress_speed.x and y>progress_speed.y and x<progress_speed.x2 and y<progress_speed.y2 then
local target = (x-progress_speed.x) / (progress_speed.width)
local hoverOver = modf(target*progress_speed.max/30)
local minute, second = modf(hoverOver/60)--second divide by 60sec-per-minute, then saperate result from its remainder
second = 60*second --multiply remainder with 60sec-per-minute to get second back.
label_hoverTime:SetCaption(format ("%d:%02d" , minute, second))
else
if label_hoverTime.caption ~= " " then
label_hoverTime:SetCaption(" ")
end
end
return
end},
}
for i = 1, #speeds do
local button = Button:New {
width = 40,
height = 20,
y = 28,
x = 5+(i-1)*40,
classname = "button_tiny",
parent=window;
padding = {0, 0, 0,0},
margin = {0, 0, 0, 0},
caption=speeds[i] .."x",
tooltip = "play at " .. speeds[i] .. "x speed";
OnClick = {
function()
snapButton(i)
progress_target:SetValue(0)
setReplaySpeed (speeds[i], i)
end
}
}
if not BUTTON_COLOR then
BUTTON_COLOR = button.backgroundColor
end
if not BUTTON_FOCUS_COLOR then
BUTTON_FOCUS_COLOR = button.focusColor
end
if not BUTTON_BORDER_COLOR then
BUTTON_BORDER_COLOR = button.borderColor
end
if i == currSpeed then
button.backgroundColor = SELECT_BUTTON_COLOR
button.focusColor = SELECT_BUTTON_FOCUS_COLOR
button:Invalidate()
end
button_setspeed[i] = button
end
if (frame == 0) then
button_skipPreGame = Button:New {
width = 180,
height = 20,
y = 50,
x = 95,
classname = "button_tiny",
parent=window;
padding = {0, 0, 0,0},
margin = {0, 0, 0, 0},
caption="skip pregame chatter",
tooltip = "Skip the pregame chat and startposition choosing, go directly to the action!";
OnClick = {function()
skipPreGameChatter ()
end}
}
else
--in case reloading luaui mid demo
widgetHandler:RemoveCallIn("AddConsoleMessage")
end
label_hoverTime = Label:New {
width = 20,
height = 15,
y = 54,
x = 125,
parent=window;
caption=" ",
}
button_startStop = Button:New {
width = 80,
height = 20,
y = 50,
x = 5,
classname = "button_tiny",
parent=window;
padding = {0, 0, 0,0},
margin = {0, 0, 0, 0},
caption="pause", --pause/continue
tooltip = "pause or continue playback";
OnClick = {function()
currentFrameTime = -3
if (isPaused) then
unpause()
else
pause()
end
end}
}
progress_target = Progressbar:New{
parent = window,
y = 5,
x = 5,
right = 5,
height = 20,
max = 1;
color = {0.75,0.75,0.75,0.5} ;
backgroundColor = {0,0,0,0} ,
value = 0,
}
local replayLen = (replayLen and replayLen* 30) or 100-- in frame
progress_speed = Progressbar:New{
parent = window,
y = 5,
x = 5,
right = 5,
height = 20,
max = replayLen;
caption = showProgress and (frame/replayLen*100 .. "%") or " ",
color = showProgress and {0.9,0.15,0.2,0.75} or {1,1,1,0.0} ; --red, --{0.2,0.9,0.3,1}; --green
backgroundColor = {1,1,1,0.8} ,
value = frame,
flash = false,
}
progress_speed.x2 = progress_speed.x + progress_speed.width
progress_speed.y2 = progress_speed.y + progress_speed.height
screen0:AddChild(window)
end
function snapButton(pushButton)
button_setspeed[window.currSpeed].backgroundColor = BUTTON_COLOR
button_setspeed[window.currSpeed].focusColor = BUTTON_FOCUS_COLOR
button_setspeed[window.currSpeed]:Invalidate()
button_setspeed[pushButton].backgroundColor = SELECT_BUTTON_COLOR
button_setspeed[pushButton].focusColor = SELECT_BUTTON_FOCUS_COLOR
button_setspeed[pushButton]:Invalidate()
end
function pause(supressCommand)
Spring.Echo ("Playback paused")
if not supressCommand then
Spring.SendCommands ("pause 1")
end
isPaused = true
button_startStop:SetCaption ("play")
--window:SetColor ({1,0,0, 1})
--window:SetCaption ("trololo")--button stays pressed down and game lags ANY INVALID CODE MAKES IT LAG, REASON WHY COM MORPH LAGS?
end
function unpause(supressCommand)
Spring.Echo ("Playback continued")
if not supressCommand then
Spring.SendCommands ("pause 0")
end
isPaused = false
button_startStop:SetCaption ("pause")
end
function setReplaySpeed (speed, i)
--put something invalid in these button function like:
--doesNotExist[3] = 5
--and there will be no error message. However, the game will stutter for a second
local s = Spring.GetGameSpeed()
--Spring.Echo ("setting speed to: " .. speed .. " current is " .. s)
if (speed > s) then --speedup
Spring.SendCommands ("setminspeed " .. speed)
Spring.SendCommands ("setminspeed " ..0.1)
else --slowdown
-- wantedSpeed = speed
--[[
--does not work:
Spring.SendCommands ("slowdown")
Spring.SendCommands ("slowdown")
Spring.SendCommands ("slowdown")
Spring.SendCommands ("slowdown")
Spring.SendCommands ("slowdown")
]]--
--does not work:
-- local i = 0
-- while (Spring.GetGameSpeed() > speed and i < 50) do
-- Spring.SendCommands ("setminspeed " ..0.1)
Spring.SendCommands ("setmaxspeed " .. speed)
Spring.SendCommands ("setmaxspeed " .. 10.0)
-- Spring.SendCommands ("slowdown")
-- i=i+1
-- end
end
--Spring.SendCommands ("setmaxpeed " .. speed)
window.currSpeed = i
end
local lastSkippedTime = 0
function widget:Update(dt)
-- if (wantedSpeed) then
-- if (Spring.GetGameSpeed() > wantedSpeed) then
-- Spring.SendCommands ("slowdown")
-- else
-- wantedSpeed = nil
-- end
-- end
if skipped and demoStarted then --do not do "skip 1" at or before demoStart because,it Hung Spring/broke the command respectively.
if lastSkippedTime > 1.5 then
Spring.SendCommands("skip 1")
lastSkippedTime = 0
else
lastSkippedTime = lastSkippedTime + dt
end
end
currentFrameTime = currentFrameTime + dt
if currentFrameTime > 0 then
if (currentFrameTime > 1) ~= isPaused then
if not isPaused then
pause(true)
else
unpause(true)
end
end
end
end
function widget:GameFrame (f)
if currentFrameTime > 0 then
currentFrameTime = 0
end
if (fastForwardTo>0) then
if f==fastForwardTo then
pause ()
snapButton(2)
progress_target:SetValue(0)
setReplaySpeed (speeds[2],2)
fastForwardTo = -1
elseif f>fastForwardTo then
progress_target:SetValue(0)
fastForwardTo = -1
end
end
if (f==1) then
window:RemoveChild(button_skipPreGame)
skipped = nil
lastSkippedTime = nil
widgetHandler:RemoveCallIn("AddConsoleMessage")
elseif showProgress and (f%2 ==0) then
progress_speed:SetValue(f)
progress_speed:SetCaption(math.modf(f/progress_speed.max*100) .. "%")
end
end
function widget:AddConsoleMessage(msg)
if msg.text == "Beginning demo playback" then
demoStarted = true
widgetHandler:RemoveCallIn("AddConsoleMessage")
end
end
function skipPreGameChatter ()
Spring.Echo("Skipping pregame chatter")
if (demoStarted) then
Spring.SendCommands("skip 1")
end
skipped = true
-- window:RemoveChild(button_skipPreGame)
end
| gpl-2.0 |
llX8Xll/DEVKEEPER1 | libs/redis.lua | 566 | 1214 | local Redis = require 'redis'
local FakeRedis = require 'fakeredis'
local params = {
host = os.getenv('REDIS_HOST') or '127.0.0.1',
port = tonumber(os.getenv('REDIS_PORT') or 6379)
}
local database = os.getenv('REDIS_DB')
local password = os.getenv('REDIS_PASSWORD')
-- Overwrite HGETALL
Redis.commands.hgetall = Redis.command('hgetall', {
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
})
local redis = nil
-- Won't launch an error if fails
local ok = pcall(function()
redis = Redis.connect(params)
end)
if not ok then
local fake_func = function()
print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m')
end
fake_func()
fake = FakeRedis.new()
print('\27[31mRedis addr: '..params.host..'\27[39m')
print('\27[31mRedis port: '..params.port..'\27[39m')
redis = setmetatable({fakeredis=true}, {
__index = function(a, b)
if b ~= 'data' and fake[b] then
fake_func(b)
end
return fake[b] or fake_func
end })
else
if password then
redis:auth(password)
end
if database then
redis:select(database)
end
end
return redis
| gpl-2.0 |
jsj2008/ValyriaTear | img/sprites/map/npcs/story/herth_walk.lua | 4 | 1987 | -- Sprite animation file descriptor
-- This file will describe the frames used to load the sprite animations
-- This files is following a special format compared to other animation scripts.
local ANIM_SOUTH = vt_map.MapMode.ANIM_SOUTH;
local ANIM_NORTH = vt_map.MapMode.ANIM_NORTH;
local ANIM_WEST = vt_map.MapMode.ANIM_WEST;
local ANIM_EAST = vt_map.MapMode.ANIM_EAST;
sprite_animation = {
-- The file to load the frames from
image_filename = "img/sprites/map/npcs/story/herth_spritesheet.png",
-- The number of rows and columns of images, will be used to compute
-- the images width and height, and also the frames number (row x col)
rows = 4,
columns = 6,
-- The frames duration in milliseconds
frames = {
[ANIM_SOUTH] = {
[0] = { id = 1, duration = 150 },
[1] = { id = 2, duration = 150 },
[2] = { id = 3, duration = 150 },
[3] = { id = 1, duration = 150 },
[4] = { id = 4, duration = 150 },
[5] = { id = 5, duration = 150 }
},
[ANIM_NORTH] = {
[0] = { id = 7, duration = 150 },
[1] = { id = 8, duration = 150 },
[2] = { id = 9, duration = 150 },
[3] = { id = 7, duration = 150 },
[4] = { id = 10, duration = 150 },
[5] = { id = 11, duration = 150 }
},
[ANIM_WEST] = {
[0] = { id = 13, duration = 150 },
[1] = { id = 14, duration = 150 },
[2] = { id = 15, duration = 150 },
[3] = { id = 13, duration = 150 },
[4] = { id = 16, duration = 150 },
[5] = { id = 17, duration = 150 }
},
[ANIM_EAST] = {
[0] = { id = 19, duration = 150 },
[1] = { id = 20, duration = 150 },
[2] = { id = 21, duration = 150 },
[3] = { id = 19, duration = 150 },
[4] = { id = 22, duration = 150 },
[5] = { id = 23, duration = 150 }
}
}
}
| gpl-2.0 |
p00ria/Grandex | plugins/Arz.lua | 5 | 1085 | local function get_arz()
local url = 'http://exchange.nalbandan.com/api.php?action=json'
local jstr, res = http.request(url)
local arz = json:decode(jstr)
return '📊 نرخ ارز ، طلا و سکه در:'..arz.dollar.date..'\n\n〽️ هر گرم طلای 18 عیار:'..arz.gold_per_geram.value..' تومان\n\n🌟 سکه طرح جدید:'..arz.coin_new.value..' تومان\n\n⭐️ سکه طرح قدیم:'..arz.coin_old.value..' تومان\n\n💵 دلار آمریکا:'..arz.dollar.value..' تومان\n\n💵 دلـار رسمی:'..arz.dollar_rasmi.value..' تومان\n\n💶 یورو:'..arz.euro.value..' تومان\n\n💷 پوند:'..arz.pond.value..' تومان\n\n💰 درهم:'..arz.derham.value..' تومان'
end
local function run(msg, matches)
local text
if matches[1] == 'arz' then
text = get_arz()
elseif matches[1] == 'gold' then
text = get_gold()
elseif matches[1] == 'coin' then
text = get_coin()
end
return text
end
return {
description = "arz in now",
usage = "arz",
patterns = {
"^[!/#](arz)$"
},
run = run
}
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Garlaige_Citadel/npcs/_5kr.lua | 1 | 1478 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Crematory Hatch
-- Type: Door
-- @zone 200
-- @pos 139 -6 127
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Garlaige_Citadel/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(trade:hasItemQty(1041,1) == true and trade:getItemCount() == 1) then
player:startEvent(0x0004); -- Open the door
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
X = player:getXPos();
Z = player:getZPos();
if(X >= 135 and X <= 144 and Z >= 128 and Z <= 135) then
player:startEvent(0x0005);
else
player:messageSpecial(OPEN_WITH_THE_RIGHT_KEY);
return 0;
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 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Southern_San_dOria/npcs/Parvipon.lua | 1 | 2395 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Parvipon
-- Starts and Finishes Quest: The Merchant's Bidding (R)
-- @zone 230
-- @pos -169 -1 13
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- OnTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(SANDORIA,THE_MERCHANT_S_BIDDING) ~= QUEST_AVAILABLE) then
if(trade:hasItemQty(856,3) and trade:getItemCount() == 3) then
player:startEvent(0x59);
end
end
-- "Flyers for Regine" conditional script
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(MagicmartFlyer,1);
if (MagicFlyer == true and count == 1) then
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TheMerchantsBidding = player:getQuestStatus(SANDORIA,THE_MERCHANT_S_BIDDING);
if (TheMerchantsBidding == QUEST_AVAILABLE) then
player:startEvent(0x5A);
else
player:startEvent(0x58);
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 == 0x5A and option == 1) then
player:addQuest(SANDORIA,THE_MERCHANT_S_BIDDING);
elseif(csid == 0x59) then
player:tradeComplete();
player:addGil(GIL_RATE*120);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*120);
if(player:getQuestStatus(SANDORIA,THE_MERCHANT_S_BIDDING) == QUEST_ACCEPTED) then
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,THE_MERCHANT_S_BIDDING);
else
player:addFame(SANDORIA,SAN_FAME*5);
end
end
end; | gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/general/objects/shields.lua | 3 | 3911 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- 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/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
local Talents = require "engine.interface.ActorTalents"
newEntity{
define_as = "BASE_SHIELD",
slot = "OFFHAND",
type = "armor", subtype="shield",
add_name = " (#ARMOR#, #SHIELD#)",
display = ")", color=colors.UMBER, image = resolvers.image_material("shield", "metal"),
moddable_tile = resolvers.moddable_tile("shield"),
rarity = 5,
encumber = 7,
metallic = true,
desc = [[Handheld deflection devices.]],
require = { talent = { {Talents.T_ARMOUR_TRAINING,2} }, },
randart_able = "/data/general/objects/random-artifacts/shields.lua",
special_combat = { talented="shield", accuracy_effect="staff", damrange = 1.2 },
egos = "/data/general/objects/egos/shield.lua", egos_chance = { prefix=resolvers.mbonus(40, 5), suffix=resolvers.mbonus(40, 5) },
}
-- All shields have a "special_combat" field, this is used to compute damage made with them
-- when using special talents
newEntity{ base = "BASE_SHIELD",
name = "iron shield", short_name = "iron",
level_range = {1, 10},
require = { stat = { str=11 }, },
cost = 5,
material_level = 1,
special_combat = {
dam = resolvers.rngavg(7,11),
block = resolvers.rngavg(15, 25),
physcrit = 2.5,
dammod = {str=1},
},
wielder = {
combat_armor = 2,
combat_def = 4,
combat_def_ranged = 4,
fatigue = 6,
learn_talent = { [Talents.T_BLOCK] = 1, },
},
}
newEntity{ base = "BASE_SHIELD",
name = "steel shield", short_name = "steel",
level_range = {10, 20},
require = { stat = { str=16 }, },
cost = 10,
material_level = 2,
special_combat = {
dam = resolvers.rngavg(10,20),
block = resolvers.rngavg(35, 45),
physcrit = 3,
dammod = {str=1},
},
wielder = {
combat_armor = 2,
combat_def = 6,
combat_def_ranged = 6,
fatigue = 8,
learn_talent = { [Talents.T_BLOCK] = 2, },
},
}
newEntity{ base = "BASE_SHIELD",
name = "dwarven-steel shield", short_name = "d.steel",
level_range = {20, 30},
require = { stat = { str=24 }, },
cost = 15,
material_level = 3,
special_combat = {
dam = resolvers.rngavg(25,35),
block = resolvers.rngavg(70, 90),
physcrit = 3.5,
dammod = {str=1},
},
wielder = {
combat_armor = 2,
combat_def = 8,
combat_def_ranged = 8,
fatigue = 12,
learn_talent = { [Talents.T_BLOCK] = 3, },
},
}
newEntity{ base = "BASE_SHIELD",
name = "stralite shield", short_name = "stralite",
level_range = {30, 40},
require = { stat = { str=35 }, },
cost = 25,
material_level = 4,
special_combat = {
dam = resolvers.rngavg(40,55),
block = resolvers.rngavg(130, 150),
physcrit = 4.5,
dammod = {str=1},
},
wielder = {
combat_armor = 2,
combat_def = 10,
combat_def_ranged = 10,
fatigue = 14,
learn_talent = { [Talents.T_BLOCK] = 4, },
},
}
newEntity{ base = "BASE_SHIELD",
name = "voratun shield", short_name = "voratun",
level_range = {40, 50},
require = { stat = { str=48 }, },
cost = 35,
material_level = 5,
special_combat = {
dam = resolvers.rngavg(60,75),
block = resolvers.rngavg(180, 220),
physcrit = 5,
dammod = {str=1},
},
wielder = {
combat_armor = 3,
combat_def = 12,
combat_def_ranged = 12,
fatigue = 14,
learn_talent = { [Talents.T_BLOCK] = 5, },
},
}
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/King_Ranperres_Tomb/Zone.lua | 1 | 1138 | -----------------------------------
--
-- Zone: King_Ranperres_Tomb
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/King_Ranperres_Tomb/TextIDs"] = nil;
require("scripts/zones/King_Ranperres_Tomb/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
| gpl-3.0 |
RyMarq/Zero-K | LuaRules/Gadgets/unit_target_on_the_move.lua | 2 | 14641 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Target on the move",
desc = "Adds a command to set unit target without using the normal command queue",
author = "Google Frog",
date = "September 25 2011",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true,
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
include("LuaRules/Configs/customcmds.h.lua")
if not gadgetHandler:IsSyncedCode() then
function gadget:Initialize()
Spring.SetCustomCommandDrawData(CMD_UNIT_SET_TARGET, "SetTarget", {1.0, 0.75, 0.0, 0.7}, true)
Spring.SetCustomCommandDrawData(CMD_UNIT_SET_TARGET_CIRCLE, "SetTarget", {1.0, 0.75, 0.0, 0.7}, true)
Spring.AssignMouseCursor("SetTarget", "cursortarget", true, false)
end
return
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spInsertUnitCmdDesc = Spring.InsertUnitCmdDesc
local spGetUnitAllyTeam = Spring.GetUnitAllyTeam
local spSetUnitTarget = Spring.SetUnitTarget
local spValidUnitID = Spring.ValidUnitID
local spGetUnitPosition = Spring.GetUnitPosition
local spGetGroundHeight = Spring.GetGroundHeight
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitLosState = Spring.GetUnitLosState
local spGiveOrderToUnit = Spring.GiveOrderToUnit
local spSetUnitRulesParam = Spring.SetUnitRulesParam
local getMovetype = Spring.Utilities.getMovetype
local CMD_WAIT = CMD.WAIT
local CMD_FIRE_STATE = CMD.FIRE_STATE
-- Constans
local TARGET_NONE = 0
local TARGET_GROUND = 1
local TARGET_UNIT = 2
--------------------------------------------------------------------------------
-- Config
-- Unseen targets will be removed after at least UNSEEN_TIMEOUT*USEEN_UPDATE_FREQUENCY frames
-- and at most (UNSEEN_TIMEOUT+1)*USEEN_UPDATE_FREQUENCY frames/
local USEEN_UPDATE_FREQUENCY = 45
local UNSEEN_TIMEOUT = 2
--------------------------------------------------------------------------------
-- Globals
local validUnits = {}
local waitWaitUnits = {}
local weaponCounts = {}
for i = 1, #UnitDefs do
local ud = UnitDefs[i]
weaponCounts[i] = (ud.weapons and #ud.weapons)
if ((not (ud.canFly and (ud.isBomber or ud.isBomberAirUnit))) and
ud.canAttack and ud.canMove and ud.maxWeaponRange and ud.maxWeaponRange > 0) or ud.isFactory then
if getMovetype(ud) == 0 then
waitWaitUnits[i] = true
end
validUnits[i] = true
end
end
local unitById = {} -- unitById[unitID] = position of unitID in unit
local unit = {count = 0, data = {}} -- data holds all unitID data
local drawPlayerAlways = {}
--------------------------------------------------------------------------------
-- Commands
local allyTargetUnits = {
[UnitDefNames["jumpsumo"].id] = true,
[UnitDefNames["amphlaunch"].id] = true,
}
local unitSetTargetCmdDesc = {
id = CMD_UNIT_SET_TARGET,
type = CMDTYPE.ICON_UNIT_OR_RECTANGLE,
name = 'Set Target',
action = 'settarget',
cursor = 'SetTarget',
tooltip = 'Set Target: Set a priority target that is indepdent of the units command queue.',
hidden = true,
}
local unitSetTargetCircleCmdDesc = {
id = CMD_UNIT_SET_TARGET_CIRCLE,
type = CMDTYPE.ICON_UNIT_OR_AREA,
name = 'Set Target Circle',
action = 'settargetcircle',
cursor = 'SetTarget',
tooltip = 'Set Target: Set a priority target that is indepdent of the units command queue.',
hidden = false,
}
local unitCancelTargetCmdDesc = {
id = CMD_UNIT_CANCEL_TARGET,
type = CMDTYPE.ICON,
name = 'Cancel Target',
action = 'canceltarget',
tooltip = 'Cancel Target: Cancel the units priority target.',
hidden = false,
}
--------------------------------------------------------------------------------
-- Target Handling
local function unitInRange(unitID, unitDefID, targetID)
return true
--local dis = Spring.GetUnitSeparation(unitID, targetID) -- 2d range
--local _, _, _, ux, uy, uz = spGetUnitPosition(unitID, true)
--local _, _, _, tx, ty, tz = spGetUnitPosition(targetID, true)
--local range = Spring.Utilities.GetUpperEffectiveWeaponRange(unitDefID, uy - ty) + 50
--return dis and range and dis < range
end
local function locationInRange(unitID, unitDefID, x, y, z)
return true
--local _, _, _, ux, uy, uz = spGetUnitPosition(unitID, true)
--local range = Spring.Utilities.GetUpperEffectiveWeaponRange(unitDefID, uy - y) + 50
--return range and ((ux - x)^2 + (uz - z)^2) < range^2
end
local function clearTarget(unitID)
spSetUnitTarget(unitID, nil) -- The second argument is needed.
spSetUnitRulesParam(unitID,"target_type",TARGET_NONE)
end
local function IsValidTargetBasedOnAllyTeam(targetID, myAllyTeamID)
if Spring.GetUnitNeutral(targetID) then
return Spring.GetUnitRulesParam(targetID, "avoidAttackingNeutral") ~= 1
end
return spGetUnitAllyTeam(targetID) ~= myAllyTeamID
end
local function setTarget(data, sendToWidget)
if spValidUnitID(data.id) then
if not data.targetID then
if locationInRange(data.id, data.unitDefID, data.x, data.y, data.z) then
spSetUnitTarget(data.id, data.x, data.y, data.z, false, true)
GG.UnitSetGroundTarget(data.id)
end
if sendToWidget then
spSetUnitRulesParam(data.id,"target_type",TARGET_GROUND)
spSetUnitRulesParam(data.id,"target_x",data.x)
spSetUnitRulesParam(data.id,"target_y",data.y)
spSetUnitRulesParam(data.id,"target_z",data.z)
end
elseif spValidUnitID(data.targetID) and (data.allyAllowed or IsValidTargetBasedOnAllyTeam(data.targetID, data.allyTeam)) then
if (not Spring.GetUnitIsCloaked(data.targetID)) and unitInRange(data.id, data.unitDefID, data.targetID) and (data.id ~= data.targetID) then
spSetUnitTarget(data.id, data.targetID, false, true)
end
if sendToWidget then
spSetUnitRulesParam(data.id,"target_type",TARGET_UNIT)
spSetUnitRulesParam(data.id,"target_id",data.targetID)
end
else
return false
end
end
return true
end
local function removeUnseenTarget(data)
if data.targetID and not data.alwaysSeen and spValidUnitID(data.targetID) then
local los = spGetUnitLosState(data.targetID, data.allyTeam, true)
if not los or (los % 4 == 0) then
if data.unseenTargetTimer == UNSEEN_TIMEOUT then
return true
elseif not data.unseenTargetTimer then
data.unseenTargetTimer = 1
else
data.unseenTargetTimer = data.unseenTargetTimer + 1
end
elseif data.unseenTargetTimer then
data.unseenTargetTimer = nil
end
end
end
--------------------------------------------------------------------------------
-- Unit adding/removal
local function addUnit(unitID, data)
if spValidUnitID(unitID) then
-- clear current traget
clearTarget(unitID)
if setTarget(data, true) then
if unitById[unitID] then
unit.data[unitById[unitID]] = data
else
unit.count = unit.count + 1
unit.data[unit.count] = data
unitById[unitID] = unit.count
end
end
end
end
local function removeUnit(unitID)
local unitDefID = spGetUnitDefID(unitID)
local ud = UnitDefs[unitDefID]
if not (unitDefID and waitWaitUnits[unitDefID]) then
clearTarget(unitID)
end
if unitDefID and validUnits[unitDefID] and unitById[unitID] then
if waitWaitUnits[unitDefID] then
clearTarget(unitID)
spGiveOrderToUnit(unitID,CMD_WAIT, {}, 0)
spGiveOrderToUnit(unitID,CMD_WAIT, {}, 0)
end
if unitById[unitID] ~= unit.count then
unit.data[unitById[unitID]] = unit.data[unit.count]
unitById[unit.data[unit.count].id] = unitById[unitID]
end
unit.data[unit.count] = nil
unit.count = unit.count - 1
unitById[unitID] = nil
end
end
function gadget:Initialize()
-- register command
gadgetHandler:RegisterCMDID(CMD_UNIT_SET_TARGET)
gadgetHandler:RegisterCMDID(CMD_UNIT_CANCEL_TARGET)
-- load active units
for _, unitID in ipairs(Spring.GetAllUnits()) do
local unitDefID = Spring.GetUnitDefID(unitID)
local teamID = Spring.GetUnitTeam(unitID)
gadget:UnitCreated(unitID, unitDefID, teamID)
end
end
function gadget:UnitCreated(unitID, unitDefID, unitTeam, builderID)
if validUnits[unitDefID] then
spInsertUnitCmdDesc(unitID, unitSetTargetCmdDesc)
spInsertUnitCmdDesc(unitID, unitSetTargetCircleCmdDesc)
spInsertUnitCmdDesc(unitID, unitCancelTargetCmdDesc)
end
end
function gadget:UnitFromFactory(unitID, unitDefID, unitTeam, facID, facDefID)
if unitById[facID] and validUnits[unitDefID] then
local data = unit.data[unitById[facID]]
addUnit(unitID, {
id = unitID,
targetID = data.targetID,
x = data.x, y = data.y, z = data.z,
allyTeam = spGetUnitAllyTeam(unitID),
unitDefID = unitDefID,
alwaysSeen = data.alwaysSeen,
})
end
end
function gadget:UnitDestroyed(unitID, unitDefID, unitTeam)
removeUnit(unitID)
end
function gadget:UnitTaken(unitID, unitDefID, oldTeamID, teamID)
removeUnit(unitID)
end
--------------------------------------------------------------------------------
-- Command Tracking
local function disSQ(x1,y1,x2,y2)
return (x1 - x2)^2 + (y1 - y2)^2
end
local function setTargetClosestFromList(unitID, unitDefID, team, choiceUnits)
local ux, uy, uz = Spring.GetUnitPosition(unitID)
local bestDis = false
local bestUnit = false
if ux and choiceUnits then
for i = 1, #choiceUnits do
local tTeam = Spring.GetUnitTeam(choiceUnits[i])
if tTeam and (not Spring.AreTeamsAllied(team,tTeam)) then
local tx,ty,tz = Spring.GetUnitPosition(choiceUnits[i])
if tx then
local newDis = disSQ(ux,uz,tx,tz)
if (not bestDis) or bestDis > newDis then
bestDis = newDis
bestUnit = choiceUnits[i]
end
end
end
end
end
if bestUnit then
local targetUnitDef = spGetUnitDefID(bestUnit)
local tud = targetUnitDef and UnitDefs[targetUnitDef]
addUnit(unitID, {
id = unitID,
targetID = bestUnit,
allyTeam = spGetUnitAllyTeam(unitID),
unitDefID = unitDefID,
alwaysSeen = tud and tud.isImmobile,
})
end
end
function gadget:AllowCommand_GetWantedCommand()
return {[CMD_FIRE_STATE] = true, [CMD_UNIT_CANCEL_TARGET] = true, [CMD_UNIT_SET_TARGET] = true, [CMD_UNIT_SET_TARGET_CIRCLE] = true}
end
function gadget:AllowCommand_GetWantedUnitDefID()
return true
end
function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions)
if cmdID == CMD_UNIT_SET_TARGET or cmdID == CMD_UNIT_SET_TARGET_CIRCLE then
if validUnits[unitDefID] then
if #cmdParams == 6 then
local team = Spring.GetUnitTeam(unitID)
if not team then
return false
end
local top, bot, left, right
if cmdParams[1] < cmdParams[4] then
left = cmdParams[1]
right = cmdParams[4]
else
left = cmdParams[4]
right = cmdParams[1]
end
if cmdParams[3] < cmdParams[6] then
top = cmdParams[3]
bot = cmdParams[6]
else
top = cmdParams[6]
bot = cmdParams[3]
end
local units = CallAsTeam(team,
function ()
return Spring.GetUnitsInRectangle(left,top,right,bot)
end
)
setTargetClosestFromList(unitID, unitDefID, team, units)
elseif #cmdParams == 3 or (#cmdParams == 4 and cmdParams[4] == 0) then
addUnit(unitID, {
id = unitID,
x = cmdParams[1],
y = CallAsTeam(teamID, function () return spGetGroundHeight(cmdParams[1],cmdParams[3]) end),
z = cmdParams[3],
allyTeam = spGetUnitAllyTeam(unitID),
unitDefID = unitDefID,
})
elseif #cmdParams == 4 then
local team = Spring.GetUnitTeam(unitID)
if not team then
return false
end
local units = CallAsTeam(team,
function ()
return Spring.GetUnitsInCylinder(cmdParams[1],cmdParams[3],cmdParams[4])
end
)
setTargetClosestFromList(unitID, unitDefID, team, units)
elseif #cmdParams == 1 then
local targetUnitDef = spGetUnitDefID(cmdParams[1])
local tud = targetUnitDef and UnitDefs[targetUnitDef]
addUnit(unitID, {
id = unitID,
targetID = cmdParams[1],
allyTeam = spGetUnitAllyTeam(unitID),
allyAllowed = allyTargetUnits[unitDefID],
unitDefID = unitDefID,
alwaysSeen = tud and tud.isImmobile,
})
end
end
return false -- command was used
elseif cmdID == CMD_UNIT_CANCEL_TARGET then
if validUnits[unitDefID] then
removeUnit(unitID)
end
return false -- command was used
elseif cmdID == CMD_FIRE_STATE and weaponCounts[unitDefID] then
-- Cancel target when firestate is not fire at will
if cmdParams and (cmdParams[1] or 0) < 2 then
for i = 1, weaponCounts[unitDefID] do
Spring.UnitWeaponHoldFire(unitID, i)
end
end
end
return true -- command was not used
end
--------------------------------------------------------------------------------
-- Gadget Interaction
function GG.GetUnitTarget(unitID)
return unitById[unitID] and unit.data[unitById[unitID]] and unit.data[unitById[unitID]].targetID
end
function GG.GetUnitTargetGround(unitID)
if unitById[unitID] and unit.data[unitById[unitID]] then
return not unit.data[unitById[unitID]].targetID
end
return false
end
function GG.SetUnitTarget(unitID, targetID)
local unitDefID = Spring.GetUnitDefID(unitID)
if not (unitDefID and validUnits[unitDefID]) then
return
end
local targetUnitDef = spGetUnitDefID(targetID)
local tud = targetUnitDef and UnitDefs[targetUnitDef]
if tud then
addUnit(unitID, {
id = unitID,
targetID = targetID,
allyTeam = spGetUnitAllyTeam(unitID),
allyAllowed = allyTargetUnits[unitDefID],
unitDefID = unitDefID,
alwaysSeen = tud.isImmobile,
})
end
end
--------------------------------------------------------------------------------
-- Target update
function gadget:GameFrame(n)
if n%5 == 4 then
-- Slow update every 15 frames
-- Ideally units would run this code the frame after their slow update
local toRemove = {count = 0, data = {}}
for i = 1, unit.count do
if not setTarget(unit.data[i], false) then
toRemove.count = toRemove.count + 1
toRemove.data[toRemove.count] = unit.data[i].id
end
end
for i = 1, toRemove.count do
removeUnit(toRemove.data[i])
end
end
if n%USEEN_UPDATE_FREQUENCY == 0 then
local toRemove = {count = 0, data = {}}
for i = 1, unit.count do
if removeUnseenTarget(unit.data[i]) then
toRemove.count = toRemove.count + 1
toRemove.data[toRemove.count] = unit.data[i].id
end
end
for i = 1, toRemove.count do
removeUnit(toRemove.data[i])
end
end
end
| gpl-2.0 |
TerminalShell/zombiesurvival | entities/weapons/weapon_zs_forcefield/shared.lua | 2 | 1175 | SWEP.ViewModel = "models/weapons/v_pistol.mdl"
SWEP.WorldModel = Model("models/props_lab/lab_flourescentlight002b.mdl")
SWEP.AmmoIfHas = true
SWEP.Primary.ClipSize = 1
SWEP.Primary.DefaultClip = 1
SWEP.Primary.Ammo = "slam"
SWEP.Primary.Delay = 1
SWEP.Primary.Automatic = true
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.WalkSpeed = 200
SWEP.FullWalkSpeed = 180
function SWEP:Initialize()
self:SetWeaponHoldType("fist")
self:SetDeploySpeed(1.1)
self:HideViewAndWorldModel()
end
function SWEP:SetReplicatedAmmo(count)
self:SetDTInt(0, count)
end
function SWEP:GetReplicatedAmmo()
return self:GetDTInt(0)
end
function SWEP:GetWalkSpeed()
if self:GetPrimaryAmmoCount() > 0 then
return self.FullWalkSpeed
end
end
function SWEP:SecondaryAttack()
end
function SWEP:Reload()
end
function SWEP:CanPrimaryAttack()
if self.Owner:IsHolding() or self.Owner:GetBarricadeGhosting() then return false end
if self:GetPrimaryAmmoCount() <= 0 then
self:SetNextPrimaryFire(CurTime() + self.Primary.Delay)
return false
end
return true
end
function SWEP:Holster()
return true
end
| gpl-3.0 |
madpilot78/ntopng | attic/scripts/lua/inc/service_map.lua | 2 | 8541 | --
-- (C) 2013-21 - ntop.org
--
require "flow_utils"
local lua_utils = require "lua_utils"
print('<link href="'.. ntop.getHttpPrefix()..'/datatables/datatables.min.css" rel="stylesheet"/>')
print ('<div class="d-flex justify-content-start"><H3>' .. i18n("service_map") .. "</H3>")
if(_GET["host"] ~= nil) then
print(' <A HREF="/lua/if_stats.lua?page=service_map"><span class="fas fa-ethernet"></span></A>')
end
local p = interface.serviceMap() or {}
local host_ip = _GET["host"]
--
-- Draw service map
--
local nodes = {}
local nodes_id = {}
local proto_number = {}
local num_services = 0
-- tprint(iec)
for k,v in pairs(p) do
local key = ""
if((host_ip == nil) or (v.client == host_ip) or (v.server == host_ip) ) then
num_services = num_services + 1
nodes[v["client"]] = true
nodes[v["server"]] = true
if v["client"] > v["server"] then
key = v["client"] .. "," .. v["server"]
if proto_number[key] == nil then
proto_number[key] = { 1, false , v["client"], v["server"], v.l7_proto} -- { num_recurrencies, bidirection true | monodirectional false, client_ip, server_ip, l7_proto}
else
proto_number[key][1] = proto_number[key][1] + 1
-- Don't show more then 3 l7 protocols
if proto_number[key][1] <= 3 then
proto_number[key][5] = proto_number[key][5] .. ", " .. v.l7_proto
end
-- Checking direction of the service, false monodirectional and true bidirectional
if v["server"] ~= proto_number[key][4] then
proto_number[key][2] = true
end
end
else
key = v["server"] .. "," .. v["client"]
if proto_number[key] == nil then
proto_number[key] = { 1, false , v["client"], v["server"], v.l7_proto} -- { num_recurrencies, bidirection true | monodirectional false, client_ip, server_ip, l7_proto}
else
proto_number[key][1] = proto_number[key][1] + 1
-- Don't show more then 3 l7 protocols
if proto_number[key][1] <= 3 then
proto_number[key][5] = proto_number[key][5] .. ", " .. v.l7_proto
end
-- Checking direction of the service, false monodirectional and true bidirectional
if v["server"] ~= proto_number[key][4] then
proto_number[key][2] = true
end
end
end
end
end
if num_services > 0 then
print [[ </div> <div> <script type="text/javascript" src="/js/vis-network.min.js"></script>
<div style="width:100%; height:30vh; " id="services_map"></div><p>
<script type="text/javascript">
var nodes = null;
var edges = null;
var network = null;
function draw() {
// create people.
// value corresponds with the age of the person
nodes = [
]]
local i = 1
for k,_ in pairs(nodes) do
local hinfo = hostkey2hostinfo(k)
local label
local ainfo = interface.getAddressInfo(k)
local stats = interface.getHostInfo(hinfo.host, hinfo.vlan)
if(stats and (stats.name ~= "")) then
label = shortenString(stats.name, 16)
else
label = shortenString(hostinfo2label(hinfo), 16)
end
if(ainfo.is_multicast or ainfo.is_broadcast) then
print('{ id: '..i..', value: \"' .. k .. '\", label: \"'..label..'\", color: "#7BE141"},\n')
else
print("{ id: "..i..", value: \"" .. k .. "\", label: \""..label.."\" },\n")
end
nodes_id[k] = i
i = i + 1
end
print [[
];
// create connections between people
// value corresponds with the amount of contact between two people
edges = [
]]
for k,v in pairs(proto_number) do
local title = v[5]
local arrow = ""
if v[1] > 3 then
title = title .. ", other " .. v[1] - 3 .. "..."
end
if v[2] == true then
arrow = "to;from"
else
arrow = "to"
end
print("{ from: " .. nodes_id[v[3]] .. ", to: " .. nodes_id[v[4]] .. ", value: " .. "1" .. ", title: \"" .. title .. "\", arrows: \"" .. arrow .. "\" },\n")
end
print [[
];
// Instantiate our network object.
var container = document.getElementById("services_map");
var data = {
nodes: nodes,
edges: edges,
};
var options = {
autoResize: true,
nodes: {
shape: "dot",
scaling: {
label: false,
min: 30,
max: 30,
},
shadow: true,
// smooth: true,
},
physics: false // disable physiscs for the graph
};
network = new vis.Network(container, data, options);
network.on("doubleClick", function (params) {
const target = params.nodes[0];
const node_selected = nodes.find(n => n.id == target);
console.log(node_selected);
window.location.href = http_prefix + '/lua/host_details.lua?host=' + node_selected.value + '&page=service_map';
});
}
draw();
</script>
]]
end
--
-- End service map draw
--
print [[
</div>
<div class='table-responsive'>
<table id="service_map" class="table table-bordered table-striped w-100">
<thead>
<tr>
<th>]] print(i18n("protocol")) print [[</th>
<th>]] print(i18n("client")) print [[</th>
<th>]] print(i18n("server")) print [[</th>
<th>]] print(i18n("vlan_id")) print [[</th>
<th>]] print(i18n("port")) print [[</th>
<th>]] print(i18n("num_uses")) print [[</th>
<th>]] print(i18n("last_seen")) print [[</th>
<th>]] print(i18n("info")) print [[</th>
<th>]] print(i18n("service_acceptance")) print [[</th>
</tr>
</thead>
</table>
</div>
]]
if(isAdministrator()) then
if(_GET["action"] == "reset") then
interface.flushServiceMap()
end
if(ifid ~= nil) then
print [[
<div class="d-flex justify-content-start">
<form>
<input type=hidden name="ifid" value="]] print(ifid.."") print [[">
<input type=hidden name="page" value="service_map">
<input type=hidden name="action" value="reset">
<button id="btn-factory-reset" data-target='#reset-modal' data-toggle="modal" class="btn btn-danger" onclick="return confirm(']] print(i18n("data_flush_confirm")) print [[')">
<i class="fas fa-undo-alt"></i> ]] print(i18n("flush_service_map_data")) print [[
</button>
</form>
<a href="]] print(ntop.getHttpPrefix()) print [[ /lua/get_service_map.lua" target="_blank" class="btn btn-primary" role="button" aria-disabled="true"><i class="fas fa-download"></i></a>
</div>
]]
end
end
print [[
<script>
$(document).ready(function() {
const filters = [
]]
local keys = {}
local keys_regex = {}
for k,v in pairs(p) do
if((host_ip == nil)
or (v.client == host_ip)
or (v.server == host_ip) ) then
local k = "^".. getL4ProtoName(v.l4_proto) .. ":" .. v.l7_proto .."$"
keys_regex[v.l7_proto] = k
k = v.l7_proto
if(keys[k] == nil) then
keys[k] = 0
end
keys[k] = keys[k] + 1
end
end
local id = 0
for k,v in pairsByKeys(keys, asc) do
print("{ key: 'filter_"..id.."', regex: '"..keys_regex[k].."', label: '"..k.." ("..v..")', countable: false },\n")
id = id + 1
end
print [[
];
let url = ']] print(ntop.getHttpPrefix()) print [[/lua/get_service_map.lua]]
if(_GET["host"] ~= nil) then print("?host=".._GET["host"]) end
print [[';
let config = DataTableUtils.getStdDatatableConfig( [ {
text: '<i class="fas fa-sync"></i>',
action: function(e, dt, node, config) {
$serviceTable.ajax.reload();
}
} ]);
config = DataTableUtils.setAjaxConfig(config, url, 'data');
config["initComplete"] = function(settings, rows) {
const tableAPI = settings.oInstance.api();
}
const $serviceTable = $('#service_map').DataTable(config);
const columnProtocolIndex = 0; /* Filter on protocol column */
const periodicityMenuFilters = new DataTableFiltersMenu({
filterTitle: "]] print(i18n("protocol")) print[[",
tableAPI: $serviceTable,
filters: filters,
filterMenuKey: 'protocol',
columnIndex: columnProtocolIndex
});
} );
i18n.all = "]] print(i18n("all")) print [[";
i18n.showing_x_to_y_rows = "]] print(i18n('showing_x_to_y_rows', {x='_START_', y='_END_', tot='_TOTAL_'})) print[[";
</script>
]]
| gpl-3.0 |
nimaghorbani/creed | plugins/google.lua | 336 | 1323 | do
local function googlethat(query)
local url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&&rsz=5&'
local parameters = 'q='..(URL.escape(query) or '')
-- Do the request
local res, code = https.request(url..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=''
i = 0
for key,val in ipairs(results) do
i = i+1
stringresults=stringresults..i..'. '..val[1]..'\n'..val[2]..'\n'
end
return stringresults
end
local function run(msg, matches)
-- comment this line if you want this plugin works in private message.
if not is_chat_msg(msg) then return nil end
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = 'Returns five results from Google. Safe search is enabled by default.',
usage = ' !google [terms]: Searches Google and send results',
patterns = {
'^!google (.*)$',
'^%.[g|G]oogle (.*)$'
},
run = run
}
end
| gpl-2.0 |
zhutaorun/2DPlatformer-SLua | Assets/StreamingAssets/Lua/Logic/LgBomb.lua | 1 | 4270 | --
-- Bomb class.
--
-- @filename LgBomb.lua
-- @copyright Copyright (c) 2015 Yaukey/yaukeywang/WangYaoqi (yaukeywang@gmail.com) all rights reserved.
-- @license The MIT License (MIT)
-- @author Yaukey
-- @date 2015-09-01
--
local YwDeclare = YwDeclare
local YwClass = YwClass
local DLog = YwDebug.Log
local DLogWarn = YwDebug.LogWarning
local DLogError = YwDebug.LogError
-- Register new class LgBomb.
local strClassName = "LgBomb"
local LgBomb = YwDeclare(strClassName, YwClass(strClassName))
-- Member variables.
-- The c# class object.
LgBomb.this = false
-- The transform.
LgBomb.transform = false
-- The c# gameObject.
LgBomb.gameObject = false
-- Public.
-- Prefab of explosion effect.
LgBomb.m_cExplosion = false
-- Private.
-- Reference to the player's LayBombs script.
LgBomb.m_cLayBombs = false
-- Reference to the PickupSpawner script.
LgBomb.m_cPickupSpawner = false
-- Reference to the particle system of the explosion effect.
LgBomb.m_cExplosionFx = false
-- Awake method.
function LgBomb:Awake()
--print("LgBomb:Awake")
-- Check variable.
if (not self.this) or (not self.transform) or (not self.gameObject) then
DLogError("Init error in LgBomb!")
return
end
self.m_cExplosionFx = GameObject.FindGameObjectWithTag("ExplosionFX"):GetComponent(ParticleSystem)
self.m_cPickupSpawner = GameObject.Find("pickupManager"):GetComponent(PickupSpawner)
if GameObject.FindGameObjectWithTag("Player") then
self.m_cLayBombs = GameObject.FindGameObjectWithTag("Player"):GetComponent(LayBombs)
end
end
-- Start method.
function LgBomb:Start()
--print("LgBomb:Start")
--If the bomb has no parent, it has been laid by the player and should detonate.
if self.transform.root == self.transform then
self:BombDetonation()
end
end
-- Explode.
function LgBomb:Explode()
--print("LgBomb:Explode")
local this = self.this
-- The player is now free to lay bombs when he has them.
self.m_cLayBombs.BombLaid = false
-- Make the pickup spawner start to deliver a new pickup.
self.m_cPickupSpawner:DeliverPickup()
-- Find all the colliders on the Enemies layer within the bombRadius.
local aEnemies = Physics2D.OverlapCircleAll(self.transform.position, this.m_bombRadius, 1 << LayerMask.NameToLayer("Enemies"))
-- For each collider...
for _, cEnemy in pairs(aEnemies) do
-- Check if it has a rigidbody (since there is only one per enemy, on the parent).
local cRb = cEnemy:GetComponent(Rigidbody2D)
if cRb and ("Enemy" == cRb.tag) then
-- Find the Enemy script and set the enemy's health to zero.
cRb.gameObject:GetComponent(Enemy).m_HP = 0
-- Find a vector from the bomb to the enemy.
local vDeltaPos = cRb.transform.position - self.transform.position
-- Apply a force in this direction with a magnitude of bombForce.
local vForce = vDeltaPos.normalized * this.m_bombForce
cRb:AddForce(vForce)
end
end
-- Set the explosion effect's position to the bomb's position and play the particle system.
self.m_cExplosionFx.transform.position = self.transform.position
self.m_cExplosionFx:Play()
-- Instantiate the explosion prefab.
GameObject.Instantiate(this.m_explosion, self.transform.position, Quaternion.identity)
-- Play the explosion sound effect.
AudioSource.PlayClipAtPoint(this.m_boom, self.transform.position)
-- Destroy the bomb.
GameObject.Destroy(self.gameObject)
end
-- LgBomb detonation.
function LgBomb:BombDetonation()
--print("LgBomb:BombDetonation")
-- Check the validation.
if Slua.IsNull(self.gameObject) then
return
end
-- LgBomb detonation.
local cCo = coroutine.create(function ()
-- Play the fuse seconds.
AudioSource.PlayClipAtPoint(self.this.m_fuse, self.transform.position)
-- Wait for 2 seconds.
Yield(WaitForSeconds(self.this.m_fuseTime))
-- Check the validation.
if Slua.IsNull(self.gameObject) then
return
end
-- Explode the bomb.
self:Explode()
end)
coroutine.resume(cCo)
end
-- Return this class.
return LgBomb
| mit |
RyMarq/Zero-K | units/staticjammer.lua | 1 | 2492 | return { staticjammer = {
unitname = [[staticjammer]],
name = [[Cornea]],
description = [[Area Cloaker/Jammer]],
activateWhenBuilt = true,
buildCostMetal = 420,
builder = false,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 4,
buildingGroundDecalSizeY = 4,
buildingGroundDecalType = [[staticjammer_aoplane.dds]],
buildPic = [[staticjammer.png]],
category = [[SINK UNARMED]],
canMove = true,
cloakCost = 1,
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[32 70 32]],
collisionVolumeType = [[CylY]],
corpse = [[DEAD]],
customParams = {
removewait = 1,
morphto = [[cloakjammer]],
morphtime = 30,
area_cloak = 1,
area_cloak_upkeep = 12,
area_cloak_radius = 550,
area_cloak_decloak_distance = 75,
priority_misc = 2, -- High
addfight = 1,
addpatrol = 1,
},
energyUse = 1.5,
explodeAs = [[BIG_UNITEX]],
floater = true,
footprintX = 2,
footprintZ = 2,
iconType = [[staticjammer]],
idleAutoHeal = 5,
idleTime = 1800,
initCloaked = true,
levelGround = false,
maxDamage = 700,
maxSlope = 36,
minCloakDistance = 100,
noAutoFire = false,
objectName = [[radarjammer.dae]],
onoffable = true,
radarDistanceJam = 550,
script = [[staticjammer.lua]],
selfDestructAs = [[BIG_UNITEX]],
sightDistance = 250,
useBuildingGroundDecal = true,
yardMap = [[oo oo]],
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[radarjammer_dead.dae]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2a.s3o]],
},
},
} }
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Port_San_dOria/npcs/Ceraulian.lua | 1 | 1328 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Ceraulian
-- Involved in Quest: The Holy Crest
-- @zone
-- @pos
-----------------------------------
package.loaded["scripts/globals/quests"] = nil;
require("scripts/globals/quests");
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getMainLvl() >= 30 and player:getQuestStatus(SANDORIA,THE_HOLY_CREST) == QUEST_AVAILABLE) then
player:startEvent(0x0018);
else
player:startEvent(0x024b);
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 == 0x0018) then
player:setVar("TheHolyCrest_Event",1);
end
end; | gpl-3.0 |
madpilot78/ntopng | scripts/plugins/monitors/network/active_monitoring/ts_schemas/min.lua | 1 | 1777 | --
-- (C) 2019-21 - ntop.org
--
local ts_utils = require "ts_utils_core"
local schema
schema = ts_utils.newSchema("am_host:val_min", {
step = 60,
metrics_type = ts_utils.metrics.gauge,
aggregation_function = ts_utils.aggregation.max,
is_system_schema = true,
})
schema:addTag("ifid")
schema:addTag("host")
schema:addTag("metric")
schema:addMetric("value")
-- ##############################################
schema = ts_utils.newSchema("am_host:http_stats_min", {
step = 60,
metrics_type = ts_utils.metrics.gauge,
aggregation_function = ts_utils.aggregation.max,
is_system_schema = true,
})
schema:addTag("ifid")
schema:addTag("host")
schema:addTag("metric")
schema:addMetric("lookup_ms")
schema:addMetric("other_ms")
-- ##############################################
schema = ts_utils.newSchema("am_host:https_stats_min", {
step = 60,
metrics_type = ts_utils.metrics.gauge,
aggregation_function = ts_utils.aggregation.max,
is_system_schema = true,
})
schema:addTag("ifid")
schema:addTag("host")
schema:addTag("metric")
schema:addMetric("lookup_ms")
schema:addMetric("connect_ms")
schema:addMetric("other_ms")
-- ##############################################
schema = ts_utils.newSchema("am_host:cicmp_stats_min", {
step = 60,
metrics_type = ts_utils.metrics.gauge,
is_system_schema = true,
})
schema:addTag("ifid")
schema:addTag("host")
schema:addTag("metric")
schema:addMetric("min_rtt")
schema:addMetric("max_rtt")
-- ##############################################
schema = ts_utils.newSchema("am_host:jitter_stats_min", {
step = 60,
metrics_type = ts_utils.metrics.gauge,
is_system_schema = true,
})
schema:addTag("ifid")
schema:addTag("host")
schema:addTag("metric")
schema:addMetric("latency")
schema:addMetric("jitter")
| gpl-3.0 |
madpilot78/ntopng | scripts/lua/modules/import_export/import_export_rest_utils.lua | 1 | 4032 | --
-- (C) 2020 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/pools/?.lua;" .. package.path
require "lua_utils"
local json = require "dkjson"
local rest_utils = require "rest_utils"
local pools = require "pools"
local pools_lua_utils = require "pools_lua_utils"
local tracker = require("tracker")
local plugins_utils = require("plugins_utils")
local checks = require("checks")
-- ##############################################
local import_export_rest_utils = {}
import_export_rest_utils.IMPORT_EXPORT_JSON_VERSION = "1.0"
-- ##############################################
-- @brief Add an envelope to the module configurations
function import_export_rest_utils.pack(modules)
local rc = rest_utils.consts.success.ok
local envelope = {}
-- Add a version to the envelope to track the dump version
envelope.version = import_export_rest_utils.IMPORT_EXPORT_JSON_VERSION
-- Add the configuration of all provided module
envelope.modules = modules
return envelope
end
-- ##############################################
-- @brief Decode the configuration in json format
-- and handle the envelope. Return the list of
-- configurations for all the modules to be imported.
function import_export_rest_utils.unpack(json_conf)
-- Decode the json
if json_conf == nil then
return nil
end
local envelope = json.decode(json_conf)
-- Check the envelope format and version
if not envelope or
not envelope.version == nil or
envelope.version ~= import_export_rest_utils.IMPORT_EXPORT_JSON_VERSION then
return nil
end
return envelope.modules
end
-- ##############################################
-- @brief Import the configuration for a list of (provided)
-- module instances
function import_export_rest_utils.import(items)
local rc = rest_utils.consts.success.ok
local list = {}
for _, module in ipairs(items) do
local res = module.instance:import(module.conf)
if res.err then
-- DEBUG
-- tprint(module.name.." failure ")
-- tprint(res)
rc = res.err
end
list[#list] = module.name
end
rest_utils.answer(rc)
-- TRACKER HOOK
tracker.log('import', { modules = list })
end
-- ##############################################
-- @brief Export the configuration for a list of (provided) module instances
function import_export_rest_utils.export(instances, is_download)
local rc = rest_utils.consts.success.ok
local modules = {}
local list = {}
local missing_modules = {}
-- Build the list of configurations for each module
for name, instance in pairs(instances) do
local conf = instance:export()
if not conf then
rc = rest_utils.consts.err.internal_error
missing_modules[#missing_modules+1] = name
else
modules[name] = conf
list[#list] = name
end
end
local envelope = import_export_rest_utils.pack(modules)
if is_download then
-- Download as file
if rc ~= rest_utils.consts.success.ok then
traceError(TRACE_ERROR, TRACE_CONSOLE, "Failure exporting configuration for " .. table.concat(missing_modules, ", "))
end
sendHTTPContentTypeHeader('application/json', 'attachment; filename="configuration.json"')
print(json.encode(envelope, nil))
else
-- Send as REST answer
rest_utils.answer(rc, envelope)
end
-- TRACKER HOOK
tracker.log('export', { modules = list })
end
-- ##############################################
-- @brief Reset the configuration for a list of (provided) module instances
function import_export_rest_utils.reset(instances)
local rc = rest_utils.consts.success.ok
local list = {}
for name, instance in pairs(instances) do
instance:reset()
list[#list] = name
end
rest_utils.answer(rc)
-- TRACKER HOOK
tracker.log('reset', { modules = list })
end
-- ##############################################
return import_export_rest_utils
| gpl-3.0 |
NPLPackages/paracraft | script/kids/3DMapSystemUI/loadworld.lua | 1 | 5902 | --[[
Title: The load world function for paraworld
Author(s): LiXizhi(code&logic), WangTian
Date: 2006/1/26
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/kids/3DMapSystemUI/loadworld.lua");
Map3DSystem.UI.LoadWorld.LoadWorldImmediate("worlds/empty")
------------------------------------------------------------
]]
local L = CommonCtrl.Locale("IDE");
local LoadWorld = commonlib.gettable("Map3DSystem.UI.LoadWorld")
--[[ load a world immediately without doing any error checking or report. This is usually called by ParaIDE from the Load world menu.
@param worldpath: the directory containing the world config file, such as "sample","worlds/demo"
or it can also be a [worldname].zip file that contains the world directory.
@param bPerserveUI: if true, UI are not cleared. default to nil
@param bHideProgressUI: if true, progress UI is hidden. default to nil
@param OnProgressCallBack: nil or a function of function(percent) end, where percent is between [0,100]
]]
function Map3DSystem.UI.LoadWorld.LoadWorldImmediate(worldpath, bPerserveUI, bHideProgressUI, OnProgressCallBack)
if(worldpath) then
worldpath = string.gsub(worldpath, "[/\\]+$", "")
end
if(string.find(worldpath, ".*%.zip$")~=nil or string.find(worldpath, ".*%.pkg$")~=nil) then
-- open zip archive with relative path
if(Map3DSystem.World.worldzipfile and Map3DSystem.World.worldzipfile~= worldpath) then
ParaAsset.CloseArchive(Map3DSystem.World.worldzipfile); -- close last world archive
end
Map3DSystem.World.worldzipfile = worldpath;
ParaAsset.OpenArchive(worldpath, true);
ParaIO.SetDiskFilePriority(-1);
local search_result = ParaIO.SearchFiles("","*.", worldpath, 0, 10, 0);
local nCount = search_result:GetNumOfResult();
if(nCount>0) then
-- just use the first directory in the world zip file as the world name.
local WorldName = search_result:GetItem(0);
WorldName = string.gsub(WorldName, "[/\\]$", "");
worldpath = string.gsub(worldpath, "([^/\\]+)%.%w%w%w$", WorldName); -- get rid of the zip file extension for display
else
-- make it the directory path
worldpath = string.gsub(worldpath, "(.*)%.%w%w%w$", "%1"); -- get rid of the zip file extension for display
end
if(not ParaIO.DoesFileExist(worldpath, false)) then
ParaIO.SetDiskFilePriority(0);
else
LOG.std(nil, "warn", "loadworld", "opening zip file while disk file already exist, use zip priority now");
end
Map3DSystem.World.readonly = true;
NPL.load("(gl)script/ide/sandbox.lua");
ParaSandBox.ApplyToWorld(nil);
ParaSandBox.Reset();
-- DISABLED: create and apply a sandbox for read only world, such as those downloaded from the network.
--local sandbox = ParaSandBox:GetSandBox("script/kids/pw_sandbox_file.lua");
--sandbox:Reset();
--ParaSandBox.ApplyToWorld(sandbox);
else
if(Map3DSystem.World.worldzipfile) then
ParaAsset.CloseArchive(Map3DSystem.World.worldzipfile);
end
Map3DSystem.World.worldzipfile = nil;
Map3DSystem.World.readonly = nil;
ParaIO.SetDiskFilePriority(0);
-- do not use a sandbox for writable world.
NPL.load("(gl)script/ide/sandbox.lua");
ParaSandBox.ApplyToWorld(nil);
ParaSandBox.Reset();
end
Map3DSystem.world.name = worldpath;
Map3DSystem.world:UseDefaultFileMapping();
if(ParaIO.DoesAssetFileExist(Map3DSystem.world.sConfigFile, true)) then
if(Map3DSystem.UI.LoadWorld.LoadWorld(bPerserveUI, bHideProgressUI, OnProgressCallBack) == true) then
-- make adiministrator by default, one needs to set a different role after this function return.
Map3DSystem.User.SetRole("administrator");
return true;
else
return worldpath..L" failed loading the world."
end
else
LOG.std(nil, "error", "LoadWorld", "unable to find file: %s", Map3DSystem.world.sConfigFile or "");
return worldpath..L" world does not exist"
end
end
-- private: clear the scene and load the world using the settings in the Map3DSystem, return false if failed.
-- @param bPerserveUI: if true, UI are not cleared and progress bar are not disabled. default to nil
-- @param bHideProgressUI: if true, progress UI is hidden. default to nil
-- @param OnProgressCallBack: nil or a function of function(percent) end, where percent is between [0,100]
function Map3DSystem.UI.LoadWorld.LoadWorld(bPerserveUI, bHideProgressUI, OnProgressCallBack)
-- clear the scene
Map3DSystem.reset(bPerserveUI);
if(Map3DSystem.World.sConfigFile ~= "") then
if(OnProgressCallBack) then
OnProgressCallBack(0)
end
-- disable the game
ParaScene.EnableScene(false);
if(not bHideProgressUI) then
NPL.load("(gl)script/kids/3DMapSystemUI/InGame/LoaderUI.lua");
Map3DSystem.UI.LoaderUI.Start(100);
Map3DSystem.UI.LoaderUI.SetProgress(20);
end
if(OnProgressCallBack) then
OnProgressCallBack(20)
end
-- TODO: security alert, this is not in sandbox. call the preload script for the given world
local sOnLoadScript = string.gsub(Map3DSystem.World.sConfigFile, "[^/\\]+$", "preload.lua");
if(ParaIO.DoesAssetFileExist(sOnLoadScript, true))then
NPL.load("(gl)"..sOnLoadScript, true);
end
-- create world
ParaScene.CreateWorld("", 32000, Map3DSystem.World.sConfigFile);
if(not bHideProgressUI) then
Map3DSystem.UI.LoaderUI.SetProgress(30);
end
if(OnProgressCallBack) then
OnProgressCallBack(30)
end
-- load from database
Map3DSystem.world:LoadWorldFromDB();
if(not bHideProgressUI) then
Map3DSystem.UI.LoaderUI.SetProgress(100);
end
if(OnProgressCallBack) then
OnProgressCallBack(100)
end
-- clear autotips elsewhere
if(autotips) then
autotips.Clear()
end
-- we have built the scene, now we can enable the game
ParaScene.EnableScene(true);
if(not bHideProgressUI) then
Map3DSystem.UI.LoaderUI.End();
end
Map3DSystem.PushState("game");
return true;
else
return false;
end
end
| gpl-2.0 |
knixeur/notion | contrib/statusd/legacy/statusd_apm2.lua | 3 | 2650 | -- Authors: Greg Steuck, Gerald Young <ion3script@gwy.org>
-- License: Public domain
-- Last Changed: Unknown
--
-- Public domain, written by Greg Steuck
-- Edited and updated by Gerald Young -- ion3script@gwy.org
-- This works on FreeBSD's apm (5.x) program added some color to indicate
-- AC connection and status (Charging, low, critical)
-- Allows displaying apm information in the statusbar.
-- To install:
-- save this file into ~/.ion3/statusd_apm.lua,
-- copy the default cfg_statusbar.lua to ~/.ion3, edit it to include (~line 81):
-- -- Battery meter
-- --[[
-- apm={},
-- --]]
-- add some of the following fields into your template in cfg_statusbar.lua:
-- %apm_ac: A/C cable on-line (connected) off-line (disconnected)
-- %apm_pct: percent of remaining battery
-- %apm_estimate: time remaining based upon usage ... or whatever apm thinks.
-- %apm_state: Status: charging/high/low/critical
-- in cfg_statusbar.lua, about line 28, add the next line without the leading "--"
-- template="[ %date || load:% %>load_1min || battery: %apm_pct AC: %apm_ac Status: %apm_state ]",
-- If you've already customized your template= line, then simply add the field(s) where you want.
local unknown = "?", "?", "?", "?"
-- Runs apm utility and grabs relevant pieces from its output.
-- Most likely will only work on OpenBSD due to reliance on its output pattern.
function get_apm()
local f=io.popen('/usr/sbin/apm', 'r')
if not f then
return unknown
end
local s=f:read('*all')
f:close()
local _, _, ac, state, pct, estimate =
string.find(s,
"AC Line status: (.*)\n"..
"Battery Status: (.*)\n"..
"Remaining battery life: (.*)\n"..
"Remaining battery time: (.*)\n"
)
if not state then
return unknown
end
return state, pct, estimate, ac
end
local function inform(key, value)
statusd.inform("apm_"..key, value)
end
local apm_timer = statusd.create_timer()
local function update_apm()
local state, pct, estimate, ac = get_apm()
local stateinf
if state=="low" then
stateinf = "important"
end
if state == "critical" then
stateinf = "critical"
end
if state == "charging" then
stateinf = "important"
end
inform("state", state)
inform("state_hint", stateinf)
inform("pct", pct)
inform("estimate", estimate)
if ac == "off-line" then
stateinf="critical"
end
if ac == "on-line" then
stateinf="important"
end
inform("ac", ac)
inform("ac_hint", stateinf)
apm_timer:set(60*1000, update_apm)
end
update_apm()
| lgpl-2.1 |
hfjgjfg/sss25 | plugins/BW-spammer.lua | 5 | 1869 | local function run(msg, matches)
if not is_momod(msg) then
return "For moderators only !"
end
if matches[1] then
return "BLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\NBLACK WOLF\N"
end
return
end
return {
description = "",
usage = {""},
patterns = {
"^[!/]([Bb]lackwolf)";
},
run = run
}
| gpl-2.0 |
vince06fr/prosody-modules | mod_vjud/vcard.lib.lua | 32 | 9198 | -- Copyright (C) 2011-2012 Kim Alvefur
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
-- TODO
-- Fix folding.
local st = require "util.stanza";
local t_insert, t_concat = table.insert, table.concat;
local type = type;
local next, pairs, ipairs = next, pairs, ipairs;
local from_text, to_text, from_xep54, to_xep54;
local line_sep = "\n";
local vCard_dtd; -- See end of file
local function fold_line()
error "Not implemented" --TODO
end
local function unfold_line()
error "Not implemented"
-- gsub("\r?\n[ \t]([^\r\n])", "%1");
end
local function vCard_esc(s)
return s:gsub("[,:;\\]", "\\%1"):gsub("\n","\\n");
end
local function vCard_unesc(s)
return s:gsub("\\?[\\nt:;,]", {
["\\\\"] = "\\",
["\\n"] = "\n",
["\\r"] = "\r",
["\\t"] = "\t",
["\\:"] = ":", -- FIXME Shouldn't need to espace : in values, just params
["\\;"] = ";",
["\\,"] = ",",
[":"] = "\29",
[";"] = "\30",
[","] = "\31",
});
end
local function item_to_xep54(item)
local t = st.stanza(item.name, { xmlns = "vcard-temp" });
local prop_def = vCard_dtd[item.name];
if prop_def == "text" then
t:text(item[1]);
elseif type(prop_def) == "table" then
if prop_def.types and item.TYPE then
if type(item.TYPE) == "table" then
for _,v in pairs(prop_def.types) do
for _,typ in pairs(item.TYPE) do
if typ:upper() == v then
t:tag(v):up();
break;
end
end
end
else
t:tag(item.TYPE:upper()):up();
end
end
if prop_def.props then
for _,v in pairs(prop_def.props) do
if item[v] then
t:tag(v):up();
end
end
end
if prop_def.value then
t:tag(prop_def.value):text(item[1]):up();
elseif prop_def.values then
local prop_def_values = prop_def.values;
local repeat_last = prop_def_values.behaviour == "repeat-last" and prop_def_values[#prop_def_values];
for i=1,#item do
t:tag(prop_def.values[i] or repeat_last):text(item[i]):up();
end
end
end
return t;
end
local function vcard_to_xep54(vCard)
local t = st.stanza("vCard", { xmlns = "vcard-temp" });
for i=1,#vCard do
t:add_child(item_to_xep54(vCard[i]));
end
return t;
end
function to_xep54(vCards)
if not vCards[1] or vCards[1].name then
return vcard_to_xep54(vCards)
else
local t = st.stanza("xCard", { xmlns = "vcard-temp" });
for i=1,#vCards do
t:add_child(vcard_to_xep54(vCards[i]));
end
return t;
end
end
function from_text(data)
data = data -- unfold and remove empty lines
:gsub("\r\n","\n")
:gsub("\n ", "")
:gsub("\n\n+","\n");
local vCards = {};
local c; -- current item
for line in data:gmatch("[^\n]+") do
local line = vCard_unesc(line);
local name, params, value = line:match("^([-%a]+)(\30?[^\29]*)\29(.*)$");
value = value:gsub("\29",":");
if #params > 0 then
local _params = {};
for k,isval,v in params:gmatch("\30([^=]+)(=?)([^\30]*)") do
k = k:upper();
local _vt = {};
for _p in v:gmatch("[^\31]+") do
_vt[#_vt+1]=_p
_vt[_p]=true;
end
if isval == "=" then
_params[k]=_vt;
else
_params[k]=true;
end
end
params = _params;
end
if name == "BEGIN" and value == "VCARD" then
c = {};
vCards[#vCards+1] = c;
elseif name == "END" and value == "VCARD" then
c = nil;
elseif vCard_dtd[name] then
local dtd = vCard_dtd[name];
local p = { name = name };
c[#c+1]=p;
--c[name]=p;
local up = c;
c = p;
if dtd.types then
for _, t in ipairs(dtd.types) do
local t = t:lower();
if ( params.TYPE and params.TYPE[t] == true)
or params[t] == true then
c.TYPE=t;
end
end
end
if dtd.props then
for _, p in ipairs(dtd.props) do
if params[p] then
if params[p] == true then
c[p]=true;
else
for _, prop in ipairs(params[p]) do
c[p]=prop;
end
end
end
end
end
if dtd == "text" or dtd.value then
t_insert(c, value);
elseif dtd.values then
local value = "\30"..value;
for p in value:gmatch("\30([^\30]*)") do
t_insert(c, p);
end
end
c = up;
end
end
return vCards;
end
local function item_to_text(item)
local value = {};
for i=1,#item do
value[i] = vCard_esc(item[i]);
end
value = t_concat(value, ";");
local params = "";
for k,v in pairs(item) do
if type(k) == "string" and k ~= "name" then
params = params .. (";%s=%s"):format(k, type(v) == "table" and t_concat(v,",") or v);
end
end
return ("%s%s:%s"):format(item.name, params, value)
end
local function vcard_to_text(vcard)
local t={};
t_insert(t, "BEGIN:VCARD")
for i=1,#vcard do
t_insert(t, item_to_text(vcard[i]));
end
t_insert(t, "END:VCARD")
return t_concat(t, line_sep);
end
function to_text(vCards)
if vCards[1] and vCards[1].name then
return vcard_to_text(vCards)
else
local t = {};
for i=1,#vCards do
t[i]=vcard_to_text(vCards[i]);
end
return t_concat(t, line_sep);
end
end
local function from_xep54_item(item)
local prop_name = item.name;
local prop_def = vCard_dtd[prop_name];
local prop = { name = prop_name };
if prop_def == "text" then
prop[1] = item:get_text();
elseif type(prop_def) == "table" then
if prop_def.value then --single item
prop[1] = item:get_child_text(prop_def.value) or "";
elseif prop_def.values then --array
local value_names = prop_def.values;
if value_names.behaviour == "repeat-last" then
for i=1,#item.tags do
t_insert(prop, item.tags[i]:get_text() or "");
end
else
for i=1,#value_names do
t_insert(prop, item:get_child_text(value_names[i]) or "");
end
end
elseif prop_def.names then
local names = prop_def.names;
for i=1,#names do
if item:get_child(names[i]) then
prop[1] = names[i];
break;
end
end
end
if prop_def.props_verbatim then
for k,v in pairs(prop_def.props_verbatim) do
prop[k] = v;
end
end
if prop_def.types then
local types = prop_def.types;
prop.TYPE = {};
for i=1,#types do
if item:get_child(types[i]) then
t_insert(prop.TYPE, types[i]:lower());
end
end
if #prop.TYPE == 0 then
prop.TYPE = nil;
end
end
-- A key-value pair, within a key-value pair?
if prop_def.props then
local params = prop_def.props;
for i=1,#params do
local name = params[i]
local data = item:get_child_text(name);
if data then
prop[name] = prop[name] or {};
t_insert(prop[name], data);
end
end
end
else
return nil
end
return prop;
end
local function from_xep54_vCard(vCard)
local tags = vCard.tags;
local t = {};
for i=1,#tags do
t_insert(t, from_xep54_item(tags[i]));
end
return t
end
function from_xep54(vCard)
if vCard.attr.xmlns ~= "vcard-temp" then
return nil, "wrong-xmlns";
end
if vCard.name == "xCard" then -- A collection of vCards
local t = {};
local vCards = vCard.tags;
for i=1,#vCards do
t[i] = from_xep54_vCard(vCards[i]);
end
return t
elseif vCard.name == "vCard" then -- A single vCard
return from_xep54_vCard(vCard)
end
end
-- This was adapted from http://xmpp.org/extensions/xep-0054.html#dtd
vCard_dtd = {
VERSION = "text", --MUST be 3.0, so parsing is redundant
FN = "text",
N = {
values = {
"FAMILY",
"GIVEN",
"MIDDLE",
"PREFIX",
"SUFFIX",
},
},
NICKNAME = "text",
PHOTO = {
props_verbatim = { ENCODING = { "b" } },
props = { "TYPE" },
value = "BINVAL", --{ "EXTVAL", },
},
BDAY = "text",
ADR = {
types = {
"HOME",
"WORK",
"POSTAL",
"PARCEL",
"DOM",
"INTL",
"PREF",
},
values = {
"POBOX",
"EXTADD",
"STREET",
"LOCALITY",
"REGION",
"PCODE",
"CTRY",
}
},
LABEL = {
types = {
"HOME",
"WORK",
"POSTAL",
"PARCEL",
"DOM",
"INTL",
"PREF",
},
value = "LINE",
},
TEL = {
types = {
"HOME",
"WORK",
"VOICE",
"FAX",
"PAGER",
"MSG",
"CELL",
"VIDEO",
"BBS",
"MODEM",
"ISDN",
"PCS",
"PREF",
},
value = "NUMBER",
},
EMAIL = {
types = {
"HOME",
"WORK",
"INTERNET",
"PREF",
"X400",
},
value = "USERID",
},
JABBERID = "text",
MAILER = "text",
TZ = "text",
GEO = {
values = {
"LAT",
"LON",
},
},
TITLE = "text",
ROLE = "text",
LOGO = "copy of PHOTO",
AGENT = "text",
ORG = {
values = {
behaviour = "repeat-last",
"ORGNAME",
"ORGUNIT",
}
},
CATEGORIES = {
values = "KEYWORD",
},
NOTE = "text",
PRODID = "text",
REV = "text",
SORTSTRING = "text",
SOUND = "copy of PHOTO",
UID = "text",
URL = "text",
CLASS = {
names = { -- The item.name is the value if it's one of these.
"PUBLIC",
"PRIVATE",
"CONFIDENTIAL",
},
},
KEY = {
props = { "TYPE" },
value = "CRED",
},
DESC = "text",
};
vCard_dtd.LOGO = vCard_dtd.PHOTO;
vCard_dtd.SOUND = vCard_dtd.PHOTO;
return {
from_text = from_text;
to_text = to_text;
from_xep54 = from_xep54;
to_xep54 = to_xep54;
-- COMPAT:
lua_to_text = to_text;
lua_to_xep54 = to_xep54;
text_to_lua = from_text;
text_to_xep54 = function (...) return to_xep54(from_text(...)); end;
xep54_to_lua = from_xep54;
xep54_to_text = function (...) return to_text(from_xep54(...)) end;
};
| mit |
madpilot78/ntopng | scripts/lua/modules/alert_definitions/flow/alert_flow_blocked.lua | 1 | 1482 | --
-- (C) 2019-21 - ntop.org
--
-- ##############################################
local flow_alert_keys = require "flow_alert_keys"
-- Import the classes library.
local classes = require "classes"
-- Make sure to import the Superclass!
local alert = require "alert"
-- ##############################################
local alert_flow_blocked = classes.class(alert)
-- ##############################################
alert_flow_blocked.meta = {
alert_key = flow_alert_keys.flow_alert_flow_blocked,
i18n_title = "flow_details.flow_blocked_by_bridge",
icon = "fas fa-fw fa-exclamation",
}
-- ##############################################
-- @brief Prepare an alert table used to generate the alert
-- @return A table with the alert built
function alert_flow_blocked:init()
-- Call the parent constructor
self.super:init()
end
-- #######################################################
-- @brief Format an alert into a human-readable string
-- @param ifid The integer interface id of the generated alert
-- @param alert The alert description table, including alert data such as the generating entity, timestamp, granularity, type
-- @param alert_type_params Table `alert_type_params` as built in the `:init` method
-- @return A human-readable string
function alert_flow_blocked.format(ifid, alert, alert_type_params)
return i18n("flow_details.flow_blocked_by_bridge")
end
-- #######################################################
return alert_flow_blocked
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Northern_San_dOria/npcs/Taulenne.lua | 1 | 4866 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Taulenne
-- Armor Storage NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
package.loaded["scripts/globals/armorstorage"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/armorstorage");
require("scripts/zones/Northern_San_dOria/TextIDs");
Deposit = 0x0304;
Withdrawl = 0x0305;
ArraySize = table.getn(StorageArray);
G1 = 0;
G2 = 0;
G3 = 0;
G4 = 0;
G5 = 0;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(MagicmartFlyer,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end;
end;
for SetId = 1,ArraySize,11 do
TradeCount = trade:getItemCount();
T1 = trade:hasItemQty(StorageArray[SetId + 5],1);
if (T1 == true) then
if (player:hasKeyItem(StorageArray[SetId + 10]) == false) then
if (TradeCount == StorageArray[SetId + 3]) then
T2 = trade:hasItemQty(StorageArray[SetId + 4],1);
T3 = trade:hasItemQty(StorageArray[SetId + 6],1);
T4 = trade:hasItemQty(StorageArray[SetId + 7],1);
T5 = trade:hasItemQty(StorageArray[SetId + 8],1);
if (StorageArray[SetId + 4] == 0) then
T2 = true;
end;
if (StorageArray[SetId + 6] == 0) then
T3 = true;
end;
if (StorageArray[SetId + 7] == 0) then
T4 = true;
end;
if (StorageArray[SetId + 8] == 0) then
T5 = true;
end;
if (T2 == true and T3 == true and T4 == true and T5 == true) then
player:startEvent(Deposit,0,0,0,0,0,StorageArray[SetId + 9]);
player:addKeyItem(StorageArray[SetId + 10]);
player:messageSpecial(KEYITEM_OBTAINED,StorageArray[SetId + 10]);
break;
end;
end;
end;
end;
end;
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
CurrGil = player:getGil();
for KeyItem = 11,ArraySize,11 do
if player:hasKeyItem(StorageArray[KeyItem]) then
if StorageArray[KeyItem - 9] == 1 then
G1 = G1 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 2 then
G2 = G2 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 3 then
G3 = G3 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 4 then
G4 = G4 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 6 then
G5 = G5 + StorageArray[KeyItem - 8];
end;
end;
end;
player:startEvent(Withdrawl,G1,G2,G3,G4,CurrGil,G5);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
if (csid == Withdrawl) then
player:updateEvent(StorageArray[option * 11 - 6],
StorageArray[option * 11 - 5],
StorageArray[option * 11 - 4],
StorageArray[option * 11 - 3],
StorageArray[option * 11 - 2],
StorageArray[option * 11 - 1]);
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == Withdrawl) then
if (option > 0 and option <= StorageArray[ArraySize] - 10) then
if (player:getFreeSlotsCount() >= StorageArray[option * 11 - 7]) then
for Item = 2,6,1 do
if (StorageArray[option * 11 - Item] > 0) then
player:addItem(StorageArray[option * 11 - Item],1);
player:messageSpecial(ITEM_OBTAINED,StorageArray[option * 11 - Item]);
end;
end;
player:delKeyItem(StorageArray[option * 11]);
player:setGil(player:getGil() - StorageArray[option * 11 - 1]);
else
for Item = 2,6,1 do
if (StorageArray[option * 11 - Item] > 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,StorageArray[option * 11 - Item]);
end;
end;
end;
end;
end;
if (csid == Deposit) then
player:tradeComplete();
end;
end; | gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Bastok_Mines/npcs/Gelzerio.lua | 1 | 1584 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Galzerio
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,GELZERIO_SHOP_DIALOG);
stock = {0x338E,19602,1, --Swordbelt
0x43ED,486,1, --Bamboo Fishing Rod
0x43F4,3,2, --Little Worm
0x43EE,212,2, --Yew Fishing Rod
0x338C,10054,3, --Silver Belt
0x43F3,10,3, --Lugworm
0x43EF,64,3, --Willow Fishing Rod
0x3138,216,3, --Robe
0x31B8,118,3, --Cuffs
0x3238,172,3, --Slops
0x32B8,111,3, --Ash Clogs
0x30B0,1742,3, --Headgear
0x3130,2470,3, --Doublet
0x31B0,1363,3, --Gloves
0x3230,1899,3, --Brais
0x32B0,1269,3} --Gaiters
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 |
RyMarq/Zero-K | effects/beamer.lua | 25 | 2991 | -- beamerray
return {
["beamerray"] = {
usedefaultexplosions = false,
groundflash = {
circlealpha = 0,
circlegrowth = 1,
flashalpha = 1.0,
flashsize = 26,
ttl = 24,
color = {
[1] = 0,
[2] = 0,
[3] = 1,
},
},
meltage = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
water = true,
properties = {
delay = 0,
explosiongenerator = [[custom:LASERS_MELT1]],
pos = [[0, 0, 0]],
},
},
pikes = {
air = true,
class = [[explspike]],
count = 5,
ground = true,
water = true,
properties = {
alpha = 1,
alphadecay = 0.06,
color = [[0.2,0.2,1]],
dir = [[-2 r4,-2 r4,-2 r4]],
length = 11,
width = 7,
},
},
sparks_yellow = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.97,
colormap = [[1 1 0 0.01 1 0.7 0.5 0.01 0 0 0 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 80,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.4, 0]],
numparticles = 5,
particlelife = 15,
particlelifespread = 0,
particlesize = 1,
particlesizespread = 2.5,
particlespeed = 3,
particlespeedspread = 2,
pos = [[0, 0, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[plasma]],
},
},
sparks_blue = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.97,
colormap = [[0.2 0.2 1.0 0.01 0.1 0.1 0.8 0.01 0 0 0 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 80,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.1, 0]],
numparticles = 5,
particlelife = 10,
particlelifespread = 3,
particlesize = 8,
particlesizespread = 2.5,
particlespeed = 4,
particlespeedspread = 2,
pos = [[0, 0, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[plasma]],
},
},
},
}
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Yhoator_Jungle/npcs/Paurelde.lua | 1 | 1224 | -----------------------------------
-- Area: Yhoator Jungle
-- NPC: Paurelde
-- Chocobo Vendor
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
price = 100;
gil = player:getGil();
hasLicense = player:hasKeyItem(CHOCOBO_LICENSE);
level = player:getMainLvl();
if (hasLicense and level >= 15) then
player:startEvent(0x000c,price,gil);
else
player:startEvent(0x000d,price,gil);
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--print("CSID:",csid);
--print("OPTION:",option);
price = 100;
level = player:getMainLvl();
if (csid == 0x000c and option == 0) then
if (level >= 20) then
player:addStatusEffect(EFFECT_CHOCOBO,1,0,1800);
else
player:addStatusEffect(EFFECT_CHOCOBO,1,0,900);
end
player:delGil(price);
end
end; | gpl-3.0 |
TerminalShell/zombiesurvival | entities/weapons/weapon_zs_crow/init.lua | 1 | 1840 | AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
function SWEP:Deploy()
self.Owner.SkipCrow = true
return true
end
function SWEP:Holster()
local owner = self.Owner
if owner:IsValid() then
owner:StopSound("NPC_Crow.Flap")
end
end
SWEP.OnRemove = SWEP.Holster
function SWEP:Think()
local owner = self.Owner
if owner:IsOnGround() or not owner:KeyDown(IN_JUMP) or not owner:KeyDown(IN_FORWARD) then
if self.PlayFlap then
owner:StopSound("NPC_Crow.Flap")
self.PlayFlap = nil
end
else
if not self.PlayFlap then
owner:EmitSound("NPC_Crow.Flap")
self.PlayFlap = true
end
end
local peckend = self:GetPeckEndTime()
if peckend == 0 or CurTime() < peckend then return end
self:SetPeckEndTime(0)
local trace = owner:TraceLine(14, MASK_SOLID)
local ent = NULL
if trace.Entity then
ent = trace.Entity
end
owner:ResetSpeed()
if ent:IsValid() then
local phys = ent:GetPhysicsObject()
if ent:IsPlayer() and (ent:Team() ~= owner:Team() or ent:GetZombieClassTable().Name ~= "Crow") then
return
end
ent:TakeSpecialDamage(2, DMG_SLASH, owner, self)
end
end
function SWEP:PrimaryAttack()
if CurTime() < self:GetNextPrimaryFire() or not self.Owner:IsOnGround() then return end
self:SetNextPrimaryFire(CurTime() + self.Primary.Delay)
if self.Owner:Team() ~= TEAM_UNDEAD then self.Owner:Kill() return end
self.Owner:EmitSound("NPC_Crow.Squawk")
self.Owner.EatAnim = CurTime() + 2
self:SetPeckEndTime(CurTime() + 1)
self.Owner:SetSpeed(1)
end
function SWEP:SecondaryAttack()
if CurTime() < self:GetNextSecondaryFire() then return end
self:SetNextSecondaryFire(CurTime() + 1.6)
if self.Owner:Team() ~= TEAM_UNDEAD then self.Owner:Kill() return end
self.Owner:EmitSound("NPC_Crow.Alert")
end
function SWEP:Reload()
self:SecondaryAttack()
return false
end
| gpl-3.0 |
madpilot78/ntopng | scripts/lua/modules/pools/flow_pools.lua | 1 | 2225 | --
-- (C) 2017-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/pools/?.lua;" .. package.path
if ntop.isPro() then
package.path = dirs.installdir .. "/pro/scripts/lua/modules/?.lua;" .. package.path
end
local pools = require "pools"
local flow_pools = {}
-- ##############################################
function flow_pools:create()
-- Instance of the base class
local _flow_pools = pools:create()
-- Subclass using the base class instance
self.key = "flow"
-- self is passed as argument so it will be set as base class metatable
-- and this will actually make it possible to override functions
local _flow_pools_instance = _flow_pools:create(self)
-- Return the instance
return _flow_pools_instance
end
-- ##############################################
-- @brief Given a member key, returns a table of member details such as member name.
-- POOL WITH NO MEMBERS
function flow_pools:get_member_details(member) return {} end
-- ##############################################
-- @brief Returns a table of all possible ids, both assigned and unassigned to pool members
-- POOL WITH NO MEMBERS
function flow_pools:get_all_members() return {} end
-- ##############################################
--@brief Tells the C++ core about the flow recipients
function flow_pools:set_flow_recipients(recipients)
-- Create a bitmap of all recipients responsible for flows (pool_id in this case is ignored)
local recipients_bitmap = 0
for _, recipient_id in ipairs(recipients) do
recipients_bitmap = recipients_bitmap | (1 << recipient_id)
end
-- Tell the C++ that flow recipients have changed
ntop.recipient_set_flow_recipients(recipients_bitmap)
end
-- ##############################################
--@brief Method called after a successful execution of method persist
function flow_pools:_post_persist(pool_id, name, members, recipients)
self:set_flow_recipients(recipients)
end
-- ##############################################
function flow_pools:default_only()
-- This is a dummy, default-only pool
return true
end
-- ##############################################
return flow_pools
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.