repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
SalvationDevelopment/Salvation-Scripts-TCG
c87294988.lua
5
1684
--紅姫チルビメ function c87294988.initial_effect(c) --cannot be battle target local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_SELECT_BATTLE_TARGET) e1:SetRange(LOCATION_MZONE) e1:SetTargetRange(0,LOCATION_MZONE) e1:SetValue(c87294988.bttg) c:RegisterEffect(e1) --summon success local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(87294988,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e2:SetCode(EVENT_TO_GRAVE) e2:SetCondition(c87294988.spcon) e2:SetTarget(c87294988.sptg) e2:SetOperation(c87294988.spop) c:RegisterEffect(e2) end function c87294988.bttg(e,c) return c~=e:GetHandler() and c:IsFaceup() and c:IsRace(RACE_PLANT) end function c87294988.spcon(e,tp,eg,ep,ev,re,r,rp) return rp~=tp and e:GetHandler():GetPreviousControler()==tp end function c87294988.filter(c,e,tp) return c:IsRace(RACE_PLANT) and not c:IsCode(87294988) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c87294988.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c87294988.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function c87294988.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c87294988.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
Turttle/darkstar
scripts/zones/Quicksand_Caves/npcs/qm2.lua
17
1245
----------------------------------- -- Area: Quicksand Caves -- NPC: qm2 -- Notes: Used to spawn Tribunus VII-I -- @pos -49.944 -0.891 -139.485 208 ----------------------------------- package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Quicksand_Caves/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Trade Antican Tag if (GetMobAction(17629643) == 0 and trade:hasItemQty(1190,1) and trade:getItemCount() == 1) then player:tradeComplete(); SpawnMob(17629643,900):updateClaim(player); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
fgenesis/Aquaria_experimental
game_scripts/scripts/entities/clockworkfish.lua
6
2827
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end -- ================================================================================================ -- M A U L -- ================================================================================================ -- entity specific local STATE_FIRE = 1000 local STATE_PULLBACK = 1001 v.fireDelay = 0 v.dir = 0 -- ================================================================================================ -- FUNCTIONS -- ================================================================================================ function init(me) setupBasicEntity( me, "", -- texture 6, -- health 1, -- manaballamount 1, -- exp 1, -- money 32, -- collideRadius STATE_IDLE, -- initState 128, -- sprite width 64, -- sprite height 1, -- particle "explosion" type, maps to particleEffects.txt -1 = none 0, -- 0/1 hit other entities off/on (uses collideRadius) -1 -- updateCull -1: disabled, default: 4000 ) entity_setDropChance(me, 50) entity_setMaxSpeedLerp(me, 0.5) entity_setMaxSpeedLerp(me, 1, 1, -1, 1) entity_initSkeletal(me, "ClockworkFish") entity_animate(me, "idle", -1) entity_setDeathParticleEffect(me, "TinyRedExplode") entity_scale(me, 0.75, 0.75) entity_setDamageTarget(me, DT_AVATAR_BITE, false) end function update(me, dt) entity_handleShotCollisions(me) entity_touchAvatarDamage(me, 32, 1, 1200) if v.dir==0 then entity_addVel(me, -1000, 0) else entity_addVel(me, 1000, 0) end entity_updateMovement(me, dt) end function enterState(me) if entity_isState(me, STATE_DEAD) then entity_sound(me, "MetalExplode", math.random(200)+1000) spawnParticleEffect("ClockworkFishDie", entity_getPosition(me)) end end function exitState(me) end function hitSurface(me) entity_flipHorizontal(me) if v.dir == 0 then v.dir = 1 elseif v.dir == 1 then v.dir = 0 end end function activate(me) end
gpl-2.0
Hajimokhradi/zli
plugins/expiretime.lua
20
2026
local function pre_process(msg) msg.text = msg.content_.text local timetoexpire = 'unknown' local expiretime = redis:hget ('expiretime', msg.chat_id_) local now = tonumber(os.time()) if expiretime then timetoexpire = math.floor((tonumber(expiretime) - tonumber(now)) / 86400) + 1 if tonumber("0") > tonumber(timetoexpire) and not is_sudo(msg) then if msg.text:match('/') then return tdcli.sendMessage(msg.chat_id_, 0, 1, '*ExpireTime Ended.*', 1, 'md') else return end end if tonumber(timetoexpire) == 0 then if redis:hget('expires0',msg.chat_id_) then end tdcli.sendMessage(msg.chat_id_, 0, 1, '*⚠️مدت استفاده ربات شما تمام شده است لطفا آن را تمدید کنید*.', 1, 'md') redis:hset('expires0',msg.chat_id_,'5') end if tonumber(timetoexpire) == 1 then if redis:hget('expires1',msg.chat_id_) then end tdcli.sendMessage(msg.chat_id_, 0, 1, '*⚠️ ⚠️ فقط 1⃣ روز تا پایان مدت استفاده از ربات باقی مانده است لطفا آن را تمدید کنید.*.', 1, 'md') redis:hset('expires1',msg.chat_id_,'5') end end end function run(msg, matches) if matches[1]:lower() == 'setexpire' then if not is_sudo(msg) then return end local time = os.time() local buytime = tonumber(os.time()) local timeexpire = tonumber(buytime) + (tonumber(matches[2]) * 86400) redis:hset('expiretime',msg.chat_id_,timeexpire) return "*انقضای ربات تنظیم شد به * _"..matches[2].. "_ *روز* " end if matches[1]:lower() == 'expire' then local expiretime = redis:hget ('expiretime', msg.chat_id_) if not expiretime then return '*Unlimited*' else local now = tonumber(os.time()) return (math.floor((tonumber(expiretime) - tonumber(now)) / 86400) + 1) .. " *روز باقی مانده⏱*" end end end return { patterns = { "^[!#/]([Ss]etexpire) (.*)$", "^[!#/]([Ee]xpire)$", }, run = run, pre_process = pre_process } -- http://permag.ir -- @permag_ir -- @permag_bots
gpl-3.0
Cloudef/mpv
player/lua/ytdl_hook.lua
1
8376
local utils = require 'mp.utils' local msg = require 'mp.msg' local ytdl = { path = "youtube-dl", minver = "2015.02.23.1", vercheck = nil, } local function exec(args) local ret = utils.subprocess({args = args}) return ret.status, ret.stdout end -- return if it was explicitly set on the command line local function option_was_set(name) return mp.get_property_bool("option-info/" .. name .. "/set-from-commandline", false) end -- youtube-dl may set special http headers for some sites (user-agent, cookies) local function set_http_headers(http_headers) if not http_headers then return end local headers = {} local useragent = http_headers["User-Agent"] if useragent and not option_was_set("user-agent") then mp.set_property("file-local-options/user-agent", useragent) end local cookies = http_headers["Cookie"] if cookies then headers[#headers + 1] = "Cookie: " .. cookies end if #headers > 0 and not option_was_set("http-header-fields") then mp.set_property_native("file-local-options/http-header-fields", headers) end end mp.add_hook("on_load", 10, function () local url = mp.get_property("stream-open-filename") if (url:find("http://") == 1) or (url:find("https://") == 1) or (url:find("ytdl://") == 1) then -- check version of youtube-dl if not done yet if (ytdl.vercheck == nil) then -- check for youtube-dl in mpv's config dir local ytdl_mcd = mp.find_config_file("youtube-dl") if not (ytdl_mcd == nil) then msg.verbose("found youtube-dl at: " .. ytdl_mcd) ytdl.path = ytdl_mcd end msg.debug("checking ytdl version ...") local es, version = exec({ytdl.path, "--version"}) if (es < 0) then msg.warn("youtube-dl not found, not executable, or broken.") ytdl.vercheck = false elseif (version < ytdl.minver) then msg.verbose("found youtube-dl version: " .. version) msg.warn("Your version of youtube-dl is too old! " .. "You need at least version '"..ytdl.minver .. "', try running `youtube-dl -U`.") ytdl.vercheck = false else msg.verbose("found youtube-dl version: " .. version) ytdl.vercheck = true end end if not (ytdl.vercheck) then return end -- strip ytdl:// if (url:find("ytdl://") == 1) then url = url:sub(8) end local format = mp.get_property("options/ytdl-format") local raw_options = mp.get_property_native("options/ytdl-raw-options") -- subformat workaround local subformat = "ass/srt/best" local command = { ytdl.path, "--no-warnings", "-J", "--flat-playlist", "--all-subs", "--sub-format", subformat, "--no-playlist" } if (format ~= "") then table.insert(command, "--format") table.insert(command, format) end for param, arg in pairs(raw_options) do table.insert(command, "--" .. param) if (arg ~= "") then table.insert(command, arg) end end table.insert(command, "--") table.insert(command, url) local es, json = exec(command) if (es < 0) or (json == nil) or (json == "") then msg.warn("youtube-dl failed, trying to play URL directly ...") return end local json, err = utils.parse_json(json) if (json == nil) then msg.error("failed to parse JSON data: " .. err) return end msg.verbose("youtube-dl succeeded!") -- what did we get? if not (json["direct"] == nil) and (json["direct"] == true) then -- direct URL, nothing to do msg.verbose("Got direct URL") return elseif not (json["_type"] == nil) and (json["_type"] == "playlist") then -- a playlist if (#json.entries == 0) then msg.warn("Got empty playlist, nothing to play.") return end -- some funky guessing to detect multi-arc videos if not (json.entries[1]["webpage_url"] == nil) and (json.entries[1]["webpage_url"] == json["webpage_url"]) then msg.verbose("multi-arc video detected, building EDL") local playlist = "edl://" for i, entry in pairs(json.entries) do playlist = playlist .. entry.url .. ";" end msg.debug("EDL: " .. playlist) -- can't change the http headers for each entry, so use the 1st if json.entries[1] then set_http_headers(json.entries[1].http_headers) end mp.set_property("stream-open-filename", playlist) if not (json.title == nil) then mp.set_property("file-local-options/media-title", json.title) end else local playlist = "#EXTM3U\n" for i, entry in pairs(json.entries) do local site = entry.url -- some extractors will still return the full info for -- all clips in the playlist and the URL will point -- directly to the file in that case, which we don't -- want so get the webpage URL instead, which is what -- we want if not (entry["webpage_url"] == nil) then site = entry["webpage_url"] end playlist = playlist .. "ytdl://" .. site .. "\n" end mp.set_property("stream-open-filename", "memory://" .. playlist) end else -- probably a video local streamurl = "" -- DASH? if not (json["requested_formats"] == nil) then msg.info("Using DASH, expect inaccurate duration.") if not (json.duration == nil) then msg.info("Actual duration: " .. mp.format_time(json.duration)) end -- video url streamurl = json["requested_formats"][1].url -- audio url mp.set_property("file-local-options/audio-file", json["requested_formats"][2].url) -- workaround for slow startup (causes inaccurate duration) mp.set_property("file-local-options/demuxer-lavf-o", "fflags=+ignidx") elseif not (json.url == nil) then -- normal video streamurl = json.url set_http_headers(json.http_headers) else msg.error("No URL found in JSON data.") return end msg.debug("streamurl: " .. streamurl) mp.set_property("stream-open-filename", streamurl) mp.set_property("file-local-options/media-title", json.title) -- add subtitles if not (json.requested_subtitles == nil) then for lang, sub_info in pairs(json.requested_subtitles) do msg.verbose("adding subtitle ["..lang.."]") local slang = lang if (lang:len() > 3) then slang = lang:sub(1,2) end if not (sub_info.data == nil) then sub = "memory://"..sub_info.data else sub = sub_info.url end mp.commandv("sub_add", sub, "auto", lang.." "..sub_info.ext, slang) end end -- for rtmp if not (json.play_path == nil) then mp.set_property("file-local-options/stream-lavf-o", "rtmp_tcurl=\""..streamurl.. "\",rtmp_playpath=\""..json.play_path.."\"") end end end end)
gpl-2.0
dickeyf/darkstar
scripts/zones/Lower_Delkfutts_Tower/npcs/Cermet_Door.lua
27
1148
----------------------------------- -- Area: Lower Delkfutt's Tower -- NPC: Cermet Door -- Notes: Leads to Upper Delkfutt's Tower. -- @pos 524 16 20 184 ----------------------------------- require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0014); -- missing walk-through animation, but it's the best I could find. return 1; end; ----------------------------------- -- onEventUpdate Action ----------------------------------- function onEventUpdate(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); if (csid == 0x0014 and option == 1) then player:setPos(313, 16, 20, 128, 0x9E); -- to Upper Delkfutt's Tower end end;
gpl-3.0
Turttle/darkstar
scripts/zones/Mhaura/npcs/Orlando.lua
15
3535
----------------------------------- -- Area: Mhaura -- NPC: Orlando -- Type: Standard NPC -- @pos -37.268 -9 58.047 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mhaura/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local QuestStatus = player:getQuestStatus(OTHER_AREAS, ORLANDO_S_ANTIQUES); local itemID = trade:getItem(); local itemList = { {564, 200}, -- Fingernail Sack {565, 250}, -- Teeth Sack {566, 200}, -- Goblin Cup {568, 120}, -- Goblin Die {656, 600}, -- Beastcoin {748, 900}, -- Gold Beastcoin {749, 800}, -- Mythril Beastcoin {750, 750}, -- Silver Beastcoin {898, 120}, -- Chicken Bone {900, 100}, -- Fish Bone {16995, 150}, -- Rotten Meat }; for x, item in pairs(itemList) do if (QuestStatus == QUEST_ACCEPTED) or (player:getLocalVar("OrlandoRepeat") == 1) then if (item[1] == itemID) then if (trade:hasItemQty(itemID, 8) and trade:getItemCount() == 8) then -- Correct amount, valid item. player:setVar("ANTIQUE_PAYOUT", (GIL_RATE*item[2])); player:startEvent(0x0066, GIL_RATE*item[2], itemID); elseif (trade:getItemCount() < 8) then -- Wrong amount, but valid item. player:startEvent(0x0068); end end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local QuestStatus = player:getQuestStatus(OTHER_AREAS, ORLANDO_S_ANTIQUES); if (player:getFameLevel(WINDURST) >= 2) then if (player:hasKeyItem(CHOCOBO_LICENSE)) then if (QuestStatus ~= QUEST_AVAILABLE) then player:startEvent(0x0067); elseif (QuestStatus == QUEST_AVAILABLE) then player:startEvent(0x0065); end else player:startEvent(0x0064); end else player:startEvent(0x006A); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local QuestStatus = player:getQuestStatus(OTHER_AREAS, ORLANDO_S_ANTIQUES); local payout = player:getVar("ANTIQUE_PAYOUT"); if (csid == 0x0065) then player:addQuest(OTHER_AREAS, ORLANDO_S_ANTIQUES); elseif (csid == 0x0066) then player:tradeComplete(); player:addFame(WINDURST,WIN_FAME*10); player:addGil(payout); player:messageSpecial(GIL_OBTAINED,payout); player:completeQuest(OTHER_AREAS, ORLANDO_S_ANTIQUES); player:setVar("ANTIQUE_PAYOUT", 0); player:setLocalVar("OrlandoRepeat", 0); elseif (csid == 0x0067) then if (QuestStatus == QUEST_COMPLETED) then player:setLocalVar("OrlandoRepeat", 1); end end end;
gpl-3.0
dickeyf/darkstar
scripts/zones/Misareaux_Coast/npcs/qm1.lua
13
1339
----------------------------------- -- Area: Misareaux_Coast -- NPC: ??? (Spawn Gration) -- @pos 113.563 -16.302 38.912 25 ----------------------------------- package.loaded["scripts/zones/Misareaux_Coast/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Misareaux_Coast/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Trade Hickory Shield OR Picaroon's Shield if (GetMobAction(16879899) == 0 and (trade:hasItemQty(12370,1) or trade:hasItemQty(12359,1)) and trade:getItemCount() == 1) then player:tradeComplete(); SpawnMob(16879899,900):updateClaim(player); npc:setStatus(STATUS_DISAPPEAR); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Turttle/darkstar
scripts/zones/Horlais_Peak/bcnms/shattering_stars.lua
19
2368
----------------------------------- -- Area: Horlais Peak -- Name: Shattering stars - Maat Fight -- @pos -509 158 -211 139 ----------------------------------- package.loaded["scripts/zones/Horlais_Peak/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/zones/Horlais_Peak/TextIDs"); ----------------------------------- -- Maat Battle in Horlais Peak -- EXAMPLE SCRIPT -- -- What should go here: -- giving key items, playing ENDING cutscenes -- -- What should NOT go here: -- Handling of "battlefield" status, spawning of monsters, -- putting loot into treasure pool, -- enforcing ANY rules (SJ/number of people/etc), moving -- chars around, playing entrance CSes (entrance CSes go in bcnm.lua) -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) -- player:messageSpecial(107); end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then if (player:getQuestStatus(JEUNO,SHATTERING_STARS) == QUEST_ACCEPTED and player:getFreeSlotsCount() > 0) then player:addItem(4181); player:messageSpecial(ITEM_OBTAINED,4181); end local pjob = player:getMainJob(); player:setVar("maatDefeated",pjob); local maatsCap = player:getVar("maatsCap") if (bit.band(maatsCap, bit.lshift(1, (pjob -1))) ~= 1) then player:setVar("maatsCap",bit.bor(maatsCap, bit.lshift(1, (pjob -1)))) end player:addTitle(MAAT_MASHER); end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c31887905.lua
6
1452
--憑依装着-アウス function c31887905.initial_effect(c) --spsummon proc local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetProperty(EFFECT_FLAG_UNCOPYABLE) e1:SetRange(LOCATION_HAND+LOCATION_DECK) e1:SetCondition(c31887905.spcon) e1:SetOperation(c31887905.spop) c:RegisterEffect(e1) end function c31887905.spfilter1(c,tp) return c:IsFaceup() and c:IsCode(37970940) and c:IsAbleToGraveAsCost() and Duel.IsExistingMatchingCard(c31887905.spfilter2,tp,LOCATION_MZONE,0,1,c) end function c31887905.spfilter2(c) return c:IsFaceup() and c:IsAttribute(ATTRIBUTE_EARTH) and c:IsAbleToGraveAsCost() end function c31887905.spcon(e,c) if c==nil then return true end local tp=c:GetControler() return Duel.GetLocationCount(tp,LOCATION_MZONE)>-2 and Duel.IsExistingMatchingCard(c31887905.spfilter1,tp,LOCATION_MZONE,0,1,nil,tp) end function c31887905.spop(e,tp,eg,ep,ev,re,r,rp,c) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g1=Duel.SelectMatchingCard(tp,c31887905.spfilter1,tp,LOCATION_MZONE,0,1,1,nil,tp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g2=Duel.SelectMatchingCard(tp,c31887905.spfilter2,tp,LOCATION_MZONE,0,1,1,g1:GetFirst()) g1:Merge(g2) Duel.SendtoGrave(g1,REASON_COST) Duel.ShuffleDeck(tp) --pierce local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_PIERCE) e1:SetReset(RESET_EVENT+0xff0000) c:RegisterEffect(e1) end
gpl-2.0
dickeyf/darkstar
scripts/zones/Escha_ZiTah/Zone.lua
34
1440
----------------------------------- -- -- Zone: Escha - Zi'Tah (288) -- ----------------------------------- package.loaded["scripts/zones/Escha_ZiTah/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Escha_ZiTah/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/zone"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then -- player:setPos(x, y, z, rot); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter( player, region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
fgenesis/Aquaria_experimental
game_scripts/scripts/entities/greenseadragon.lua
6
6527
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.dir = 0 v.dirTimer = 0 v.attackDelay = 2 v.fireDelay = 0 v.n = 0 v.dodgePhase = 0 v.bone_body = 0 v.rideTimer = 0 v.maxRideTime = 20 v.throwOffTimer = 0 v.maxThrowOffTime = 15 local STATE_THROWOFF = 1000 v.roarDelay = 0 v.aggro = 0 v.firstSeen = true function init(me) setupBasicEntity( me, "", -- texture 64, -- health 1, -- manaballamount 1, -- exp 1, -- money 32, -- collideRadius STATE_IDLE, -- initState 0, -- sprite width 0, -- sprite height 0, -- particle "explosion" type, maps to particleEffects.txt -1 = none 0, -- 0/1 hit other entities off/on (uses collideRadius) 3000 ) entity_initSkeletal(me, "GreenSeaDragon") entity_generateCollisionMask(me) entity_animate(me, "idle", LOOP_INF) entity_setMaxSpeed(me, 800) v.fireLoc = entity_getBoneByName(me, "FireLoc") bone_alpha(v.fireLoc) entity_setDeathParticleEffect(me, "GreenSeaDragonExplode") bone_setSegs(entity_getBoneByName(me, "Weeds1"), 2, 16, 0.5, 0.3, -0.018, 0, 12, 1) bone_setSegs(entity_getBoneByName(me, "Weeds2"), 2, 16, 0.5, 0.3, -0.018, 0, 12, 1) v.bone_body = entity_getBoneByName(me, "Body") entity_setCullRadius(me, 1024) loadSound("greenseadragon-die") loadSound("greenseadragon-roar") loadSound("greenseadragon-fire") entity_setDeathSound(me, "greenseadragon-die") end function postInit(me) v.n = getNaija() entity_setTarget(me, v.n) end function dieNormal(me) if chance(5) then spawnIngredient("SpicyRoll", entity_getPosition(me)) else if chance(10) then spawnIngredient("SpecialBulb", entity_getPosition(me)) else if chance(10) then spawnIngredient("Poultice", entity_getPosition(me)) else for i=1,3,1 do spawnIngredient("PlantLeaf", entity_getPosition(me)) end end end end end function update(me, dt) --entity_handleShotCollisions(me) --entity_touchAvatarDamage(me, entity_getCollideRadius(me), 0, 1000) if not isForm(FORM_FISH) then v.aggro = 1 elseif isForm(FORM_FISH) and not entity_isEntityInRange(me, v.n, 1024) then v.aggro = 0 end if v.firstSeen and entity_isTargetInRange(me, 800) then v.roarDelay = v.roarDelay - dt if v.roarDelay < 0 then playSfx("greenseadragon-roar") shakeCamera(6, 3) v.roarDelay = 5 + math.random(3) avatar_fallOffWall() end --v.firstSeen = false end --[[ if dir == 0 then entity_addVel(me, -100*dt, 0) else entity_addVel(me, 100*dt, 0) end v.dirTimer = v.dirTimer - dt if v.dirTimer < 0 then v.dirTimer = 1 if dir == 0 then dir = 1 else dir = 0 end end ]]-- v.dodgePhase = v.dodgePhase + dt if v.dodgePhase > 6 then v.dodgePhase = 0 end if entity_isTargetInRange(me, 256) and v.aggro == 1 then entity_moveTowardsTarget(me, dt, -1000) elseif entity_isTargetInRange(me, 1024) and v.aggro == 1 then entity_moveTowardsTarget(me, dt, 500) end if v.dodgePhase > 3 then --entity_doSpellAvoidance(me, dt, 128, 0.5) end entity_doCollisionAvoidance(me, dt, 4, 1.0) if (math.abs(entity_x(v.n) - entity_x(me)) > 140) then entity_flipToEntity(me, v.n) end if entity_isState(me, STATE_IDLE) and v.aggro == 1 then v.attackDelay = v.attackDelay - dt if v.attackDelay < 0 then entity_setState(me, STATE_ATTACK) end elseif entity_isState(me, STATE_ATTACK) then v.fireDelay = v.fireDelay - dt if v.fireDelay < 0 then v.fireDelay = 0.2 local vx, vy = bone_getNormal(v.fireLoc) local x, y = bone_getWorldPosition(v.fireLoc) local s = createShot("GreenSeaDragon", me, entity_getTarget(me), x, y) shot_setAimVector(s, vx, vy) --local s = entity_fireAtTarget(me, "", 1, 100, 0, 3, 32, 0, 0, vx, vy, x, y) --shot_setNice(s, "Shots/HotEnergy", "HeatTrailSmall", "HeatHit") end elseif entity_isState(me, STATE_THROWOFF) then local range = 5 + v.throwOffTimer * 10 if range > 30 then range = 30 end entity_offset(me, math.random(range/2)-range, math.random(range/2)-range) v.throwOffTimer = v.throwOffTimer + dt * math.random(3) if v.throwOffTimer > v.maxThrowOffTime then avatar_fallOffWall() entity_moveTowards(v.n, entity_x(me), entity_y(me), 1, -2000) entity_moveTowards(me, entity_x(v.n), entity_y(v.n), 1, -1200) end end entity_updateMovement(me, dt) local ent = entity_getBoneLockEntity(v.n) if ent == me then v.rideTimer = v.rideTimer + dt if v.rideTimer > v.maxRideTime and not entity_isState(me, STATE_THROWOFF) then entity_setState(me, STATE_THROWOFF) end else if entity_isState(me, STATE_THROWOFF) then entity_setState(me, STATE_IDLE) end v.rideTimer = 0 end local bone = entity_collideSkeletalVsCircle(me, v.n) if avatar_isBursting() and bone == v.bone_body and entity_setBoneLock(v.n, me, bone) then else entity_touchAvatarDamage(me, entity_getCollideRadius(me), 0, 1000) end entity_handleShotCollisionsSkeletal(me) end function hitSurface(me) end function enterState(me, state) if entity_isState(me, STATE_IDLE) then entity_animate(me, "idle", -1) elseif entity_isState(me, STATE_ATTACK) then entity_setStateTime(me, entity_animate(me, "attack")) v.attackDelay = 0.5 + math.random(150)/100.0 v.fireDelay = 0.3 elseif entity_isState(me, STATE_THROWOFF) then v.throwOffTimer = v.throwOffTimer - 5 if v.throwOffTimer < 0 then v.throwOffTimer = 0 end elseif entity_isState(me, STATE_DEAD) then shakeCamera(10, 3) end end function exitState(me, state) if entity_isState(me, STATE_ATTACK) then entity_setState(me, STATE_IDLE) end end function damage(me) v.rideTimer = v.rideTimer + 1.5 v.aggro = 1 return true end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c8275702.lua
5
1203
--宝玉の契約 function c8275702.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c8275702.sptg) e1:SetOperation(c8275702.spop) c:RegisterEffect(e1) end function c8275702.filter(c,e,sp) return c:IsFaceup() and c:IsSetCard(0x1034) and c:IsCanBeSpecialSummoned(e,0,sp,true,false) end function c8275702.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_SZONE) and chkc:IsControler(tp) and c8275702.filter(chkc,e,tp) end if chk==0 then return Duel.IsExistingTarget(c8275702.filter,tp,LOCATION_SZONE,0,1,nil,e,tp) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c8275702.filter,tp,LOCATION_SZONE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c8275702.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,true,false,POS_FACEUP) end end
gpl-2.0
Turttle/darkstar
scripts/zones/Castle_Oztroja/npcs/_47b.lua
17
1935
----------------------------------- -- Area: Castle Oztroja -- NPC: _47b (Handle) -- Notes: Opens Trap Door (_47a) or Brass Door (_470) -- @pos 22.310 -1.087 -14.320 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/missions"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local X = player:getXPos(); local Z = player:getZPos(); local BrassDoor = npc:getID() - 2; local TrapDoor = npc:getID() - 1; local BrassA = GetNPCByID(BrassDoor):getAnimation(); local TrapA = GetNPCByID(TrapDoor):getAnimation(); if (X < 21.6 and X > 18 and Z > -15.6 and Z < -12.4) then if (VanadielDayOfTheYear() % 2 == 0) then if (TrapA == 9 and npc:getAnimation() == 9) then npc:openDoor(8); -- wait 1 second delay goes here GetNPCByID(TrapDoor):openDoor(6); end if (player:getCurrentMission(WINDURST) == TO_EACH_HIS_OWN_RIGHT and player:getVar("MissionStatus") == 3) then player:startEvent(0x002B); end else if (BrassA == 9 and npc:getAnimation() == 9) then npc:openDoor(8); -- wait 1 second delay goes here GetNPCByID(BrassDoor):openDoor(6); end end else player:messageSpecial(0); 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); if (csid == 0x002B) then player:setVar("MissionStatus",4); end end;
gpl-3.0
Turttle/darkstar
scripts/zones/Port_Bastok/npcs/Aishah.lua
37
1043
----------------------------------- -- Area: Port Bastok -- NPC: Aishah -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x008C); 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
SalvationDevelopment/Salvation-Scripts-TCG
c42969214.lua
5
1106
--アイアイアン function c42969214.initial_effect(c) --atkup local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(42969214,0)) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCost(c42969214.cost) e1:SetOperation(c42969214.operation) c:RegisterEffect(e1) end function c42969214.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():GetAttackAnnouncedCount()==0 end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_ATTACK) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_OATH) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e:GetHandler():RegisterEffect(e1) end function c42969214.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsFaceup() and c:IsRelateToEffect(e) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetProperty(EFFECT_FLAG_COPY_INHERIT) e1:SetValue(400) e1:SetReset(RESET_EVENT+0x1ff0000) c:RegisterEffect(e1) end end
gpl-2.0
dickeyf/darkstar
scripts/globals/spells/bluemagic/metallic_body.lua
45
1520
----------------------------------------- -- Spell: Metallic Body -- Absorbs an certain amount of damage from physical and magical attacks -- Spell cost: 19 MP -- Monster Type: Aquans -- Spell Type: Magical (Earth) -- Blue Magic Points: 1 -- Stat Bonus: None -- Level: 8 -- Casting Time: 7 seconds -- Recast Time: 60 seconds -- Duration: 5 minutes -- -- Combos: Max MP Boost ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_STONESKIN local blueskill = caster:getSkillLevel(BLUE_SKILL); local power = (blueskill/3) + (caster:getMainLvl()/3) + 10; local duration = 300; if (power > 150) then power = 150; end; if (caster:hasStatusEffect(EFFECT_DIFFUSION)) then local diffMerit = caster:getMerit(MERIT_DIFFUSION); if (diffMerit > 0) then duration = duration + (duration/100)* diffMerit; end; caster:delStatusEffect(EFFECT_DIFFUSION); end; if (target:addStatusEffect(typeEffect,power,0,duration) == false) then spell:setMsg(75); end; return typeEffect; end;
gpl-3.0
ld-test/cqueues
examples/getopt.lua
5
1114
-- -- getopt(":a:b", ...) -- works just like getopt(3). -- -- Send bug reports to william@25thandClement.com. -- local function getopt(optstring, ...) local opts = { } local args = { ... } for optc, optv in optstring:gmatch"(%a)(:?)" do opts[optc] = { hasarg = optv == ":" } end return coroutine.wrap(function() local yield = coroutine.yield local i = 1 while i <= #args do local arg = args[i] i = i + 1 if arg == "--" then break elseif arg:sub(1, 1) == "-" then for j = 2, #arg do local opt = arg:sub(j, j) if opts[opt] then if opts[opt].hasarg then if j == #arg then if args[i] then yield(opt, args[i]) i = i + 1 elseif optstring:sub(1, 1) == ":" then yield(':', opt) else yield('?', opt) end else yield(opt, arg:sub(j + 1)) end break else yield(opt, false) end else yield('?', opt) end end else yield(false, arg) end end for i = i, #args do yield(false, args[i]) end end) end return getopt
mit
SalvationDevelopment/Salvation-Scripts-TCG
c62472614.lua
7
2569
--疫病 function c62472614.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_EQUIP) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetTarget(c62472614.target) e1:SetOperation(c62472614.operation) c:RegisterEffect(e1) --Atk,def local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_EQUIP) e2:SetCode(EFFECT_SET_ATTACK) e2:SetValue(0) c:RegisterEffect(e2) --Equip limit local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_EQUIP_LIMIT) e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e3:SetValue(c62472614.eqlimit) c:RegisterEffect(e3) --damage local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(62472614,0)) e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e4:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e4:SetCode(EVENT_PHASE+PHASE_STANDBY) e4:SetRange(LOCATION_SZONE) e4:SetCountLimit(1) e4:SetCondition(c62472614.damcon) e4:SetTarget(c62472614.damtg) e4:SetOperation(c62472614.damop) c:RegisterEffect(e4) end function c62472614.eqlimit(e,c) return c:IsRace(RACE_WARRIOR+RACE_BEASTWARRIOR+RACE_SPELLCASTER) end function c62472614.filter(c) return c:IsFaceup() and c:IsRace(RACE_WARRIOR+RACE_BEASTWARRIOR+RACE_SPELLCASTER) end function c62472614.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsFaceup() and c62472614.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c62472614.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) Duel.SelectTarget(tp,c62472614.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0) end function c62472614.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if e:GetHandler():IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then Duel.Equip(tp,e:GetHandler(),tc) end end function c62472614.damcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp end function c62472614.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local damp=e:GetHandler():GetEquipTarget():GetControler() Duel.SetTargetPlayer(damp) Duel.SetTargetParam(500) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,damp,500) end function c62472614.damop(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local damp=e:GetHandler():GetEquipTarget():GetControler() local d=Duel.GetChainInfo(0,CHAININFO_TARGET_PARAM) Duel.Damage(damp,d,REASON_EFFECT) end
gpl-2.0
Turttle/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/Cannau.lua
38
1038
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Cannau -- Type: Escort NPC -- @pos 419.838 -56.999 -114.870 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0033); 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
SalvationDevelopment/Salvation-Scripts-TCG
c34830502.lua
3
2579
--アルティメット・インセクト LV5 function c34830502.initial_effect(c) --atk down local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetRange(LOCATION_MZONE) e1:SetTargetRange(0,LOCATION_MZONE) e1:SetCondition(c34830502.con) e1:SetValue(-500) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(34830502,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e2:SetRange(LOCATION_MZONE) e2:SetCode(EVENT_PHASE+PHASE_STANDBY) e2:SetCondition(c34830502.spcon) e2:SetCost(c34830502.spcost) e2:SetTarget(c34830502.sptg) e2:SetOperation(c34830502.spop) c:RegisterEffect(e2) --reg local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e3:SetCode(EVENT_SUMMON_SUCCESS) e3:SetOperation(c34830502.regop) c:RegisterEffect(e3) local e4=e3:Clone() e4:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e4) local e5=e3:Clone() e5:SetCode(EVENT_FLIP) c:RegisterEffect(e5) end c34830502.lvupcount=2 c34830502.lvup={34088136,19877898} c34830502.lvdncount=2 c34830502.lvdn={49441499,34088136} function c34830502.con(e) return e:GetHandler():GetFlagEffect(34830502)~=0 end function c34830502.regop(e,tp,eg,ep,ev,re,r,rp) e:GetHandler():RegisterFlagEffect(34830503,RESET_EVENT+0x1ec0000+RESET_PHASE+PHASE_END,0,1) end function c34830502.spcon(e,tp,eg,ep,ev,re,r,rp) return tp==Duel.GetTurnPlayer() and e:GetHandler():GetFlagEffect(34830503)==0 end function c34830502.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() end Duel.SendtoGrave(e:GetHandler(),REASON_COST) end function c34830502.spfilter(c,e,tp) return c:IsCode(19877898) and c:IsCanBeSpecialSummoned(e,0,tp,true,true) end function c34830502.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1 and Duel.IsExistingMatchingCard(c34830502.spfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_DECK) end function c34830502.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c34830502.spfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,1,nil,e,tp) local tc=g:GetFirst() if tc then Duel.SpecialSummon(tc,0,tp,tp,true,true,POS_FACEUP) tc:RegisterFlagEffect(19877898,RESET_EVENT+0x16e0000,0,0) tc:CompleteProcedure() end end
gpl-2.0
fgenesis/Aquaria_experimental
game_scripts/scripts/maps/_unused/node_memorycrystalscene.lua
6
2197
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end function init(me) end function activate(me) end function run(me) if isFlag(FLAG_NAIJA_MEMORYCRYSTAL, 0) then setFlag(FLAG_NAIJA_MEMORYCRYSTAL, 1) local n = getNaija() entity_idle(n) entity_flipToNode(n, getNode("SAVEPOINT")) local camNode = getNode("MEMORYCRYSTALCAM1") local camNode2 = getNode("MEMORYCRYSTALCAM2") local camNode3 = getNode("MEMORYCRYSTALCAM3") local camNode4 = getNode("SAVEPOINT") local camDummy = createEntity("Empty") entity_warpToNode(camDummy, camNode) setCameraLerpDelay(1.0) cam_toEntity(camDummy) overrideZoom(0.75, 1) entity_animate(getNaija(), "look45", LOOP_INF, LAYER_HEAD) entity_swimToNode(camDummy, camNode2, SPEED_SLOW) entity_watchForPath(camDummy) voice("naija_memorycrystal") entity_swimToNode(camDummy, camNode3, SPEED_SLOW) entity_watchForPath(camDummy) entity_swimToNode(camDummy, camNode4, SPEED_SLOW) entity_watchForPath(camDummy) overrideZoom(0.6, 9) watch(9) screenFadeCapture() --overrideZoom(1, 4) overrideZoom(0) setCameraLerpDelay(0.0001) cam_toEntity(n) screenFadeGo(6) watch(6) entity_idle(n) setCameraLerpDelay(0) entity_delete(camDummy) end end function update(me, dt) if node_isEntityIn(me, getNaija()) then run(me) end end
gpl-2.0
eggBOY91/opencore
src/scripts/lua/LuaBridge/Stable Scripts/Azeroth/Karazhan/BOSS_Karazhan_Nightbane.lua
30
1906
function Nightbane_Cleave(Unit, event, miscunit, misc) print "Nightbane Cleave" Unit:FullCastSpellOnTarget(42587,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "Cleave on you...") end function Nightbane_Tail_Sweep(Unit, event, miscunit, misc) print "Nightbane Tail Sweep" Unit:FullCastSpellOnTarget(25653,Unit:GetRandomPlayer()) Unit:SendChatMessage(11, 0, "Take that...") end function Nightbane_Bone_Shards(Unit, event, miscunit, misc) print "Nightbane Bone Shards" Unit:FullCastSpell(17014) Unit:SendChatMessage(11, 0, "Bones protect me...") end function Nightbane_Distracting_Ash(Unit, event, miscunit, misc) print "Nightbane Distracting Ash" Unit:FullCastSpellOnTarget(30130,Unit:GetRandomPlayer()) Unit:SendChatMessage(11, 0, "Ho, your are distracting...") end function Nightbane_Bellowing_Roar(Unit, event, miscunit, misc) print "Nightbane Bellowing Roar" Unit:FullCastSpellOnTarget(37066,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "FEAR on you guys...") end function Nightbane_Charred_Earth(Unit, event, miscunit, misc) print "Nightbane Charred Earth" Unit:FullCastSpellOnTarget(30129,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "FIRE...") end function Nightbane_Smoldering_Breath(Unit, event, miscunit, misc) print "Nightbane Smoldering Breath" Unit:FullCastSpellOnTarget(39385,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "A Good breath...") end function Nightbane(unit, event, miscunit, misc) print "Nightbane" unit:RegisterEvent("Nightbane_Cleave",10000,0) unit:RegisterEvent("Nightbane_Tail_Sweep",13000,0) unit:RegisterEvent("Nightbane_Bone_Shards",17000,0) unit:RegisterEvent("Nightbane_Distracting_Ash",23000,0) unit:RegisterEvent("Nightbane_Bellowing_Roar",31000,0) unit:RegisterEvent("Nightbane_Charred_Earth",37000,0) unit:RegisterEvent("Nightbane_Smoldering_Breath",43000,0) end RegisterUnitEvent(17225,1,"Nightbane")
agpl-3.0
Turttle/darkstar
scripts/zones/QuBia_Arena/mobs/Archlich_Taber_quoan.lua
27
4133
----------------------------------- -- Area: Qu'Bia Arena -- NM: Archlich Taber'quoan -- Mission 5-1 BCNM Fight ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob, target) local BattleTime = mob:getBattleTime(); local War_1 = mob:getID()+3; local War_2 = mob:getID()+4; local War_3 = mob:getID()+5; local War_4 = mob:getID()+6; -- Tries to spawn 1 group of 2 Warriors to aid Archlich every 30 sec. The sorcerers DO NOT repop. -- If you think they should repop, you are WRONG. If you think all 7 skelly attack at start, YOU ARE WRONG. if (BattleTime - mob:getLocalVar("RepopWarriors") > 30) then if ((GetMobAction(War_1) == ACTION_NONE or GetMobAction(War_1) == ACTION_SPAWN) and (GetMobAction(War_2) == ACTION_NONE or GetMobAction(War_2) == ACTION_SPAWN)) then SpawnMob(War_1):updateEnmity(target); SpawnMob(War_2):updateEnmity(target); mob:setLocalVar("RepopWarriors", BattleTime); elseif ((GetMobAction(War_1) == ACTION_NONE or GetMobAction(War_1) == ACTION_SPAWN) and (GetMobAction(War_3) == ACTION_NONE or GetMobAction(War_3) == ACTION_SPAWN)) then SpawnMob(War_1):updateEnmity(target); SpawnMob(War_3):updateEnmity(target); mob:setLocalVar("RepopWarriors", BattleTime); elseif ((GetMobAction(War_1) == ACTION_NONE or GetMobAction(War_1) == ACTION_SPAWN) and (GetMobAction(War_4) == ACTION_NONE or GetMobAction(War_4) == ACTION_SPAWN)) then SpawnMob(War_1):updateEnmity(target); SpawnMob(War_4):updateEnmity(target); mob:setLocalVar("RepopWarriors", BattleTime); elseif ((GetMobAction(War_2) == ACTION_NONE or GetMobAction(War_2) == ACTION_SPAWN) and (GetMobAction(War_3) == ACTION_NONE or GetMobAction(War_3) == ACTION_SPAWN)) then SpawnMob(War_2):updateEnmity(target); SpawnMob(War_3):updateEnmity(target); mob:setLocalVar("RepopWarriors", BattleTime); elseif ((GetMobAction(War_2) == ACTION_NONE or GetMobAction(War_2) == ACTION_SPAWN) and (GetMobAction(War_4) == ACTION_NONE or GetMobAction(War_4) == ACTION_SPAWN)) then SpawnMob(War_2):updateEnmity(target); SpawnMob(War_4):updateEnmity(target); mob:setLocalVar("RepopWarriors", BattleTime); elseif ((GetMobAction(War_3) == ACTION_NONE or GetMobAction(War_3) == ACTION_SPAWN) and (GetMobAction(War_4) == ACTION_NONE or GetMobAction(War_4) == ACTION_SPAWN)) then SpawnMob(War_3):updateEnmity(target); SpawnMob(War_4):updateEnmity(target); mob:setLocalVar("RepopWarriors", BattleTime); -- Can't find a pair to pop at once, so popping single (dunno if this part is retail...) elseif (GetMobAction(War_1) == ACTION_NONE or GetMobAction(War_1) == ACTION_SPAWN) then SpawnMob(War_1):updateEnmity(target); mob:setLocalVar("RepopWarriors", BattleTime); elseif (GetMobAction(War_2) == ACTION_NONE or GetMobAction(War_2) == ACTION_SPAWN) then SpawnMob(War_2):updateEnmity(target); mob:setLocalVar("RepopWarriors", BattleTime); elseif (GetMobAction(War_3) == ACTION_NONE or GetMobAction(War_3) == ACTION_SPAWN) then SpawnMob(War_3):updateEnmity(target); mob:setLocalVar("RepopWarriors", BattleTime); elseif (GetMobAction(War_4) == ACTION_NONE or GetMobAction(War_4) == ACTION_SPAWN) then SpawnMob(War_4):updateEnmity(target); mob:setLocalVar("RepopWarriors", BattleTime); end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) killer:addTitle(ARCHMAGE_ASSASSIN); end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c52900000.lua
2
3942
--霊魂鳥神-彦孔雀 function c52900000.initial_effect(c) c:EnableReviveLimit() --special summon condition local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetValue(aux.ritlimit) c:RegisterEffect(e1) --tohand local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(52900000,0)) e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_DELAY) e2:SetCode(EVENT_SPSUMMON_SUCCESS) e2:SetCondition(c52900000.thcon) e2:SetTarget(c52900000.thtg) e2:SetOperation(c52900000.thop) c:RegisterEffect(e2) --return local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e3:SetCode(EVENT_SPSUMMON_SUCCESS) e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e3:SetOperation(c52900000.retreg) c:RegisterEffect(e3) end function c52900000.thcon(e,tp,eg,ep,ev,re,r,rp) return bit.band(e:GetHandler():GetSummonType(),SUMMON_TYPE_RITUAL)==SUMMON_TYPE_RITUAL end function c52900000.spfilter(c,e,tp) return c:IsType(TYPE_SPIRIT) and c:IsLevelBelow(4) and c:IsCanBeSpecialSummoned(e,0,tp,true,false) end function c52900000.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToHand,tp,0,LOCATION_MZONE,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,0,0) end function c52900000.thop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(Card.IsAbleToHand,tp,0,LOCATION_MZONE,nil) if g:GetCount()<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND) local sg=g:Select(tp,1,3,nil) if Duel.SendtoHand(sg,nil,REASON_EFFECT)~=0 then local sg2=Duel.GetOperatedGroup() if not sg2:IsExists(Card.IsLocation,1,nil,LOCATION_HAND) then return end local tg=Duel.GetMatchingGroup(c52900000.spfilter,tp,LOCATION_HAND,0,nil,e,tp) if tg:GetCount()>0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.SelectYesNo(tp,aux.Stringid(52900000,1)) then Duel.BreakEffect() Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local tc=tg:Select(tp,1,1,nil) Duel.SpecialSummon(tc,0,tp,tp,true,false,POS_FACEUP) end end end function c52900000.retreg(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e1:SetDescription(1104) e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SPECIAL_SUMMON+CATEGORY_TOKEN) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetReset(RESET_EVENT+0x1ee0000+RESET_PHASE+PHASE_END) e1:SetCondition(aux.SpiritReturnCondition) e1:SetTarget(c52900000.rettg) e1:SetOperation(c52900000.retop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) c:RegisterEffect(e2) end function c52900000.rettg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then if e:IsHasType(EFFECT_TYPE_TRIGGER_F) then return true else return Duel.GetLocationCount(tp,LOCATION_MZONE)>1 and not Duel.IsPlayerAffectedByEffect(tp,59822133) and Duel.IsPlayerCanSpecialSummonMonster(tp,52900001,0,0x4011,1500,1500,4,RACE_WINDBEAST,ATTRIBUTE_WIND) end end Duel.SetOperationInfo(0,CATEGORY_TOHAND,e:GetHandler(),1,0,0) Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,2,0,0) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,0,0) end function c52900000.retop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() and Duel.SendtoHand(c,nil,REASON_EFFECT)~=0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>1 and not Duel.IsPlayerAffectedByEffect(tp,59822133) and Duel.IsPlayerCanSpecialSummonMonster(tp,52900001,0,0x4011,1500,1500,4,RACE_WINDBEAST,ATTRIBUTE_WIND) then for i=1,2 do local token=Duel.CreateToken(tp,52900001) Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP) end Duel.SpecialSummonComplete() end end
gpl-2.0
dickeyf/darkstar
scripts/globals/items/plate_of_shrimp_sushi_+1.lua
18
1606
----------------------------------------- -- ID: 5692 -- Item: plate_of_shrimp_sushi_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Vitality 1 -- Defense 5 -- Accuracy % 12 (unknown, assuming HQ stat) -- Store TP 2 -- Triple Attack 1 (unknown, assuming same as NQ) ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5692); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_VIT, 1); target:addMod(MOD_DEF, 5); target:addMod(MOD_FOOD_ACCP, 12); target:addMod(MOD_FOOD_ACC_CAP, 999); target:addMod(MOD_STORETP, 2); target:addMod(MOD_TRIPLE_ATTACK, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_VIT, 1); target:delMod(MOD_DEF, 5); target:delMod(MOD_FOOD_ACCP, 12); target:delMod(MOD_FOOD_ACC_CAP, 999); target:delMod(MOD_STORETP, 2); target:delMod(MOD_TRIPLE_ATTACK, 1); end;
gpl-3.0
dickeyf/darkstar
scripts/globals/items/moon_carrot.lua
18
1173
----------------------------------------- -- ID: 4567 -- Item: moon_carrot -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility 1 -- Vitality -1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4567); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, -1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, -1); end;
gpl-3.0
dickeyf/darkstar
scripts/zones/RuLude_Gardens/npcs/Macchi_Gazlitah.lua
12
1947
----------------------------------- -- Area: Ru'Lud Gardens -- NPC: Macchi Gazlitah -- Standard Mechant NPC -- Sells base items, then sells better items based -- on a gil amount of what has been already purchased -- in a given timeframe. ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- TODO: The contents of her shop changes based on gil over time (resets on JP midnight) -- Right now only her first tier of stock is shown -- See WIKI for the shop tiers based on the amount sold player:showText(npc,MACCHI_GAZLITAH_SHOP_DIALOG1); stock = {0x1647,100, --Uleguerand Milk 0x1634,250, --Chalaimbille 0x45f1,100,} --Wormy Broth -- 0x1636,800, --Cheese Sandwich -- 0x1661,3360, --Bavarois -- 0x1656,1300, --Cream Puff -- 0x01cd,5000, --Buffalo Milk Case -- 0x1420,1280, --Buffalo Meat -- 0x1272,31878, --Enfire II -- 0x1273,30492, --Enblizzard II -- 0x1274,27968, --Enaero II -- 0x1275,26112, --Enstone II -- 0x1276,25600, --Enthunder II -- 0x1277,33000, --Enwater II -- 0x12f2,150000} --Refresh II showShop(player, JEUNO, 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
SalvationDevelopment/Salvation-Scripts-TCG
c40937767.lua
6
1335
--グレイヴ・オージャ function c40937767.initial_effect(c) --cannot be battle target local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_CANNOT_BE_BATTLE_TARGET) e1:SetCondition(c40937767.ccon) e1:SetValue(aux.imval1) c:RegisterEffect(e1) --damage local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(40937767,0)) e2:SetCategory(CATEGORY_DAMAGE) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetRange(LOCATION_MZONE) e2:SetCode(EVENT_FLIP_SUMMON_SUCCESS) e2:SetCondition(c40937767.damcon) e2:SetTarget(c40937767.damtg) e2:SetOperation(c40937767.damop) c:RegisterEffect(e2) end function c40937767.ccon(e) return Duel.IsExistingMatchingCard(Card.IsPosition,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil,POS_FACEDOWN_DEFENSE) end function c40937767.damcon(e,tp,eg,ep,ev,re,r,rp) return ep==tp and eg:GetFirst()~=e:GetHandler() end function c40937767.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(300) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,300) end function c40937767.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) end
gpl-2.0
dickeyf/darkstar
scripts/globals/weaponskills/sunburst.lua
11
1292
----------------------------------- -- Sunburst -- Staff weapon skill -- Skill Level: 150 -- Deals light or darkness elemental damage. Damage varies with TP. -- Aligned with the Shadow Gorget & Aqua Gorget. -- Aligned with the Shadow Belt & Aqua Belt. -- Element: Light/Dark -- Modifiers: : STR:40% MND:40% -- 100%TP 200%TP 300%TP -- 1.00 2.50 4.00 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary) local params = {}; params.ftp100 = 1; params.ftp200 = 2.5; params.ftp300 = 4; params.str_wsc = 0.4; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.4; params.chr_wsc = 0.0; params.ele = ELE_DARK; params.ele = ELE_LIGHT; params.skill = SKILL_STF; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.4; params.mnd_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
fgenesis/Aquaria_experimental
game_scripts/scripts/entities/slendereel.lua
6
5466
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end -- ================================================================================================ -- EEL -- ================================================================================================ -- ================================================================================================ -- FUNCTIONS -- ================================================================================================ v.dir = 0 v.switchDirDelay = 0 v.wiggleTime = 0 v.wiggleDir = 1 v.interestTimer = 0 v.colorRevertTimer = 0 v.collisionSegs = 50 v.avoidLerp = 0 v.avoidDir = 1 v.interest = false -- initializes the entity function init(me) -- oldhealth : 40 setupBasicEntity( me, "", -- texture 6, -- health 1, -- manaballamount 1, -- exp 1, -- money 32, -- collideRadius (only used if hit entities is on) STATE_IDLE, -- initState 90, -- sprite width 90, -- sprite height 1, -- particle "explosion" type, maps to particleEffects.txt -1 = none 0, -- 0/1 hit other entities off/on (uses collideRadius) -1, -- updateCull -1: disabled, default: 4000 1 ) entity_setDropChance(me, 50) v.lungeDelay = 1.0 -- prevent the nautilus from attacking right away entity_initHair(me, 64, 4, 16, "SlenderEel") if chance(50) then v.dir = 0 else v.dir = 1 end if chance(50) then v.interest = true end v.switchDirDelay = math.random(800)/100.0 v.naija = getNaija() entity_addVel(me, math.random(1000)-500, math.random(1000)-500) entity_setDeathParticleEffect(me, "Explode") entity_setUpdateCull(me, 2000) entity_setDamageTarget(me, DT_AVATAR_LIZAP, false) entity_setDamageTarget(me, DT_AVATAR_PET, false) end -- the entity's main update function function update(me, dt) if v.colorRevertTimer > 0 then v.colorRevertTimer = v.colorRevertTimer - dt if v.colorRevertTimer < 0 then entity_setColor(me, 1, 1, 1, 3) end end entity_handleShotCollisionsHair(me, v.collisionSegs) --entity_handleShotCollisions(me) --[[ if entity_collideHairVsCircle(me, v.naija, v.collisionSegs) then entity_touchAvatarDamage(me, 0, 0, 500) end ]]-- -- in idle state only if entity_getState(me)==STATE_IDLE then -- count down the v.lungeDelay timer to 0 if v.lungeDelay > 0 then v.lungeDelay = v.lungeDelay - dt if v.lungeDelay < 0 then v.lungeDelay = 0 end end -- if we don't have a target, find one if not entity_hasTarget(me) then entity_findTarget(me, 1000) else v.wiggleTime = v.wiggleTime + (dt*200)*v.wiggleDir if v.wiggleTime > 1000 then v.wiggleDir = -1 elseif v.wiggleTime < 0 then v.wiggleDir = 1 end v.interestTimer = v.interestTimer - dt if v.interestTimer < 0 then if v.interest then v.interest = false else v.interest = true entity_addVel(me, math.random(1000)-500, math.random(1000)-500) end v.interestTimer = math.random(400.0)/100.0 + 2.0 end if v.interest then if entity_isNearObstruction(getNaija(), 8) then v.interest = false else if entity_isTargetInRange(me, 1600) then if entity_isTargetInRange(me, 100) then entity_moveTowardsTarget(me, dt, -500) elseif not entity_isTargetInRange(me, 300) then entity_moveTowardsTarget(me, dt, 1000) end entity_moveAroundTarget(me, dt, 1000+v.wiggleTime, v.dir) end end else if entity_isTargetInRange(me, 1600) then entity_moveTowardsTarget(me, dt, -100) end end v.avoidLerp = v.avoidLerp + dt*v.avoidDir if v.avoidLerp >= 1 or v.avoidLerp <= 0 then v.avoidLerp = 0 if v.avoidDir == -1 then v.avoidDir = 1 else v.avoidDir = -1 end end -- avoid other things nearby entity_doEntityAvoidance(me, dt, 32, 0.1) -- entity_doSpellAvoidance(dt, 200, 1.5); entity_doCollisionAvoidance(me, dt, 10, 0.1) entity_doCollisionAvoidance(me, dt, 4, 0.8) end end entity_updateMovement(me, dt) entity_setHairHeadPosition(me, entity_x(me), entity_y(me)) entity_updateHair(me, dt) end function enterState(me) if entity_isState(me, STATE_IDLE) then entity_setMaxSpeed(me, 400) end end function exitState(me) end function hitSurface(me) end function damage(me, attacker, bone, damageType, dmg) entity_setMaxSpeed(me, 600) return true end function songNote(me, note) if getForm()~=FORM_NORMAL then return end v.interest = true local r,g,b = getNoteColor(note) entity_setColor(me, r,g,b,1) v.colorRevertTimer = 2 + math.random(300)/100.0 --entity_setColor(me, 1,1,1,10) end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c25669282.lua
2
3684
--完全燃焼 function c25669282.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCountLimit(1,25669282+EFFECT_COUNT_CODE_OATH) e1:SetCost(c25669282.cost) e1:SetTarget(c25669282.target) e1:SetOperation(c25669282.activate) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(25669282,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_ATTACK_ANNOUNCE) e2:SetRange(LOCATION_GRAVE) e2:SetCondition(c25669282.spcon) e2:SetCost(c25669282.spcost) e2:SetTarget(c25669282.sptg) e2:SetOperation(c25669282.spop) c:RegisterEffect(e2) end function c25669282.cfilter(c) return c:IsFaceup() and c:IsSetCard(0xeb) and c:IsAbleToRemoveAsCost() end function c25669282.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c25669282.cfilter,tp,LOCATION_MZONE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c25669282.cfilter,tp,LOCATION_MZONE,0,1,1,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) end function c25669282.spfilter1(c,e,tp) return c:IsSetCard(0xeb) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.IsExistingMatchingCard(c25669282.spfilter2,tp,LOCATION_DECK,0,1,nil,e,tp,c:GetCode()) end function c25669282.spfilter2(c,e,tp,code) return c:IsSetCard(0xeb) and not c:IsCode(code) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c25669282.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return not Duel.IsPlayerAffectedByEffect(tp,59822133) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c25669282.spfilter1,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_DECK) end function c25669282.activate(e,tp,eg,ep,ev,re,r,rp) if not Duel.IsPlayerAffectedByEffect(tp,59822133) and Duel.GetLocationCount(tp,LOCATION_MZONE)>1 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g1=Duel.SelectMatchingCard(tp,c25669282.spfilter1,tp,LOCATION_DECK,0,1,1,nil,e,tp) if g1:GetCount()<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g2=Duel.SelectMatchingCard(tp,c25669282.spfilter2,tp,LOCATION_DECK,0,1,1,nil,e,tp,g1:GetFirst():GetCode()) g1:Merge(g2) Duel.SpecialSummon(g1,0,tp,tp,false,false,POS_FACEUP) end end function c25669282.spcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetAttacker():IsControler(1-tp) and Duel.GetAttackTarget()==nil and aux.exccon(e,tp,eg,ep,ev,re,r,rp) end function c25669282.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c25669282.spfilter3(c,e,tp) return c:IsFaceup() and c:IsType(TYPE_DUAL) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c25669282.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_REMOVED) and chkc:IsControler(tp) and c25669282.spfilter3(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c25669282.spfilter3,tp,LOCATION_REMOVED,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c25669282.spfilter3,tp,LOCATION_REMOVED,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c25669282.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)~=0 then tc:EnableDualState() end end
gpl-2.0
Turttle/darkstar
scripts/globals/items/balik_sis_+1.lua
35
1664
----------------------------------------- -- ID: 5601 -- Item: Balik Sis +1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 5 -- Mind -2 -- Attack % 15 -- Attack Cap 45 -- Ranged ACC 1 -- Ranged ATT % 15 -- Ranged ATT Cap 45 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5601); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 5); target:addMod(MOD_MND, -2); target:addMod(MOD_FOOD_ATTP, 15); target:addMod(MOD_FOOD_ATT_CAP, 45); target:addMod(MOD_RACC, 1); target:addMod(MOD_FOOD_RATTP, 15); target:addMod(MOD_FOOD_RATT_CAP, 45); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 5); target:delMod(MOD_MND, -2); target:delMod(MOD_FOOD_ATTP, 15); target:delMod(MOD_FOOD_ATT_CAP, 45); target:delMod(MOD_RACC, 1); target:delMod(MOD_FOOD_RATTP, 15); target:delMod(MOD_FOOD_RATT_CAP, 45); end;
gpl-3.0
fgenesis/Aquaria_experimental
game_scripts/scripts/maps/node_finalbossdeath.lua
6
3140
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.ent = 0 v.incut = false function init(me) v.ent = node_getNearestEntity(me, "CreatorForm6") loadSound("creatorform6-die3") end local function flash() fade(1, 0, 1, 1, 1) fade(0, 1, 1, 1, 1) end function update(me, dt) if v.incut then return end v.incut = true if entity_isState(v.ent, STATE_TRANSITION) then local vision = getNode("VISION") local visionNaija = getNode("VISIONNAIJA") local n = getNaija() changeForm(FORM_NORMAL) entity_setInvincible(n) entity_setPosition(v.ent, entity_x(v.ent), entity_y(v.ent), 0.01) disableInput() entity_idle(n) entity_heal(n, 999) watch(1) entity_flipToEntity(n, v.ent) playMusicOnce("EndingPart1") overrideZoom(0.8) overrideZoom(0.7, 5) fade(1, 0.01, 1, 1, 1) fade(0, 5, 1, 1, 1) entity_msg(v.ent, "eye") entity_setAnimLayerTimeMult(v.ent, 0, 1.2) entity_setPosition(v.ent, entity_x(v.ent)+600, entity_y(v.ent), 7) playSfx("creatorform6-die3", 0, 0.2) flash() entity_animate(v.ent, "die1", -1) watch(5) flash() overrideZoom(0.5, 2) entity_msg(v.ent, "neck") watch(3) overrideZoom(0.4, 5) entity_setAnimLayerTimeMult(v.ent, 0, 4) flash() entity_animate(v.ent, "die2", -1) shakeCamera(5, 5) watch(5) overrideZoom(0.3, 9) entity_setAnimLayerTimeMult(v.ent, 0, 0.5) playSfx("creatorform6-die3") flash() entity_animate(v.ent, "die3", 0) shakeCamera(8, 4) watch(4) shakeCamera(15, 4) watch(4) --entity_setStateTime(v.ent, 0.01) fade(1, 0.5, 1,1,1) entity_setState(v.ent, STATE_WAIT) watch(0.5) entity_update(v.ent, 0) entity_setPosition(n, node_x(visionNaija), node_y(visionNaija)) cam_toNode(vision) local kid = node_getNearestEntity(me, "CC_EndOfGame") entity_color(kid, 0, 0, 0) entity_color(n, 0, 0, 0) overrideZoom(1) watch(2) overrideZoom(1) fade(0, 1, 1, 1, 1) watch(3) watch(1) entity_setPosition(kid, entity_x(n)+34, entity_y(n)+8, 4, 0, 0, 1) watch(3) entity_animate(kid, "hug") fade2(1, 2, 1, 1, 1) watch(2) --[[ fade(0, 2, 1,1,1) watch(2) --entity_setStateTime(me, 28 - 22) watch(6) ]]-- entity_setStateTime(v.ent, 0.01) loadMap("eric") --jumpState("credits") end v.incut = false end
gpl-2.0
mohammadclash/STAR
plugins/quotes.lua
651
1630
local quotes_file = './data/quotes.lua' local quotes_table function read_quotes_file() local f = io.open(quotes_file, "r+") if f == nil then print ('Created a new quotes file on '..quotes_file) serialize_to_file({}, quotes_file) else print ('Quotes loaded: '..quotes_file) f:close() end return loadfile (quotes_file)() end function save_quote(msg) local to_id = tostring(msg.to.id) if msg.text:sub(11):isempty() then return "Usage: !addquote quote" end if quotes_table == nil then quotes_table = {} end if quotes_table[to_id] == nil then print ('New quote key to_id: '..to_id) quotes_table[to_id] = {} end local quotes = quotes_table[to_id] quotes[#quotes+1] = msg.text:sub(11) serialize_to_file(quotes_table, quotes_file) return "done!" end function get_quote(msg) local to_id = tostring(msg.to.id) local quotes_phrases quotes_table = read_quotes_file() quotes_phrases = quotes_table[to_id] return quotes_phrases[math.random(1,#quotes_phrases)] end function run(msg, matches) if string.match(msg.text, "!quote$") then return get_quote(msg) elseif string.match(msg.text, "!addquote (.+)$") then quotes_table = read_quotes_file() return save_quote(msg) end end return { description = "Save quote", description = "Quote plugin, you can create and retrieve random quotes", usage = { "!addquote [msg]", "!quote", }, patterns = { "^!addquote (.+)$", "^!quote$", }, run = run }
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c42155488.lua
5
2431
--ジェノミックス・ファイター function c42155488.initial_effect(c) --summon with no tribute local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(42155488,0)) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SUMMON_PROC) e1:SetCondition(c42155488.ntcon) e1:SetOperation(c42155488.ntop) c:RegisterEffect(e1) --declear local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(42155488,1)) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetTarget(c42155488.dectg) e2:SetOperation(c42155488.decop) c:RegisterEffect(e2) end function c42155488.ntcon(e,c,minc) if c==nil then return true end return minc==0 and c:GetLevel()>4 and Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0 end function c42155488.ntop(e,tp,eg,ep,ev,re,r,rp,c) --change base attack local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetReset(RESET_EVENT+0xff0000) e1:SetCode(EFFECT_SET_BASE_ATTACK) e1:SetValue(1100) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_CHANGE_LEVEL) e2:SetValue(3) c:RegisterEffect(e2) end function c42155488.dectg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.Hint(HINT_SELECTMSG,tp,563) local rc=Duel.AnnounceRace(tp,1,0xffffff) e:SetLabel(rc) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_SUMMON) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetTargetRange(1,0) e1:SetTarget(c42155488.sumlimit) e1:SetReset(RESET_PHASE+PHASE_END) e1:SetLabel(rc) Duel.RegisterEffect(e1,tp) local e2=e1:Clone() e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) Duel.RegisterEffect(e2,tp) end function c42155488.sumlimit(e,c) return c:GetRace()~=e:GetLabel() end function c42155488.decop(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then local rc=e:GetLabel() c:SetHint(CHINT_RACE,rc) local e1=Effect.CreateEffect(c) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SYNCHRO_CHECK) e1:SetValue(c42155488.syncheck) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e1:SetLabel(rc) c:RegisterEffect(e1) end end function c42155488.syncheck(e,c) c:AssumeProperty(ASSUME_RACE,e:GetLabel()) end
gpl-2.0
Turttle/darkstar
scripts/zones/Bastok_Mines/npcs/Tibelda.lua
36
1405
----------------------------------- -- Area: Bastok Mines -- NPC: Tibelda -- Only sells when Bastok controlls Valdeaunia Region ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); 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) RegionOwner = GetRegionOwner(VALDEAUNIA); if (RegionOwner ~= BASTOK) then player:showText(npc,TIBELDA_CLOSED_DIALOG); else player:showText(npc,TIBELDA_OPEN_DIALOG); stock = { 0x111e, 29, --Frost Turnip 0x027e, 170 --Sage } showShop(player,BASTOK,stock); 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
SalvationDevelopment/Salvation-Scripts-TCG
c100912079.lua
2
2304
--醒めない悪夢 --Eternal Nightmares --Script by dest function c100912079.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(0,TIMING_END_PHASE+TIMING_EQUIP) e1:SetTarget(c100912079.target1) c:RegisterEffect(e1) --destroy local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(36970611,0)) e2:SetCategory(CATEGORY_DESTROY) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetRange(LOCATION_SZONE) e2:SetCode(EVENT_FREE_CHAIN) e2:SetHintTiming(0,TIMING_END_PHASE+TIMING_EQUIP) e2:SetCost(c100912079.cost2) e2:SetTarget(c100912079.target2) e2:SetOperation(c100912079.operation) c:RegisterEffect(e2) end function c100912079.filter(c) return c:IsFaceup() and c:IsType(TYPE_SPELL+TYPE_TRAP) end function c100912079.target1(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return c100912079.target2(e,tp,eg,ep,ev,re,r,rp,chk,chkc) end if chk==0 then return true end if c100912079.cost2(e,tp,eg,ep,ev,re,r,rp,0) and c100912079.target2(e,tp,eg,ep,ev,re,r,rp,0,chkc) and Duel.SelectYesNo(tp,94) then e:SetCategory(CATEGORY_DESTROY) e:SetProperty(EFFECT_FLAG_CARD_TARGET) e:SetOperation(c100912079.operation) c100912079.cost2(e,tp,eg,ep,ev,re,r,rp,1) c100912079.target2(e,tp,eg,ep,ev,re,r,rp,1,chkc) else e:SetProperty(0) e:SetOperation(nil) end end function c100912079.cost2(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckLPCost(tp,1000) and e:GetHandler():GetFlagEffect(100912079)==0 end Duel.PayLPCost(tp,1000) e:GetHandler():RegisterFlagEffect(100912079,RESET_CHAIN,0,1) end function c100912079.target2(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() and c100912079.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c100912079.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,c100912079.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) end function c100912079.operation(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.Destroy(tc,REASON_EFFECT) end end
gpl-2.0
dickeyf/darkstar
scripts/zones/West_Ronfaure/npcs/Tottoto_WW.lua
13
3325
----------------------------------- -- Area: West Ronfaure -- NPC: Tottoto, W.W. -- Type: Border Conquest Guards -- @pos -560.292 -0.961 -576.655 100 ----------------------------------- package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/West_Ronfaure/TextIDs"); local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = RONFAURE; local csid = 0x7ff6; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
Andrew-Collins/nodemcu-firmware
lua_modules/mpr121/mpr121.lua
19
2055
--------------------------------------------------------------- -- MPR121 I2C module for NodeMCU -- Based on code from: http://bildr.org/2011/05/mpr121_arduino/ -- Tiago Custódio <tiagocustodio1@gmail.com> --------------------------------------------------------------- local moduleName = ... local M = {} _G[moduleName] = M -- Default value for i2c communication local id = 0 --device address local devAddr = 0 --make it faster local i2c = i2c function M.setRegister(address, r, v) i2c.start(id) local ans = i2c.address(id, address, i2c.TRANSMITTER) i2c.write(id, r) i2c.write(id, v) i2c.stop(id) end function M.init(address) devAddr = address M.setRegister(devAddr, 0x5E, 0x00) -- ELE_CFG -- Section A - Controls filtering when data is > baseline. M.setRegister(devAddr, 0x2B, 0x01) -- MHD_R M.setRegister(devAddr, 0x2C, 0x01) -- NHD_R M.setRegister(devAddr, 0x2D, 0x00) -- NCL_R M.setRegister(devAddr, 0x2E, 0x00) -- FDL_R -- Section B - Controls filtering when data is < baseline. M.setRegister(devAddr, 0x2F, 0x01) -- MHD_F M.setRegister(devAddr, 0x30, 0x01) -- NHD_F M.setRegister(devAddr, 0x31, 0xFF) -- NCL_F M.setRegister(devAddr, 0x32, 0x02) -- FDL_F -- Section C - Sets touch and release thresholds for each electrode for i = 0, 11 do M.setRegister(devAddr, 0x41+(i*2), 0x06) -- ELE0_T M.setRegister(devAddr, 0x42+(i*2), 0x0A) -- ELE0_R end -- Section D - Set the Filter Configuration - Set ESI2 M.setRegister(devAddr, 0x5D, 0x04) -- FIL_CFG -- Section E - Electrode Configuration - Set 0x5E to 0x00 to return to standby mode M.setRegister(devAddr, 0x5E, 0x0C) -- ELE_CFG tmr.delay(50000) -- Delay to let the electrodes settle after config end function M.readTouchInputs() i2c.start(id) i2c.address(id, devAddr, i2c.RECEIVER) local c = i2c.read(id, 2) i2c.stop(id) local LSB = tonumber(string.byte(c, 1)) local MSB = tonumber(string.byte(c, 2)) local touched = bit.lshift(MSB, 8) + LSB local t = {} for i = 0, 11 do t[i+1] = bit.isset(touched, i) and 1 or 0 end return t end return M
mit
Ablu/ValyriaTear
dat/maps/layna_village/layna_village_riverbank_house.lua
1
31194
-- Valyria Tear map editor begin. Do not edit this line or put anything before this line. -- -- Set the namespace according to the map name. local ns = {}; setmetatable(ns, {__index = _G}); layna_village_riverbank_house = ns; setfenv(1, ns); -- A reference to the C++ MapMode object that was created with this file map = {} -- The map name, subname and location image map_name = "Mountain Village of Layna" map_image_filename = "img/menus/locations/mountain_village.png" map_subname = "Lilly's house" -- The number of rows, and columns that compose the map num_tile_cols = 32 num_tile_rows = 24 -- The contexts names and inheritance definition -- Tells the context id the current context inherit from -- This means that the parent context will be used as a base, and the current -- context will only have its own differences from it. -- At least, the base context (id:0) can't a parent context, thus it should be equal to -1. -- Note that a context cannot inherit from itself or a context with a higher id -- since it would lead to nasty and useless loading use cases. contexts = {} contexts[0] = {} contexts[0].name = "Base" contexts[0].inherit_from = -1 -- The music file used as default background music on this map. -- Other musics will have to handled through scripting. music_filename = "mus/Caketown_1-OGA-mat-pablo.ogg" -- The names of the tilesets used, with the path and file extension omitted tileset_filenames = {} tileset_filenames[1] = "building_interior_objects_01" tileset_filenames[2] = "mountain_house_interior" tileset_filenames[3] = "village_exterior" -- The map grid to indicate walkability. The size of the grid is 4x the size of the tile layer tables -- Walkability status of tiles for 32 contexts. Zero indicates walkable for all contexts. Valid range: [0:2^32-1] -- Example: 1 (BIN 001) = wall for first context only, 2 (BIN 010) means wall for second context only, 5 (BIN 101) means Wall for first and third context. map_grid = {} map_grid[0] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[1] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[2] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[3] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[4] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[5] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[6] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[7] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[8] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[9] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[10] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[11] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[12] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[13] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[14] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[15] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[16] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[17] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[18] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[19] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[20] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[21] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[22] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[23] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[24] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[25] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[26] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[27] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[28] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[29] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[30] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[31] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[33] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[34] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[35] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[36] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[37] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[38] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[39] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[40] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[41] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[42] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[43] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[44] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[45] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[46] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_grid[47] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } -- The tile layers. The numbers are indeces to the tile_mappings table. layers = {} layers[0] = {} layers[0].type = "ground" layers[0].name = "Background" layers[0][0] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][1] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][2] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][4] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 196, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][5] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 368, 369, 370, 370, 371, 370, 197, 226, 198, 371, 370, 371, 372, 373, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][6] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 384, 385, 386, 386, 387, 386, 226, 226, 226, 387, 386, 387, 388, 389, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][7] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 400, 401, 402, 402, 403, 402, 226, 226, 226, 403, 402, 403, 404, 405, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][8] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 416, 419, 419, 224, 227, 226, 226, 226, 226, 226, 419, 419, 419, 421, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][9] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 432, 435, 419, 419, 419, 419, 419, 419, 435, 419, 419, 419, 419, 437, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][10] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 416, 224, 419, 435, 419, 419, 419, 419, 435, 419, 419, 435, 419, 421, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][11] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 432, 435, 435, 419, 435, 435, 419, 419, 435, 419, 435, 419, 419, 437, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][12] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 448, 435, 419, 419, 419, 419, 419, 419, 435, 435, 419, 419, 419, 453, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][13] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 464, 435, 435, 435, 435, 435, 435, 435, 435, 419, 419, 419, 419, 469, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][14] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 368, 369, 370, 371, 408, 419, 419, 419, 419, 407, 370, 371, 372, 373, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][15] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 384, 385, 386, 387, 424, 435, 435, 435, 435, 423, 386, 387, 388, 389, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][16] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 400, 401, 402, 403, 440, 419, 419, 419, 419, 439, 402, 403, 404, 405, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 419, 419, 419, 419, 435, 435, 419, 435, 419, 419, 419, 419, 421, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][18] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 435, 435, 419, 435, 419, 419, 435, 419, 435, 435, 435, 435, 437, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][19] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 416, 419, 419, 435, 419, 435, 435, 419, 435, 419, 419, 419, 419, 421, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][20] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 432, 435, 435, 419, 435, 419, 435, 435, 419, 435, 435, 419, 435, 437, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][21] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 448, 419, 419, 435, 419, 435, 419, 419, 435, 419, 419, 435, 435, 453, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 464, 435, 435, 435, 435, 419, 435, 435, 419, 435, 435, 419, 419, 469, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[0][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 432, 418, 434, 437, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1] = {} layers[1].type = "ground" layers[1].name = "Background 2" layers[1][0] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][1] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][2] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][4] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][5] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][6] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][7] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 195, -1, 197, 197, 208, 176, 177, 178, 198, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][8] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 209, -1, -1, -1, -1, 192, 193, 194, -1, -1, -1, 420, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][9] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 196, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][10] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][11] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 547, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][12] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 548, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][13] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][14] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 409, -1, -1, 406, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][15] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 425, -1, -1, 422, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][16] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 441, -1, -1, 438, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 416, 417, -1, -1, 456, 457, -1, -1, 454, 455, -1, -1, 420, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][18] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 432, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][19] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][20] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 513, 514, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][21] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 528, 529, 530, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 545, 546, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[1][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2] = {} layers[2].type = "ground" layers[2].name = "Background 3" layers[2][0] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][1] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][2] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][4] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][5] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][6] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 16, 17, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][7] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 32, 33, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][8] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][9] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][10] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][11] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][12] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][13] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][14] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][15] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][16] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][18] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][19] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][20] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][21] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[2][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3] = {} layers[3].type = "sky" layers[3].name = "Sky" layers[3][0] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][1] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][2] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][4] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][5] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][6] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][7] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][8] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][9] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][10] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][11] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][12] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 449, -1, -1, 376, 377, -1, -1, 374, 375, -1, -1, 452, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][13] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 465, 466, 467, 392, 393, -1, -1, 390, 391, 466, 467, 468, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][14] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][15] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][16] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 400, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 405, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 416, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 421, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][18] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 432, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 437, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][19] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 416, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 421, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][20] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 432, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 437, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][21] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 449, -1, -1, -1, 376, 377, 374, 375, -1, -1, -1, 452, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 465, 466, 467, 466, 392, 393, 390, 391, 467, 466, 467, 468, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } layers[3][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } -- Valyria Tear map editor end. Do not edit this line. Place your scripts after this line. -- -- the main character handler local bronann = {}; -- the main map loading code function Load(m) Map = m; ObjectManager = Map.object_supervisor; DialogueManager = Map.dialogue_supervisor; EventManager = Map.event_supervisor; Map.unlimited_stamina = true; _CreateCharacters(); _CreateObjects(); -- Set the camera focus on bronann Map:SetCamera(bronann); _CreateEvents(); _CreateZones(); -- The only entrance close door sound AudioManager:PlaySound("snd/door_close.wav"); end -- the map update function handles checks done on each game tick. function Update() -- Check whether the character is in one of the zones _CheckZones(); end -- Character creation function _CreateCharacters() bronann = CreateSprite(Map, "Bronann", 32, 45); bronann:SetDirection(hoa_map.MapMode.NORTH); bronann:SetMovementSpeed(hoa_map.MapMode.NORMAL_SPEED); Map:AddGroundObject(bronann); end function _CreateObjects() object = {} -- Bronann's room object = CreateObject(Map, "Bed1", 42, 27); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Box1", 23, 18); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Chair1_inverted", 39, 20); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Small Wooden Table", 42, 21); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Candle1", 43, 19); object:SetDrawOnSecondPass(true); -- Above the table if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Left Window Light", 20, 38); object:SetDrawOnSecondPass(true); -- Above any other ground object object:SetCollisionMask(hoa_map.MapMode.NO_COLLISION); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Clock1", 33, 13); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Table1", 39, 42); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Chair1_inverted", 35, 41); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Chair1", 43, 40); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Bench2", 39, 38); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Barrel1", 21, 36); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Barrel1", 22, 37); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Barrel1", 21, 41); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Barrel1", 23, 40); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Barrel1", 25, 39); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Box1", 21, 39); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Flower Pot1", 25, 16); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Right Window Light", 44, 38); object:SetDrawOnSecondPass(true); -- Above any other ground object object:SetCollisionMask(hoa_map.MapMode.NO_COLLISION); if (object ~= nil) then Map:AddGroundObject(object) end; end -- Creates all events and sets up the entire event sequence chain function _CreateEvents() local event = {}; local dialogue = {}; local text = {}; -- Triggered events event = hoa_map.MapTransitionEvent("exit floor", "dat/maps/layna_village/layna_village_riverbank.lua", "from_riverbank_house"); EventManager:RegisterEvent(event); end -- Create the different map zones triggering events function _CreateZones() -- N.B.: left, right, top, bottom room_exit_zone = hoa_map.CameraZone(30, 34, 47, 48, hoa_map.MapMode.CONTEXT_01); Map:AddZone(room_exit_zone); end -- Check whether the active camera has entered a zone. To be called within Update() function _CheckZones() if (room_exit_zone:IsCameraEntering() == true) then bronann:SetMoving(false); EventManager:StartEvent("exit floor"); AudioManager:PlaySound("snd/door_open2.wav"); end end -- Map Custom functions -- Used through scripted events if (map_functions == nil) then map_functions = {} end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c85704698.lua
2
3450
--リサイコロ function c85704698.initial_effect(c) --Special Summon local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_DICE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c85704698.sptg) e1:SetOperation(c85704698.spop) c:RegisterEffect(e1) --Synchro Summon local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetCode(EVENT_FREE_CHAIN) e2:SetHintTiming(0,0x1c0) e2:SetRange(LOCATION_GRAVE) e2:SetCost(c85704698.syncost) e2:SetTarget(c85704698.syntg) e2:SetOperation(c85704698.synop) c:RegisterEffect(e2) end function c85704698.filter(c,e,tp) return c:IsSetCard(0x2016) and c:IsType(TYPE_TUNER) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c85704698.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c85704698.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c85704698.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c85704698.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) Duel.SetOperationInfo(0,CATEGORY_DICE,nil,0,tp,1) end function c85704698.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_DISABLE) e1:SetReset(RESET_EVENT+0x1fe0000) tc:RegisterEffect(e1,true) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_DISABLE_EFFECT) e2:SetReset(RESET_EVENT+0x1fe0000) tc:RegisterEffect(e2,true) Duel.SpecialSummonComplete() local lv=Duel.TossDice(tp,1) local e3=Effect.CreateEffect(e:GetHandler()) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_CHANGE_LEVEL) e3:SetValue(lv) e3:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e3) end end function c85704698.syncost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c85704698.mfilter(c) return c:IsSetCard(0x2016) and c:IsType(TYPE_TUNER) end function c85704698.cfilter(c,syn) return syn:IsSynchroSummonable(c) end function c85704698.spfilter(c,mg) return c:IsAttribute(ATTRIBUTE_WIND) and mg:IsExists(c85704698.cfilter,1,nil,c) end function c85704698.syntg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then local mg=Duel.GetMatchingGroup(c85704698.mfilter,tp,LOCATION_MZONE,0,nil) return Duel.IsExistingMatchingCard(c85704698.spfilter,tp,LOCATION_EXTRA,0,1,nil,mg) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA) end function c85704698.synop(e,tp,eg,ep,ev,re,r,rp) local mg=Duel.GetMatchingGroup(c85704698.mfilter,tp,LOCATION_MZONE,0,nil) local g=Duel.GetMatchingGroup(c85704698.spfilter,tp,LOCATION_EXTRA,0,nil,mg) if g:GetCount()>0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local sg=g:Select(tp,1,1,nil) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SMATERIAL) local tg=mg:FilterSelect(tp,c85704698.cfilter,1,1,nil,sg:GetFirst()) Duel.SynchroSummon(tp,sg:GetFirst(),tg:GetFirst()) end end
gpl-2.0
Team-CC-Corp/ClamShell
tools/glep.lua
1
1257
local argparse = grin.getPackageAPI("Team-CC-Corp/Grin", "argparse") local parser = argparse.new() parser :argument"pattern" parser :switch"n" parser :argument"files" :count"*" local options = parser:parse({}, ...) if not options then return end local color = not options.n and term.isColour() local startColor = term.getTextColor() assert(options.pattern, "Usage: glep <pattern> [files]") local files if options.files and #options.files > 0 then files = {} for i,v in ipairs(options.files) do fh = grin.assert(fs.open(shell.resolve(v), "r"), "File not found: " .. v, 0) table.insert(files, fh) end else files = {stdin} end for i,fh in ipairs(files) do while true do local line = fh.readLine() if not line then break end local start, finish = line:find(options.pattern) if start then if color then write(line:sub(1, start - 1)) term.setTextColour(colors.red) write(line:sub(start, finish)) term.setTextColour(startColor) print(line:sub(finish + 1)) else print(line) end end end fh.close() end
mit
Turttle/darkstar
scripts/zones/Eastern_Altepa_Desert/npcs/Lindgard_IM.lua
30
3065
----------------------------------- -- Area: Eastern Altepa Desert -- NPC: Lindgard, I.M. -- Outpost Conquest Guards -- @pos -258.041 7.473 -254.527 114 ----------------------------------- package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Eastern_Altepa_Desert/TextIDs"); local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = KUZOTZ; local csid = 0x7ff9; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c25206027.lua
2
1235
--異界の棘紫竜 function c25206027.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(25206027,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP) e1:SetRange(LOCATION_HAND) e1:SetCode(EVENT_TO_GRAVE) e1:SetCondition(c25206027.spcon) e1:SetTarget(c25206027.sptg) e1:SetOperation(c25206027.spop) c:RegisterEffect(e1) end function c25206027.spfilter(c,tp) return c:IsReason(REASON_DESTROY) and c:IsPreviousLocation(LOCATION_MZONE) and c:GetPreviousControler()==tp and c:IsType(TYPE_MONSTER) end function c25206027.spcon(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c25206027.spfilter,1,nil,tp) end function c25206027.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsRelateToEffect(e) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c25206027.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP) end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c61181383.lua
9
1296
--充電器 function c61181383.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(c61181383.cost) e1:SetTarget(c61181383.target) e1:SetOperation(c61181383.activate) c:RegisterEffect(e1) end function c61181383.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckLPCost(tp,500) end Duel.PayLPCost(tp,500) end function c61181383.filter(c,e,tp) return c:IsSetCard(0x28) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c61181383.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c61181383.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c61181383.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c61181383.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c61181383.activate(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
thedraked/darkstar
scripts/zones/Lufaise_Meadows/npcs/qm4.lua
14
1311
----------------------------------- -- Area: Lufaise Meadows -- NPC: ??? - spawns Splinterspine Grukjuk for quest "A Hard Day's Knight" -- @pos -38.605 -9.022 -290.700 24 ----------------------------------- package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Lufaise_Meadows/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- NOTE: uncertain of retailness of messages. Had expected but did not find any csid. if (GetMobAction(16875774) == 0 and player:getQuestStatus(OTHER_AREAS,A_HARD_DAY_S_KNIGHT) == QUEST_ACCEPTED and player:getVar("SPLINTERSPINE_GRUKJUK") <= 1) then player:messageSpecial(SURVEY_THE_SURROUNDINGS); player:messageSpecial(MURDEROUS_PRESENCE); player:setVar("SPLINTERSPINE_GRUKJUK",1); SpawnMob(16875774):updateClaim(player); -- Splinterspine Grukjuk else player:messageSpecial(YOU_CAN_SEE_FOR_MALMS); player:messageSpecial(NOTHING_OUT_OF_THE_ORDINARY); end end;
gpl-3.0
SnabbCo/snabbswitch
src/apps/lwaftr/constants.lua
10
2283
module(..., package.seeall) local ffi = require("ffi") local C = ffi.C -- IPv6 next-header values -- http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml proto_icmp = 1 proto_ipv4 = 4 proto_tcp = 6 proto_udp = 17 ipv6_frag = 44 proto_icmpv6 = 58 -- Ethernet types -- http://www.iana.org/assignments/ieee-802-numbers/ieee-802-numbers.xhtml ethertype_ipv4 = 0x0800 ethertype_ipv6 = 0x86DD n_ethertype_ipv4 = C.htons(0x0800) n_ethertype_ipv6 = C.htons(0x86DD) n_ethertype_arp = C.htons(0x0806) -- ICMPv4 types icmpv4_echo_reply = 0 icmpv4_dst_unreachable = 3 icmpv4_echo_request = 8 icmpv4_time_exceeded = 11 -- ICMPv4 codes icmpv4_ttl_exceeded_in_transit = 0 icmpv4_host_unreachable = 1 icmpv4_datagram_too_big_df = 4 -- ICMPv6 types icmpv6_dst_unreachable = 1 icmpv6_packet_too_big = 2 icmpv6_time_limit_exceeded = 3 icmpv6_parameter_problem = 4 icmpv6_echo_request = 128 icmpv6_echo_reply = 129 icmpv6_ns = 135 icmpv6_na = 136 -- ICMPv6 codes icmpv6_code_packet_too_big = 0 icmpv6_hop_limit_exceeded = 0 icmpv6_failed_ingress_egress_policy = 5 -- Header sizes ethernet_header_size = 14 -- TODO: deal with 802.1Q tags/other extensions? ipv6_fixed_header_size = 40 ipv6_frag_header_size = 8 ipv6_pseudoheader_size = 40 icmp_base_size = 8 -- size excluding the IP header/playload max_icmpv4_packet_size = 576 -- RFC 1812 max_icmpv6_packet_size = 1280 -- 802.1q dotq_tpid = 0x8100 -- Offsets, 0-indexed o_ethernet_dst_addr = 0 o_ethernet_src_addr = 6 o_ethernet_ethertype = 12 o_ipv4_ver_and_ihl = 0 o_ipv4_dscp_and_ecn = 1 o_ipv4_total_length = 2 o_ipv4_identification = 4 o_ipv4_flags = 6 o_ipv4_ttl = 8 o_ipv4_proto = 9 o_ipv4_checksum = 10 o_ipv4_src_addr = 12 o_ipv4_dst_addr = 16 o_ipv6_payload_len = 4 o_ipv6_next_header = 6 o_ipv6_hop_limit = 7 o_ipv6_src_addr = 8 o_ipv6_dst_addr = 24 o_ipv6_frag_offset = 2 o_ipv6_frag_id = 4 o_icmpv4_msg_type = 0 o_icmpv4_msg_code = 1 o_icmpv4_checksum = 2 o_icmpv4_echo_identifier = 4 o_icmpv6_msg_type = 0 o_icmpv6_msg_code = 1 o_icmpv6_checksum = 2 -- Config values default_ttl = 255 min_ipv6_mtu = 1280 -- The following should actually be 2^16, but that will require support for -- larger packets. TODO FIXME ipv6_max_packet_size = C.PACKET_PAYLOAD_SIZE ipv4_max_packet_size = C.PACKET_PAYLOAD_SIZE
apache-2.0
mtroyka/Zero-K
effects/nuke_600.lua
24
15878
-- nuke_600_landcloud_pillar -- nuke_600_landcloud_topcap -- nuke_600_seacloud_cap -- nuke_600_landcloud -- nuke_600_seacloud_topcap -- nuke_600_landcloud_ring -- nuke_600_seacloud -- nuke_600_landcloud_cap -- nuke_600 -- nuke_600_seacloud_ring -- nuke_600_seacloud_pillar return { ["nuke_600_landcloud_pillar"] = { land = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, alwaysvisible = true, colormap = [[0 0 0 0 1 1 0.5 1 1 0.75 0.5 0.75 0.25 0.25 0.25 0.5 0 0 0 0]], directional = false, emitrot = 0, emitrotspread = 90, emitvector = [[0, 1, 0]], gravity = [[0, 0.05, 0]], numparticles = 1, particlelife = 240, particlelifespread = 40, particlesize = 4, particlesizespread = 4, particlespeed = 1, particlespeedspread = 1, pos = [[0, 0, 0]], sizegrowth = 64, sizemod = 0.75, texture = [[smokesmall]], }, }, }, ["nuke_600_landcloud_topcap"] = { land = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, alwaysvisible = true, colormap = [[0 0 0 0 1 1 0 1 1 1 1 0.75 0.25 0.25 0.25 0.5 0 0 0 0]], directional = false, emitrot = 90, emitrotspread = 5, emitvector = [[0, 1, 0]], gravity = [[0, 0.05, 0]], numparticles = 4, particlelife = 240, particlelifespread = 40, particlesize = 4, particlesizespread = 4, particlespeed = 4, particlespeedspread = 4, pos = [[0, 0, 0]], sizegrowth = 64, sizemod = 0.75, texture = [[fireball]], }, }, }, ["nuke_600_seacloud_cap"] = { cloud = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, underwater = true, properties = { airdrag = 0.97, alwaysvisible = true, colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]], directional = false, emitrot = 90, emitrotspread = 5, emitvector = [[0, 1, 0]], gravity = [[0, 0.05, 0]], numparticles = 4, particlelife = 30, particlelifespread = 20, particlesize = 4, particlesizespread = 4, particlespeed = 4, particlespeedspread = 4, pos = [[0, 0, 0]], sizegrowth = 64, sizemod = 0.75, texture = [[smokesmall]], }, }, }, ["nuke_600_landcloud"] = { usedefaultexplosions = false, cap = { air = true, class = [[CExpGenSpawner]], count = 96, ground = true, water = true, properties = { delay = [[i1]], dir = [[dir]], explosiongenerator = [[custom:NUKE_600_LANDCLOUD_CAP]], pos = [[0, i8, 0]], }, }, pillar = { air = true, class = [[CExpGenSpawner]], count = 128, ground = true, water = true, properties = { delay = [[i1]], dir = [[dir]], explosiongenerator = [[custom:NUKE_600_LANDCLOUD_PILLAR]], pos = [[0, i8, 0]], }, }, ring = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 64, dir = [[dir]], explosiongenerator = [[custom:NUKE_600_LANDCLOUD_RING]], pos = [[0, 512, 0]], }, }, topcap = { air = true, class = [[CExpGenSpawner]], count = 32, ground = true, water = true, properties = { delay = [[96 i1]], dir = [[dir]], explosiongenerator = [[custom:NUKE_600_LANDCLOUD_TOPCAP]], pos = [[0, 768 i8, 0]], }, }, }, ["nuke_600_seacloud_topcap"] = { cloud = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, underwater = true, properties = { airdrag = 0.97, alwaysvisible = true, colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]], directional = false, emitrot = 90, emitrotspread = 5, emitvector = [[0, 1, 0]], gravity = [[0, 0.05, 0]], numparticles = 4, particlelife = 240, particlelifespread = 40, particlesize = 4, particlesizespread = 4, particlespeed = 4, particlespeedspread = 4, pos = [[0, 0, 0]], sizegrowth = 64, sizemod = 0.75, texture = [[smokesmall]], }, }, }, ["nuke_600_landcloud_ring"] = { land = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, alwaysvisible = true, colormap = [[0 0 0 0 1 1 0.75 1 1 0.75 0.5 1 0.75 0.75 0.75 1 0 0 0 0]], directional = false, emitrot = 90, emitrotspread = 5, emitvector = [[0, 1, 0]], gravity = [[0, 0.05, 0]], numparticles = 128, particlelife = 240, particlelifespread = 40, particlesize = 4, particlesizespread = 4, particlespeed = 16, particlespeedspread = 1, pos = [[0, 0, 0]], sizegrowth = 32, sizemod = 0.5, texture = [[smokesmall]], }, }, }, ["nuke_600_seacloud"] = { usedefaultexplosions = false, cap = { air = true, class = [[CExpGenSpawner]], count = 96, ground = true, water = true, underwater = true, properties = { delay = [[i1]], dir = [[dir]], explosiongenerator = [[custom:NUKE_600_SEACLOUD_CAP]], pos = [[0, i8, 0]], }, }, pillar = { air = true, class = [[CExpGenSpawner]], count = 128, ground = true, water = true, underwater = true, properties = { delay = [[i1]], dir = [[dir]], explosiongenerator = [[custom:NUKE_600_SEACLOUD_PILLAR]], pos = [[0, i8, 0]], }, }, ring = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, underwater = true, properties = { delay = 64, dir = [[dir]], explosiongenerator = [[custom:NUKE_600_SEACLOUD_RING]], pos = [[0, 512, 0]], }, }, topcap = { air = true, class = [[CExpGenSpawner]], count = 32, ground = true, water = true, underwater = true, properties = { delay = [[96 i1]], dir = [[dir]], explosiongenerator = [[custom:NUKE_600_SEACLOUD_TOPCAP]], pos = [[0, 768 i8, 0]], }, }, }, ["nuke_600_landcloud_cap"] = { land = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, alwaysvisible = true, colormap = [[0 0 0 0 1 1 0 1 1 1 1 0.75 0.25 0.25 0.25 0.5 0 0 0 0]], directional = false, emitrot = 90, emitrotspread = 5, emitvector = [[0, 1, 0]], gravity = [[0, 0.05, 0]], numparticles = 4, particlelife = 30, particlelifespread = 20, particlesize = 4, particlesizespread = 4, particlespeed = 4, particlespeedspread = 4, pos = [[0, 0, 0]], sizegrowth = 64, sizemod = 0.75, texture = [[fireball]], }, }, }, ["nuke_600"] = { usedefaultexplosions = false, groundflash = { alwaysvisible = true, circlealpha = 1, circlegrowth = 10, flashalpha = 0.5, flashsize = 1200, ttl = 60, color = { [1] = 1, [2] = 0.5, [3] = 0, }, }, landcloud = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, properties = { delay = 30, dir = [[dir]], explosiongenerator = [[custom:NUKE_600_LANDCLOUD]], pos = [[0, 0, 0]], }, }, landdirt = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, properties = { airdrag = 0.95, alwaysvisible = true, colormap = [[0 0 0 0 0.5 0.4 0.3 1 0.6 0.4 0.2 0.75 0.5 0.4 0.3 0.5 0 0 0 0]], directional = false, emitrot = 85, emitrotspread = 5, emitvector = [[0, 1, 0]], gravity = [[0, 0.025, 0]], numparticles = 64, particlelife = 120, particlelifespread = 20, particlesize = 4, particlesizespread = 4, particlespeed = 2, particlespeedspread = 12, pos = [[0, 0, 0]], sizegrowth = 32, sizemod = 0.75, texture = [[dirt]], }, }, pikes = { air = true, class = [[explspike]], count = 32, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.006, alwaysvisible = true, color = [[1,0.5,0.1]], dir = [[-8 r16, -8 r16, -8 r16]], length = 1, lengthgrowth = 1, width = 64, }, }, seacloud = { class = [[CExpGenSpawner]], count = 1, water = true, underwater = true, properties = { delay = 30, dir = [[dir]], explosiongenerator = [[custom:NUKE_600_SEACLOUD]], pos = [[0, 0, 0]], }, }, sphere = { air = true, class = [[CSpherePartSpawner]], count = 1, ground = true, water = true, properties = { alpha = 0.5, alwaysvisible = true, color = [[1,1,0.5]], expansionspeed = 15, ttl = 80, }, }, watermist = { class = [[CSimpleParticleSystem]], count = 1, water = true, underwater = true, properties = { airdrag = 0.99, alwaysvisible = true, colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]], directional = false, emitrot = 0, emitrotspread = 90, emitvector = [[0, 1, 0]], gravity = [[0, -0.05, 0]], numparticles = 64, particlelife = 80, particlelifespread = 20, particlesize = 7, particlesizespread = 4, particlespeed = 8, particlespeedspread = 1, pos = [[0, 0, 0]], sizegrowth = 2, sizemod = 1, texture = [[smokesmall]], }, }, }, ["nuke_600_seacloud_ring"] = { cloud = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, underwater = true, properties = { airdrag = 0.97, alwaysvisible = true, colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]], directional = false, emitrot = 90, emitrotspread = 5, emitvector = [[0, 1, 0]], gravity = [[0, 0.05, 0]], numparticles = 128, particlelife = 240, particlelifespread = 40, particlesize = 4, particlesizespread = 4, particlespeed = 16, particlespeedspread = 1, pos = [[0, 0, 0]], sizegrowth = 32, sizemod = 0.5, texture = [[smokesmall]], }, }, }, ["nuke_600_seacloud_pillar"] = { cloud = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, underwater = true, properties = { airdrag = 0.97, alwaysvisible = true, colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]], directional = false, emitrot = 0, emitrotspread = 90, emitvector = [[0, 1, 0]], gravity = [[0, 0.05, 0]], numparticles = 1, particlelife = 240, particlelifespread = 40, particlesize = 4, particlesizespread = 4, particlespeed = 1, particlespeedspread = 1, pos = [[0, 0, 0]], sizegrowth = 64, sizemod = 0.75, texture = [[smokesmall]], }, }, }, }
gpl-2.0
thedraked/darkstar
scripts/zones/Mount_Kamihr/Zone.lua
30
1254
----------------------------------- -- -- Zone: Mount Kamihr -- ----------------------------------- package.loaded["scripts/zones/Mount_Kamihr/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Mount_Kamihr/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then -- player:setPos(x, y, z, r); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
mtroyka/Zero-K
LuaRules/Gadgets/ai_testing_functions.lua
3
8134
function gadget:GetInfo() return { name = "AI testing functions", desc = "Test small parts of AI.", author = "Google Frog", date = "April 20 2014", license = "GNU GPL, v2 or later", layer = 0, enabled = false -- loaded by default? } end local ceil = math.ceil local floor = math.floor local max = math.max local min = math.min local sqrt = math.sqrt local MAP_WIDTH = Game.mapSizeX local MAP_HEIGHT = Game.mapSizeZ local PATH_SQUARE = 256 local PATH_MID = PATH_SQUARE/2 local PATH_X = ceil(MAP_WIDTH/PATH_SQUARE) local PATH_Z = ceil(MAP_HEIGHT/PATH_SQUARE) ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- if (gadgetHandler:IsSyncedCode()) and false then ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local HeatmapHandler = VFS.Include("LuaRules/Gadgets/CAI/HeatmapHandler.lua") local PathfinderGenerator = VFS.Include("LuaRules/Gadgets/CAI/PathfinderGenerator.lua") local AssetTracker = VFS.Include("LuaRules/Gadgets/CAI/AssetTracker.lua") local ScoutHandler = VFS.Include("LuaRules/Gadgets/CAI/ScoutHandler.lua") local UnitClusterHandler = VFS.Include("LuaRules/Gadgets/CAI/UnitClusterHandler.lua") --------------------------------------------------------------- -- Heatmapping --------------------------------------------------------------- local enemyForceHandler = AssetTracker.CreateAssetTracker(0,0) local aaHeatmap = HeatmapHandler.CreateHeatmap(256, 0) _G.heatmap = aaHeatmap.heatmap local scoutHandler = ScoutHandler.CreateScoutHandler(0) local enemyUnitCluster = UnitClusterHandler.CreateUnitCluster(0, 900) function gadget:UnitCreated(unitID, unitDefID, teamID) if teamID == 1 then enemyUnitCluster.AddUnit(unitID, UnitDefs[unitDefID].metalCost) end --scoutHandler.AddUnit(unitID) end function gadget:UnitDestroyed(unitID, unitDefID, teamID) if teamID == 1 then enemyUnitCluster.RemoveUnit(unitID) end end --------------------------------------------------------------- -- Pathfinding --------------------------------------------------------------- -- veh, bot, spider, ship, hover, amph, air local paths = { --PathfinderGenerator.CreatePathfinder(UnitDefNames["correap"].id, "tank4", true), --PathfinderGenerator.CreatePathfinder(UnitDefNames["dante"].id, "kbot4", true), --PathfinderGenerator.CreatePathfinder(UnitDefNames["armcrabe"].id, "tkbot4", true), --PathfinderGenerator.CreatePathfinder(UnitDefNames["armmanni"].id, "hover3"), --PathfinderGenerator.CreatePathfinder(UnitDefNames["subraider"].id, "uboat3", true), --PathfinderGenerator.CreatePathfinder(UnitDefNames["amphassault"].id, "akbot4", true), --PathfinderGenerator.CreatePathfinder(UnitDefNames["armmanni"].id, "hover3"), --PathfinderGenerator.CreatePathfinder(), } --_G.pathMap = paths[1].pathMap --_G.botPathMap = botPath.pathMap --_G.amphPathMap = amphPath.pathMap --_G.hoverPathMap = hoverPath.pathMap --_G.shipPathMap = shipPath.pathMap function gadget:UnitEnteredLos(unitID, unitTeam, allyTeam, unitDefID) if allyTeam == 0 then local x, _,z = Spring.GetUnitPosition(unitID) aaHeatmap.AddUnitHeat(unitID, x, z, 780, 260 ) enemyForceHandler.AddUnit(unitID, unitDefID) end end function gadget:GameFrame(f) if f%60 == 14 then scoutHandler.UpdateHeatmap(f) scoutHandler.RunJobHandler() --Spring.Echo(scoutHandler.GetScoutedProportion()) end if f%30 == 3 then enemyUnitCluster.UpdateUnitPositions(200) for x,z,cost,count in enemyUnitCluster.ClusterIterator() do --Spring.MarkerAddPoint(x,0,z, cost .. " " .. count) end aaHeatmap.UpdateUnitPositions(true) end end function gadget:AllowCommand_GetWantedCommand() return {[CMD.MOVE] = true, [CMD.FIGHT] = true, [CMD.WAIT] = true} end function gadget:AllowCommand_GetWantedUnitDefID() return true end function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions) if cmdID == CMD.MOVE then --turretHeat.AddHeatCircle(cmdParams[1], cmdParams[3], 500, 50) return true end if cmdID == CMD.WAIT then return false --local economyList = enemyForceHandler.GetUnitList("economy") --economyList.UpdateClustering() --economyList.ExtractCluster() --local coord = economyList.GetClusterCoordinates() --Spring.Echo(#coord) --for i = 1, #coord do -- local c = coord[i] -- Spring.MarkerAddPoint(c[1],0,c[3], "Coord, " .. c[4] .. ", Count " .. c[5]) --end --local centriod = economyList.GetClusterCostCentroid() --Spring.Echo(#centriod) --for i = 1, #centriod do -- local c = centriod[i] -- Spring.MarkerAddPoint(c[1],0,c[3], "Centriod, Cost " .. c[4] .. ", Count " .. c[5]) --end ----turretHeat.AddHeatCircle(cmdParams[1], cmdParams[3], 500, 50) --return false end if cmdID == CMD.FIGHT then --vehPath.SetDefenseHeatmaps({aaHeatmap}) --local waypoints, waypointCount = vehPath.GetPath(1150, 650, cmdParams[1], cmdParams[3], false, 0.02) --if waypoints then -- for i = 1, waypointCount do -- Spring.MarkerAddPoint(waypoints[i].x, 0, waypoints[i].z,i) -- end --end return true end return true end function gadget:Initialize() for _, unitID in ipairs(Spring.GetAllUnits()) do local unitDefID = Spring.GetUnitDefID(unitID) local teamID = Spring.GetUnitTeam(unitID) gadget:UnitCreated(unitID, unitDefID, teamID) end end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- else -- UNSYNCED ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local function DrawLine(x0, y0, z0, c0, x1, y1, z1, c1) gl.Color(c0) gl.Vertex(x0, y0, z0) gl.Color(c1) gl.Vertex(x1, y1, z1) end local function DrawPathLink(start, finish, relation, color) if start.linkRelationMap[relation[1]] and start.linkRelationMap[relation[1]][relation[2]] then local sx, sz = start.x, start.z local fx, fz = finish.x, finish.z local sColor = ((SYNCED.heatmap[sx] and SYNCED.heatmap[sx][sz] and SYNCED.heatmap[sx][sz].value) or 0)*0.01 local fColor = ((SYNCED.heatmap[fx] and SYNCED.heatmap[fx][fz] and SYNCED.heatmap[fx][fz].value) or 0)*0.01 DrawLine( start.px, start.py, start.pz, {sColor, sColor, sColor, 1}, finish.px, finish.py, finish.pz, {fColor, fColor, fColor, 1} ) end end local function DrawGraph(array, color) for i = 1, PATH_X do for j = 1, PATH_Z do if i < PATH_X then DrawPathLink(array[i][j], array[i+1][j], {1,0}) end if j < PATH_Z then DrawPathLink(array[i][j], array[i][j+1], {0,1}) end end end end local function DrawPathMaps() --gl.LineWidth(10) --if SYNCED and SYNCED.shipPathMap then -- gl.BeginEnd(GL.LINES, DrawGraph, SYNCED.shipPathMap, {0,1,1,0.5}) --end --gl.LineWidth(7) --if SYNCED and SYNCED.hoverPathMap then -- gl.BeginEnd(GL.LINES, DrawGraph, SYNCED.hoverPathMap, {1,0,1,0.5}) --end --gl.LineWidth(5) --if SYNCED and SYNCED.amphPathMap then -- gl.BeginEnd(GL.LINES, DrawGraph, SYNCED.amphPathMap, {0.8,0.8,0,0.5}) --end --gl.LineWidth(3) --if SYNCED and SYNCED.botPathMap then -- gl.BeginEnd(GL.LINES, DrawGraph, SYNCED.botPathMap, {0,1,0.1,1}) --end gl.LineWidth(2) if SYNCED and SYNCED.pathMap and SYNCED.heatmap then gl.BeginEnd(GL.LINES, DrawGraph, SYNCED.pathMap) end end --function gadget:DrawWorldPreUnit() -- --DrawPathMaps() --end -- --function gadget:Initialize() -- gadgetHandler:AddSyncAction('SetHeatmapDrawData',SetHeatmapDrawData) --end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- end -- END UNSYNCED ------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------
gpl-2.0
thedraked/darkstar
scripts/zones/Outer_Horutoto_Ruins/npcs/Grounds_Tome.lua
30
1115
----------------------------------- -- Area: Outer Horutoto Ruins -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_OUTER_HORUTOTO_RUINS,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,663,664,665,666,667,668,669,670,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,663,664,665,666,667,668,669,670,0,0,GOV_MSG_OUTER_HORUTOTO_RUINS); end;
gpl-3.0
OpenNMT/OpenNMT
onmt/utils/FileReader.lua
1
3070
local FileReader = torch.class("FileReader") function FileReader:__init(filename, idxSent, featSequence) if filename == '-' then self.file = io.stdin else self.file = onmt.utils.Error.assert(io.open(filename, "r")) end self.idxSent = idxSent self.featSequence = featSequence end --[[ Read next line in the file and split it on spaces. If EOF is reached, returns nil. If skip - do not process the sentence, it will be skipped. ]] function FileReader:next(doTokenize) doTokenize = not (doTokenize == false) local line = self.file:read() local idx if line == nil then return nil end local sent = {} if self.idxSent then local p = line:find(" ") onmt.utils.Error.assert(p and p ~= 1, 'Invalid line - missing idx: '..line) idx = line:sub(1,p-1) line = line:sub(p+1) end if not self.featSequence then if doTokenize then for word in line:gmatch'([^ ]+)' do table.insert(sent, word) end else return line, idx end else local p = 1 while p<=#line and line:sub(p,p) == ' ' do p = p + 1 end assert(p <= #line and line:sub(p,p) == '[', 'Invalid feature start line (pos '..p..'): '..line) while p<=#line and line:sub(p,p) == ' ' do p = p + 1 end line = line:sub(p+1) if line == '' then line = self.file:read() end while true do local row = {} local hasEOS = false for tok in line:gmatch'([^%s]+)' do if tok == ']' then hasEOS=true break end table.insert(row, tok) end assert(hasEOS or #row ~= 0, 'Empty line in feature description: '..line) if #row > 0 then table.insert(sent, row) end if hasEOS then break end line = self.file:read() end end return sent, idx end function FileReader.countLines(filename, idx_files) if not idx_files and io.popen then local fwc = io.popen('wc -l '..filename) if fwc then local l = fwc:read('*all') fwc:close() if l then return tonumber(string.gmatch(l, "%d+")()) end end end local f = io.input(filename) local lc = 0 if not idx_files then local BUFSIZE = 2^13 while true do local lines, rest = f:read(BUFSIZE, "*line") if not lines then break end if rest then lines = lines .. rest .. '\n' end -- count newlines in the chunk local t t = select(2, string.gsub(lines, "\n", "\n")) lc = lc + t end else while true do local line = f:read() if not line then break end local p = line:find(" ") onmt.utils.Error.assert(p and p ~= 1, "Invalid line in file '"..filename.."' - missing idx: "..line) local multiline = line:find("%[") while line and multiline and not line:find("%]") do line = f:read() end onmt.utils.Error.assert(line, "Block not closed in file '"..filename.."'") lc = lc + 1 end end f:close() return lc end function FileReader:close() self.file:close() end return FileReader
mit
rjeli/luvit
examples/broken/web-app/modules/static.lua
8
5157
local fs = require 'fs' local pathJoin = require('path').join local osPathSep = require('path').sep local pathNormalize = require('path').normalize local urlParse = require('url').parse local getType = require('mime').getType local osType = require('os').type local osDate = require('os').date local iStream = require('core').iStream local floor = require('math').floor local table = require 'table' -- For encoding numbers using bases up to 64 local digits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "_", "$" } local function numToBase(num, base) local parts = {} repeat table.insert(parts, digits[(num % base) + 1]) num = floor(num / base) until num == 0 return table.concat(parts) end local function calcEtag(stat) return (not stat.is_file and 'W/' or '') .. '"' .. numToBase(stat.ino or 0, 64) .. '-' .. numToBase(stat.size, 64) .. '-' .. numToBase(stat.mtime, 64) .. '"' end local function createDirStream(path, options) local stream = iStream:new() fs.readdir(path, function (err, files) if err then stream:emit("error", err) end local html = { '<!doctype html>', '<html>', '<head>', '<title>' .. path .. '</title>', '</head>', '<body>', '<h1>' .. path .. '</h1>', '<ul><li><a href="../">..</a></li>' } for i, file in ipairs(files) do html[#html + 1] = '<li><a href="' .. file .. '">' .. file .. '</a></li>' end html[#html + 1] = '</ul></body></html>\n' html = table.concat(html) stream:emit("data", html) stream:emit("end") end) return stream end return function (app, options) if not options.root then error("options.root is required") end local root = options.root return function (req, res) -- Ignore non-GET/HEAD requests if not (req.method == "HEAD" or req.method == "GET") then return app(req, res) end local function serve(path, fallback) -- Windows doesn't allow to mix '/' and '\' within fs requests. if osType() == "win32" then path = path:gsub("/", osPathSep) path = pathNormalize(path) end fs.open(path, "r", function (err, fd) if err then if err.code == 'ENOENT' or err.code == 'ENOTDIR' then if fallback then return serve(fallback) end if err.code == 'ENOTDIR' and path:sub(#path) == osPathSep then return res(302, { ["Location"] = req.url.path:sub(1, #req.url.path - 1) }) end return app(req, res) end return res(500, {}, tostring(err) .. "\n" .. require('debug').traceback() .. "\n") end fs.fstat(fd, function (err, stat) if err then -- This shouldn't happen often, forward it just in case. fs.close(fd) return res(500, {}, tostring(err) .. "\n" .. require('debug').traceback() .. "\n") end local etag = calcEtag(stat) local code = 200 local headers = { ['Last-Modified'] = osDate("!%a, %d %b %Y %H:%M:%S GMT", stat.mtime), ['ETag'] = etag } local stream if etag == req.headers['if-none-match'] then code = 304 end if path:sub(#path) == osPathSep then -- We're done with the fd, createDirStream opens it again by path. fs.close(fd) if not options.autoIndex then -- Ignore directory requests if we don't have autoIndex on return app(req, res) end if not stat.is_directory then -- Can't autoIndex non-directories return res(302, { ["Location"] = req.url.path:sub(1, #req.url.path - 1) }) end headers["Content-Type"] = "text/html" -- Create the index stream if not (req.method == "HEAD" or code == 304) then stream = createDirStream(path, options.autoIndex) end else if stat.is_directory then -- Can't serve directories as files fs.close(fd) return res(302, { ["Location"] = req.url.path .. "/" }) end headers["Content-Type"] = getType(path) headers["Content-Length"] = stat.size if req.method ~= "HEAD" then stream = fs.createReadStream(nil, {fd=fd}) else fs.close(fd) end end res(code, headers, stream) end) end) end local path = pathJoin(options.root, req.url.path) if options.index and path:sub(#path) == '/' then serve(pathJoin(path, options.index), path) else serve(path) end end end
apache-2.0
thedraked/darkstar
scripts/zones/The_Shrine_of_RuAvitau/npcs/Monolith.lua
14
5393
----------------------------------- -- Area: The Shrine of Ru'Avitau -- NPC: Monolith -- @pos <many> ----------------------------------- package.loaded["scripts/zones/The_Shrine_of_RuAvitau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Shrine_of_RuAvitau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local npcID = npc:getID(); local Door_Offset = 17506718; -- _4y0 if (npcID == Door_Offset+31 or npcID == Door_Offset+33 or npcID == Door_Offset+35 or npcID == Door_Offset+37 or npcID == Door_Offset+43 or npcID == Door_Offset+45 or npcID == Door_Offset+51 or npcID == Door_Offset+53 or npcID == Door_Offset+61) then GetNPCByID(Door_Offset+4):setAnimation(8); --blue door GetNPCByID(Door_Offset+5):setAnimation(8); GetNPCByID(Door_Offset+6):setAnimation(8); GetNPCByID(Door_Offset+7):setAnimation(8); GetNPCByID(Door_Offset+10):setAnimation(8); GetNPCByID(Door_Offset+11):setAnimation(8); GetNPCByID(Door_Offset+16):setAnimation(8); GetNPCByID(Door_Offset+17):setAnimation(8); GetNPCByID(Door_Offset+18):setAnimation(8); GetNPCByID(Door_Offset+20):setAnimation(8); GetNPCByID(Door_Offset+3):setAnimation(9); --yellow door GetNPCByID(Door_Offset+2):setAnimation(9); GetNPCByID(Door_Offset+1):setAnimation(9); GetNPCByID(Door_Offset):setAnimation(9); GetNPCByID(Door_Offset+12):setAnimation(9); GetNPCByID(Door_Offset+13):setAnimation(9); GetNPCByID(Door_Offset+14):setAnimation(9); GetNPCByID(Door_Offset+15):setAnimation(9); GetNPCByID(Door_Offset+19):setAnimation(9); GetNPCByID(Door_Offset+21):setAnimation(9); GetNPCByID(Door_Offset+30):setAnimation(8); --blue monolith GetNPCByID(Door_Offset+32):setAnimation(8); GetNPCByID(Door_Offset+34):setAnimation(8); GetNPCByID(Door_Offset+36):setAnimation(8); GetNPCByID(Door_Offset+42):setAnimation(8); GetNPCByID(Door_Offset+44):setAnimation(8); GetNPCByID(Door_Offset+50):setAnimation(8); GetNPCByID(Door_Offset+52):setAnimation(8); GetNPCByID(Door_Offset+60):setAnimation(8); GetNPCByID(Door_Offset+22):setAnimation(9); --yellow monolith GetNPCByID(Door_Offset+24):setAnimation(9); GetNPCByID(Door_Offset+26):setAnimation(9); GetNPCByID(Door_Offset+28):setAnimation(9); GetNPCByID(Door_Offset+46):setAnimation(9); GetNPCByID(Door_Offset+48):setAnimation(9); GetNPCByID(Door_Offset+54):setAnimation(9); GetNPCByID(Door_Offset+56):setAnimation(9); GetNPCByID(Door_Offset+58):setAnimation(9); else GetNPCByID(Door_Offset+4):setAnimation(9); -- blue door GetNPCByID(Door_Offset+5):setAnimation(9); GetNPCByID(Door_Offset+6):setAnimation(9); GetNPCByID(Door_Offset+7):setAnimation(9); GetNPCByID(Door_Offset+10):setAnimation(9); GetNPCByID(Door_Offset+11):setAnimation(9); GetNPCByID(Door_Offset+16):setAnimation(9); GetNPCByID(Door_Offset+17):setAnimation(9); GetNPCByID(Door_Offset+18):setAnimation(9); GetNPCByID(Door_Offset+20):setAnimation(9); GetNPCByID(Door_Offset+3):setAnimation(8); -- yellow door GetNPCByID(Door_Offset+2):setAnimation(8); GetNPCByID(Door_Offset+1):setAnimation(8); GetNPCByID(Door_Offset):setAnimation(8); GetNPCByID(Door_Offset+12):setAnimation(8); GetNPCByID(Door_Offset+13):setAnimation(8); GetNPCByID(Door_Offset+14):setAnimation(8); GetNPCByID(Door_Offset+15):setAnimation(8); GetNPCByID(Door_Offset+19):setAnimation(8); GetNPCByID(Door_Offset+21):setAnimation(8); GetNPCByID(Door_Offset+30):setAnimation(9); --blue monolith GetNPCByID(Door_Offset+32):setAnimation(9); GetNPCByID(Door_Offset+34):setAnimation(9); GetNPCByID(Door_Offset+36):setAnimation(9); GetNPCByID(Door_Offset+42):setAnimation(9); GetNPCByID(Door_Offset+44):setAnimation(9); GetNPCByID(Door_Offset+50):setAnimation(9); GetNPCByID(Door_Offset+52):setAnimation(9); GetNPCByID(Door_Offset+60):setAnimation(9); GetNPCByID(Door_Offset+22):setAnimation(8); --yellow monolith GetNPCByID(Door_Offset+24):setAnimation(8); GetNPCByID(Door_Offset+26):setAnimation(8); GetNPCByID(Door_Offset+28):setAnimation(8); GetNPCByID(Door_Offset+46):setAnimation(8); GetNPCByID(Door_Offset+48):setAnimation(8); GetNPCByID(Door_Offset+54):setAnimation(8); GetNPCByID(Door_Offset+56):setAnimation(8); GetNPCByID(Door_Offset+58):setAnimation(8); 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
thedraked/darkstar
scripts/zones/Windurst_Waters/npcs/Angelica.lua
14
5826
----------------------------------- -- Area: Windurst Waters -- NPC: Angelica -- Starts and Finished Quest: A Pose By Any Other Name -- Working 100% -- @zone = 238 -- @pos = -70 -10 -6 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) posestatus = player:getQuestStatus(WINDURST,A_POSE_BY_ANY_OTHER_NAME); if (posestatus == QUEST_AVAILABLE and player:getVar("QuestAPoseByOtherName_prog") == 0 and player:needToZone() == false) then player:startEvent(0x0057); -- A POSE BY ANY OTHER NAME: Before Quest player:setVar("QuestAPoseByOtherName_prog",1); elseif (posestatus == QUEST_AVAILABLE and player:getVar("QuestAPoseByOtherName_prog") == 1) then player:setVar("QuestAPoseByOtherName_prog",2); mjob = player:getMainJob(); if (mjob == JOBS.WAR or mjob == JOBS.PLD or mjob == JOBS.DRK or mjob == JOBS.DRG or mjob == JOBS.COR) then -- Quest Start: Bronze Harness (War/Pld/Drk/Drg/Crs) player:startEvent(0x005c,0,0,0,12576); player:setVar("QuestAPoseByOtherName_equip",12576); elseif (mjob == JOBS.MNK or mjob == JOBS.BRD or mjob == JOBS.BLU) then -- Quest Start: Robe (Mnk/Brd/Blu) player:startEvent(0x005c,0,0,0,12600); player:setVar("QuestAPoseByOtherName_equip",12600); elseif (mjob == JOBS.THF or mjob == JOBS.BST or mjob == JOBS.RNG or mjob == JOBS.DNC) then -- Quest Start: Leather Vest (Thf/Bst/Rng/Dnc) player:startEvent(0x005c,0,0,0,12568); player:setVar("QuestAPoseByOtherName_equip",12568); elseif (mjob == JOBS.WHM or mjob == JOBS.BLM or mjob == JOBS.SMN or mjob == JOBS.PUP or mjob == JOBS.SCH) then -- Quest Start: Tunic (Whm/Blm/Rdm/Smn/Pup/Sch) player:startEvent(0x005c,0,0,0,12608); player:setVar("QuestAPoseByOtherName_equip",12608); elseif (mjob == JOBS.SAM or mjob == JOBS.NIN) then -- Quest Start: Kenpogi(Sam/Nin) player:startEvent(0x005c,0,0,0,12584); player:setVar("QuestAPoseByOtherName_equip",12584); end elseif (posestatus == QUEST_ACCEPTED) then starttime = player:getVar("QuestAPoseByOtherName_time"); if ((starttime + 600) >= os.time()) then if (player:getEquipID(SLOT_BODY) == player:getVar("QuestAPoseByOtherName_equip")) then player:startEvent(0x0060); ------------------------------------------ QUEST FINISH else player:startEvent(0x005d,0,0,0,player:getVar("QuestAPoseByOtherName_equip"));-- QUEST REMINDER end else player:startEvent(0x0066); ------------------------------------------ QUEST FAILURE end elseif (posestatus == QUEST_COMPLETED and player:needToZone()) then player:startEvent(0x0065); ----------------------------------------------- AFTER QUEST else rand = math.random(1,3); if (rand == 1) then player:startEvent(0x0056); -------------------------------------------- Standard Conversation 1 elseif (rand == 2) then player:startEvent(0x0058); -------------------------------------------- Standard Conversation 2 else player:startEvent(0x0059); -------------------------------------------- Standard Conversation 3 end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x005c) then -------------------------- QUEST START player:addQuest(WINDURST,A_POSE_BY_ANY_OTHER_NAME); player:setVar("QuestAPoseByOtherName_time",os.time()); elseif (csid == 0x0060) then --------------------- QUEST FINFISH if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,206); else player:completeQuest(WINDURST,A_POSE_BY_ANY_OTHER_NAME) player:addTitle(SUPER_MODEL); player:addItem(206); player:messageSpecial(ITEM_OBTAINED,206); player:addKeyItem(ANGELICAS_AUTOGRAPH); player:messageSpecial(KEYITEM_OBTAINED,ANGELICAS_AUTOGRAPH); player:addFame(WINDURST,75); player:setVar("QuestAPoseByOtherName_time",0); player:setVar("QuestAPoseByOtherName_equip",0); player:setVar("QuestAPoseByOtherName_prog",0); player:needToZone(true); end elseif (csid == 0x0066) then ---------------------- QUEST FAILURE player:delQuest(WINDURST,A_POSE_BY_ANY_OTHER_NAME); player:addTitle(LOWER_THAN_THE_LOWEST_TUNNEL_WORM); player:setVar("QuestAPoseByOtherName_time",0); player:setVar("QuestAPoseByOtherName_equip",0); player:setVar("QuestAPoseByOtherName_prog",0); player:needToZone(true); end end;
gpl-3.0
thedraked/darkstar
scripts/zones/Leujaoam_Sanctum/instances/leujaoam_cleansing.lua
28
2422
----------------------------------- -- -- Assault: Leujaoam Cleansing -- ----------------------------------- require("scripts/globals/instance") local Leujaoam = require("scripts/zones/Leujaoam_Sanctum/IDs"); ----------------------------------- -- afterInstanceRegister ----------------------------------- function afterInstanceRegister(player) local instance = player:getInstance(); player:messageSpecial(Leujaoam.text.ASSAULT_01_START, 1); player:messageSpecial(Leujaoam.text.TIME_TO_COMPLETE, instance:getTimeLimit()); end; ----------------------------------- -- onInstanceCreated ----------------------------------- function onInstanceCreated(instance) for i,v in pairs(Leujaoam.mobs[1]) do SpawnMob(v, instance); end local rune = instance:getEntity(bit.band(Leujaoam.npcs.RUNE_OF_RELEASE, 0xFFF), TYPE_NPC); local box = instance:getEntity(bit.band(Leujaoam.npcs.ANCIENT_LOCKBOX, 0xFFF), TYPE_NPC); rune:setPos(476,8.479,39,49); box:setPos(476,8.479,40,49); instance:getEntity(bit.band(Leujaoam.npcs._1XN, 0xFFF), TYPE_NPC):setAnimation(8); end; ----------------------------------- -- onInstanceTimeUpdate ----------------------------------- function onInstanceTimeUpdate(instance, elapsed) updateInstanceTime(instance, elapsed, Leujaoam.text) end; ----------------------------------- -- onInstanceFailure ----------------------------------- function onInstanceFailure(instance) local chars = instance:getChars(); for i,v in pairs(chars) do v:messageSpecial(Leujaoam.text.MISSION_FAILED,10,10); v:startEvent(0x66); end end; ----------------------------------- -- onInstanceProgressUpdate ----------------------------------- function onInstanceProgressUpdate(instance, progress) if (progress >= 15) then instance:complete(); end end; ----------------------------------- -- onInstanceComplete ----------------------------------- function onInstanceComplete(instance) local chars = instance:getChars(); for i,v in pairs(chars) do v:messageSpecial(Leujaoam.text.RUNE_UNLOCKED_POS, 8, 8); end local rune = instance:getEntity(bit.band(Leujaoam.npcs.RUNE_OF_RELEASE, 0xFFF), TYPE_NPC); local box = instance:getEntity(bit.band(Leujaoam.npcs.ANCIENT_LOCKBOX, 0xFFF), TYPE_NPC); rune:setStatus(STATUS_NORMAL); box:setStatus(STATUS_NORMAL); end;
gpl-3.0
mtroyka/Zero-K
lups/ParticleClasses/SimpleParticles.lua
11
14267
-- $Id: SimpleParticles.lua 3171 2008-11-06 09:06:29Z det $ ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local SimpleParticles = {} SimpleParticles.__index = SimpleParticles local billShader,sizeUniform,frameUniform,rotUniform,movCoeffUniform local colormapUniform,colorsUniform = {},0 ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function SimpleParticles.GetInfo() return { name = "SimpleParticles", backup = "", --// backup class, if this class doesn't work (old cards,ati's,etc.) desc = "", layer = 0, --// extreme simply z-ordering :x --// gfx requirement fbo = false, shader = true, rtt = false, ctt = false, } end SimpleParticles.Default = { dlist = 0, emitVector = {0,1,0}, pos = {0,0,0}, --// start pos partpos = "0,0,0", --// particle relative start pos (can contain lua code!) layer = 0, --// visibility check los = true, airLos = true, radar = false, force = {0,0,0}, --// global effect force airdrag = 1, speed = 0, speedSpread = 0, life = 0, lifeSpread = 0, rotSpeed = 0, rotFactor = 0, --// we can't have a rotSpeedSpread cos of hardware limitation (you can't compute the airdrag in a shader), instead rotFactorSpread = 0, --// rotFactor+rotFactorSpread simulate it: vertex_pos = vertex * rot_matrix(alpha*rotFactor+rand()*rotFactorSpread) rotSpread = 0, --// this is >not< a rotSpeedSpread! it is an offset of the 0 angle, so not all particles start as upangles rotairdrag = 1, rot2Speed = 0, --// global effect rotation rot2airdrag = 1, --// global effect rotation airdrag emitRot = 0, emitRotSpread = 0, size = 0, sizeSpread = 0, sizeGrowth = 0, colormap = { {0, 0, 0, 0} }, --//max 12 entries srcBlend = GL.ONE, dstBlend = GL.ONE_MINUS_SRC_ALPHA, alphaTest = 0, --FIXME texture = '', count = 1, repeatEffect = false, --can be a number,too } ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- --// speed ups local abs = math.abs local sqrt = math.sqrt local rand = math.random local twopi= 2*math.pi local cos = math.cos local sin = math.sin local min = math.min local degreeToPI = math.pi/180 local spGetUnitViewPosition = Spring.GetUnitViewPosition local spGetPositionLosState = Spring.GetPositionLosState local spGetUnitLosState = Spring.GetUnitLosState local spIsSphereInView = Spring.IsSphereInView local spGetUnitRadius = Spring.GetUnitRadius local spGetProjectilePosition = Spring.GetProjectilePosition local IsPosInLos = Spring.IsPosInLos local IsPosInAirLos = Spring.IsPosInAirLos local IsPosInRadar = Spring.IsPosInRadar local glTexture = gl.Texture local glBlending = gl.Blending local glUniform = gl.Uniform local glUniformInt = gl.UniformInt local glPushMatrix = gl.PushMatrix local glPopMatrix = gl.PopMatrix local glTranslate = gl.Translate local glCreateList = gl.CreateList local glCallList = gl.CallList local glRotate = gl.Rotate local glColor = gl.Color local glUseShader = gl.UseShader local GL_QUADS = GL.QUADS local GL_SRC_ALPHA = GL.SRC_ALPHA local GL_ONE_MINUS_SRC_ALPHA = GL.ONE_MINUS_SRC_ALPHA local glBeginEnd = gl.BeginEnd local glMultiTexCoord= gl.MultiTexCoord local glVertex = gl.Vertex local ProcessParamCode = ProcessParamCode local ParseParamString = ParseParamString local Vmul = Vmul local Vlength = Vlength ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function SimpleParticles:CreateParticleAttributes(up, right, forward,partpos,n) local life, pos, speed, size, rot, rotFactor; local az = rand()*twopi; local ay = (self.emitRot + rand() * self.emitRotSpread) * degreeToPI; local a,b,c = cos(ay), cos(az)*sin(ay), sin(az)*sin(ay) speed = { up[1]*a - right[1]*b + forward[1]*c, up[2]*a - right[2]*b + forward[2]*c, up[3]*a - right[3]*b + forward[3]*c} speed = Vmul( speed, self.speed + rand() * self.speedSpread ) rot = rand()*self.rotSpread rotFactor = self.rotFactor + rand()*self.rotFactorSpread size = self.size + rand()*self.sizeSpread life = self.life + rand()*self.lifeSpread local part = {speed=Vlength(speed),rot=rot,size=size,life=life,i=n} pos = { ProcessParamCode(partpos, part) } return life, size, pos[1],pos[2],pos[3], speed[1],speed[2],speed[3], rot, rotFactor; end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function SimpleParticles:BeginDraw() glUseShader(billShader) end function SimpleParticles:EndDraw() glTexture(false) glBlending(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glUseShader(0) end function SimpleParticles:Draw() glTexture(self.texture) glBlending(self.srcBlend,self.dstBlend) glUniform(rotUniform, self.urot) glUniform(sizeUniform, self.usize) glUniform(frameUniform, self.frame) glUniform(movCoeffUniform, self.uMovCoeff) glUniformInt(colorsUniform, self.ncolors) for i=1,min(self.ncolors+1,12) do local color = self.colormap[i] glUniform( colormapUniform[i] , color[1], color[2], color[3], color[4] ) end local pos = self.pos local force = self.uforce local emit = self.emitVector glPushMatrix() glTranslate(pos[1],pos[2],pos[3]) glRotate(90,emit[1],emit[2],emit[3]) glRotate(self.urot2Speed,0,1,0) glTranslate(force[1],force[2],force[3]) glCallList(self.dlist) glPopMatrix() end local function DrawParticleForDList(size,life,x,y,z,dx,dy,dz,rot,rotFactor,colors) glMultiTexCoord(0,x,y,z,colors/life) glMultiTexCoord(1,dx,dy,dz,rot) glMultiTexCoord(2,size,rotFactor) glVertex(0,0) glVertex(1,0) glVertex(1,1) glVertex(0,1) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function SimpleParticles:Initialize() billShader = gl.CreateShader({ vertex = [[ uniform float size; uniform float rot; uniform float frame; uniform float movCoeff; uniform vec4 colormap[12]; uniform int colors; varying vec2 texCoord; void main() { //gl.MultiTexCoord(0,x,y,z,colors/life) //gl.MultiTexCoord(1,dx,dy,dz,rot) //gl.MultiTexCoord(2,size,rotFactor) //gl.Vertex(s,t) float cpos = frame*gl_MultiTexCoord0.w; int ipos1 = int(cpos); float psize = size+gl_MultiTexCoord2.x; if (ipos1>=colors || psize<=0.0) { // paste dead particles offscreen, this way we don't dump the fragment shader with it gl_Position = vec4(-2000.0,-2000.0,-2000.0,-2000.0); }else{ int ipos2 = ipos1+1; if (ipos2>colors) ipos2 = colors; gl_FrontColor = mix(colormap[ipos1],colormap[ipos2],fract(cpos)); // calc vertex position vec4 pos = vec4( gl_MultiTexCoord0.xyz + movCoeff * gl_MultiTexCoord1.xyz ,1.0); gl_Position = gl_ModelViewMatrix * pos; // calc particle rotation float alpha = (gl_MultiTexCoord1.w + rot) * 0.159 * gl_MultiTexCoord2.y; //0.159 := ~(1/2pi) float ca = cos(alpha); float sa = sin(alpha); mat2 rotation = mat2( ca , -sa, sa, ca ); // offset vertex from center of the polygon gl_Position.xy += rotation * ( (gl_Vertex.xy-0.5) * psize ); // end gl_Position = gl_ProjectionMatrix * gl_Position; texCoord = gl_Vertex.xy; } } ]], fragment = [[ uniform sampler2D tex0; varying vec2 texCoord; void main() { gl_FragColor = texture2D(tex0,texCoord) * gl_Color; } ]], uniformInt = { tex0 = 0, }, uniform = { size = 0, rot = 0, frame = 0, movCoeff = 0, }, }) if (billShader==nil) then print(PRIO_MAJOR,"LUPS->SimpleParticles: Critical Shader Error: " ..gl.GetShaderLog()) return false end rotUniform = gl.GetUniformLocation(billShader,"rot") sizeUniform = gl.GetUniformLocation(billShader,"size") frameUniform = gl.GetUniformLocation(billShader,"frame") movCoeffUniform = gl.GetUniformLocation(billShader,"movCoeff") colorsUniform = gl.GetUniformLocation(billShader,"colors") for i=1,12 do colormapUniform[i] = gl.GetUniformLocation(billShader,"colormap["..(i-1).."]") end end function SimpleParticles:Finalize() gl.DeleteShader(billShader) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function SimpleParticles:Update(n) if (n==1) then --// in the case of 1 frame we can use much faster equations self.uMovCoeff = self.airdrag^self.frame + self.uMovCoeff; self.urot = (self.urot + self.rotSpeed)*self.rotairdrag; else local rotBoost = 0 for i=1,n do rotBoost = self.rotSpeed*(self.rotairdrag^i) + rotBoost; self.uMovCoeff = self.airdrag^(self.frame+i) + self.uMovCoeff; end self.urot = (self.urot * (self.rotairdrag^n)) + rotBoost end self.usize = self.usize + n*self.sizeGrowth self.frame = self.frame + n self.urot2Speed = self.rot2Speed*self.frame self.uforce[1],self.uforce[2],self.uforce[3] = self.force[1]*self.frame,self.force[2]*self.frame,self.force[3]*self.frame end -- used if repeatEffect=true; function SimpleParticles:ReInitialize() self.frame = 0 self.usize = 0 self.urot = 0 self.uMovCoeff = 1 self.dieGameFrame = self.dieGameFrame + self.life + self.lifeSpread self.urot2Speed = 0 self.uforce[1],self.uforce[2],self.uforce[3] = 0,0,0 end local function InitializeParticles(self) -- calc base of the emitvector system local up = self.emitVector; local right = Vcross( up, {up[2],up[3],-up[1]} ); local forward = Vcross( up, right ); local partposCode = ParseParamString(self.partpos) self.maxSpawnRadius = 0 for i=1,self.count do local life,size,x,y,z,dx,dy,dz,rot,rotFactor = self:CreateParticleAttributes(up,right,forward, partposCode,i-1) glBeginEnd(GL_QUADS,DrawParticleForDList, size,life, x,y,z, -- relative start pos dx,dy,dz, -- speed vector rot,rotFactor, self.ncolors) local spawnDist = x*x + y*y + z*z if (spawnDist>self.maxSpawnRadius) then self.maxSpawnRadius=spawnDist end end self.maxSpawnRadius = sqrt(self.maxSpawnRadius) end function SimpleParticles:CreateParticle() self.ncolors = #self.colormap-1 self.dlist = glCreateList(InitializeParticles,self) self.frame = 0 self.firstGameFrame = thisGameFrame self.dieGameFrame = self.firstGameFrame + self.life + self.lifeSpread self.urot = 0 self.usize = 0 self.uMovCoeff = 1 self.urot2Speed = 0 self.uforce = {0,0,0} --// visibility check vars self.radius = self.size + self.sizeSpread + self.maxSpawnRadius + 100 self.maxSpeed = self.speed+ abs(self.speedSpread) self.forceStrength = Vlength(self.force) self.sphereGrowth = self.forceStrength+self.sizeGrowth end function SimpleParticles:Destroy() gl.DeleteList(self.dlist) --gl.DeleteTexture(self.texture) end function SimpleParticles:Visible() local radius = self.radius + self.uMovCoeff*self.maxSpeed + self.frame*self.sphereGrowth --FIXME: frame is only updated on Update() local posX,posY,posZ = self.pos[1],self.pos[2],self.pos[3] local losState if (self.unit and not self.worldspace) then losState = GetUnitLosState(self.unit) local ux,uy,uz = spGetUnitViewPosition(self.unit) posX,posY,posZ = posX+ux,posY+uy,posZ+uz radius = radius + spGetUnitRadius(self.unit) elseif (self.projectile and not self.worldspace) then local px,py,pz = spGetProjectilePosition(self.projectile) posX,posY,posZ = posX+px,posY+py,posZ+pz end if (losState==nil) then if (self.radar) then losState = IsPosInRadar(posX,posY,posZ) end if ((not losState) and self.airLos) then losState = IsPosInAirLos(posX,posY,posZ) end if ((not losState) and self.los) then losState = IsPosInLos(posX,posY,posZ) end end return (losState)and(spIsSphereInView(posX,posY,posZ,radius)) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local MergeTable = MergeTable local setmetatable = setmetatable function SimpleParticles.Create(Options) local newObject = MergeTable(Options, SimpleParticles.Default) setmetatable(newObject,SimpleParticles) --// make handle lookup newObject:CreateParticle() return newObject end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- return SimpleParticles
gpl-2.0
thedraked/darkstar
scripts/globals/items/serving_of_flint_caviar.lua
18
1422
----------------------------------------- -- ID: 4276 -- Item: serving_of_flint_caviar -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 10 -- Magic 10 -- Dexterity 4 -- Mind -1 -- Charisma 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4276); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_MP, 10); target:addMod(MOD_DEX, 4); target:addMod(MOD_MND, -1); target:addMod(MOD_CHR, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_MP, 10); target:delMod(MOD_DEX, 4); target:delMod(MOD_MND, -1); target:delMod(MOD_CHR, 4); end;
gpl-3.0
thedraked/darkstar
scripts/zones/RuAun_Gardens/npcs/HomePoint#5.lua
27
1265
----------------------------------- -- Area: RuAun_Gardens -- NPC: HomePoint#5 -- @pos 305 -42 -427 130 ----------------------------------- package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/RuAun_Gardens/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x2200, 63); 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 == 0x2200) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
NPLPackages/main
script/ide/Effect/stoneEffect.lua
1
2001
--[[ NPL.load("(gl)script/ide/Effect/stoneEffect.lua"); local StoneEffect = commonlib.gettable("MyCompany.Aries.StoneEffect"); --]] NPL.load("(gl)script/apps/Aries/Quest/NPC.lua"); local NPC = commonlib.gettable("MyCompany.Aries.Quest.NPC"); local StoneEffect = commonlib.gettable("MyCompany.Aries.StoneEffect"); local stone_shader_file = "script/ide/Effect/Shaders/stoneEffect.fxo"; local stone_effect_handle = 1103; local default_effect_handle = 12; function StoneEffect.CreateEffect() local effect = ParaAsset.GetEffectFile("stone"); if(effect:IsValid() == false)then LOG.std(nil,"debug","StoneEffect","shader file %s is loaded",stone_shader_file); effect = ParaAsset.LoadEffectFile("stone",stone_shader_file); effect = ParaAsset.GetEffectFile("stone"); effect:SetHandle(stone_effect_handle); local params = effect:GetParamBlock(); params:SetTexture(1,"Texture/Aries/ShaderResource/stoneNoise.dds"); else local handle = effect:GetHandle(); if(handle == -1)then effect:SetHandle(stone_effect_handle); end end return effect,stone_effect_handle; end function StoneEffect.ApplyEffect(character) if(character and character:IsValid())then local prevEffectHandle = character:GetField("render_tech", 0); if(prevEffectHandle < 100) then character:SetDynamicField("previousEffect", prevEffectHandle) end local effect,effectHandle = StoneEffect.CreateEffect(); character:SetField("render_tech",effectHandle); character:SetField("IsAnimPaused",true); return prevEffectHandle; end end function StoneEffect.ResetEffect(character,effectHandle) local prevEffect = effectHandle or default_effect_handle; if(character and character:IsValid())then character:SetField("render_tech",prevEffect); character:SetField("IsAnimPaused",false); end end function StoneEffect.Update() local effect = ParaAsset.GetEffectFile("stone"); if(effect and effect:IsValid())then local params = effect:GetParamBlock(); params:SetVector3("blendFactor",0.9,0,0); end end
gpl-2.0
thedraked/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Rytaal.lua
24
4539
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Rytaal -- Type: Standard NPC -- @pos 112.002 -1.338 -45.038 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/besieged"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local currentday = tonumber(os.date("%j")); local lastIDtag = player:getVar("LAST_IMPERIAL_TAG"); local tagCount = player:getCurrency("id_tags"); local diffday = currentday - lastIDtag ; local currentAssault = player:getCurrentAssault(); local haveimperialIDtag; if (player:getCurrentMission(TOAU) == PRESIDENT_SALAHEEM and player:getVar("AhtUrganStatus") == 0) then player:startEvent(269,0,0,0,0,0,0,0,0,0); elseif (player:getCurrentMission(TOAU) <= IMMORTAL_SENTRIES or player:getMainLvl() <= 49) then player:startEvent(270); elseif (currentAssault ~= 0 and hasAssaultOrders(player) == 0) then if (player:getVar("AssaultComplete") == 1) then player:messageText(player,RYTAAL_MISSION_COMPLETE); player:completeAssault(currentAssault); else player:messageText(player,RYTAAL_MISSION_FAILED); player:addAssault(0); end player:setVar("AssaultComplete",0); elseif ((player:getCurrentMission(TOAU) > PRESIDENT_SALAHEEM) or (player:getCurrentMission(TOAU) == PRESIDENT_SALAHEEM and player:getVar("AhtUrganStatus") >= 1)) then if (lastIDtag == 0) then -- first time you get the tag tagCount = 1; player:setCurrency("id_tags", tagCount); player:setVar("LAST_IMPERIAL_TAG",currentday); elseif (diffday > 0) then tagCount = tagCount + diffday ; if (tagCount > 3) then -- store 3 TAG max tagCount = 3; end player:setCurrency("id_tags", tagCount); player:setVar("LAST_IMPERIAL_TAG",currentday); end if (player:hasKeyItem(IMPERIAL_ARMY_ID_TAG)) then haveimperialIDtag = 1; else haveimperialIDtag = 0; end player:startEvent(268,IMPERIAL_ARMY_ID_TAG,tagCount,currentAssault,haveimperialIDtag); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local tagCount = player:getCurrency("id_tags"); local currentAssault = player:getCurrentAssault(); if (csid == 269) then player:setVar("AhtUrganStatus",1); elseif (csid == 268 and option == 1 and player:hasKeyItem(IMPERIAL_ARMY_ID_TAG) == false and tagCount > 0) then player:addKeyItem(IMPERIAL_ARMY_ID_TAG); player:messageSpecial(KEYITEM_OBTAINED,IMPERIAL_ARMY_ID_TAG); player:setCurrency("id_tags", tagCount - 1); elseif (csid == 268 and option == 2 and player:hasKeyItem(IMPERIAL_ARMY_ID_TAG) == false and hasAssaultOrders(player) ~= 0) then if (player:hasKeyItem(LEUJAOAM_ASSAULT_ORDERS)) then player:delKeyItem(LEUJAOAM_ASSAULT_ORDERS); elseif (player:hasKeyItem(MAMOOL_JA_ASSAULT_ORDERS)) then player:delKeyItem(MAMOOL_JA_ASSAULT_ORDERS); elseif (player:hasKeyItem(LEBROS_ASSAULT_ORDERS)) then player:delKeyItem(LEBROS_ASSAULT_ORDERS); elseif (player:hasKeyItem(PERIQIA_ASSAULT_ORDERS)) then player:delKeyItem(PERIQIA_ASSAULT_ORDERS); elseif (player:hasKeyItem(ILRUSI_ASSAULT_ORDERS )) then player:delKeyItem(ILRUSI_ASSAULT_ORDERS); elseif (player:hasKeyItem(NYZUL_ISLE_ASSAULT_ORDERS)) then player:delKeyItem(NYZUL_ISLE_ASSAULT_ORDERS); end player:addKeyItem(IMPERIAL_ARMY_ID_TAG); player:messageSpecial(KEYITEM_OBTAINED,IMPERIAL_ARMY_ID_TAG); player:delAssault(currentAssault); end end;
gpl-3.0
filug/nodemcu-firmware
lua_modules/lm92/lm92.lua
52
2140
-- ****************************************************** -- LM92 module for ESP8266 with nodeMCU -- -- Written by Levente Tamas <levente.tamas@navicron.com> -- -- GNU LGPL, see https://www.gnu.org/copyleft/lesser.html -- ****************************************************** -- Module Bits local moduleName = ... local M = {} _G[moduleName] = M -- Default ID local id = 0 -- Local vars local address = 0 -- read regs for len number of bytes -- return table with data local function read_reg(reg_addr, len) local ret={} local c local x i2c.start(id) i2c.address(id, address ,i2c.TRANSMITTER) i2c.write(id,reg_addr) i2c.stop(id) i2c.start(id) i2c.address(id, address,i2c.RECEIVER) c=i2c.read(id,len) for x=1,len,1 do tc=string.byte(c,x) table.insert(ret,tc) end i2c.stop(id) return ret end --write reg with data table local function write_reg(reg_addr, data) i2c.start(id) i2c.address(id, address, i2c.TRANSMITTER) i2c.write(id, reg_addr) i2c.write(id, data) i2c.stop(id) end -- initialize i2c -- d: sda -- c: scl -- a: i2c addr 0x48|A1<<1|A0 (A0-A1: chip pins) function M.init(d,c,a) if (d ~= nil) and (c ~= nil) and (d >= 0) and (d <= 11) and (c >= 0) and ( c <= 11) and (d ~= l) and (a ~= nil) and (a >= 0x48) and (a <= 0x4b ) then sda = d scl = c address = a i2c.start(id) res = i2c.address(id, address, i2c.TRANSMITTER) --verify that the address is valid i2c.stop(id) if (res == false) then print("device not found") return nil end else print("i2c configuration failed") return nil end i2c.setup(id,sda,scl,i2c.SLOW) end -- Return the temperature data function M.getTemperature() local temperature local tmp=read_reg(0x00,2) --read 2 bytes from the temperature register temperature=bit.rshift(tmp[1]*256+tmp[2],3) --lower 3 bits are status bits if (temperature>=0x1000) then temperature= temperature-0x2000 --convert the two's complement end return temperature * 0.0625 end -- Put the LM92 into shutdown mode function M.shutdown() write_reg(0x01,0x01) end -- Bring the LM92 out of shutdown mode function M.wakeup() write_reg(0x01,0x00) end return M
mit
lyzardiar/RETools
PublicTools/bin/tools/bin/ios/x86_64/jit/dis_x86.lua
61
29376
---------------------------------------------------------------------------- -- LuaJIT x86/x64 disassembler module. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- Sending small code snippets to an external disassembler and mixing the -- output with our own stuff was too fragile. So I had to bite the bullet -- and write yet another x86 disassembler. Oh well ... -- -- The output format is very similar to what ndisasm generates. But it has -- been developed independently by looking at the opcode tables from the -- Intel and AMD manuals. The supported instruction set is quite extensive -- and reflects what a current generation Intel or AMD CPU implements in -- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3, -- SSE4.1, SSE4.2, SSE4a and even privileged and hypervisor (VMX/SVM) -- instructions. -- -- Notes: -- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported. -- * No attempt at optimization has been made -- it's fast enough for my needs. -- * The public API may change when more architectures are added. ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local lower, rep = string.lower, string.rep local bit = require("bit") local tohex = bit.tohex -- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on. local map_opc1_32 = { --0x [0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es", "orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*", --1x "adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss", "sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds", --2x "andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa", "subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das", --3x "xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa", "cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas", --4x "incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR", "decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR", --5x "pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR", "popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR", --6x "sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr", "fs:seg","gs:seg","o16:","a16", "pushUi","imulVrmi","pushBs","imulVrms", "insb","insVS","outsb","outsVS", --7x "joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj", "jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj", --8x "arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms", "testBmr","testVmr","xchgBrm","xchgVrm", "movBmr","movVmr","movBrm","movVrm", "movVmg","leaVrm","movWgm","popUm", --9x "nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR", "xchgVaR","xchgVaR","xchgVaR","xchgVaR", "sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait", "sz*pushfw,pushf","sz*popfw,popf","sahf","lahf", --Ax "movBao","movVao","movBoa","movVoa", "movsb","movsVS","cmpsb","cmpsVS", "testBai","testVai","stosb","stosVS", "lodsb","lodsVS","scasb","scasVS", --Bx "movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi", "movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI", --Cx "shift!Bmu","shift!Vmu","retBw","ret","$lesVrm","$ldsVrm","movBmi","movVmi", "enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS", --Dx "shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb", "fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7", --Ex "loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj", "inBau","inVau","outBua","outVua", "callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda", --Fx "lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm", "clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm", } assert(#map_opc1_32 == 255) -- Map for 1st opcode byte in 64 bit mode (overrides only). local map_opc1_64 = setmetatable({ [0x06]=false, [0x07]=false, [0x0e]=false, [0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false, [0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false, [0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:", [0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb", [0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb", [0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb", [0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb", [0x82]=false, [0x9a]=false, [0xc4]=false, [0xc5]=false, [0xce]=false, [0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false, }, { __index = map_opc1_32 }) -- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you. -- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2 local map_opc2 = { --0x [0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret", "invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu", --1x "movupsXrm|movssXrm|movupdXrm|movsdXrm", "movupsXmr|movssXmr|movupdXmr|movsdXmr", "movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm", "movlpsXmr||movlpdXmr", "unpcklpsXrm||unpcklpdXrm", "unpckhpsXrm||unpckhpdXrm", "movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm", "movhpsXmr||movhpdXmr", "$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm", "hintnopVm","hintnopVm","hintnopVm","hintnopVm", --2x "movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil, "movapsXrm||movapdXrm", "movapsXmr||movapdXmr", "cvtpi2psXrMm|cvtsi2ssXrVmt|cvtpi2pdXrMm|cvtsi2sdXrVmt", "movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr", "cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm", "cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm", "ucomissXrm||ucomisdXrm", "comissXrm||comisdXrm", --3x "wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec", "opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil, --4x "cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm", "cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm", "cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm", "cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm", --5x "movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm", "rsqrtpsXrm|rsqrtssXrm","rcppsXrm|rcpssXrm", "andpsXrm||andpdXrm","andnpsXrm||andnpdXrm", "orpsXrm||orpdXrm","xorpsXrm||xorpdXrm", "addpsXrm|addssXrm|addpdXrm|addsdXrm","mulpsXrm|mulssXrm|mulpdXrm|mulsdXrm", "cvtps2pdXrm|cvtss2sdXrm|cvtpd2psXrm|cvtsd2ssXrm", "cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm", "subpsXrm|subssXrm|subpdXrm|subsdXrm","minpsXrm|minssXrm|minpdXrm|minsdXrm", "divpsXrm|divssXrm|divpdXrm|divsdXrm","maxpsXrm|maxssXrm|maxpdXrm|maxsdXrm", --6x "punpcklbwPrm","punpcklwdPrm","punpckldqPrm","packsswbPrm", "pcmpgtbPrm","pcmpgtwPrm","pcmpgtdPrm","packuswbPrm", "punpckhbwPrm","punpckhwdPrm","punpckhdqPrm","packssdwPrm", "||punpcklqdqXrm","||punpckhqdqXrm", "movPrVSm","movqMrm|movdquXrm|movdqaXrm", --7x "pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pmu", "pshiftd!Pmu","pshiftq!Mmu||pshiftdq!Xmu", "pcmpeqbPrm","pcmpeqwPrm","pcmpeqdPrm","emms|", "vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$", nil,nil, "||haddpdXrm|haddpsXrm","||hsubpdXrm|hsubpsXrm", "movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr", --8x "joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj", "jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj", --9x "setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm", "setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm", --Ax "push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil, "push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm", --Bx "cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr", "$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt", "|popcntVrm","ud2Dp","bt!Vmu","btcVmr", "bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt", --Cx "xaddBmr","xaddVmr", "cmppsXrmu|cmpssXrmu|cmppdXrmu|cmpsdXrmu","$movntiVmr|", "pinsrwPrWmu","pextrwDrPmu", "shufpsXrmu||shufpdXrmu","$cmpxchg!Qmp", "bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR", --Dx "||addsubpdXrm|addsubpsXrm","psrlwPrm","psrldPrm","psrlqPrm", "paddqPrm","pmullwPrm", "|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm", "psubusbPrm","psubuswPrm","pminubPrm","pandPrm", "paddusbPrm","padduswPrm","pmaxubPrm","pandnPrm", --Ex "pavgbPrm","psrawPrm","psradPrm","pavgwPrm", "pmulhuwPrm","pmulhwPrm", "|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr", "psubsbPrm","psubswPrm","pminswPrm","porPrm", "paddsbPrm","paddswPrm","pmaxswPrm","pxorPrm", --Fx "|||lddquXrm","psllwPrm","pslldPrm","psllqPrm", "pmuludqPrm","pmaddwdPrm","psadbwPrm","maskmovqMrm||maskmovdquXrm$", "psubbPrm","psubwPrm","psubdPrm","psubqPrm", "paddbPrm","paddwPrm","padddPrm","ud", } assert(map_opc2[255] == "ud") -- Map for three-byte opcodes. Can't wait for their next invention. local map_opc3 = { ["38"] = { -- [66] 0f 38 xx --0x [0]="pshufbPrm","phaddwPrm","phadddPrm","phaddswPrm", "pmaddubswPrm","phsubwPrm","phsubdPrm","phsubswPrm", "psignbPrm","psignwPrm","psigndPrm","pmulhrswPrm", nil,nil,nil,nil, --1x "||pblendvbXrma",nil,nil,nil, "||blendvpsXrma","||blendvpdXrma",nil,"||ptestXrm", nil,nil,nil,nil, "pabsbPrm","pabswPrm","pabsdPrm",nil, --2x "||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm", "||pmovsxwqXrm","||pmovsxdqXrm",nil,nil, "||pmuldqXrm","||pcmpeqqXrm","||$movntdqaXrm","||packusdwXrm", nil,nil,nil,nil, --3x "||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm", "||pmovzxwqXrm","||pmovzxdqXrm",nil,"||pcmpgtqXrm", "||pminsbXrm","||pminsdXrm","||pminuwXrm","||pminudXrm", "||pmaxsbXrm","||pmaxsdXrm","||pmaxuwXrm","||pmaxudXrm", --4x "||pmulddXrm","||phminposuwXrm", --Fx [0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt", }, ["3a"] = { -- [66] 0f 3a xx --0x [0x00]=nil,nil,nil,nil,nil,nil,nil,nil, "||roundpsXrmu","||roundpdXrmu","||roundssXrmu","||roundsdXrmu", "||blendpsXrmu","||blendpdXrmu","||pblendwXrmu","palignrPrmu", --1x nil,nil,nil,nil, "||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru", nil,nil,nil,nil,nil,nil,nil,nil, --2x "||pinsrbXrVmu","||insertpsXrmu","||pinsrXrVmuS",nil, --4x [0x40] = "||dppsXrmu", [0x41] = "||dppdXrmu", [0x42] = "||mpsadbwXrmu", --6x [0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu", [0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu", }, } -- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands). local map_opcvm = { [0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff", [0xc8]="monitor",[0xc9]="mwait", [0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave", [0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga", [0xf8]="swapgs",[0xf9]="rdtscp", } -- Map for FP opcodes. And you thought stack machines are simple? local map_opcfp = { -- D8-DF 00-BF: opcodes with a memory operand. -- D8 [0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm", "fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm", -- DA "fiaddDm","fimulDm","ficomDm","ficompDm", "fisubDm","fisubrDm","fidivDm","fidivrDm", -- DB "fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp", -- DC "faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm", -- DD "fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm", -- DE "fiaddWm","fimulWm","ficomWm","ficompWm", "fisubWm","fisubrWm","fidivWm","fidivrWm", -- DF "fildWm","fisttpWm","fistWm","fistpWm", "fbld twordFmp","fildQm","fbstp twordFmp","fistpQm", -- xx C0-FF: opcodes with a pseudo-register operand. -- D8 "faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf", -- D9 "fldFf","fxchFf",{"fnop"},nil, {"fchs","fabs",nil,nil,"ftst","fxam"}, {"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"}, {"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"}, {"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"}, -- DA "fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil, -- DB "fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf", {nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil, -- DC "fadd toFf","fmul toFf",nil,nil, "fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf", -- DD "ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil, -- DE "faddpFf","fmulpFf",nil,{nil,"fcompp"}, "fsubrpFf","fsubpFf","fdivrpFf","fdivpFf", -- DF nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil, } assert(map_opcfp[126] == "fcomipFf") -- Map for opcode groups. The subkey is sp from the ModRM byte. local map_opcgroup = { arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" }, shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" }, testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" }, testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" }, incb = { "inc", "dec" }, incd = { "inc", "dec", "callUmp", "$call farDmp", "jmpUmp", "$jmp farDmp", "pushUm" }, sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" }, sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt", "smsw", nil, "lmsw", "vm*$invlpg" }, bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" }, cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil, nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" }, pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" }, pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" }, pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" }, pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" }, fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr", nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" }, prefetch = { "prefetch", "prefetchw" }, prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" }, } ------------------------------------------------------------------------------ -- Maps for register names. local map_regs = { B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" }, D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" }, Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" }, M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext! X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" }, } local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" } -- Maps for size names. local map_sz2n = { B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16, } local map_sz2prefix = { B = "byte", W = "word", D = "dword", Q = "qword", M = "qword", X = "xword", F = "dword", G = "qword", -- No need for sizes/register names for these two. } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local code, pos, hex = ctx.code, ctx.pos, "" local hmax = ctx.hexdump if hmax > 0 then for i=ctx.start,pos-1 do hex = hex..format("%02X", byte(code, i, i)) end if #hex > hmax then hex = sub(hex, 1, hmax)..". " else hex = hex..rep(" ", hmax-#hex+2) end end if operands then text = text.." "..operands end if ctx.o16 then text = "o16 "..text; ctx.o16 = false end if ctx.a32 then text = "a32 "..text; ctx.a32 = false end if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end if ctx.rex then local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "").. (ctx.rexx and "x" or "")..(ctx.rexb and "b" or "") if t ~= "" then text = "rex."..t.." "..text end ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false end if ctx.seg then local text2, n = gsub(text, "%[", "["..ctx.seg..":") if n == 0 then text = ctx.seg.." "..text else text = text2 end ctx.seg = false end if ctx.lock then text = "lock "..text; ctx.lock = false end local imm = ctx.imm if imm then local sym = ctx.symtab[imm] if sym then text = text.."\t->"..sym end end ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text)) ctx.mrm = false ctx.start = pos ctx.imm = nil end -- Clear all prefix flags. local function clearprefixes(ctx) ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false; ctx.a32 = false end -- Fallback for incomplete opcodes at the end. local function incomplete(ctx) ctx.pos = ctx.stop+1 clearprefixes(ctx) return putop(ctx, "(incomplete)") end -- Fallback for unknown opcodes. local function unknown(ctx) clearprefixes(ctx) return putop(ctx, "(unknown)") end -- Return an immediate of the specified size. local function getimm(ctx, pos, n) if pos+n-1 > ctx.stop then return incomplete(ctx) end local code = ctx.code if n == 1 then local b1 = byte(code, pos, pos) return b1 elseif n == 2 then local b1, b2 = byte(code, pos, pos+1) return b1+b2*256 else local b1, b2, b3, b4 = byte(code, pos, pos+3) local imm = b1+b2*256+b3*65536+b4*16777216 ctx.imm = imm return imm end end -- Process pattern string and generate the operands. local function putpat(ctx, name, pat) local operands, regs, sz, mode, sp, rm, sc, rx, sdisp local code, pos, stop = ctx.code, ctx.pos, ctx.stop -- Chars used: 1DFGIMPQRSTUVWXacdfgijmoprstuwxyz for p in gmatch(pat, ".") do local x = nil if p == "V" or p == "U" then if ctx.rexw then sz = "Q"; ctx.rexw = false elseif ctx.o16 then sz = "W"; ctx.o16 = false elseif p == "U" and ctx.x64 then sz = "Q" else sz = "D" end regs = map_regs[sz] elseif p == "T" then if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end regs = map_regs[sz] elseif p == "B" then sz = "B" regs = ctx.rex and map_regs.B64 or map_regs.B elseif match(p, "[WDQMXFG]") then sz = p regs = map_regs[sz] elseif p == "P" then sz = ctx.o16 and "X" or "M"; ctx.o16 = false regs = map_regs[sz] elseif p == "S" then name = name..lower(sz) elseif p == "s" then local imm = getimm(ctx, pos, 1); if not imm then return end x = imm <= 127 and format("+0x%02x", imm) or format("-0x%02x", 256-imm) pos = pos+1 elseif p == "u" then local imm = getimm(ctx, pos, 1); if not imm then return end x = format("0x%02x", imm) pos = pos+1 elseif p == "w" then local imm = getimm(ctx, pos, 2); if not imm then return end x = format("0x%x", imm) pos = pos+2 elseif p == "o" then -- [offset] if ctx.x64 then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("[0x%08x%08x]", imm2, imm1) pos = pos+8 else local imm = getimm(ctx, pos, 4); if not imm then return end x = format("[0x%08x]", imm) pos = pos+4 end elseif p == "i" or p == "I" then local n = map_sz2n[sz] if n == 8 and ctx.x64 and p == "I" then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("0x%08x%08x", imm2, imm1) else if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then imm = (0xffffffff+1)-imm x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm) else x = format(imm > 65535 and "0x%08x" or "0x%x", imm) end end pos = pos+n elseif p == "j" then local n = map_sz2n[sz] if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "B" and imm > 127 then imm = imm-256 elseif imm > 2147483647 then imm = imm-4294967296 end pos = pos+n imm = imm + pos + ctx.addr if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end ctx.imm = imm if sz == "W" then x = format("word 0x%04x", imm%65536) elseif ctx.x64 then local lo = imm % 0x1000000 x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo) else x = "0x"..tohex(imm) end elseif p == "R" then local r = byte(code, pos-1, pos-1)%8 if ctx.rexb then r = r + 8; ctx.rexb = false end x = regs[r+1] elseif p == "a" then x = regs[1] elseif p == "c" then x = "cl" elseif p == "d" then x = "dx" elseif p == "1" then x = "1" else if not mode then mode = ctx.mrm if not mode then if pos > stop then return incomplete(ctx) end mode = byte(code, pos, pos) pos = pos+1 end rm = mode%8; mode = (mode-rm)/8 sp = mode%8; mode = (mode-sp)/8 sdisp = "" if mode < 3 then if rm == 4 then if pos > stop then return incomplete(ctx) end sc = byte(code, pos, pos) pos = pos+1 rm = sc%8; sc = (sc-rm)/8 rx = sc%8; sc = (sc-rx)/8 if ctx.rexx then rx = rx + 8; ctx.rexx = false end if rx == 4 then rx = nil end end if mode > 0 or rm == 5 then local dsz = mode if dsz ~= 1 then dsz = 4 end local disp = getimm(ctx, pos, dsz); if not disp then return end if mode == 0 then rm = nil end if rm or rx or (not sc and ctx.x64 and not ctx.a32) then if dsz == 1 and disp > 127 then sdisp = format("-0x%x", 256-disp) elseif disp >= 0 and disp <= 0x7fffffff then sdisp = format("+0x%x", disp) else sdisp = format("-0x%x", (0xffffffff+1)-disp) end else sdisp = format(ctx.x64 and not ctx.a32 and not (disp >= 0 and disp <= 0x7fffffff) and "0xffffffff%08x" or "0x%08x", disp) end pos = pos+dsz end end if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end if ctx.rexr then sp = sp + 8; ctx.rexr = false end end if p == "m" then if mode == 3 then x = regs[rm+1] else local aregs = ctx.a32 and map_regs.D or ctx.aregs local srm, srx = "", "" if rm then srm = aregs[rm+1] elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end ctx.a32 = false if rx then if rm then srm = srm.."+" end srx = aregs[rx+1] if sc > 0 then srx = srx.."*"..(2^sc) end end x = format("[%s%s%s]", srm, srx, sdisp) end if mode < 3 and (not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck. x = map_sz2prefix[sz].." "..x end elseif p == "r" then x = regs[sp+1] elseif p == "g" then x = map_segregs[sp+1] elseif p == "p" then -- Suppress prefix. elseif p == "f" then x = "st"..rm elseif p == "x" then if sp == 0 and ctx.lock and not ctx.x64 then x = "CR8"; ctx.lock = false else x = "CR"..sp end elseif p == "y" then x = "DR"..sp elseif p == "z" then x = "TR"..sp elseif p == "t" then else error("bad pattern `"..pat.."'") end end if x then operands = operands and operands..", "..x or x end end ctx.pos = pos return putop(ctx, name, operands) end -- Forward declaration. local map_act -- Fetch and cache MRM byte. local function getmrm(ctx) local mrm = ctx.mrm if not mrm then local pos = ctx.pos if pos > ctx.stop then return nil end mrm = byte(ctx.code, pos, pos) ctx.pos = pos+1 ctx.mrm = mrm end return mrm end -- Dispatch to handler depending on pattern. local function dispatch(ctx, opat, patgrp) if not opat then return unknown(ctx) end if match(opat, "%|") then -- MMX/SSE variants depending on prefix. local p if ctx.rep then p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)" ctx.rep = false elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false else p = "^[^%|]*" end opat = match(opat, p) if not opat then return unknown(ctx) end -- ctx.rep = false; ctx.o16 = false --XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi] --XXX remove in branches? end if match(opat, "%$") then -- reg$mem variants. local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)") if opat == "" then return unknown(ctx) end end if opat == "" then return unknown(ctx) end local name, pat = match(opat, "^([a-z0-9 ]*)(.*)") if pat == "" and patgrp then pat = patgrp end return map_act[sub(pat, 1, 1)](ctx, name, pat) end -- Get a pattern from an opcode map and dispatch to handler. local function dispatchmap(ctx, opcmap) local pos = ctx.pos local opat = opcmap[byte(ctx.code, pos, pos)] pos = pos + 1 ctx.pos = pos return dispatch(ctx, opat) end -- Map for action codes. The key is the first char after the name. map_act = { -- Simple opcodes without operands. [""] = function(ctx, name, pat) return putop(ctx, name) end, -- Operand size chars fall right through. B = putpat, W = putpat, D = putpat, Q = putpat, V = putpat, U = putpat, T = putpat, M = putpat, X = putpat, P = putpat, F = putpat, G = putpat, -- Collect prefixes. [":"] = function(ctx, name, pat) ctx[pat == ":" and name or sub(pat, 2)] = name if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes. end, -- Chain to special handler specified by name. ["*"] = function(ctx, name, pat) return map_act[name](ctx, name, sub(pat, 2)) end, -- Use named subtable for opcode group. ["!"] = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2)) end, -- o16,o32[,o64] variants. sz = function(ctx, name, pat) if ctx.o16 then ctx.o16 = false else pat = match(pat, ",(.*)") if ctx.rexw then local p = match(pat, ",(.*)") if p then pat = p; ctx.rexw = false end end end pat = match(pat, "^[^,]*") return dispatch(ctx, pat) end, -- Two-byte opcode dispatch. opc2 = function(ctx, name, pat) return dispatchmap(ctx, map_opc2) end, -- Three-byte opcode dispatch. opc3 = function(ctx, name, pat) return dispatchmap(ctx, map_opc3[pat]) end, -- VMX/SVM dispatch. vm = function(ctx, name, pat) return dispatch(ctx, map_opcvm[ctx.mrm]) end, -- Floating point opcode dispatch. fp = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end local rm = mrm%8 local idx = pat*8 + ((mrm-rm)/8)%8 if mrm >= 192 then idx = idx + 64 end local opat = map_opcfp[idx] if type(opat) == "table" then opat = opat[rm+1] end return dispatch(ctx, opat) end, -- REX prefix. rex = function(ctx, name, pat) if ctx.rex then return unknown(ctx) end -- Only 1 REX prefix allowed. for p in gmatch(pat, ".") do ctx["rex"..p] = true end ctx.rex = true end, -- Special case for nop with REX prefix. nop = function(ctx, name, pat) return dispatch(ctx, ctx.rex and pat or "nop") 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 ofs = ofs + 1 ctx.start = ofs ctx.pos = ofs ctx.stop = stop ctx.imm = nil ctx.mrm = false clearprefixes(ctx) while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end if ctx.pos ~= ctx.start then incomplete(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) - 1 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 16 ctx.x64 = false ctx.map1 = map_opc1_32 ctx.aregs = map_regs.D return ctx end local function create64(code, addr, out) local ctx = create(code, addr, out) ctx.x64 = true ctx.map1 = map_opc1_64 ctx.aregs = map_regs.Q 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 local function disass64(code, addr, out) create64(code, addr, out):disass() end -- Return register name for RID. local function regname(r) if r < 8 then return map_regs.D[r+1] end return map_regs.X[r-7] end local function regname64(r) if r < 16 then return map_regs.Q[r+1] end return map_regs.X[r-15] end -- Public module functions. return { create = create, create64 = create64, disass = disass, disass64 = disass64, regname = regname, regname64 = regname64 }
mit
mtroyka/Zero-K
LuaUI/Widgets/chili_new/controls/image.lua
9
3306
--//============================================================================= --- Image module --- Image fields. -- Inherits from Control. -- @see button.Button -- @table Image -- @tparam {r,g,b,a} color color, (default {1,1,1,1}) -- @string[opt=nil] file path -- @bool[opt=true] keepAspect aspect should be kept -- @tparam {func1,func2} OnClick function listeners to be invoked on click (default {}) Image = Button:Inherit{ classname= "image", defaultWidth = 64, defaultHeight = 64, padding = {0,0,0,0}, color = {1,1,1,1}, color2 = nil, file = nil, file2 = nil, flip = true; flip2 = true; keepAspect = true; useRTT = false; OnClick = {}, } local this = Image local inherited = this.inherited --//============================================================================= local function _DrawTextureAspect(x,y,w,h ,tw,th, flipy) local twa = w/tw local tha = h/th local aspect = 1 if (twa < tha) then aspect = twa y = y + h*0.5 - th*aspect*0.5 h = th*aspect else aspect = tha x = x + w*0.5 - tw*aspect*0.5 w = tw*aspect end local right = math.ceil(x+w) local bottom = math.ceil(y+h) x = math.ceil(x) y = math.ceil(y) gl.TexRect(x,y,right,bottom,false,flipy) end function Image:DrawControl() if (not (self.file or self.file2)) then return end if (self.keepAspect) then if (self.file2) then gl.Color(self.color2 or self.color) TextureHandler.LoadTexture(0,self.file2,self) local texInfo = gl.TextureInfo(self.file2) or {xsize=1, ysize=1} local tw,th = texInfo.xsize, texInfo.ysize _DrawTextureAspect(0,0,self.width,self.height, tw,th, self.flip2) end if (self.file) then gl.Color(self.color) TextureHandler.LoadTexture(0,self.file,self) local texInfo = gl.TextureInfo(self.file) or {xsize=1, ysize=1} local tw,th = texInfo.xsize, texInfo.ysize _DrawTextureAspect(0,0,self.width,self.height, tw,th, self.flip) end else if (self.file2) then gl.Color(self.color2 or self.color) TextureHandler.LoadTexture(0,self.file2,self) gl.TexRect(0,0,self.width,self.height,false,self.flip2) end if (self.file) then gl.Color(self.color) TextureHandler.LoadTexture(0,self.file,self) gl.TexRect(0,0,self.width,self.height,false,self.flip) end end gl.Texture(0,false) end --//============================================================================= function Image:IsActive() local onclick = self.OnClick if (onclick and onclick[1]) then return true end end function Image:HitTest() --FIXME check if there are any eventhandlers linked (OnClick,OnMouseUp,...) return self:IsActive() and self end function Image:MouseDown(...) --// we don't use `this` here because it would call the eventhandler of the button class, --// which always returns true, but we just want to do so if a calllistener handled the event return Control.MouseDown(self, ...) or self:IsActive() and self end function Image:MouseUp(...) return Control.MouseUp(self, ...) or self:IsActive() and self end function Image:MouseClick(...) return Control.MouseClick(self, ...) or self:IsActive() and self end --//=============================================================================
gpl-2.0
X-Coder/wire
lua/entities/gmod_wire_expression2/core/e2doc.lua
10
5189
local eliminate_varname_conflicts = true if not e2_parse_args then include("extpp.lua") end local readfile = readfile or function(filename) return file.Read("entities/gmod_wire_expression2/core/" .. filename, "LUA") end local writefile = writefile or function(filename, contents) print("--- Writing to file 'data/e2doc/" .. filename .. "' ---") return file.Write("e2doc/" .. filename, contents) end local p_typename = "[a-z][a-z0-9]*" local p_typeid = "[a-z][a-z0-9]?[a-z0-9]?[a-z0-9]?[a-z0-9]?" local p_argname = "[a-zA-Z][a-zA-Z0-9]*" local p_funcname = "[a-z][a-zA-Z0-9]*" local p_func_operator = "[-a-zA-Z0-9+*/%%^=!><&|$_]*" local function ltrim(s) return string.match(s, "^%s*(.-)$") end local function rtrim(s) return string.match(s, "^(.-)%s*$") end local function trim(s) return string.match(s, "^%s*(.-)%s*$") end local mess_with_args function mess_with_args(args, desc, thistype) local args_referenced = string.match(desc, "<" .. p_argname .. ">") local argtable, ellipses = e2_parse_args(args) local indices = {} if thistype ~= "" then indices[string.upper(e2_get_typeid(thistype))] = 2 end args = '' for i, name in ipairs(argtable.argnames) do local typeid = string.upper(argtable.typeids[i]) local index = "" if args_referenced then index = indices[typeid] if index then indices[typeid] = index + 1 else index = "" indices[typeid] = 2 end end local newname = typeid .. "<sub>" .. index .. "</sub>" if index == "" then newname = typeid end desc = desc:gsub("<" .. name .. ">", "''" .. newname .. "''") if i ~= 1 then args = args .. "," end args = args .. newname end if ellipses then if #argtable.argnames ~= 0 then args = args .. "," end args = args .. "..." end return args, desc end local function e2doc(filename, outfile) if not outfile then outfile = string.match(filename, "^.*%.") .. "txt" end local current = {} local output = { '====Commands====\n:{|style="background:#E6E6FA"\n!align="left" width="150"| Function\n!align="left" width="60"| Returns\n!align="left" width="1000"| Description\n' } local insert_line = true for line in string.gmatch(readfile(filename), "%s*(.-)%s*\n") do if line:sub(1, 3) == "---" then if line:match("[^-%s]") then table.insert(current, ltrim(line:sub(4))) end elseif line:sub(1, 3) == "///" then table.insert(current, ltrim(line:sub(4))) elseif line:sub(1, 12) == "--[[********" or line:sub(1, 9) == "/********" then if line:find("^%-%-%[%[%*%*%*%*%*%*%*%*+%]%]%-%-$") or line:find("^/%*%*%*%*%*%*%*%*+/$") then insert_line = true end elseif line:sub(1, 10) == "e2function" then local ret, thistype, colon, name, args = line:match("e2function%s+(" .. p_typename .. ")%s+([a-z0-9]-)%s*(:?)%s*(" .. p_func_operator .. ")%(([^)]*)%)") if thistype ~= "" and colon == "" then error("E2doc syntax error: Function names may not start with a number.", 0) end if thistype == "" and colon ~= "" then error("E2doc syntax error: No type for 'this' given.", 0) end if thistype:sub(1, 1):find("[0-9]") then error("E2doc syntax error: Type names may not start with a number.", 0) end desc = table.concat(current, "<br />") current = {} if name:sub(1, 8) ~= "operator" and not desc:match("@nodoc") then if insert_line then table.insert(output, '|-\n| bgcolor="SteelBlue" | || bgcolor="SteelBlue" | || bgcolor="SteelBlue" | \n') insert_line = false end args, desc = mess_with_args(args, desc, thistype) if ret == "void" then ret = "" else ret = string.upper(e2_get_typeid(ret)) end if thistype ~= "" then thistype = string.upper(e2_get_typeid(thistype)) desc = desc:gsub("<this>", "''" .. thistype .. "''") thistype = thistype .. ":" end table.insert(output, string.format("|-\n|%s%s(%s) || %s || ", thistype, name, args, ret)) --desc = desc:gsub("<([^<>]+)>", "''%1''") table.insert(output, desc) table.insert(output, "\n") end end end -- for line output = table.concat(output) .. "|}\n" print(output) writefile(outfile, output) end -- Add a client-side "e2doc" console command if SERVER then AddCSLuaFile() e2doc = nil elseif CLIENT then concommand.Add("e2doc", function(player, command, args) if not file.IsDir("e2doc", "DATA") then file.CreateDir("e2doc") end if not file.IsDir("e2doc/custom", "DATA") then file.CreateDir("e2doc/custom") end local path = string.match(args[2] or args[1], "^%s*(.+)/") if path and not file.IsDir("e2doc/" .. path, "DATA") then file.CreateDir("e2doc/" .. path) end e2doc(args[1], args[2]) end, function(commandName, args) -- autocomplete function args = string.match(args, "^%s*(.-)%s*$") local path = string.match(args, "^%s*(.+/)") or "" local files = file.Find("entities/gmod_wire_expression2/core/" .. args .. "*", "LUA") local ret = {} for _, v in ipairs(files) do if string.sub(v, 1, 1) ~= "." then if file.IsDir("entities/gmod_wire_expression2/core/" .. path .. v, "LUA") then table.insert(ret, "e2doc " .. path .. v .. "/") else table.insert(ret, "e2doc " .. path .. v) end end end return ret end) end
gpl-3.0
mtroyka/Zero-K
units/fakeunit_los.lua
3
1530
unitDef = { unitname = [[fakeunit_los]], name = [[LOS Provider]], description = [[Knows all and sees all]], acceleration = 1, brakeRate = 0.8, buildCostEnergy = 0.45, buildCostMetal = 0.45, builder = false, buildPic = [[levelterra.png]], buildTime = 0.45, canFly = true, canGuard = true, canMove = true, canPatrol = true, canSubmerge = false, canSelfDestruct = false, category = [[FAKEUNIT]], cruiseAlt = 300, customParams = { dontcount = [[1]], completely_hidden = 1, -- for widget-senpai not to notice me }, explodeAs = [[TINY_BUILDINGEX]], floater = true, footprintX = 3, footprintZ = 3, hoverAttack = true, iconType = [[none]], idleAutoHeal = 10, idleTime = 300, levelGround = false, maxDamage = 900000, maxVelocity = 5, maxWaterDepth = 0, minCloakDistance = 9, noAutoFire = false, objectName = [[debris1x1b.s3o]], script = [[fakeunit_los.lua]], seismicSignature = 0, sightDistance = 500, stealth = true, turnRate = 0, workerTime = 0, } return lowerkeys({ fakeunit_los = unitDef })
gpl-2.0
ztesbot/ztesbot
plugins/stats.lua
1
4017
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'teleseed' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "teleseed" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (ztesbot)",-- Put everything you like :) "^[!/]([Zz][Tt][Ee][Ss][Bb][Oo][Tt])"-- Put everything you like :) }, run = run } end
gpl-2.0
Bpalkmim/ProjetoFinal
Logic/Edge.lua
4
3139
------------------------------------------------------------------------------ -- Edge Module -- -- This module defines ... -- -- @authors: Vitor -- ------------------------------------------------------------------------------- Edge = {} Edge_Metatable = { __index = Edge } --- Class Constructor function Edge:new (label, origem, destino) assert( getmetatable(origem) == Node_Metatable , "Edge:new expects a Node. Origin is not a node.") assert( getmetatable(destino) == Node_Metatable , "Edge:new expects a Node. Destination is not a node.") assert( type(label) == "string" , "Edge:new expects a string." ) local ini = {} ini = {label = label, origem = origem, destino = destino, info = {}} local newEdge = setmetatable( ini, Edge_Metatable ) origem:setEdgeOut(newEdge) destino:setEdgeIn(newEdge) return newEdge end --- Define the label of the edge function Edge:setLabel( label ) assert( type(label) == "string" , "Edge:setLabel expects a string." ) self.label = label end --- Return the label of the edge function Edge:getLabel() return self.label end --- Create a field named "infoName" with the value "infoValue". If the field already exists, the value of it is atualized -- @param infoName: A string or a number containing the name of the field of the desired information. -- @param infoValue: A value which the field "infoName" will have. function Edge:setInformation(infoName, infoValue) self.info[infoName] = infoValue end --- Retorna o valor da informaçao do campo infoName -- @param infoName: A string or a number containing the name of the field of the desired information. function Edge:getInformation(infoName) return self.info[infoName] end function Edge:getInformationTable() return self.info end --- Return the origin node of the edge function Edge:getOrigem() return self.origem end --- Define the origin node of the edge function Edge:setOrigem(node) assert( getmetatable(node) == Node_Metatable , "Edge:setOrigem expects a Node.") -- Garantir que é um vertice self.origem = node end --- Return the destination node of the edge function Edge:getDestino() return self.destino end --- Define the destination node of the edge function Edge:setDestino(node) assert( getmetatable(node) == Node_Metatable , "Edge:setDestino expects a Node.") -- Garantir que é um vertice self.destino = node end --- Define the origin node and the destination node of the edge -- @param origin: A node that is the origin of the edge -- @param destination: A node that is the destination of the edge function Edge:setConections(origin, destination) assert( getmetatable(origin) == Node_Metatable , "Edge:setConections expects a Node, origin is not a node.") -- Garantir que é um vertice assert( getmetatable(destination) == Node_Metatable , "Edge:setConections expects a Node, destination is not a node.") -- Garantir que é um vertice self.origem = origin self.destino = destination end -- Return two nodes: the origin and the destination of the edge function Edge:getConections() return self.origem, self.destino end
gpl-2.0
alalazo/wesnoth
data/lua/wml/modify_side.lua
2
2784
local helper = wesnoth.require "helper" local utils = wesnoth.require "wml-utils" local T = helper.set_wml_tag_metatable {} local side_changes_needing_redraw = { 'shroud', 'fog', 'reset_map', 'reset_view', 'shroud_data', 'share_vision', 'share_maps', 'share_view', 'color', 'flag', } function wesnoth.wml_actions.modify_side(cfg) local sides = utils.get_sides(cfg) for i,side in ipairs(sides) do if cfg.team_name then side.team_name = cfg.team_name end if cfg.user_team_name then side.user_team_name = cfg.user_team_name end if cfg.controller then side.controller = cfg.controller end if cfg.defeat_condition then side.defeat_condition = cfg.defeat_condition end if cfg.recruit then local recruits = {} for recruit in utils.split(cfg.recruit) do table.insert(recruits, recruit) end side.recruit = recruits end if cfg.village_support then side.village_support = cfg.village_support end if cfg.village_gold then side.village_gold = cfg.village_gold end if cfg.income then side.base_income = cfg.income end if cfg.gold then side.gold = cfg.gold end if cfg.hidden ~= nil then side.hidden = cfg.hidden end if cfg.color or cfg.flag then wesnoth.set_side_id(side.side, cfg.flag, cfg.color) end if cfg.flag_icon then side.flag_icon = cfg.flag_icon end if cfg.suppress_end_turn_confirmation ~= nil then side.suppress_end_turn_confirmation = cfg.suppress_end_turn_confirmation end if cfg.scroll_to_leader ~= nil then side.scroll_to_leader = cfg.scroll_to_leader end if cfg.shroud ~= nil then side.shroud = cfg.shroud end if cfg.reset_maps then wesnoth.remove_shroud(side.side, "all") end if cfg.fog ~= nil then side.fog = cfg.fog end if cfg.reset_view then wesnoth.add_fog(side.side, {}, true) end if cfg.shroud_data then wesnoth.remove_shroud(side.side, cfg.shroud_data) end if cfg.share_vision then side.share_vision = cfg.share_vision end -- Legacy support if cfg.share_view ~= nil or cfg.share_maps ~= nil then if cfg.share_view then side.share_vision = 'all' elseif cfg.share_maps then side.share_vision = 'shroud' else side.share_vision = 'none' end end if cfg.switch_ai then wesnoth.switch_ai(side.side, cfg.switch_ai) end local ai, replace_ai = {}, false for next_ai in helper.child_range(cfg, "ai") do table.insert(ai, T.ai(next_ai)) if next_ai.ai_algorithm then replace_ai = true end end if #ai > 0 then if replace_ai then wesnoth.switch_ai(side.side, ai) else wesnoth.append_ai(side.side, ai) end end end for i,key in ipairs(side_changes_needing_redraw) do if cfg[key] ~= nil then wesnoth.wml_actions.redraw{} return end end end
gpl-2.0
mtroyka/Zero-K
LuaUI/Widgets/chili_new/themes/theme.lua
9
1495
--//============================================================================= --// Theme theme = {} theme.name = "default" --//============================================================================= --// Define default skins local defaultSkin = "Robocracy" --local defaultSkin = "DarkGlass" theme.skin = { general = { skinName = defaultSkin, }, imagelistview = { -- imageFolder = LUA_DIRNAME .. "images/folder.png", -- imageFolderUp = LUA_DIRNAME .. "images/folder_up.png", }, icons = { -- imageplaceholder = LUA_DIRNAME .. "images/placeholder.png", }, } --//============================================================================= --// Theme function theme.GetDefaultSkin(class) local skinName repeat skinName = theme.skin[class.classname].skinName class = class.inherited --FIXME check if the skin contains the current control class! if not use inherit the theme table before doing so in the skin until ((skinName)and(SkinHandler.IsValidSkin(skinName)))or(not class); if (not skinName)or(not SkinHandler.IsValidSkin(skinName)) then skinName = theme.skin.general.skinName end if (not skinName)or(not SkinHandler.IsValidSkin(skinName)) then skinName = "default" end return skinName end function theme.LoadThemeDefaults(control) if (theme.skin[control.classname]) then table.merge(control,theme.skin[control.classname]) end -- per-class defaults table.merge(control,theme.skin.general) end
gpl-2.0
thedraked/darkstar
scripts/zones/Cloister_of_Storms/bcnms/sugar-coated_directive.lua
30
1810
---------------------------------------- -- Area: Cloister of Storms -- BCNM: Sugar Coated Directive (ASA-4) ---------------------------------------- package.loaded["scripts/zones/Cloister_of_Storms/TextIDs"] = nil; ---------------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Cloister_of_Storms/TextIDs"); ---------------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:hasCompletedMission(ASA,SUGAR_COATED_DIRECTIVE)) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,0); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then player:addExp(400); player:setVar("ASA4_Violet","1"); end end;
gpl-3.0
mtroyka/Zero-K
units/shipskirm.lua
1
4288
unitDef = { unitname = [[shipskirm]], name = [[Mistral]], description = [[Rocket Boat (Skirmisher)]], acceleration = 0.039, activateWhenBuilt = true, brakeRate = 0.115, buildCostEnergy = 240, buildCostMetal = 240, builder = false, buildPic = [[shipskirm.png]], buildTime = 240, canAttack = true, canGuard = true, canMove = true, canPatrol = true, canstop = [[1]], category = [[SHIP]], collisionVolumeOffsets = [[0 2 0]], collisionVolumeScales = [[24 24 60]], collisionVolumeType = [[cylZ]], corpse = [[DEAD]], customParams = { helptext = [[This Rocket Boat fires a salvo of four medium-range rockets, useful for bombarding sea and shore targets. Beware of subs and anything with enough speed to get close.]], turnatfullspeed = [[1]], modelradius = [[24]], }, explodeAs = [[SMALL_UNITEX]], floater = true, footprintX = 2, footprintZ = 2, iconType = [[shipskirm]], idleAutoHeal = 5, idleTime = 1800, losEmitHeight = 30, maxDamage = 650, maxVelocity = 2.3, minCloakDistance = 350, minWaterDepth = 10, movementClass = [[BOAT3]], moveState = 0, noAutoFire = false, noChaseCategory = [[TERRAFORM SATELLITE SUB]], objectName = [[shipskirm.s3o]], script = [[shipskirm.lua]], seismicSignature = 4, selfDestructAs = [[SMALL_UNITEX]], sfxtypes = { explosiongenerators = { [[custom:MISSILE_EXPLOSION]], [[custom:MEDMISSILE_EXPLOSION]], }, }, sightDistance = 720, sonarDistance = 720, turninplace = 0, turnRate = 400, waterline = 4, workerTime = 0, weapons = { { def = [[ROCKET]], badTargetCategory = [[FIXEDWING GUNSHIP]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { ROCKET = { name = [[Unguided Rocket]], areaOfEffect = 75, burst = 4, burstRate = 0.3, cegTag = [[missiletrailred]], craterBoost = 1, craterMult = 2, customParams = { light_camera_height = 1800, }, damage = { default = 280, planes = 280, subs = 28, }, fireStarter = 70, flightTime = 3.5, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 2, model = [[wep_m_hailstorm.s3o]], noSelfDamage = true, predictBoost = 1, range = 610, reloadtime = 8.0, smokeTrail = true, soundHit = [[explosion/ex_med4]], soundHitVolume = 8, soundStart = [[weapon/missile/missile2_fire_bass]], soundStartVolume = 7, startVelocity = 230, texture2 = [[darksmoketrail]], tracks = false, trajectoryHeight = 0.6, turnrate = 1000, turret = true, weaponType = [[MissileLauncher]], weaponVelocity = 230, wobble = 5000, }, }, featureDefs = { DEAD = { blocking = false, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, object = [[shipskirm_dead.s3o]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris2x2c.s3o]], }, }, } return lowerkeys({ shipskirm = unitDef })
gpl-2.0
thedraked/darkstar
scripts/zones/Carpenters_Landing/npcs/relic.lua
14
1880
----------------------------------- -- Area: Carpenter's Landing -- NPC: <this space intentionally left blank> -- @pos -99 -0 -514 2 ----------------------------------- package.loaded["scripts/zones/Carpenters_Landing/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Carpenters_Landing/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece if (player:getVar("RELIC_IN_PROGRESS") == 15069 and trade:getItemCount() == 4 and trade:hasItemQty(15069,1) and trade:hasItemQty(1822,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1454,1)) then player:startEvent(44,15070); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 44) then if (player:getFreeSlotsCount() < 2) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,15070); player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1453); else player:tradeComplete(); player:addItem(15070); player:addItem(1453,30); player:messageSpecial(ITEM_OBTAINED,15070); player:messageSpecial(ITEMS_OBTAINED,1453,30); player:setVar("RELIC_IN_PROGRESS",0); end end end;
gpl-3.0
thedraked/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Parukoko.lua
14
1061
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Parukoko -- Type: Standard NPC -- @zone 94 -- @pos -32.400 -3.5 -103.666 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01b4); 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
thedraked/darkstar
scripts/zones/The_Garden_of_RuHmet/mobs/Ix_aern_drg_s_Wynav.lua
17
1753
----------------------------------- -- Area: The Garden of Ru'Hmet -- MOB: Ix'aern (drg)'s Wynav ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setLocalVar("hpTrigger", math.random(10,75)); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) local hpTrigger = mob:getLocalVar("hpTrigger"); if (mob:getLocalVar("SoulVoice") == 0 and mob:getHPP() <= hpTrigger) then mob:setLocalVar("SoulVoice", 1); mob:useMobAbility(696); -- Soul Voice end end; ----------------------------------- -- onMonsterMagicPrepare ----------------------------------- function onMonsterMagicPrepare(mob,target) local spellList = { [1] = 382, [2] = 376, [3] = 372, [4] = 392, [5] = 397, [6] = 400, [7] = 422, [8] = 462, [9] = 466 -- Virelai (charm) }; if (mob:hasStatusEffect(EFFECT_SOUL_VOICE)) then return spellList[math.random(1,9)]; -- Virelai possible. else return spellList[math.random(1,8)]; -- No Virelai! end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end; ----------------------------------- -- OnMobDespawn ----------------------------------- function onMobDespawn(mob) mob:setLocalVar("repop", mob:getBattleTime()); -- This get erased on respawn automatic. end;
gpl-3.0
thedraked/darkstar
scripts/zones/Lower_Jeuno/npcs/_6tc.lua
25
4144
----------------------------------- -- Area: Lower Jeuno -- NPC: Door: "Neptune's Spire" -- Starts and Finishes Quest: Beat Around the Bushin -- @zone 245 -- @pos 35 0 -15 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,BEAT_AROUND_THE_BUSHIN) == QUEST_ACCEPTED) then if (trade:hasItemQty(1526,1) == true and trade:getItemCount() == 1 and player:getVar("BeatAroundTheBushin") == 2) then player:startEvent(0x009c); -- After trade Wyrm Beard elseif (trade:hasItemQty(1527,1) == true and trade:getItemCount() == 1 and player:getVar("BeatAroundTheBushin") == 4) then player:startEvent(0x009d); -- After trade Behemoth Tongue elseif (trade:hasItemQty(1525,1) == true and trade:getItemCount() == 1 and player:getVar("BeatAroundTheBushin") == 6) then player:startEvent(0x009e); -- After trade Adamantoise Egg elseif (trade:hasItemQty(13202,1) == true and trade:getItemCount() == 1 and player:getVar("BeatAroundTheBushin") == 7) then player:startEvent(0x009f); -- After trade Brown Belt, Finish Quest "Beat around the Bushin" end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) ==A_VESSEL_WITHOUT_A_CAPTAIN and player:getVar("PromathiaStatus")==0) then player:startEvent(0x0056); --COP event elseif (player:getCurrentMission(COP) ==TENDING_AGED_WOUNDS and player:getVar("PromathiaStatus")==1) then player:startEvent(0x0016); --COP event elseif (player:getVar("BeatAroundTheBushin") == 1) then player:startEvent(0x009b); -- Start Quest "Beat around the Bushin" elseif (player:hasKeyItem(TENSHODO_MEMBERS_CARD) == true) then player:startEvent(0x0069); -- Open the door else player:messageSpecial(ITS_LOCKED); return 1; 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 == 0x0056 ) then player:setVar("PromathiaStatus",1); player:startEvent(0x0009); elseif (csid == 0x0016 ) then player:completeMission(COP,TENDING_AGED_WOUNDS); player:addMission(COP,DARKNESS_NAMED); player:setVar("PromathiaStatus",0); player:startEvent(0x000A); elseif (csid == 0x009b) then player:addQuest(JEUNO,BEAT_AROUND_THE_BUSHIN); player:setVar("BeatAroundTheBushin",2); elseif (csid == 0x009c) then player:setVar("BeatAroundTheBushin",3); player:tradeComplete(); elseif (csid == 0x009d) then player:setVar("BeatAroundTheBushin",5); player:tradeComplete(); elseif (csid == 0x009e) then player:setVar("BeatAroundTheBushin",7); player:tradeComplete(); elseif (csid == 0x009f) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13186); else player:addTitle(BLACK_BELT); player:addItem(13186); player:messageSpecial(ITEM_OBTAINED,13186); player:setVar("BeatAroundTheBushin",0); player:addFame(NORG,125); player:tradeComplete(); player:completeQuest(JEUNO,BEAT_AROUND_THE_BUSHIN); end end end;
gpl-3.0
TitanTeamGit/SelfBot
plugins/weather.lua
2
1435
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather" local function get_weather(location) print("Finding weather in ", location) local url = BASE_URL url = url..'?q='..location..'&APPID=eedbc05ba060c787ab0614cad1f2e12b' url = url..'&units=metric' local b, c, h = http.request(url) if c ~= 200 then return nil end local weather = json:decode(b) local city = weather.name local country = weather.sys.country local temp = 'دمای شهر '..city..' هم اکنون '..weather.main.temp..' درجه سانتی گراد می باشد' local conditions = 'شرایط فعلی آب و هوا : ' if weather.weather[1].main == 'Clear' then conditions = conditions .. 'آفتابی ☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. 'ابری ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. 'بارانی ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. 'طوفانی ☔☔☔☔' elseif weather.weather[1].main == 'Mist' then conditions = conditions .. 'مه 💨' end return temp .. '\n' .. conditions end local function run(msg, matches) city = matches[1] local wtext = get_weather(city) if not wtext then wtext = 'مکان وارد شده صحیح نیست' end return wtext end return { patterns = { "^weather (.*)$", }, run = run }
gpl-2.0
thedraked/darkstar
scripts/zones/Al_Zahbi/npcs/Bjibar.lua
14
1037
----------------------------------- -- Area: Al Zahbi -- NPC: Bjibar -- Type: Standard NPC -- @zone 48 -- @pos -105.178 0.999 60.115 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0107); 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
thedraked/darkstar
scripts/zones/Lower_Delkfutts_Tower/npcs/_545.lua
17
1574
----------------------------------- -- Area: Lower Delkfutt's Tower -- NPC: Cermet Door -- Notes: Involved in Missions: THREE_PATHS ----------------------------------- package.loaded["scripts/zones/Lower_Delkfutts_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Lower_Delkfutts_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 6 and player:hasKeyItem(DELKFUTT_RECOGNITION_DEVICE)) then SpawnMob(17531121):updateClaim(player); elseif (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 7 and player:hasKeyItem(DELKFUTT_RECOGNITION_DEVICE)) then player:startEvent(0x0019); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); if (csid == 0x0019) then player:setVar("COP_Tenzen_s_Path",8); end end;
gpl-3.0
thedraked/darkstar
scripts/globals/items/pitcher_of_homemade_herbal_tea.lua
18
1116
----------------------------------------- -- ID: 5221 -- Item: pitcher_of_homemade_herbal_tea -- Food Effect: 30Min, All Races ----------------------------------------- -- Charisma 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5221); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_CHR, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_CHR, 1); end;
gpl-3.0
OpenNMT/OpenNMT
onmt/tagger/Tagger.lua
4
5901
local Tagger = torch.class('Tagger') local options = { { '-model', '', [[Path to the serialized model file.]], { valid = onmt.utils.ExtendedCmdLine.fileExists } }, { '-batch_size', 30, [[Batch size.]], { valid = onmt.utils.ExtendedCmdLine.isInt(1) } } } function Tagger.declareOpts(cmd) cmd:setCmdLineOptions(options, 'Tagger') end function Tagger:__init(args) self.opt = args _G.logger:info('Loading \'' .. self.opt.model .. '\'...') self.checkpoint = torch.load(self.opt.model) self.dataType = self.checkpoint.options.data_type or 'bitext' if not self.checkpoint.options.model_type or self.checkpoint.options.model_type ~= 'seqtagger' then _G.logger:error('Tagger can only process seqtagger models') os.exit(0) end self.model = onmt.SeqTagger.load(self.checkpoint.options, self.checkpoint.models, self.checkpoint.dicts) onmt.utils.Cuda.convert(self.model) self.dicts = self.checkpoint.dicts end function Tagger:srcFeat() return self.dataType == 'feattext' end function Tagger:buildInput(tokens) local data = {} if self.dataType == 'feattext' then data.vectors = torch.Tensor(tokens) else local words, features = onmt.utils.Features.extract(tokens) local vocabs = onmt.utils.Placeholders.norm(words) data.words = vocabs if #features > 0 then data.features = features end end return data end function Tagger:buildInputGold(tokens) local data = {} local words, features = onmt.utils.Features.extract(tokens) data.words = words if #features > 0 then data.features = features end return data end function Tagger:buildOutput(data) return table.concat(onmt.utils.Features.annotate(data.words, data.features), ' ') end function Tagger:buildData(src) local srcData = {} srcData.words = {} srcData.features = {} local ignored = {} local indexMap = {} local index = 1 for b = 1, #src do if src[b].words and #src[b].words == 0 then table.insert(ignored, b) else indexMap[index] = b index = index + 1 if self.dicts.src then table.insert(srcData.words, self.dicts.src.words:convertToIdx(src[b].words, onmt.Constants.UNK_WORD)) if #self.dicts.src.features > 0 then table.insert(srcData.features, onmt.utils.Features.generateSource(self.dicts.src.features, src[b].features)) end else table.insert(srcData.words,onmt.utils.Cuda.convert(src[b].vectors)) end end end return onmt.data.Dataset.new(srcData), ignored, indexMap end function Tagger:buildGoldData(src, tgt) local srcData = {} srcData.words = {} srcData.features = {} local tgtData = {} tgtData.words = {} tgtData.features = {} local ignored = {} local indexMap = {} local index = 1 for b = 1, #src do if (src[b].words and #src[b].words == 0) or (tgt[b].words and #tgt[b].words == 0) then table.insert(ignored, b) else indexMap[index] = b index = index + 1 if self.dicts.src then table.insert(srcData.words, self.dicts.src.words:convertToIdx(src[b].words, onmt.Constants.UNK_WORD)) if #self.dicts.src.features > 0 then table.insert(srcData.features, onmt.utils.Features.generateSource(self.dicts.src.features, src[b].features)) end else table.insert(srcData.words,onmt.utils.Cuda.convert(src[b].vectors)) end if self.dicts.tgt then table.insert(tgtData.words, self.dicts.tgt.words:convertToIdx(tgt[b].words, onmt.Constants.UNK_WORD, onmt.Constants.BOS_WORD, onmt.Constants.EOS_WORD)) if #self.dicts.tgt.features > 0 then table.insert(tgtData.features, onmt.utils.Features.generateTarget(self.dicts.tgt.features, tgt[b].features)) end else table.insert(tgtData.words,onmt.utils.Cuda.convert(tgt[b].vectors)) end end end return onmt.data.Dataset.new(srcData, tgtData), ignored, indexMap end function Tagger:buildTargetWords(pred) local tokens = self.dicts.tgt.words:convertToLabels(pred, onmt.Constants.EOS) return tokens end function Tagger:buildTargetFeatures(predFeats) local numFeatures = #predFeats[1] if numFeatures == 0 then return {} end local feats = {} for _ = 1, numFeatures do table.insert(feats, {}) end for i = 1, #predFeats do for j = 1, numFeatures do table.insert(feats[j], self.dicts.tgt.features[j]:lookup(predFeats[i][j])) end end return feats end --[[ Tag a batch of source sequences. Parameters: * `src` - a batch of tables containing: - `words`: the table of source words - `features`: the table of feaures sequences (`src.features[i][j]` is the value of the ith feature of the jth token) Returns: * `results` - a batch of tables containing: - `words`: the table of target words - `features`: the table of target features sequences ]] function Tagger:tag(src) local data, ignored = self:buildData(src) local results = {} if data:batchCount() > 0 then local batch = onmt.utils.Cuda.convert(data:getBatch()) local pred, predFeats = self.model:tagBatch(batch) for b = 1, batch.size do results[b] = {} results[b].words = self:buildTargetWords(pred[b]) results[b].features = self:buildTargetFeatures(predFeats[b]) end end for i = 1, #ignored do table.insert(results, ignored[i], {}) end return results end function Tagger:computeLosses(src, tgt) local losses = {} for b=1,#src do local data, _ = self:buildGoldData({src[b]}, {tgt[b]}) local batch = onmt.utils.Cuda.convert(data:getBatch()) local loss = self.model:forwardComputeLoss(batch) table.insert(losses, loss) end return losses end return Tagger
mit
ukoloff/rufus-lua-win
vendor/lua/lib/lua/oil/kernel/cooperative/Receiver.lua
6
5380
-------------------------------------------------------------------------------- ------------------------------ ##### ## ------------------------------ ------------------------------ ## ## # ## ------------------------------ ------------------------------ ## ## ## ## ------------------------------ ------------------------------ ## ## # ## ------------------------------ ------------------------------ ##### ### ###### ------------------------------ -------------------------------- -------------------------------- ----------------------- An Object Request Broker in Lua ------------------------ -------------------------------------------------------------------------------- -- Project: OiL - ORB in Lua: An Object Request Broker in Lua -- -- Release: 0.5 -- -- Title : Request Acceptor -- -- Authors: Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- -- acceptor:Facet -- configs:table, [except:table] setupaccess([configs:table]) -- success:boolean, [except:table] hasrequest(configs:table) -- success:boolean, [except:table] acceptone(configs:table) -- success:boolean, [except:table] acceptall(configs:table) -- success:boolean, [except:table] halt(configs:table) -- -- listener:Receptacle -- configs:table default([configs:table]) -- channel:object, [except:table] getchannel(configs:table) -- success:boolean, [except:table] freeaccess(configs:table) -- success:boolean, [except:table] freechannel(channel:object) -- request:table, [except:table] = getrequest(channel:object, [probe:boolean]) -- success:booelan, [except:table] = sendreply(request:table, success:booelan, results...) -- -- dispatcher:Receptacle -- success:boolean, [except:table]|results... dispatch(objectkey:string, operation:string|function, params...) -- -- tasks:Receptacle -- current:thread -- start(func:function, args...) -- remove(thread:thread) -------------------------------------------------------------------------------- local next = next local pairs = pairs local oo = require "oil.oo" local Exception = require "oil.Exception" local Receiver = require "oil.kernel.base.Receiver" --[[VERBOSE]] local verbose = require "oil.verbose" module "oil.kernel.cooperative.Receiver" oo.class(_M, Receiver) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function __init(self, object) self = oo.rawnew(self, object) self.thread = {} self.threads = {} return self end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function processrequest(self, request) local result, except = Receiver.processrequest(self, request) if not result and not self.except then self.except = except end return result, except end function getallrequests(self, accesspoint, channel) local listener = self.listener local thread = self.tasks.current local threads = self.threads[accesspoint] threads[thread] = channel local result, except repeat result, except = listener:getrequest(channel) if result then if result == true then break else self.tasks:start(self.processrequest, self, result) end elseif not self.except then self.except = except break end until self.except if (result and result ~= true) or (not result and except.reason ~= "closed") then listener:putchannel(channel) end threads[thread] = nil end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function acceptall(self) local accesspoint = self.accesspoint --[[VERBOSE]] verbose:acceptor(true, "accept all requests from channel ",accesspoint) self.thread[accesspoint] = self.tasks.current self.threads[accesspoint] = {} local result, except repeat result, except = self.listener:getchannel(accesspoint) if result then self.tasks:start(self.getallrequests, self, accesspoint, result) end until not result or self.except self.threads[accesspoint] = nil self.thread[accesspoint] = nil --[[VERBOSE]] verbose:acceptor(false) return nil, self.except or except end function halt(self) --[[VERBOSE]] verbose:acceptor("halt acceptor",accesspoint) local accesspoint = self.accesspoint local tasks = self.tasks local listener = self.listener local result, except = nil, Exception{ reason = "halted", message = "orb already halted", } local thread = self.thread[accesspoint] if thread then tasks:remove(thread) result, except = listener:freeaccess(accesspoint) self.thread[accesspoint] = nil end local threads = self.threads[accesspoint] if threads then for thread, channel in pairs(threads) do tasks:remove(thread) result, except = listener:freechannel(channel) end self.threads[accesspoint] = nil end return result, except end
mit
thedraked/darkstar
scripts/zones/Uleguerand_Range/npcs/HomePoint#5.lua
27
1258
----------------------------------- -- Area: Uleguerand_Range -- NPC: HomePoint#5 -- @pos ----------------------------------- package.loaded["scripts/zones/Uleguerand_Range/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Uleguerand_Range/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x2200, 80); 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 == 0x2200) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
thedraked/darkstar
scripts/zones/Inner_Horutoto_Ruins/npcs/_5ca.lua
14
2341
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: Mahogany Door -- Involved In Quest: Making Headlines -- Involved in Mission 2-1 -- @pos -11 0 20 192 ----------------------------------- package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Inner_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES); local CurrentMission = player:getCurrentMission(WINDURST) local MissionStatus = player:getVar("MissionStatus"); -- Check for Missions first (priority?) -- We should allow both missions and quests to activate if (CurrentMission == LOST_FOR_WORDS and MissionStatus == 4) then player:startEvent(0x002e); elseif (MakingHeadlines == 1) then function testflag(set,flag) return (set % (2*flag) >= flag) end local prog = player:getVar("QuestMakingHeadlines_var"); if (testflag(tonumber(prog),16) == false and testflag(tonumber(prog),8) == true) then player:messageSpecial(7208,1,WINDURST_WOODS_SCOOP); -- Confirm Story player:setVar("QuestMakingHeadlines_var",prog+16); else player:startEvent(0x002c); -- "The door is firmly shut" end else player:startEvent(0x002c); -- "The door is firmly shut" end; return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x002e) then -- Mark the progress player:setVar("MissionStatus",5); end end;
gpl-3.0
GitoriousLispBackup/praxis
prods/Synthbench/geometry.lua
2
1544
-- Name: geometry.lua Vector3D = {} local Vector3D_meta = {} function Vector3D.new(x,y,z) local vec = {x=x,y=y,z=z} setmetatable(vec, Vector3D_meta) return vec end function vec2d(x,z) return Vector3D.new(x, 0, z) end function vec3d(x,y,z) return Vector3D.new(x, y, z) end function Vector3D.getArgs(v) return v.x,v.y,v.z end function Vector3D.set(v,x,y,z) v.x = x v.y = y v.z = z end function Vector3D.magnitude(v) return math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z) end function Vector3D.normalize(v) mag = Vector3D.magnitude(v) return v * (1/mag) end function Vector3D.add(a,b) return Vector3D.new(a.x + b.x, a.y + b.y, a.z + b.z) end function Vector3D.sub(a,b) return Vector3D.new(a.x - b.x, a.y - b.y, a.z - b.z) end function Vector3D.scale(v,s) return Vector3D.new(v.x * s, v.y * s, v.z * s) end function Vector3D.ortho2D(v) return Vector3D.new(-v.z, v.y, v.x) end function Vector3D.dot(a, b) return a.x * b.x + a.y * b.y + a.z * b.z end function Vector3D.cross(a, b) return Vector3D.new(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x) end Vector3D_meta.__add = Vector3D.add Vector3D_meta.__sub = Vector3D.sub Vector3D_meta.__mul = Vector3D.scale function Vector3D_meta.__index(tbl,key) return Vector3D[key] end function calcCurve(p1, p2, t) t2 = t*t t3 = t2*t return p1.p * ( 2*t3 - 3*t2 + 1) + p2.p * ( -2*t3 + 3*t2 ) + p1.t * ( t3 - 2*t2 + t) + p2.t * ( t3 - t2 ) end
mit
NPLPackages/main
script/ide/Debugger/JITProfiler.lua
1
8807
--[[ Author: LiXizhi Date: 2021/3/10 Desc: Luajit 2.1 profiler ----------------------------------------------- local p = NPL.load("script/ide/Debugger/JITProfiler.lua") p.start("G", "temp/profile.txt") commonlib.TimerManager.SetTimeout(function() p.stop() end, 10*1000) ]] ---------------------------------------------------------------------------- -- LuaJIT profiler. -- -- Copyright (C) 2005-2017 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- Example usage: -- -- luajit -jp myapp.lua -- luajit -jp=s myapp.lua -- luajit -jp=-s myapp.lua -- luajit -jp=vl myapp.lua -- luajit -jp=G,profile.txt myapp.lua -- -- The following dump features are available: -- -- f Stack dump: function name, otherwise module:line. Default mode. -- F Stack dump: ditto, but always prepend module. -- l Stack dump: module:line. -- <number> stack dump depth (callee < caller). Default: 1. -- -<number> Inverse stack dump depth (caller > callee). -- s Split stack dump after first stack level. Implies abs(depth) >= 2. -- p Show full path for module names. -- v Show VM states. Can be combined with stack dumps, e.g. vf or fv. -- z Show zones. Can be combined with stack dumps, e.g. zf or fz. -- r Show raw sample counts. Default: show percentages. -- a Annotate excerpts from source code files. -- A Annotate complete source code files. -- G Produce raw output suitable for graphical tools (e.g. flame graphs). -- m<number> Minimum sample percentage to be shown. Default: 3. -- i<number> Sampling interval in milliseconds. Default: 10. -- ---------------------------------------------------------------------------- -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local profile = require("jit.profile") local math = math local pairs, ipairs, tonumber, floor = pairs, ipairs, tonumber, math.floor local sort, format = table.sort, string.format local stdout = io.stdout local zone -- Load jit.zone module on demand. -- Output file handle. local out ------------------------------------------------------------------------------ local prof_ud local prof_states, prof_split, prof_min, prof_raw, prof_fmt, prof_depth local prof_ann, prof_count1, prof_count2, prof_samples local map_vmmode = { N = "Compiled", I = "Interpreted", C = "C code", G = "Garbage Collector", J = "JIT Compiler", } -- Profiler callback. local function prof_cb(th, samples, vmmode) prof_samples = prof_samples + samples local key_stack, key_stack2, key_state -- Collect keys for sample. if prof_states then if prof_states == "v" then key_state = map_vmmode[vmmode] or vmmode else key_state = zone:get() or "(none)" end end if prof_fmt then key_stack = profile.dumpstack(th, prof_fmt, prof_depth) if prof_split == 2 then local k1, k2 = key_stack:match("(.-) [<>] (.*)") if k2 then key_stack, key_stack2 = k1, k2 end elseif prof_split == 3 then key_stack2 = profile.dumpstack(th, "l", 1) end end -- Order keys. local k1, k2 if prof_split == 1 then if key_state then k1 = key_state if key_stack then k2 = key_stack end end elseif key_stack then k1 = key_stack if key_stack2 then k2 = key_stack2 elseif key_state then k2 = key_state end end -- Coalesce samples in one or two levels. if k1 then local t1 = prof_count1 t1[k1] = (t1[k1] or 0) + samples if k2 then local t2 = prof_count2 local t3 = t2[k1] if not t3 then t3 = {}; t2[k1] = t3 end t3[k2] = (t3[k2] or 0) + samples end end end ------------------------------------------------------------------------------ -- Show top N list. local function prof_top(count1, count2, samples, indent) local t, n = {}, 0 for k in pairs(count1) do n = n + 1 t[n] = k end sort(t, function(a, b) return count1[a] > count1[b] end) for i = 1, n do local k = t[i] local v = count1[k] local pct = floor(v * 100 / samples + 0.5) if pct < prof_min then break end if not prof_raw then out:write(format("%s%2d%% %s\n", indent, pct, k)) elseif prof_raw == "r" then out:write(format("%s%5d %s\n", indent, v, k)) else out:write(format("%s %d\n", k, v)) end if count2 then local r = count2[k] if r then prof_top(r, nil, v, (prof_split == 3 or prof_split == 1) and " -- " or (prof_depth < 0 and " -> " or " <- ")) end end end end -- Annotate source code local function prof_annotate(count1, samples) local files = {} local ms = 0 for k, v in pairs(count1) do local pct = floor(v * 100 / samples + 0.5) ms = math.max(ms, v) if pct >= prof_min then local file, line = k:match("^(.*):(%d+)$") if not file then file = k; line = 0 end local fl = files[file] if not fl then fl = {}; files[file] = fl; files[#files + 1] = file end line = tonumber(line) fl[line] = prof_raw and v or pct end end sort(files) local fmtv, fmtn = " %3d%% | %s\n", " | %s\n" if prof_raw then local n = math.max(5, math.ceil(math.log10(ms))) fmtv = "%"..n.."d | %s\n" fmtn = (" "):rep(n).." | %s\n" end local ann = prof_ann for _, file in ipairs(files) do local f0 = file:byte() if f0 == 40 or f0 == 91 then out:write(format("\n====== %s ======\n[Cannot annotate non-file]\n", file)) break end local fp, err = io.open(file) if not fp then out:write(format("====== ERROR: %s: %s\n", file, err)) break end out:write(format("\n====== %s ======\n", file)) local fl = files[file] local n, show = 1, false if ann ~= 0 then for i = 1, ann do if fl[i] then show = true; out:write("@@ 1 @@\n"); break end end end for line in fp:lines() do if line:byte() == 27 then out:write("[Cannot annotate bytecode file]\n") break end local v = fl[n] local bNoOutput if ann ~= 0 then local v2 = fl[n + ann] if show then if v2 then show = n + ann elseif v then show = n elseif show + ann < n then show = false end elseif v2 then show = n + ann out:write(format("@@ %d @@\n", n)) end if not show then bNoOutput = true end end if(not bNoOutput) then if v then out:write(format(fmtv, v, line)) else out:write(format(fmtn, line)) end end n = n + 1 end fp:close() end end ------------------------------------------------------------------------------ -- Finish profiling and dump result. local function prof_finish() if prof_ud then profile.stop() local samples = prof_samples if samples == 0 then if prof_raw ~= true then out:write("[No samples collected]\n") end return end if prof_ann then prof_annotate(prof_count1, samples) else prof_top(prof_count1, prof_count2, samples, "") end out:close() prof_count1 = nil prof_count2 = nil prof_ud = nil end end -- Start profiling. local function prof_start(mode) local interval = "" mode = mode:gsub("i%d*", function(s) interval = s; return "" end) prof_min = 3 mode = mode:gsub("m(%d+)", function(s) prof_min = tonumber(s); return "" end) prof_depth = 1 mode = mode:gsub("%-?%d+", function(s) prof_depth = tonumber(s); return "" end) local m = {} for c in mode:gmatch(".") do m[c] = c end prof_states = m.z or m.v if prof_states == "z" then zone = require("jit.zone") end local scope = m.l or m.f or m.F or(prof_states and "" or "f") local flags = (m.p or "") prof_raw = m.r if m.s then prof_split = 2 if prof_depth == -1 or m["-"] then prof_depth = -2 elseif prof_depth == 1 then prof_depth = 2 end elseif mode:find("[fF].*l") then scope = "l" prof_split = 3 else prof_split = (scope == "" or mode:find("[zv].*[lfF]")) and 1 or 0 end prof_ann = m.A and 0 or (m.a and 3) if prof_ann then scope = "l" prof_fmt = "pl" prof_split = 0 prof_depth = 1 elseif m.G and scope ~= "" then prof_fmt = flags..scope.."Z;" prof_depth = -100 prof_raw = true prof_min = 0 elseif scope == "" then prof_fmt = false else local sc = prof_split == 3 and m.f or m.F or scope prof_fmt = flags..sc..(prof_depth >= 0 and "Z < " or "Z > ") end prof_count1 = {} prof_count2 = {} prof_samples = 0 profile.start(scope:lower()..interval, prof_cb) prof_ud = newproxy(true) getmetatable(prof_ud).__gc = prof_finish end ------------------------------------------------------------------------------ local function start(mode, outfile) if not outfile then outfile = os.getenv("LUAJIT_PROFILEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stdout end prof_start(mode or "f") end -- Public module functions. return { start = start, -- For -j command line option. stop = prof_finish }
gpl-2.0
mtroyka/Zero-K
LuaRules/Gadgets/mex_spot_finder.lua
2
14101
function gadget:GetInfo() return { name = "Metalspot Finder Gadget", desc = "Finds metal spots", author = "Niobium, modified by Google Frog", version = "v1.1", date = "November 2010", license = "GNU GPL, v2 or later", layer = -math.huge + 5, enabled = true } end -------------------------------------------------------------------------------- -- SYNCED -------------------------------------------------------------------------------- if (gadgetHandler:IsSyncedCode()) then ------------------------------------------------------------ -- Config ------------------------------------------------------------ local MAPSIDE_METALMAP = "mapconfig/map_metal_layout.lua" local GAMESIDE_METALMAP = "LuaRules/Configs/MetalSpots/" .. (Game.mapName or "") .. ".lua" local DEFAULT_MEX_INCOME = 2 local MINIMUN_MEX_INCOME = 0.2 local gridSize = 16 -- Resolution of metal map local buildGridSize = 8 -- Resolution of build positions local METAL_MAP_SQUARE_SIZE = 16 local MEX_RADIUS = Game.extractorRadius local MAP_SIZE_X = Game.mapSizeX local MAP_SIZE_X_SCALED = MAP_SIZE_X / METAL_MAP_SQUARE_SIZE local MAP_SIZE_Z = Game.mapSizeZ local MAP_SIZE_Z_SCALED = MAP_SIZE_Z / METAL_MAP_SQUARE_SIZE local gameConfig = VFS.FileExists(GAMESIDE_METALMAP) and VFS.Include(GAMESIDE_METALMAP) or false local mapConfig = VFS.FileExists(MAPSIDE_METALMAP) and VFS.Include(MAPSIDE_METALMAP) or false ------------------------------------------------------------ -- Speedups ------------------------------------------------------------ local min, max = math.min, math.max local floor, ceil = math.floor, math.ceil local sqrt = math.sqrt local huge = math.huge local spGetGroundInfo = Spring.GetGroundInfo local spGetGroundHeight = Spring.GetGroundHeight local spTestBuildOrder = Spring.TestBuildOrder local spSetGameRulesParam = Spring.SetGameRulesParam local extractorRadius = Game.extractorRadius local extractorRadiusSqr = extractorRadius * extractorRadius local buildmapSizeX = Game.mapSizeX - buildGridSize local buildmapSizeZ = Game.mapSizeZ - buildGridSize local buildmapStartX = buildGridSize local buildmapStartZ = buildGridSize local metalmapSizeX = Game.mapSizeX - 1.5 * gridSize local metalmapSizeZ = Game.mapSizeZ - 1.5 * gridSize local metalmapStartX = 1.5 * gridSize local metalmapStartZ = 1.5 * gridSize ------------------------------------------------------------ -- Variables ------------------------------------------------------------ local mexUnitDef = UnitDefNames["cormex"] local mexDefInfo = { extraction = 0.001, square = false, oddX = mexUnitDef.xsize % 4 == 2, oddZ = mexUnitDef.zsize % 4 == 2, } local modOptions if (Spring.GetModOptions) then modOptions = Spring.GetModOptions() end ------------------------------------------------------------ -- Speedup ------------------------------------------------------------ local function GetSpotsByPos(spots) local spotPos = {} for i = 1, #spots do local spot = spots[i] local x = spot.x local z = spot.z --Spring.MarkerAddPoint(x,0,z,x .. ", " .. z) spotPos[x] = spotPos[x] or {} spotPos[x][z] = i end return spotPos end ------------------------------------------------------------ -- Set Game Rules so widgets can read metal spots ------------------------------------------------------------ local function SetMexGameRulesParams(metalSpots) if not metalSpots then -- Mexes can be built anywhere spSetGameRulesParam("mex_count", -1) return end local mexCount = #metalSpots spSetGameRulesParam("mex_count", mexCount) for i = 1, mexCount do local mex = metalSpots[i] spSetGameRulesParam("mex_x" .. i, mex.x) spSetGameRulesParam("mex_y" .. i, mex.y) spSetGameRulesParam("mex_z" .. i, mex.z) spSetGameRulesParam("mex_metal" .. i, mex.metal) end end ------------------------------------------------------------ -- Callins ------------------------------------------------------------ function gadget:Initialize() Spring.Log(gadget:GetInfo().name, LOG.INFO, "Mex Spot Finder Initialising") local metalSpots, fromEngineMetalmap = GetSpots() local metalSpotsByPos = false if fromEngineMetalmap and #metalSpots < 6 then Spring.Log(gadget:GetInfo().name, LOG.INFO, "Indiscrete metal map detected") metalSpots = false end local metalValueOverride = gameConfig and gameConfig.metalValueOverride if metalSpots then local mult = (modOptions and modOptions.metalmult) or 1 local i = 1 while i <= #metalSpots do local spot = metalSpots[i] if spot.metal > MINIMUN_MEX_INCOME then if metalValueOverride then spot.metal = metalValueOverride end spot.metal = spot.metal*mult i = i + 1 else metalSpots[i] = metalSpots[#metalSpots] metalSpots[#metalSpots] = nil end end metalSpotsByPos = GetSpotsByPos(metalSpots) end SetMexGameRulesParams(metalSpots) GG.metalSpots = metalSpots GG.metalSpotsByPos = metalSpotsByPos GG.IntegrateMetal = IntegrateMetal Spring.Log(gadget:GetInfo().name, LOG.INFO, "Metal Spots found and GGed") end ------------------------------------------------------------ -- Extractor Income Processing ------------------------------------------------------------ function IntegrateMetal(x, z, radius) local centerX, centerZ radius = radius or MEX_RADIUS if (mexDefInfo.oddX) then centerX = (floor( x / METAL_MAP_SQUARE_SIZE) + 0.5) * METAL_MAP_SQUARE_SIZE else centerX = floor( x / METAL_MAP_SQUARE_SIZE + 0.5) * METAL_MAP_SQUARE_SIZE end if (mexDefInfo.oddZ) then centerZ = (floor( z / METAL_MAP_SQUARE_SIZE) + 0.5) * METAL_MAP_SQUARE_SIZE else centerZ = floor( z / METAL_MAP_SQUARE_SIZE + 0.5) * METAL_MAP_SQUARE_SIZE end local startX = floor((centerX - radius) / METAL_MAP_SQUARE_SIZE) local startZ = floor((centerZ - radius) / METAL_MAP_SQUARE_SIZE) local endX = floor((centerX + radius) / METAL_MAP_SQUARE_SIZE) local endZ = floor((centerZ + radius) / METAL_MAP_SQUARE_SIZE) startX, startZ = max(startX, 0), max(startZ, 0) endX, endZ = min(endX, MAP_SIZE_X_SCALED - 1), min(endZ, MAP_SIZE_Z_SCALED - 1) local mult = mexDefInfo.extraction local square = mexDefInfo.square local result = 0 if (square) then for i = startX, endX do for j = startZ, endZ do local cx, cz = (i + 0.5) * METAL_MAP_SQUARE_SIZE, (j + 0.5) * METAL_MAP_SQUARE_SIZE local _, metal = spGetGroundInfo(cx, cz) result = result + metal end end else for i = startX, endX do for j = startZ, endZ do local cx, cz = (i + 0.5) * METAL_MAP_SQUARE_SIZE, (j + 0.5) * METAL_MAP_SQUARE_SIZE local dx, dz = cx - centerX, cz - centerZ local dist = sqrt(dx * dx + dz * dz) if (dist < radius) then local _, metal = spGetGroundInfo(cx, cz) result = result + metal end end end end return result * mult, centerX, centerZ end ------------------------------------------------------------ -- Mex finding ------------------------------------------------------------ local function SanitiseSpots(spots) local i = 1 while i <= #spots do local spot = spots[i] if spot and spot.x and spot.z then local metal metal, spot.x, spot.z = IntegrateMetal(spot.x, spot.z) spot.y = spGetGroundHeight(spot.x, spot.z) spot.metal = metalValueOverride or spot.metal or (metal > 0 and metal) or DEFAULT_MEX_INCOME i = i + 1 else spot[i] = spot[#spots] spot[#spots] = nil end end return spots end local function makeString(group) if group then local ret = "" for i, v in pairs(group.left) do ret = ret .. i .. v end ret = ret .. " " for i, v in pairs(group.right) do ret = ret .. i .. v end ret = ret .. " " .. group.minZ .. " " .. group.maxZ .. " " .. group.worth return ret else return "" end end function GetSpots() local spots = {} -- Check configs if gameConfig then Spring.Log(gadget:GetInfo().name, LOG.INFO, "Loading gameside mex config") if gameConfig.spots then spots = SanitiseSpots(gameConfig.spots) return spots, false end end if mapConfig then Spring.Log(gadget:GetInfo().name, LOG.INFO, "Loading mapside mex config") loadConfig = true spots = SanitiseSpots(mapConfig.spots) return spots, false end Spring.Log(gadget:GetInfo().name, LOG.INFO, "Detecting mex config from metalmap") -- Main group collection local uniqueGroups = {} -- Strip info local nStrips = 0 local stripLeft = {} local stripRight = {} local stripGroup = {} -- Indexes local aboveIdx local workingIdx -- Strip processing function (To avoid some code duplication) local function DoStrip(x1, x2, z, worth) local assignedTo for i = aboveIdx, workingIdx - 1 do if stripLeft[i] > x2 + gridSize then break elseif stripRight[i] + gridSize >= x1 then local matchGroup = stripGroup[i] if assignedTo then if matchGroup ~= assignedTo then for iz = matchGroup.minZ, assignedTo.minZ - gridSize, gridSize do assignedTo.left[iz] = matchGroup.left[iz] end for iz = matchGroup.minZ, matchGroup.maxZ, gridSize do assignedTo.right[iz] = matchGroup.right[iz] end if matchGroup.minZ < assignedTo.minZ then assignedTo.minZ = matchGroup.minZ end assignedTo.maxZ = z assignedTo.worth = assignedTo.worth + matchGroup.worth uniqueGroups[makeString(matchGroup)] = nil end else assignedTo = matchGroup assignedTo.left[z] = assignedTo.left[z] or x1 -- Only accept the first assignedTo.right[z] = x2 -- Repeated overwrite gives us result we want assignedTo.maxZ = z -- Repeated overwrite gives us result we want assignedTo.worth = assignedTo.worth + worth end else aboveIdx = aboveIdx + 1 end end nStrips = nStrips + 1 stripLeft[nStrips] = x1 stripRight[nStrips] = x2 if assignedTo then stripGroup[nStrips] = assignedTo else local newGroup = { left = {[z] = x1}, right = {[z] = x2}, minZ = z, maxZ = z, worth = worth } stripGroup[nStrips] = newGroup uniqueGroups[makeString(newGroup)] = newGroup end end -- Strip finding workingIdx = huge for mz = metalmapStartX, metalmapSizeZ, gridSize do aboveIdx = workingIdx workingIdx = nStrips + 1 local stripStart = nil local stripWorth = 0 for mx = metalmapStartZ, metalmapSizeX, gridSize do local _, groundMetal = spGetGroundInfo(mx, mz) if groundMetal > 0 then stripStart = stripStart or mx stripWorth = stripWorth + groundMetal elseif stripStart then DoStrip(stripStart, mx - gridSize, mz, stripWorth) stripStart = nil stripWorth = 0 end end if stripStart then DoStrip(stripStart, metalmapSizeX, mz, stripWorth) end end -- Final processing for _, g in pairs(uniqueGroups) do local d = {} local gMinX, gMaxX = huge, -1 local gLeft, gRight = g.left, g.right for iz = g.minZ, g.maxZ, gridSize do if gLeft[iz] < gMinX then gMinX = gLeft[iz] end if gRight[iz] > gMaxX then gMaxX = gRight[iz] end end local x = (gMinX + gMaxX) * 0.5 local z = (g.minZ + g.maxZ) * 0.5 d.metal, d.x, d.z = IntegrateMetal(x,z) d.y = spGetGroundHeight(d.x, d.z) local merged = false for i = 1, #spots do local spot = spots[i] local dis = (d.x - spot.x)^2 + (d.z - spot.z)^2 if dis < extractorRadiusSqr*4 then local metal, mx, mz = IntegrateMetal((d.x + spot.x) * 0.5, (d.z + spot.z) * 0.5) if dis < extractorRadiusSqr*1.7 or metal > (d.metal + spot.metal)*0.95 then spot.x = mx spot.y = spGetGroundHeight(mx, mx) spot.z = mz spot.metal = metal merged = true break end end end if not merged then spots[#spots + 1] = d end end --for i = 1, #spots do -- Spring.MarkerAddPoint(spots[i].x,spots[i].y,spots[i].z,"") --end return spots, true end function GetValidStrips(spot) local sMinZ, sMaxZ = spot.minZ, spot.maxZ local sLeft, sRight = spot.left, spot.right local validLeft = {} local validRight = {} local maxZOffset = buildGridSize * ceil(extractorRadius / buildGridSize - 1) for mz = max(sMaxZ - maxZOffset, buildmapStartZ), min(sMinZ + maxZOffset, buildmapSizeZ), buildGridSize do local vLeft, vRight = buildmapStartX, buildmapSizeX for sz = sMinZ, sMaxZ, gridSize do local dz = sz - mz local maxXOffset = buildGridSize * ceil(sqrt(extractorRadiusSqr - dz * dz) / buildGridSize - 1) -- Test for metal being included is dist < extractorRadius local left, right = sRight[sz] - maxXOffset, sLeft[sz] + maxXOffset if left > vLeft then vLeft = left end if right < vRight then vRight = right end end validLeft[mz] = vLeft validRight[mz] = vRight end spot.validLeft = validLeft spot.validRight = validRight end -------------------------------------------------------------------------------- else -- UNSYNCED -------------------------------------------------------------------------------- function gadget:GameStart() Spring.Utilities = Spring.Utilities or {} VFS.Include("LuaRules/Utilities/json.lua"); local teamlist = Spring.GetTeamList(); local localPlayer = Spring.GetLocalPlayerID(); local mexes = ""; local encoded = false; for _, teamID in pairs(teamlist) do local _,_,_,isAI = Spring.GetTeamInfo(teamID) if isAI then local aiid, ainame, aihost = Spring.GetAIInfo(teamID); if (aihost == localPlayer) then if not encoded then local metalSpots = GetMexSpotsFromGameRules(); mexes = 'METAL_SPOTS:'..Spring.Utilities.json.encode(metalSpots); encoded = true; end Spring.SendSkirmishAIMessage(teamID, mexes); end end end end function GetMexSpotsFromGameRules() local spGetGameRulesParam = Spring.GetGameRulesParam local mexCount = spGetGameRulesParam("mex_count") if (not mexCount) or mexCount == -1 then return {} end local metalSpots = {} for i = 1, mexCount do metalSpots[i] = { x = spGetGameRulesParam("mex_x" .. i), y = spGetGameRulesParam("mex_y" .. i), z = spGetGameRulesParam("mex_z" .. i), metal = spGetGameRulesParam("mex_metal" .. i), } end return metalSpots end end
gpl-2.0
thedraked/darkstar
scripts/zones/West_Sarutabaruta/npcs/Cavernous_Maw.lua
29
1467
----------------------------------- -- Area: West Sarutabaruta -- NPC: Cavernous Maw -- Teleports Players to West Sarutabaruta [S] -- @pos -2.229 0.001 -162.715 115 ----------------------------------- package.loaded["scripts/zones/West_Sarutabaruta/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/campaign"); require("scripts/zones/West_Sarutabaruta/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) and hasMawActivated(player,8)) then player:startEvent(0x0388); else player:messageSpecial(NOTHING_HAPPENS); 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); if (csid == 0x0388 and option == 1) then toMaw(player,7); end end;
gpl-3.0
thedraked/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/_5f5.lua
12
1097
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Shiva's Gate -- @pos 270 -34 100 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 9) then player:messageSpecial(SOLID_STONE); end return 0; 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
mamaddeveloper/7894
plugins/anti_spam.lua
191
5291
--An empty table for solving multiple kicking problem(thanks to @topkecleon ) kicktable = {} do local TIME_CHECK = 2 -- seconds -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then return msg end if msg.from.id == our_id then return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Save stats on Redis if msg.to.type == 'channel' then -- User is on channel local hash = 'channel:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end if msg.to.type == 'user' then -- User is on chat local hash = 'PM:'..msg.from.id redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) --Load moderation data local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then --Check if flood is on or off if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then return msg end end -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) local data = load_data(_config.moderation.data) local NUM_MSG_MAX = 5 if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity end end local max_msg = NUM_MSG_MAX * 1 if msgs > max_msg then local user = msg.from.id local chat = msg.to.id local whitelist = "whitelist" local is_whitelisted = redis:sismember(whitelist, user) -- Ignore mods,owner and admins if is_momod(msg) then return msg end if is_whitelisted == true then return msg end local receiver = get_receiver(msg) if msg.to.type == 'user' then local max_msg = 7 * 1 print(msgs) if msgs >= max_msg then print("Pass2") send_large_msg("user#id"..msg.from.id, "User ["..msg.from.id.."] blocked for spam.") savelog(msg.from.id.." PM", "User ["..msg.from.id.."] blocked for spam.") block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private end end if kicktable[user] == true then return end delete_msg(msg.id, ok_cb, false) kick_user(user, chat) local username = msg.from.username local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", "") if msg.to.type == 'chat' or msg.to.type == 'channel' then if username then savelog(msg.to.id, name_log.." @"..username.." ["..msg.from.id.."] kicked for #spam") send_large_msg(receiver , "Flooding is not allowed here\n@"..username.."["..msg.from.id.."]\nStatus: User kicked") else savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked for #spam") send_large_msg(receiver , "Flooding is not allowed here\nName:"..name_log.."["..msg.from.id.."]\nStatus: User kicked") end end -- incr it on redis local gbanspam = 'gban:spam'..msg.from.id redis:incr(gbanspam) local gbanspam = 'gban:spam'..msg.from.id local gbanspamonredis = redis:get(gbanspam) --Check if user has spammed is group more than 4 times if gbanspamonredis then if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then --Global ban that user banall_user(msg.from.id) local gbanspam = 'gban:spam'..msg.from.id --reset the counter redis:set(gbanspam, 0) if msg.from.username ~= nil then username = msg.from.username else username = "---" end local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") --Send this to that chat send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)") send_large_msg("channel#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)") local GBan_log = 'GBan_log' local GBan_log = data[tostring(GBan_log)] for k,v in pairs(GBan_log) do log_SuperGroup = v gban_text = "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)" --send it to log group/channel send_large_msg(log_SuperGroup, gban_text) end end end kicktable[user] = true msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function cron() --clear that table on the top of the plugins kicktable = {} end return { patterns = {}, cron = cron, pre_process = pre_process } end
gpl-2.0
thedraked/darkstar
scripts/globals/spells/temper.lua
27
1135
----------------------------------------- -- -- Spell: Temper -- ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effect = EFFECT_MULTI_STRIKES; local enhskill = caster:getSkillLevel(ENHANCING_MAGIC_SKILL); local final = 0; local duration = 180; if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then duration = duration * 3; end if (enhskill<360) then final = 5; elseif (enhskill>=360) then final = math.floor( (enhskill - 300) / 10 ); else print("Warning: Unknown enhancing magic skill for Temper."); end if (final>20) then final = 20; end if (target:addStatusEffect(effect,final,0,duration)) then spell:setMsg(230); else spell:setMsg(75); end return effect; end;
gpl-3.0
MonkeyFirst/Urho3D
Source/Urho3D/LuaScript/pkgs/ToCppHook.lua
8
7914
-- -- Copyright (c) 2008-2018 the Urho3D project. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- local toWrite = {} local currentString = '' local out local WRITE, OUTPUT = write, output function output(s) out = _OUTPUT output = OUTPUT -- restore output(s) end function write(a) if out == _OUTPUT then currentString = currentString .. a if string.sub(currentString,-1) == '\n' then toWrite[#toWrite+1] = currentString currentString = '' end else WRITE(a) end end function post_output_hook(package) local result = table.concat(toWrite) local function replace(pattern, replacement) local k = 0 local nxt, currentString = 1, '' repeat local s, e = string.find(result, pattern, nxt, true) if e then currentString = currentString .. string.sub(result, nxt, s-1) .. replacement nxt = e + 1 k = k + 1 end until not e result = currentString..string.sub(result, nxt) end replace("\t", " ") replace([[#ifndef __cplusplus #include "stdlib.h" #endif #include "string.h" #include "tolua++.h"]], [[// // Copyright (c) 2008-2018 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "Precompiled.h" #include <toluapp/tolua++.h> #include "LuaScript/ToluaUtils.h" #if __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #endif]]) if not _extra_parameters["Urho3D"] then replace([[#include "LuaScript/ToluaUtils.h"]], [[#include <Urho3D/LuaScript/ToluaUtils.h>]]) end -- Special handling for vector to table conversion which would simplify the implementation of the template functions result = string.gsub(result, "ToluaIs(P?O?D?)Vector([^\"]-)\"c?o?n?s?t? ?P?O?D?Vector<([^*>]-)%*?>\"", "ToluaIs%1Vector%2\"%3\"") result = string.gsub(result, "ToluaPush(P?O?D?)Vector([^\"]-)\"c?o?n?s?t? ?P?O?D?Vector<([^*>]-)%*?>\"", "ToluaPush%1Vector%2\"%3\"") result = string.gsub(result, "@1%(", "(\"\",") -- is_pointer overload uses const char* as signature result = string.gsub(result, "@2%(", "(0.f,") -- is_arithmetic overload uses double as signature WRITE(result) WRITE([[ #if __clang__ #pragma clang diagnostic pop #endif]]) end _push_functions['Component'] = "ToluaPushObject" _push_functions['Resource'] = "ToluaPushObject" _push_functions['UIElement'] = "ToluaPushObject" -- Is Urho3D Vector type. function urho3d_is_vector(t) return t:find("Vector<") ~= nil end -- Is Urho3D PODVector type. function urho3d_is_podvector(t) return t:find("PODVector<") ~= nil end local old_get_push_function = get_push_function local old_get_to_function = get_to_function local old_get_is_function = get_is_function function is_pointer(t) return t:find("*>") end function is_arithmetic(t) for _, type in pairs({ "char", "short", "int", "unsigned", "long", "float", "double", "bool" }) do _, pos = t:find(type) if pos ~= nil and t:sub(pos + 1, pos + 1) ~= "*" then return true end end return false end function overload_if_necessary(t) return is_pointer(t) and "@1" or (is_arithmetic(t) and "@2" or "") end function get_push_function(t) if not urho3d_is_vector(t) then return old_get_push_function(t) end local T = t:match("<.*>") if not urho3d_is_podvector(t) then return "ToluaPushVector" .. T else return "ToluaPushPODVector" .. T .. overload_if_necessary(T) end end function get_to_function(t) if not urho3d_is_vector(t) then return old_get_to_function(t) end local T = t:match("<.*>") if not urho3d_is_podvector(t) then return "ToluaToVector" .. T else return "ToluaToPODVector" .. T .. overload_if_necessary(T) end end function get_is_function(t) if not urho3d_is_vector(t) then return old_get_is_function(t) end local T = t:match("<.*>") if not urho3d_is_podvector(t) then return "ToluaIsVector" .. T else return "ToluaIsPODVector" .. T .. overload_if_necessary(T) end end function get_property_methods_hook(ptype, name) if ptype == "get_set" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return "Get"..Name, "Set"..Name end if ptype == "is_set" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return "Is"..Name, "Set"..Name end if ptype == "has_set" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return "Has"..Name, "Set"..Name end if ptype == "no_prefix" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return Name, "Set"..Name end end -- Rudimentary checker to prevent function overloads being declared in a wrong order -- The checker assumes function overloads are declared in group one after another within a same pkg file -- The checker only checks for single argument function at the moment, but it can be extended to support more when it is necessary local overload_checker = {name="", has_number=false} function pre_call_hook(self) if table.getn(self.args) ~= 1 then return end if overload_checker.name ~= self.name then overload_checker.name = self.name overload_checker.has_number = false end local t = self.args[1].type if overload_checker.has_number then if t:find("String") or t:find("char*") then warning(self:inclass() .. ":" .. self.name .. " has potential binding problem: number overload becomes dead code if it is declared before string overload") end else overload_checker.has_number = t ~= "bool" and is_arithmetic(t) end end
mit
thedraked/darkstar
scripts/zones/Sauromugue_Champaign/npcs/qm6.lua
14
2470
----------------------------------- -- Area: Sauromugue Champaign -- NPC: qm6 (???) (Tower 6) -- Involved in Quest: THF AF "As Thick As Thieves" -- @pos 363.481 23.600 6.335 120 ----------------------------------- package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Sauromugue_Champaign/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local thickAsThievesGrapplingCS = player:getVar("thickAsThievesGrapplingCS"); if (thickAsThievesGrapplingCS >= 2 and thickAsThievesGrapplingCS <= 7) then if (trade:hasItemQty(17474,1) and trade:getItemCount() == 1) then -- Trade grapel player:messageSpecial(THF_AF_WALL_OFFSET+3,0,17474); -- You cannot get a decent grip on the wall using the [Grapnel]. end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local thickAsThieves = player:getQuestStatus(WINDURST,AS_THICK_AS_THIEVES); local thickAsThievesGrapplingCS = player:getVar("thickAsThievesGrapplingCS"); if (thickAsThieves == QUEST_ACCEPTED) then if (thickAsThievesGrapplingCS == 6) then player:messageSpecial(THF_AF_MOB); GetMobByID(17269107):setSpawn(371,24,8); SpawnMob(17269107):updateClaim(player); -- Climbpix Highrise elseif (thickAsThievesGrapplingCS == 0 or thickAsThievesGrapplingCS == 1 or thickAsThievesGrapplingCS == 2 or thickAsThievesGrapplingCS == 3 or thickAsThievesGrapplingCS == 4 or thickAsThievesGrapplingCS == 5 or thickAsThievesGrapplingCS == 7) then player:messageSpecial(THF_AF_WALL_OFFSET); end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
ukoloff/rufus-lua-win
vendor/lua/lib/lua/logging/rolling_file.lua
3
2248
--------------------------------------------------------------------------- -- RollingFileAppender is a FileAppender that rolls over the logfile -- once it has reached a certain size limit. It also mantains a -- maximum number of log files. -- -- @author Tiago Cesar Katcipis (tiagokatcipis@gmail.com) -- -- @copyright 2004-2007 Kepler Project --------------------------------------------------------------------------- require"logging" local function openFile(self) self.file = io.open(self.filename, "a") if not self.file then return nil, string.format("file `%s' could not be opened for writing", self.filename) end self.file:setvbuf ("line") return self.file end local rollOver = function (self) for i = self.maxIndex - 1, 1, -1 do -- files may not exist yet, lets ignore the possible errors. os.rename(self.filename.."."..i, self.filename.."."..i+1) end self.file:close() self.file = nil local _, msg = os.rename(self.filename, self.filename..".".."1") if msg then return nil, string.format("error %s on log rollover", msg) end return openFile(self) end local openRollingFileLogger = function (self) if not self.file then return openFile(self) end local filesize = self.file:seek("end", 0) if (filesize < self.maxSize) then return self.file end return rollOver(self) end function logging.rolling_file(filename, maxFileSize, maxBackupIndex, logPattern) if type(filename) ~= "string" then filename = "lualogging.log" end local obj = { filename = filename, maxSize = maxFileSize, maxIndex = maxBackupIndex or 1 } return logging.new( function(self, level, message) local f, msg = openRollingFileLogger(obj) if not f then return nil, msg end local s = logging.prepareLogMsg(logPattern, os.date(), level, message) f:write(s) return true end ) end
mit
SnabbCo/snabbswitch
src/apps/intel_mp/testrecv.lua
6
2675
-- Helper module for testing intel_mp driver receive module(..., package.seeall) local intel = require("apps.intel_mp.intel_mp") local basic = require("apps.basic.basic_apps") local ffi = require("ffi") local C = ffi.C function test(pciaddr, qno, vmdq, poolno, macaddr, vlan) local c = config.new() if vmdq then config.app(c, "nic", intel.Intel, { pciaddr=pciaddr, macaddr=macaddr, vlan=vlan, vmdq=true, poolnum=poolno, rxq = qno, rxcounter = qno+1, wait_for_link=true }) else config.app(c, "nic", intel.Intel, { pciaddr=pciaddr, rxq = qno, rxcounter = qno+1, wait_for_link=true }) end config.app(c, "sink", basic.Sink) if os.getenv("SNABB_RECV_EXPENSIVE") then local filter = require("apps.packet_filter.pcap_filter") local count = 10 config.link(c, "nic.output -> filter0.input") for i=0,count do local n = tostring(i) local s = "filter"..n config.app(c, s, filter.PcapFilter, { filter = [[ not dst host 10.2.29.1 and not dst host 10.2.50.1 ]]}) end for i=1,count do local m = tostring(i-1) local n = tostring(i) local s = "filter"..m..".output -> filter"..n..".input" config.link(c, s) end config.app(c, "sane", filter.PcapFilter, { filter = [[ src host 172.16.172.3 and dst net 1.2.0.0/16 and ip proto 0 ]] }) config.link(c, "filter"..tostring(count)..".output -> sane.input") config.link(c, "sane.output -> sink.input") else config.link(c, "nic.output -> sink.input") end engine.configure(c) local spinup = os.getenv("SNABB_RECV_SPINUP") if spinup then engine.main({duration = spinup}) end local counters = { Intel82599 = { "GPRC", "RXDGPC" }, Intel1g = { "GPRC", "RPTHC" } } local duration = os.getenv("SNABB_RECV_DURATION") or 2 local before = {} local nic = engine.app_table.nic local master = nic.master if master then for _,v in pairs(counters[nic.driver]) do before[v] = nic.r[v]() end end if os.getenv("SNABB_RECV_DEBUG") then for _=1,duration do engine.main({duration = 1}) nic:debug() end else engine.main({duration = duration}) end if master then for _,v in pairs(counters[nic.driver]) do print(string.format("%s %d", v, tonumber(nic.r[v]() - before[v])/duration)) end end main.exit(0) end
apache-2.0
NPLPackages/main
script/kids/3DMapSystemApp/mcml/mcml_base.lua
1
59937
--[[ Title: base mcml function and base Node implementation of mcml Author(s): LiXizhi Date: 2008/2/15 Desc: only included and used by mcml use the lib: ------------------------------------------------------------ NPL.load("(gl)script/kids/3DMapSystemApp/mcml/mcml_base.lua"); local node = Map3DSystem.mcml.new("pe:profile", {}) local o = Map3DSystem.mcml.buildclass(o); -- the following is an example of creating a custom mcml tag control. local pe_locationtracker = commonlib.gettable("MyCompany.Aries.mcml_controls.pe_locationtracker"); function pe_locationtracker.render_callback(mcmlNode, rootName, bindingContext, _parent, left, top, right, bottom, myLayout, css) -- TODO: your render code here -- local _this=ParaUI.CreateUIObject("button","b","_lt", left, top, right-left, bottom-top); -- _this.background = "Texture/alphadot.png"; -- _parent:AddChild(_this); -- mcmlNode:DrawChildBlocks_Callback(rootName, bindingContext, _parent, left, top, right, bottom, myLayout, css) return true, true, true; -- ignore_onclick, ignore_background, ignore_tooltip; end function pe_locationtracker.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout) return mcmlNode:DrawDisplayBlock(rootName, bindingContext, _parent, left, top, width, height, parentLayout, style, pe_locationtracker.render_callback); end ------------------------------------------------------- ]] NPL.load("(gl)script/ide/System/localserver/UrlHelper.lua"); NPL.load("(gl)script/kids/3DMapSystemApp/mcml/StyleItem.lua"); local StyleItem = commonlib.gettable("Map3DSystem.mcml_controls.StyleItem"); local pe_css = commonlib.gettable("Map3DSystem.mcml_controls.pe_css"); if(not Map3DSystem.mcml) then Map3DSystem.mcml = {} end local mcml = Map3DSystem.mcml; local pairs = pairs local ipairs = ipairs local tostring = tostring local tonumber = tonumber local type = type local string_find = string.find; local string_format = string.format; local string_gsub = string.gsub; local string_lower = string.lower local string_match = string.match; local table_getn = table.getn; local mcml_controls = commonlib.gettable("Map3DSystem.mcml_controls"); local LOG = LOG; local CommonCtrl = commonlib.gettable("CommonCtrl"); local NameNodeMap_ = {}; local commonlib = commonlib.gettable("commonlib"); local pe_html = commonlib.gettable("Map3DSystem.mcml_controls.pe_html"); ---------------------------- -- helper functions ---------------------------- -- set a node by a string name, so that the node can later be retrieved by name using GetNode(). -- @param name: string, this is usually the string returned by mcml.baseNode:GetInstanceName() -- @param node: the node table object. function mcml.SetNode(name, node) NameNodeMap_[name] = node; end -- get a node by a string name. -- @param name: string, function mcml.GetNode(name) return NameNodeMap_[name]; end ---------------------------- -- base functions ---------------------------- -- create or init a new object o of tag. it will return the input object, if tag name is not found. -- e.g. mcml.new(nil, {name="div"}) -- @param tagName: the tag (node) name to be created or initialized. if nil, the default "baseNode" is used. -- @param o: the tag object to be initialized. if nil, a new one will be created. -- @return: the tag (node) object is returned. methods of the object can be called thereafterwards. function mcml.new(tagName, o) local baseNode = mcml[tagName or "baseNode"]; if(baseNode) then o = o or {} if(baseNode.attr and o.attr) then setmetatable(o.attr, baseNode.attr) baseNode.attr.__index = baseNode.attr end setmetatable(o, baseNode) baseNode.__index = baseNode return o else -- return the input object, if tag name is not found. return o; end end -- o is a pure mcml table, after building class with it, it will be deserialized from pure data to a class contain all methods and parent|child relationships. -- o must be a pure table that does not contains cyclic table references. -- for unknown node in o, it will inherite from the baseNode. -- @return the input o is returned. function mcml.buildclass(o) local baseNode = mcml[o.name or "baseNode"]; if(not baseNode) then baseNode = mcml["baseNode"]; end if(baseNode.attr and o.attr) then setmetatable(o.attr, baseNode.attr) baseNode.attr.__index = baseNode.attr end setmetatable(o, baseNode) baseNode.__index = baseNode local i, child; for i, child in ipairs(o) do if(type(child) == "table") then mcml.buildclass(child); child.parent = o; child.index = i; end end return o; end ---------------------------- -- base node class ---------------------------- -- base class for all nodes. mcml.baseNode = { name = nil, parent = nil, -- control index in its parent index = 1, } -- return a copy of this object, everything is cloned including the parent and index of its child node. function mcml.baseNode:clone() local o = mcml.new(nil, {name = self.name}) if(self.attr) then o.attr = {}; commonlib.partialcopy(o.attr, self.attr) end local nSize = table_getn(self); if(nSize>0) then local i, node; for i=1, nSize do node = self[i]; if(type(node)=="table" and type(node.clone)=="function") then o[i] = node:clone(); o[i].index = i; o[i].parent = o; elseif(type(node)=="string") then o[i] = node; else LOG.warn("unknown node type when mcml.baseNode:clone() \n") end end table.resize(o, nSize); -- table.setn(o, nSize); end return o; end -- set the value of an attribute of this node. This function is rarely used. function mcml.baseNode:SetAttribute(attrName, value) self.attr = self.attr or {}; self.attr[attrName] = value; if(attrName == "style") then -- tricky code: since we will cache style table on the node, we need to delete the cached style when it is changed. self.style = nil; end end function mcml.baseNode:SetUIAttribute(attrName, value) self.attr = self.attr or {}; self.attr[attrName] = value; if(attrName == "style") then -- tricky code: since we will cache style table on the node, we need to delete the cached style when it is changed. self.style = nil; end local page = self:GetPageCtrl() if (page) then page:Refresh(0.01) end end -- set the attribute if attribute is not code. function mcml.baseNode:SetAttributeIfNotCode(attrName, value) self.attr = self.attr or {}; local old_value = self.attr[attrName]; if(type(old_value) == "string") then local code = string_match(old_value, "^[<%%]%%(=.*)%%[%%>]$") if(not code) then self.attr[attrName] = value; end else self.attr[attrName] = value; end end -- get the value of an attribute of this node as its original format (usually string) function mcml.baseNode:GetAttribute(attrName,defaultValue) if(self.attr) then return self.attr[attrName]; end return defaultValue; end -- get the value of an attribute of this node (usually string) -- this differs from GetAttribute() in that the attribute string may contain embedded code block which may evaluates to a different string, table or even function. -- please note that only the first call of this method will evaluate embedded code block, subsequent calls simply return the previous evaluated result. -- in most cases the result is nil or string, but it can also be a table or function. -- @param bNoOverwrite: default to nil. if true, the code will be reevaluated the next time this is called, otherwise the evaluated value will be saved and returned the next time this is called. -- e.g. attrName='<%="string"+Eval("index")}%>' attrName1='<%={fieldname="table"}%>' function mcml.baseNode:GetAttributeWithCode(attrName,defaultValue, bNoOverwrite) if(self.attr) then local value = self.attr[attrName]; if(type(value) == "string") then local code = string_match(value, "^[<%%]%%(=.*)%%[%%>]$") if(code) then value = mcml_controls.pe_script.DoPageCode(code, self:GetPageCtrl()); if(not bNoOverwrite) then self.attr[attrName] = value; end end end if(value ~= nil) then return value; end end return defaultValue; end -- get an attribute as string function mcml.baseNode:GetString(attrName,defaultValue) if(self.attr) then return self.attr[attrName]; end return defaultValue; end -- get an attribute as number function mcml.baseNode:GetNumber(attrName,defaultValue) if(self.attr) then return tonumber(self.attr[attrName]); end return defaultValue; end -- get an attribute as integer function mcml.baseNode:GetInt(attrName, defaultValue) if(self.attr) then return math.floor(tonumber(self.attr[attrName])); end return defaultValue; end -- get an attribute as boolean function mcml.baseNode:GetBool(attrName, defaultValue) if(self.attr) then local v = string_lower(tostring(self.attr[attrName])); if(v == "false") then return false elseif(v == "true") then return true end end return defaultValue; end -- get all pure text of only text node function mcml.baseNode:GetPureText() local nSize = table_getn(self); local i, node; local text = ""; for i=1, nSize do node = self[i]; if(node) then if(type(node) == "string") then text = text..node; end end end return text; end -- get all inner text recursively (i.e. without tags) as string. function mcml.baseNode:GetInnerText() local nSize = table_getn(self); local i, node; local text = ""; for i=1, nSize do node = self[i]; if(node) then if(type(node) == "string") then text = text..node; elseif(type(node) == "table") then text = text..node:GetInnerText(); elseif(type(node) == "number") then text = text..tostring(node); end end end return text; end -- set inner text. It will replace all child nodes with a text node function mcml.baseNode:SetInnerText(text) self[1] = text; commonlib.resize(self, 1); -- table.setn(self, 1) end -- get value: it is usually one of the editor tag, such as <input> function mcml.baseNode:GetValue() local controlClass = mcml_controls.control_mapping[self.name]; if(controlClass and controlClass.GetValue) then return controlClass.GetValue(self); else --LOG.warn("GetValue on object "..self.name.." is not supported\n") end end -- set value: it is usually one of the editor tag, such as <input> function mcml.baseNode:SetValue(value) local controlClass = mcml_controls.control_mapping[self.name]; if(controlClass and controlClass.SetValue) then return controlClass.SetValue(self, value); else --LOG.warn("SetValue on object "..self.name.." is not supported\n") end end -- get UI value: get the value on the UI object with current node -- @param instName: the page instance name. function mcml.baseNode:GetUIValue(pageInstName) local controlClass = mcml_controls.control_mapping[self.name]; if(controlClass and controlClass.GetUIValue) then return controlClass.GetUIValue(self, pageInstName); else --LOG.warn("GetUIValue on object "..self.name.." is not supported\n") end end -- set UI value: set the value on the UI object with current node function mcml.baseNode:SetUIValue(pageInstName, value) local controlClass = mcml_controls.control_mapping[self.name]; if(controlClass and controlClass.SetUIValue) then return controlClass.SetUIValue(self, pageInstName, value); else --LOG.warn("SetUIValue on object "..self.name.." is not supported\n") end end -- set UI enabled: set the enabled on the UI object with current node function mcml.baseNode:SetUIEnabled(pageInstName, value) local controlClass = mcml_controls.control_mapping[self.name]; if(controlClass and controlClass.SetUIEnabled) then return controlClass.SetUIEnabled(self, pageInstName, value); else --LOG.warn("SetUIEnabled on object "..self.name.." is not supported\n") end end -- get UI value: get the value on the UI object with current node -- @param instName: the page instance name. function mcml.baseNode:GetUIBackground(pageInstName) local controlClass = mcml_controls.control_mapping[self.name]; if(controlClass and controlClass.GetUIBackground) then return controlClass.GetUIBackground(self, pageInstName); else --LOG.warn("GetUIValue on object "..self.name.." is not supported\n") end end -- set UI value: set the value on the UI object with current node function mcml.baseNode:SetUIBackground(pageInstName, value) local controlClass = mcml_controls.control_mapping[self.name]; if(controlClass and controlClass.SetUIBackground) then return controlClass.SetUIBackground(self, pageInstName, value); else --LOG.warn("SetSetUIBackgroundUIValue on object "..self.name.." is not supported\n") end end -- call a control method -- @param instName: the page instance name. -- @param methodName: name of the method. -- @return: the value from method is returned function mcml.baseNode:CallMethod(pageInstName, methodName, ...) local controlClass = mcml_controls.control_mapping[self.name]; if(controlClass and controlClass[methodName]) then return controlClass[methodName](self, pageInstName, ...); else LOG.warn("CallMethod (%s) on object %s is not supported\n", tostring(methodName), self.name) end end -- return true if the page node contains a method called methodName function mcml.baseNode:HasMethod(pageInstName, methodName) local controlClass = mcml_controls.control_mapping[self.name]; if(controlClass and controlClass[methodName]) then return true; end end -- invoke a control method. this is same as CallMethod, except that pageInstName is ignored. -- @param methodName: name of the method. -- @return: the value from method is returned function mcml.baseNode:InvokeMethod(methodName, ...) local controlClass = mcml_controls.control_mapping[self.name]; if(controlClass and controlClass[methodName]) then return controlClass[methodName](self, ...); else LOG.warn("InvokeMethod (%s) on object %s is not supported\n", tostring(methodName), self.name) end end function mcml.baseNode:SetObjId(id) self.uiobject_id = id; end -- get the control associated with this node. -- if self.uiobject_id is not nil, we will fetch it using this id, if self.control is not nil, it will be returned, otherwise we will use the unique path name to locate the control or uiobject by name. -- @param instName: the page instance name. if nil, we will ignore global control search in page. -- @return: It returns the ParaUIObject or CommonCtrl object depending on the type of the control found. function mcml.baseNode:GetControl(pageName) if(self.uiobject_id) then local uiobj = ParaUI.GetUIObject(self.uiobject_id); if(uiobj:IsValid()) then return uiobj; end elseif(self.control) then return self.control; elseif(pageName) then local instName = self:GetInstanceName(pageName); if(instName) then local ctl = CommonCtrl.GetControl(instName); if(ctl == nil) then local uiobj = ParaUI.GetUIObject(instName); if(uiobj:IsValid()) then return uiobj; end else return ctl; end end end end -- return font: "System;12;norm"; return nil if not available. function mcml.baseNode:CalculateFont(css) local font; if(css and (css["font-family"] or css["font-size"] or css["font-weight"]))then local font_family = css["font-family"] or "System"; -- this is tricky. we convert font size to integer, and we will use scale if font size is either too big or too small. local font_size = math.floor(tonumber(css["font-size"] or 12)); local font_weight = css["font-weight"] or "norm"; font = string.format("%s;%d;%s", font_family, font_size, font_weight); end return font; end -- get UI control function mcml.baseNode:GetUIControl(pageName) if(self.uiobject_id) then local uiobj = ParaUI.GetUIObject(self.uiobject_id); if(uiobj:IsValid()) then return uiobj; end else local instName = self:GetInstanceName(pageName); if(instName) then local uiobj = ParaUI.GetUIObject(instName); if(uiobj:IsValid()) then return uiobj; end end end end -- print information about the parent nodes function mcml.baseNode:printParents() log(tostring(self.name).." is a child of ") if(self.parent == nil) then log("\n") else self.parent:printParents(); end end -- print this node to log file for debugging purposes. function mcml.baseNode:print() log("<"..tostring(self.name)); if(self.attr) then local name, value for name, value in pairs(self.attr) do commonlib.log(" %s=\"%s\"", name, value); end end local nChildSize = table_getn(self); if(nChildSize>0) then log(">"); local i, node; local text = ""; for i=1, nChildSize do node = self[i]; if(type(node) == "table") then log("\n") node:print(); elseif(type(node) == "string") then log(node) end end log("</"..self.name..">\n"); else log("/>\n"); end end -- set the value of a css style attribute after mcml node is evaluated. This function is rarely used. -- @note: one can only call this function when the mcml node is evaluated at least once, calling this function prior to evaluation will cause the style not to inherit its parent style -- alternatively, we can use self:SetAttribute("style", value) to change the entire attribute. -- @return true if succeed. function mcml.baseNode:SetCssStyle(attrName, value) if(type(self.style) == "table") then self.style[attrName] = value; return true else local style = self:GetStyle(); style[attrName] = value; end end -- get the ccs attribute of a given css style attribute value. function mcml.baseNode:GetCssStyle(attrName) if(type(self.style) == "table") then return self.style[attrName]; end end -- apply any css classnames in class attribute function mcml.baseNode:ApplyClasses() -- apply attribute class names if(self.attr and self.attr.class) then local pageStyle = self:GetPageStyle(); if(pageStyle) then local style = self:GetStyle(); local class_names = self:GetAttributeWithCode("class", nil, true); if(class_names) then for class_name in class_names:gmatch("[^ ]+") do style:Merge(pe_css.default[class_name]); pageStyle:ApplyToStyleItem(style, class_name); end end end end end -- get the css style object if any. Style will only be evaluated once and saved to self.style as a table object, unless style attribute is changed by self:SetAttribute("style", value) method. -- @param baseStyle: nil or parent node's style object with which the current node's style is merged. -- if the class property of this node is not nil, it the class style is applied over baseStyle. The style property if any is applied above the class and baseStyle -- @param base_baseStyle: this is optional. it is the base style of baseStyle -- @return: nil or the style table which is a table of name value pairs. such as {color=string, href=string} function mcml.baseNode:GetStyle(baseStyle, base_baseStyle) if(self.style) then return self.style; end local style = StyleItem:new(); self.style = style; style:Merge(base_baseStyle); style:Merge(baseStyle); self:ApplyClasses(); -- -- apply instance if any -- if(self.attr and self.attr.style) then local style_code = self:GetAttributeWithCode("style", nil, true); style:Merge(style_code); end return style; end -- @param child: it can be mcmlNode or string node. -- @param index: 1 based index, at which to insert the item. if nil, it will be inserted to the end function mcml.baseNode:AddChild(child, index) if(type(child)=="table") then local nCount = table_getn(self) or 0; child.index = commonlib.insertArrayItem(self, index, child) child.parent = self; -- table.setn(self, nCount + 1); elseif(type(child)=="string") then local nCount = table_getn(self) or 0; commonlib.insertArrayItem(self, index, child) -- table.setn(self, nCount + 1); end end -- detach this node from its parent node. function mcml.baseNode:Detach() local parentNode = self.parent if(parentNode == nil) then return end local nSize = table_getn(parentNode); local i, node; if(nSize == 1) then parentNode[1] = nil; parentNode:ClearAllChildren(); return; end local i = self.index; local node; if(i<nSize) then local k; for k=i+1, nSize do node = parentNode[k]; parentNode[k-1] = node; if(node~=nil) then node.index = k-1; parentNode[k] = nil; end end else parentNode[i] = nil; end -- table.setn(parentNode, nSize - 1); end -- check whether this baseNode has a parent with the given name. It will search recursively for all ancesters. -- @param name: the parent name to search for. If nil, it will return parent regardless of its name. -- @return: the parent object is returned. function mcml.baseNode:GetParent(name) if(name==nil) then return self.parent end local parent = self.parent; while (parent~=nil) do if(parent.name == name) then return parent; end parent = parent.parent; end end -- get the root node, it will find in ancestor nodes until one without parent is found -- @return root node. function mcml.baseNode:GetRoot() local parent = self; while (parent.parent~=nil) do parent = parent.parent; end return parent; end -- Get the page control(PageCtrl) that loaded this mcml page. function mcml.baseNode:GetPageCtrl() return self:GetAttribute("page_ctrl") or self:GetParentAttribute("page_ctrl"); end -- get the page style object shared by all page elements. function mcml.baseNode:GetPageStyle() local page = self:GetPageCtrl(); if(page) then return page:GetStyle(); end end -- search all parent with a given attribute name. It will search recursively for all ancesters. -- this function is usually used for getting the "request_url" field which is inserted by MCML web browser to the top level node. -- @param attrName: the parent field name to search for -- @return: the nearest parent object field is returned. it may return, if no such parent is found. function mcml.baseNode:GetParentAttribute(attrName) local parent = self.parent; while (parent~=nil) do if(parent:GetAttribute(attrName)~=nil) then return parent:GetAttribute(attrName); end parent = parent.parent; end end -- get the url request of the mcml node if any. It will search for "request_url" attribtue field in the ancestor of this node. -- PageCtrl and BrowserWnd will automatically insert "request_url" attribtue field to the root MCML node before instantiate them. -- @return: nil or the request_url is returned. we can extract requery string parameters using regular expressions or using GetRequestParam function mcml.baseNode:GetRequestURL() return self:GetParentAttribute("request_url") or self:GetAttribute("request_url"); end -- get request url parameter by its name. for example if page url is "www.paraengine.com/user?id=10&time=20", then GetRequestParam("id") will be 10. -- @return: nil or string value. function mcml.baseNode:GetRequestParam(paramName) local request_url = self:GetRequestURL(); return System.localserver.UrlHelper.url_getparams(request_url, paramName) end -- convert a url to absolute path using "request_url" if present -- it will replace %NAME% with their values before processing next. -- @param url: it is any script, image or page url path which may be absolute, site root or relative path. -- relative to url path can not contain "/", anotherwise it is regarded as client side relative path. such as "Texture/whitedot.png" -- @return: it always returns absolute path. however, if path cannot be resolved, the input is returned unchanged. function mcml.baseNode:GetAbsoluteURL(url) if(not url or url=="") then return url end -- it will replace %NAME% with their values before processing next. if(paraworld and paraworld.TranslateURL) then url = paraworld.TranslateURL(url); end if(string_find(url, "^([%w]*)://"))then -- already absolute path else local request_url = self:GetRequestURL(); if(request_url) then NPL.load("(gl)script/ide/System/localserver/security_model.lua"); local secureOrigin = System.localserver.SecurityOrigin:new(request_url) if(string_find(url, "^/\\")) then -- relative to site root. if(secureOrigin.url) then url = secureOrigin.url..url; end elseif(string_find(url, "[/\\]")) then -- if relative to url path contains "/", it is regarded as client side SDK root folder. such as "Texture/whitedot.png" elseif(string_find(url, "^#")) then -- this is an anchor url = string_gsub(request_url,"^([^#]*)#.-$", "%1")..url else -- relative to request url path url = string_gsub(string_gsub(request_url, "%?.*$", ""), "^(.*)/[^/\\]-$", "%1/")..url end end end return url; end -- get the user ID of the owner of the profile. function mcml.baseNode:GetOwnerUserID() local profile = self:GetParent("pe:profile") or self; if(profile) then return profile:GetAttribute("uid"); end end -- Get child count function mcml.baseNode:GetChildCount() return table_getn(self); end -- Clear all child nodes function mcml.baseNode:ClearAllChildren() commonlib.resize(self, 0); -- table.setn(self, 0); end -- generate a less compare function according to a node field name. -- @param fieldName: the name of the field, such as "text", "name", etc function mcml.baseNode.GenerateLessCFByField(fieldName) fieldName = fieldName or "name"; return function(node1, node2) if(node1[fieldName] == nil) then return true elseif(node2[fieldName] == nil) then return false else return node1[fieldName] < node2[fieldName]; end end end -- generate a greater compare function according to a node field name. -- @param fieldName: the name of the field, such as "text", "name", etc -- One can also build a compare function by calling mcml.baseNode.GenerateLessCFByField(fieldName) or mcml.baseNode.GenerateGreaterCFByField(fieldName) function mcml.baseNode.GenerateGreaterCFByField(fieldName) fieldName = fieldName or "name"; return function(node1, node2) if(node2[fieldName] == nil) then return true elseif(node1[fieldName] == nil) then return false else return node1[fieldName] > node2[fieldName]; end end end -- sorting the children according to a compare function. Internally it uses table.sort(). -- Note: child indices are rebuilt and may cause UI binded controls to misbehave -- compareFunc: if nil, it will compare by node.name. function mcml.baseNode:SortChildren(compareFunc) compareFunc = compareFunc or mcml.baseNode.GenerateLessCFByField("name"); -- quick sort table.sort(self, compareFunc) -- rebuild index. local i, node for i,node in ipairs(self) do node.index = i; end end -- get a string containing the node path. such as "1/1/1/3" -- as long as the baseNode does not change, the node path uniquely identifies a baseNode. function mcml.baseNode:GetNodePath() local path = tostring(self.index); while (self.parent ~=nil) do path = tostring(self.parent.index).."/"..path; self = self.parent; end return path; end -- @param rootName: a name that uniquely identifies a UI instance of this object, usually the userid or app_key. The function will generate a sub control name by concartinating this rootname with relative baseNode path. function mcml.baseNode:GetInstanceName(rootName) return tostring(rootName)..self:GetNodePath(); end -- get the first occurance of first level child node whose name is name -- @param name: if can be the name of the node, or it can be a interger index. function mcml.baseNode:GetChild(name) if(type(name) == "number") then return self[name]; else local nSize = table_getn(self); local i, node; for i=1, nSize do node = self[i]; if(type(node)=="table" and name == node.name) then return node; end end end end -- get the first occurance of first level child node whose name is name -- @param name: if can be the name of the node, or it can be a interger index. -- @return nil if not found function mcml.baseNode:GetChildWithAttribute(name, value) local nSize = table_getn(self); local i, node; for i=1, nSize do node = self[i]; if(type(node)=="table") then if(value == node:GetAttribute(name)) then return node; end end end end -- get the first occurance of child node whose attribute name is value. it will search for all child nodes recursively. function mcml.baseNode:SearchChildByAttribute(name, value) local nSize = table_getn(self); local i, node; for i=1, nSize do node = self[i]; if(type(node)=="table") then if(value == node:GetAttribute(name)) then return node; else node = node:SearchChildByAttribute(name, value); if(node) then return node; end end end end end -- return an iterator of all first level child nodes whose name is name -- a more advanced way to tranverse mcml tree is using ide/Xpath -- @param name: if name is nil, all child is returned. function mcml.baseNode:next(name) local nSize = table_getn(self); local i = 1; return function () local node; while i <= nSize do node = self[i]; i = i+1; if(not name or (type(node) == "table" and name == node.name)) then return node; end end end end -- this is a jquery meta table, if one wants to add jquery-like function calls, just set this metatable as the class array table. -- e.g. setmetatable(some_table, jquery_metatable) local jquery_metatable = { -- each invocation will create additional tables and closures, hence the performance is not supper good. __index = function(t, k) if(type(k) == "string") then local func = {}; setmetatable(func, { -- the first parameter is always the mcml_node. -- the return value is always the last node's result __call = function(self, self1, ...) local output; local i, node for i, node in ipairs(t) do if(type(node[k]) == "function")then output = node[k](node, ...); end end return output; end, }); return func; elseif(type(k) == "number") then return t[k]; end end, } -- provide jquery-like syntax to find all nodes that match a given name pattern and then use the returned object to invoke a method on all returned nodes. -- it can also be used to create a new node like "<div />" -- e.g. node:jquery("a"):show(); -- @param pattern: The valid format is [tag_name][#name_id][.class_name] or "<tag_name />". -- e.g. "div#name.class_name", "#some_name", ".some_class", "div" -- e.g. "<div />" will create a new node. -- @param param1: additional xml node when pattern is "<tag_name />" function mcml.baseNode:jquery(pattern, param1) local tagName = pattern and pattern:match("^<([^%s/>]*)"); if(tagName) then param1 = param1 or {name=tagName, attr={}}; param1.name = param1.name or tagName; return System.mcml.new(nil, param1); else local output = {} if(pattern) then local tag_name, pattern = pattern:match("^([^#%.]*)(.*)"); if(tag_name == "") then tag_name = nil; end local id; if(pattern) then id = pattern:match("#([^#%.]+)"); end local class_name; if(pattern) then class_name = pattern:match("%.([^#%.]+)"); end self:GetAllChildWithNameIDClass(tag_name, id, class_name, output); end setmetatable(output, jquery_metatable) return output; end end -- show this node. one may needs to refresh the page if page is already rendered function mcml.baseNode:show() self:SetAttribute("display", nil) end -- hide this node. one may needs to refresh the page if page is already rendered function mcml.baseNode:hide() self:SetAttribute("display", "none") end -- get/set inner text -- @param v: if not nil, it will set inner text instead of get -- return the inner text or empty string. function mcml.baseNode:text(v) if(v == nil) then local inner_text = self[1]; if(type(inner_text) == "string") then return inner_text; else return "" end else self:ClearAllChildren(); self[1] = v; end end -- get/set ui or node value of the node. -- @param v: if not nil, it will set value instead of get function mcml.baseNode:value(v) if(v == nil) then local value_ = self:GetUIValue(); if(value_==nil) then return self:GetValue(); else return value_; end else self:SetUIValue(v); self:SetValue(v); end end -- return a table containing all child nodes whose name is name. (it will search recursively) -- a more advanced way to tranverse mcml tree is using ide/Xpath -- @param name: the tag name. if nil it matches all -- @param id: the name attribute. if nil it matches all -- @param class: the class attribute. if nil it matches all -- @param output: nil or a table to receive the result. child nodes with the name is saved to this table array. if nil, a new table will be created. -- @return output: the output table containing all children. It may be nil if no one is found and input "output" is also nil. function mcml.baseNode:GetAllChildWithNameIDClass(name, id, class, output) local nSize = table_getn(self); local i = 1; local node; while i <= nSize do node = self[i]; i = i+1; if(type(node) == "table") then if( (not name or name == node.name) and (not id or id == node:GetAttribute("name")) and (not class or class==node:GetAttribute("class")) ) then output = output or {}; table.insert(output, node); else output = node:GetAllChildWithNameIDClass(name, id, class, output) end end end return output; end -- return a table containing all child nodes whose name is name. (it will search recursively) -- a more advanced way to tranverse mcml tree is using ide/Xpath -- @param name: the tag name -- @param output: nil or a table to receive the result. child nodes with the name is saved to this table array. if nil, a new table will be created. -- @return output: the output table containing all children. It may be nil if no one is found and input "output" is also nil. function mcml.baseNode:GetAllChildWithName(name, output) local nSize = table_getn(self); local i = 1; local node; while i <= nSize do node = self[i]; i = i+1; if(type(node) == "table") then if(name == node.name) then output = output or {}; table.insert(output, node); else output = node:GetAllChildWithName(name, output) end end end return output; end -- return an iterator of all child nodes whose attribtue attrName is attrValue. (it will search recursively) -- a more advanced way to tranverse mcml tree is using ide/Xpath -- @param name: if name is nil, all child is returned. -- @param output: nil or a table to receive the result. child nodes with the name is saved to this table array. if nil, a new table will be created. -- @return output: the output table containing all children. It may be nil if no one is found and input "output" is also nil. function mcml.baseNode:GetAllChildWithAttribute(attrName, attrValue, output) local nSize = table_getn(self); local i = 1; local node; while i <= nSize do node = self[i]; i = i+1; if(type(node) == "table") then if(node:GetAttribute(attrName) == attrValue) then output = output or {}; table.insert(output, node); else output = node:GetAllChildWithAttribute(attrName, attrValue, output) end end end return output; end -- this function will apply self.pre_values to current page scope during rendering. -- making it accessible to XPath and Eval function. function mcml.baseNode:ApplyPreValues() if(type(self.pre_values) == "table") then local pageScope = self:GetPageCtrl():GetPageScope(); if(pageScope) then for name, value in pairs(self.pre_values) do pageScope[name] = value; end end end end -- apply a given pre value to this node, so that when the node is rendered, the name, value pairs will be -- written to the current page scope. Not all mcml node support pre values. it is most often used by databinding template node. function mcml.baseNode:SetPreValue(name, value) self.pre_values = self.pre_values or {}; self.pre_values[name] = value; end -- get a prevalue by name. this function is usually called on data binded mcml node -- @param name: name of the pre value -- @param bSearchParent: if true, it will search parent node recursively until name is found or root node is reached. function mcml.baseNode:GetPreValue(name, bSearchParent) if(self.pre_values) then return self.pre_values[name]; elseif(bSearchParent) then local parent = self.parent; while (parent~=nil) do if(parent.pre_values) then return parent.pre_values[name]; end parent = parent.parent; end end end -- here we will translate current node and all of its child nodes recursively, using the given langTable -- unless any of the child attribute disables or specifies a different lang using the trans attribute -- @note: it will secretly mark an already translated node, so it will not be translated twice when the next time this method is called. -- @param langTable: this is a translation table from CommonCtrl.Locale(transName); if this is nil, -- @param transName: the translation name of the langTable. function mcml.baseNode:TranslateMe(langTable, transName) local trans = self:GetAttribute("trans"); if(trans) then if(trans == "no" or trans == "none") then return elseif(trans ~= transName) then langTable = CommonCtrl.Locale(trans); transName = trans; if(not langTable) then LOG.warn("lang table %s is not found for the mcml page\n", trans); end end -- secretly mark an already translated node, so it will not be translated twice when the next time this method is called. if(self.IsTranslated) then return else self.IsTranslated = true; end end -- translate this and all child nodes recursively if(langTable) then -- translate attributes of current node. if(self.attr) then local name, value for name, value in pairs(self.attr) do -- we will skip some attributes. if(name~="style" and name~="id" and name~="name") then if(type(value) == "string") then -- TRANSLATE: translate value if(langTable:HasTranslation(value)) then --commonlib.echo(langTable(value)) self.attr[name] = langTable(value); end end end end end -- translate child nodes recursively. local nSize = table_getn(self); local i = 1; local node; while i <= nSize do node = self[i]; if(type(node) == "table") then node:TranslateMe(langTable, transName) elseif(type(node) == "string") then -- only translate if the node is not unknown and not script node. if(self.name ~= "script" and self.name ~= "unknown" and self.name ~= "pe:script") then -- TRANSLATE: translate inner text if(langTable:HasTranslation(node)) then --commonlib.echo(langTable(node)) self[i] = langTable(node) end end end i = i+1; end end end -- if there an attribute called variables. -- variables are frequently used for localization in mcml. Both table based localization and commonlib.Locale based localization are supported. function mcml.baseNode:ProcessVariables() local variables_str = self:GetAttribute("variables"); if(variables_str and not self.__variable_processed) then self.__variable_processed = true; -- a table containing all variables local variables = {}; local var_name, var_value for var_name, var_value in string.gmatch(variables_str, "%$(%w*)=([^;%$]+)") do local func = commonlib.getfield(var_value) or commonlib.Locale:GetByName(var_value); variable = { var_name=var_name, match_exp="%$"..var_name.."{([^}]*)}", gsub_exp="%$"..var_name.."{[^}]*}", }; if(not func) then -- try to find a locale file with value under the given folder -- suppose var_value is "locale.mcml.IDE", then we will first try "locale/mcml/IDE.lua" and then try "locale/mcml/IDE_enUS.lua" local filename = var_value:gsub("%.", "/"); local locale_file1 = format("%s.lua", filename); local locale_file2 = format("%s_%s.lua", filename, ParaEngine.GetLocale()); if(ParaIO.DoesFileExist(locale_file1)) then filename = locale_file1; elseif(ParaIO.DoesFileExist(locale_file2)) then filename = locale_file2; else filename = nil; end if(filename) then NPL.load("(gl)"..filename); LOG.std(nil, "system", "mcml", "loaded variable file %s for %s", filename, var_value); func = commonlib.getfield(var_value) or commonlib.Locale:GetByName(var_value); if(not func) then func = commonlib.gettable(var_value); LOG.std(nil, "warn", "mcml", "empty table is created and used for variable %s. Ideally it should be %s or %s", var_value, locale_file1, locale_file2); end else LOG.std(nil, "warn", "mcml", "can not find variable table file for %s. It should be %s or %s", var_value, locale_file1, locale_file2); end end if(type(func) == "function") then variable.func = func variables[#variables+1] = variable; elseif(type(func) == "table") then local meta_table = getmetatable(func); if(meta_table and meta_table.__call) then variable.func = func else variable.func = function(name) return func[name]; end end variables[#variables+1] = variable; else LOG.std(nil, "warn", "mcml", "unsupported $ %s params", var_name); end end if(#variables>0) then self:ReplaceVariables(variables); end end end function mcml.baseNode:ReplaceVariables(variables) if(variables) then -- translate this and all child nodes recursively -- translate attributes of current node. if(self.attr) then local name, value for name, value in pairs(self.attr) do -- we will skip some attributes. if(type(value) == "string") then -- REPLACE local k; for k=1, #variables do local variable = variables[k]; local var_value = value:match(variable.match_exp) if(var_value) then value = value:gsub(variable.gsub_exp, variable.func(var_value) or var_value); self.attr[name] = value; end end end end end -- translate child nodes recursively. local nSize = table_getn(self); local i = 1; local node; while i <= nSize do node = self[i]; if(type(node) == "table") then node:ReplaceVariables(variables) elseif(type(node) == "string") then local value = node; -- REPLACE local k; for k=1, #variables do local variable = variables[k]; local var_value = value:match(variable.match_exp) if(var_value) then value = value:gsub(variable.gsub_exp, variable.func(var_value) or var_value); self[i] = value; end end end i = i+1; end end end -- This callback is used mostly with DrawDisplayBlock() function. -- @param mcmlNode: this mcml node. -- @param _parent: the ui object inside which UI controls should be created. -- @param left, top, width, height: this is actually left, top, right, bottom relative to _parent control (css padding is NOT applied). -- @param myLayout: this is the layout inside which child nodes should be created (css padding is applied). function mcml.baseNode.DrawChildBlocks_Callback(mcmlNode, rootName, bindingContext, _parent, left, top, width, height, myLayout, css) for childnode in mcmlNode:next() do local left, top, width, height = myLayout:GetPreferredRect(); Map3DSystem.mcml_controls.create(rootName, childnode, bindingContext, _parent, left, top, width, height, {display=css["display"], color = css.color, ["font-family"] = css["font-family"], ["font-size"]=css["font-size"], ["font-weight"] = css["font-weight"], ["text-align"] = css["text-align"], ["text-shadow"] = css["text-shadow"], ["base-font-size"] = css["base-font-size"]}, myLayout) end end -- Call this function to draw display block with a custom callback. -- This function is usually called by the mcml tag's create() function. -- Right now, mcml renderer uses one pass rendering, hence there is some limitation on block layout capabilities. -- One of the biggest limitation is that all floating display blocks must have explicit size specified in css in order to function. -- A multi-pass renderer can do more flexible layout, yet at the cost of code complexity and CPU. -- This function supports all features of the original mcml's div tag. -- @param parentLayout: the parent layout structure. When this function returns, the parent layout will be modified. -- @param _parent: the ui object inside which UI controls should be created. -- @param left, top, width, height: this is actually left, top, right, bottom relative to _parent control. -- @param style: the parent css style. -- @param render_callback: a function(mcmlNode, rootName, bindingContext, _parent, myLayout, css) end, inside which we can render the content. -- this function can return ignore_onclick, ignore_background. if true it will ignore onclick and background handling -- see self.DrawChildBlocks_Callback for an example callback function mcml.baseNode:DrawDisplayBlock(rootName, bindingContext, _parent, left, top, width, height, parentLayout, style, render_callback) local mcmlNode = self; if(mcmlNode:GetAttribute("display") == "none") then return end -- process any variables that is taking place. mcmlNode:ProcessVariables(); local css = mcmlNode:GetStyle(pe_html.css[mcmlNode.name], style) or {}; if(style) then -- pass through some css styles from parent. css.color = css.color or style.color; css["font-family"] = css["font-family"] or style["font-family"]; css["font-size"] = css["font-size"] or style["font-size"]; css["font-weight"] = css["font-weight"] or style["font-weight"]; css["text-shadow"] = css["text-shadow"] or style["text-shadow"]; end local padding_left, padding_top, padding_bottom, padding_right = (css["padding-left"] or css["padding"] or 0),(css["padding-top"] or css["padding"] or 0), (css["padding-bottom"] or css["padding"] or 0),(css["padding-right"] or css["padding"] or 0); local margin_left, margin_top, margin_bottom, margin_right = (css["margin-left"] or css["margin"] or 0),(css["margin-top"] or css["margin"] or 0), (css["margin-bottom"] or css["margin"] or 0),(css["margin-right"] or css["margin"] or 0); local availWidth, availHeight = parentLayout:GetPreferredSize(); local maxWidth, maxHeight = parentLayout:GetMaxSize(); if(css["max-width"]) then local max_width = css["max-width"]; if(maxWidth>max_width) then local left, top, right, bottom = parentLayout:GetAvailableRect(); -- align at center. local align = mcmlNode:GetAttribute("align") or css["align"]; if(align == "center") then left = left + (maxWidth - max_width)/2 elseif(align == "right") then left = right - max_width; end right = left + max_width; parentLayout:reset(left, top, right, bottom); end end if(css["max-height"]) then local max_height = css["max-height"]; if(maxHeight>max_height) then local left, top, right, bottom = parentLayout:GetAvailableRect(); -- align at center. local valign = mcmlNode:GetAttribute("valign") or css["valign"]; if(valign == "center") then top = top + (maxHeight - max_height)/2 elseif(valign == "bottom") then top = bottom - max_height; end bottom = top + max_height; parentLayout:reset(left, top, right, bottom); end end if(mcmlNode:GetAttribute("trans")) then -- here we will translate all child nodes recursively, using the given lang -- unless any of the child attribute disables or specifies a different lang mcmlNode:TranslateMe(); end local width, height = mcmlNode:GetAttribute("width"), mcmlNode:GetAttribute("height"); if(width) then css.width = tonumber(string.match(width, "%d+")); if(css.width and string.match(width, "%%$")) then if(css.position == "screen") then css.width = ParaUI.GetUIObject("root").width * css.width/100; else css.width=math.floor((maxWidth-margin_left-margin_right)*css.width/100); if(availWidth<(css.width+margin_left+margin_right)) then css.width=availWidth-margin_left-margin_right; end if(css.width<=0) then css.width = nil; end end end end if(height) then css.height = tonumber(string.match(height, "%d+")); if(css.height and string.match(height, "%%$")) then if(css.position == "screen") then css.height = ParaUI.GetUIObject("root").height * css.height/100; else css.height=math.floor((maxHeight-margin_top-margin_bottom)*css.height/100); if(availHeight<(css.height+margin_top+margin_bottom)) then css.height=availHeight-margin_top-margin_bottom; end if(css.height<=0) then css.height = nil; end end end end -- whether this control takes up space local bUseSpace; if(css.float) then local minWidth = css.width or css["min-width"]; if(minWidth) then if(availWidth<(minWidth+margin_left+margin_right)) then parentLayout:NewLine(); end end else parentLayout:NewLine(); end local myLayout = parentLayout:clone(); myLayout:ResetUsedSize(); if(css.width) then local align = mcmlNode:GetAttribute("align") or css["align"]; if(align and align~="left") then local max_width = css.width; local left, top, right, bottom = myLayout:GetAvailableRect(); -- align at center. if(align == "center") then left = left + (maxWidth - max_width)/2 elseif(align == "right") then max_width = max_width + margin_left + margin_right; left = right - max_width; end right = left + max_width myLayout:reset(left, top, right, bottom); end end if(css.height) then -- align at center. local valign = mcmlNode:GetAttribute("valign") or css["valign"]; if(valign and valign~="top") then local max_height = css.height; local left, top, right, bottom = myLayout:GetAvailableRect(); if(valign == "center") then top = top + (maxHeight - max_height)/2 elseif(valign == "bottom") then max_height = max_height + margin_top + margin_bottom; top = bottom - max_height; end bottom = top + max_height myLayout:reset(left, top, right, bottom); end end if(css.position == "absolute") then -- absolute positioning in parent if(css.width and css.height and css.left and css.top) then -- if all rect is provided, we will do true absolute position. myLayout:reset(css.left, css.top, css.left + css.width, css.top + css.height); else -- this still subject to parent rect. myLayout:SetPos(css.left, css.top); end myLayout:ResetUsedSize(); elseif(css.position == "relative") then -- relative positioning in next render position. myLayout:OffsetPos(css.left, css.top); elseif(css.position == "screen") then -- relative positioning in screen client area local offset_x, offset_y = 0, 0; local left, top = mcmlNode:GetAttribute("left"), mcmlNode:GetAttribute("top"); if(left) then left = tonumber(string.match(left, "(%d+)%%$")); offset_x = ParaUI.GetUIObject("root").width * left/100; end if(top) then top = tonumber(string.match(top, "(%d+)%%$")); offset_y = ParaUI.GetUIObject("root").height * top/100; end local px,py = _parent:GetAbsPosition(); myLayout:SetPos((css.left or 0)-px + offset_x, (css.top or 0)-py + offset_y); else myLayout:OffsetPos(css.left, css.top); bUseSpace = true; end left,top = myLayout:GetAvailablePos(); myLayout:SetPos(left,top); width,height = myLayout:GetSize(); if(css.width) then myLayout:IncWidth(left+margin_left+margin_right+css.width-width) end if(css.height) then myLayout:IncHeight(top+margin_top+margin_bottom+css.height-height) end -- for inner control preferred size myLayout:OffsetPos(margin_left+padding_left, margin_top+padding_top); myLayout:IncWidth(-margin_right-padding_right) myLayout:IncHeight(-margin_bottom-padding_bottom) --------------------------------- -- draw inner nodes. --------------------------------- local ignore_onclick, ignore_background, ignore_tooltip; if(render_callback) then local left, top, width, height = myLayout:GetPreferredRect(); ignore_onclick, ignore_background, ignore_tooltip = render_callback(mcmlNode, rootName, bindingContext, _parent, left-padding_left, top-padding_top, width+padding_right, height+padding_bottom, myLayout, css); end local width, height = myLayout:GetUsedSize() width = width + padding_right + margin_right height = height + padding_bottom + margin_bottom if(css.width) then width = left + css.width + margin_left+margin_right; end if(css.height) then height = top + css.height + margin_top+margin_bottom; end if(css["min-width"]) then local min_width = css["min-width"]; if((width-left) < min_width) then width = left + min_width; end end if(css["min-height"]) then local min_height = css["min-height"]; if((height-top) < min_height) then height = top + min_height; end end if(css["max-height"]) then local max_height = css["max-height"]; if((height-top) > max_height) then height = top + max_height; end end if(bUseSpace) then parentLayout:AddObject(width-left, height-top); if(not css.float) then parentLayout:NewLine(); end end local onclick, ontouch; local onclick_for; if(not ignore_onclick) then onclick = mcmlNode:GetString("onclick"); if(onclick == "") then onclick = nil; end onclick_for = mcmlNode:GetString("for"); if(onclick_for == "") then onclick_for = nil; end ontouch = mcmlNode:GetString("ontouch"); if(ontouch == "") then ontouch = nil; end end local tooltip if(not ignore_tooltip) then tooltip = mcmlNode:GetAttributeWithCode("tooltip",nil,true); if(tooltip == "") then tooltip = nil; end end local background; if(not ignore_background) then background = mcmlNode:GetAttribute("background") or css.background; end if(css["background-color"] and not ignore_background) then if(not background and not css.background2) then background = "Texture/whitedot.png"; end end if(onclick_for or onclick or tooltip or ontouch) then -- if there is onclick event, the inner nodes will not be interactive. local instName = mcmlNode:GetAttributeWithCode("uiname", nil, true) or mcmlNode:GetInstanceName(rootName); local _this=ParaUI.CreateUIObject("button",instName or "b","_lt", left+margin_left, top+margin_top, width-left-margin_left-margin_right, height-top-margin_top-margin_bottom); mcmlNode.uiobject_id = _this.id; if(background) then _this.background = background; if(background~="") then if(css["background-color"]) then _guihelper.SetUIColor(_this, css["background-color"]); end if(css["background-rotation"]) then _this.rotation = tonumber(css["background-rotation"]) end if(css["background-repeat"] == "repeat") then _this:GetAttributeObject():SetField("UVWrappingEnabled", true); end end if(css["background-animation"]) then local anim_file = string.gsub(css["background-animation"], "url%((.*)%)", "%1"); local fileName,animName = string.match(anim_file, "^([^#]+)#(.*)$"); if(fileName and animName) then UIAnimManager.PlayUIAnimationSequence(_this, fileName, animName, true); end end else _this.background = ""; end if(css.background2 and not ignore_background) then _guihelper.SetVistaStyleButton(_this, nil, css.background2); end local zorder = mcmlNode:GetNumber("zorder"); if(zorder) then _this.zorder = zorder end if(onclick_for or onclick or ontouch) then local btnName = mcmlNode:GetAttributeWithCode("name") -- tricky: we will just prefetch any params with code that may be used in the callback local i; for i=1,5 do if(not mcmlNode:GetAttributeWithCode("param"..i)) then break; end end if(onclick_for or onclick) then _this:SetScript("onclick", Map3DSystem.mcml_controls.pe_editor_button.on_click, mcmlNode, instName, bindingContext, btnName); elseif(ontouch) then _this:SetScript("ontouch", Map3DSystem.mcml_controls.pe_editor_button.on_touch, mcmlNode, instName, bindingContext, btnName); end end if(tooltip) then local tooltip_page = string.match(tooltip or "", "page://(.+)"); local tooltip_static_page = string.match(tooltip or "", "page_static://(.+)"); if(tooltip_page) then CommonCtrl.TooltipHelper.BindObjTooltip(mcmlNode.uiobject_id, tooltip_page, mcmlNode:GetNumber("tooltip_offset_x"), mcmlNode:GetNumber("tooltip_offset_y"), mcmlNode:GetNumber("show_width"),mcmlNode:GetNumber("show_height"),mcmlNode:GetNumber("show_duration"), mcmlNode:GetBool("enable_tooltip_hover"), nil, mcmlNode:GetBool("tooltip_is_interactive"), mcmlNode:GetBool("is_lock_position"), mcmlNode:GetBool("use_mouse_offset"), mcmlNode:GetNumber("screen_padding_bottom"), nil, nil, nil, mcmlNode:GetBool("offset_ctrl_width"), mcmlNode:GetBool("offset_ctrl_height")); elseif(tooltip_static_page) then CommonCtrl.TooltipHelper.BindObjTooltip(mcmlNode.uiobject_id, tooltip_static_page, mcmlNode:GetNumber("tooltip_offset_x"), mcmlNode:GetNumber("tooltip_offset_y"), mcmlNode:GetNumber("show_width"),mcmlNode:GetNumber("show_height"),mcmlNode:GetNumber("show_duration"),mcmlNode:GetBool("enable_tooltip_hover"),mcmlNode:GetBool("click_through")); else _this.tooltip = tooltip; end end _parent:AddChild(_this); else if(background) then local instName; if(mcmlNode:GetAttribute("name") or mcmlNode:GetAttribute("id")) then -- this is solely for giving a global name to background image control so that it can be animated -- background image control is mutually exclusive with inner text control. hence if there is a background, inner text becomes anonymous instName = mcmlNode:GetInstanceName(rootName); end local _this=ParaUI.CreateUIObject("button",instName or "b","_lt", left+margin_left, top+margin_top, width-left-margin_left-margin_right, height-top-margin_top-margin_bottom); _this.background = background; _this.enabled = false; mcmlNode.uiobject_id = _this.id; if(css["background-color"]) then _guihelper.SetUIColor(_this, css["background-color"]); else _guihelper.SetUIColor(_this, "255 255 255 255"); end if(css["background-rotation"]) then _this.rotation = tonumber(css["background-rotation"]) end if(css["background-repeat"] == "repeat") then _this:GetAttributeObject():SetField("UVWrappingEnabled", true); end _parent:AddChild(_this); local zorder = mcmlNode:GetNumber("zorder"); if(zorder) then _this.zorder = zorder end _this:BringToBack(); if(css["background-animation"]) then local anim_file = string.gsub(css["background-animation"], "url%((.*)%)", "%1"); local fileName,animName = string.match(anim_file, "^([^#]+)#(.*)$"); if(fileName and animName) then UIAnimManager.PlayUIAnimationSequence(_this, fileName, animName, true); end end elseif(mcmlNode:GetBool("enabled") == false) then local _this=ParaUI.CreateUIObject("button","b","_lt", left+margin_left, top+margin_top, width-left-margin_left-margin_right, height-top-margin_top-margin_bottom); if(tooltip) then _this.tooltip = tooltip; end _this.background = background or ""; _parent:AddChild(_this); end end -- call onload(mcmlNode) function if any. local onloadFunc = mcmlNode:GetString("onload"); if(onloadFunc and onloadFunc~="") then Map3DSystem.mcml_controls.pe_script.BeginCode(mcmlNode); local pFunc = commonlib.getfield(onloadFunc); if(type(pFunc) == "function") then pFunc(mcmlNode); else LOG.std("", "warn", "mcml", "%s node's onload call back: %s is not a valid function.", mcmlNode.name, onloadFunc) end Map3DSystem.mcml_controls.pe_script.EndCode(rootName, mcmlNode, bindingContext, _parent, left, top, width, height,style, parentLayout); end end -- fire a given page event by its name -- @param event_name: such as "onclick". function mcml.baseNode:OnPageEvent(event_name, ...) local callback_script = self:GetString(event_name); if(callback_script and callback_script~="") then Map3DSystem.mcml_controls.OnPageEvent(self, callback_script, ...); end end
gpl-2.0
yunGit/skynet
examples/client.lua
67
2101
package.cpath = "luaclib/?.so" package.path = "lualib/?.lua;examples/?.lua" if _VERSION ~= "Lua 5.3" then error "Use lua 5.3" end local socket = require "clientsocket" local proto = require "proto" local sproto = require "sproto" local host = sproto.new(proto.s2c):host "package" local request = host:attach(sproto.new(proto.c2s)) local fd = assert(socket.connect("127.0.0.1", 8888)) local function send_package(fd, pack) local package = string.pack(">s2", pack) socket.send(fd, package) end local function unpack_package(text) local size = #text if size < 2 then return nil, text end local s = text:byte(1) * 256 + text:byte(2) if size < s+2 then return nil, text end return text:sub(3,2+s), text:sub(3+s) end local function recv_package(last) local result result, last = unpack_package(last) if result then return result, last end local r = socket.recv(fd) if not r then return nil, last end if r == "" then error "Server closed" end return unpack_package(last .. r) end local session = 0 local function send_request(name, args) session = session + 1 local str = request(name, args, session) send_package(fd, str) print("Request:", session) end local last = "" local function print_request(name, args) print("REQUEST", name) if args then for k,v in pairs(args) do print(k,v) end end end local function print_response(session, args) print("RESPONSE", session) if args then for k,v in pairs(args) do print(k,v) end end end local function print_package(t, ...) if t == "REQUEST" then print_request(...) else assert(t == "RESPONSE") print_response(...) end end local function dispatch_package() while true do local v v, last = recv_package(last) if not v then break end print_package(host:dispatch(v)) end end send_request("handshake") send_request("set", { what = "hello", value = "world" }) while true do dispatch_package() local cmd = socket.readstdin() if cmd then if cmd == "quit" then send_request("quit") else send_request("get", { what = cmd }) end else socket.usleep(100) end end
mit
thedraked/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Mariyaam.lua
14
1080
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Mariyaam -- Type: Item Deliverer -- @pos -125 -6 90 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); 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
thedraked/darkstar
scripts/globals/items/culinarians_belt.lua
18
1172
----------------------------------------- -- ID: 15451 -- Item: Culinarian's Belt -- Enchantment: Synthesis image support -- 2Min, All Races ----------------------------------------- -- Enchantment: Synthesis image support -- Duration: 2Min -- Alchemy Skill +3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_COOKING_IMAGERY) == true) then result = 243; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_COOKING_IMAGERY,3,0,120); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_SKILL_COK, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_SKILL_COK, 1); end;
gpl-3.0