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
Mashape/kong
spec/02-integration/05-proxy/18-client_certificate_spec.lua
1
3638
local helpers = require "spec.helpers" local ssl_fixtures = require "spec.fixtures.ssl" local fixtures = { http_mock = { upstream_mtls = [[ server { server_name example.com; listen 16798 ssl; ssl_certificate ../spec/fixtures/mtls_certs/example.com.crt; ssl_certificate_key ../spec/fixtures/mtls_certs/example.com.key; ssl_client_certificate ../spec/fixtures/mtls_certs/ca.crt; ssl_verify_client on; ssl_session_tickets off; ssl_session_cache off; keepalive_requests 0; location = / { echo 'it works'; } } ]] }, } for _, strategy in helpers.each_strategy() do describe("mutual TLS authentication against upstream with DB: #" .. strategy, function() local proxy_client, admin_client local bp local service local certificate lazy_setup(function() bp = helpers.get_db_utils(strategy, { "routes", "services", "certificates", }) service = assert(bp.services:insert({ name = "protected-service", url = "https://127.0.0.1:16798/" })) certificate = assert(bp.certificates:insert({ cert = ssl_fixtures.cert_client, key = ssl_fixtures.key_client, })) assert(bp.routes:insert({ service = { id = service.id, }, hosts = { "example.com", }, })) assert(helpers.start_kong({ database = strategy, nginx_conf = "spec/fixtures/custom_nginx.template", }, nil, nil, fixtures)) proxy_client = assert(helpers.proxy_client()) admin_client = assert(helpers.admin_client()) end) lazy_teardown(function() if proxy_client then proxy_client:close() end helpers.stop_kong() end) describe("no client certificate supplied", function() it("accessing protected upstream", function() local res = assert(proxy_client:send { path = "/", headers = { ["Host"] = "example.com", } }) local body = assert.res_status(400, res) assert.matches("400 No required SSL certificate was sent", body, nil, true) end) end) describe("#db client certificate supplied via service.client_certificate", function() lazy_setup(function() local res = assert(admin_client:patch("/services/" .. service.id, { body = { client_certificate = { id = certificate.id, }, }, headers = { ["Content-Type"] = "application/json" }, })) assert.res_status(200, res) end) it("accessing protected upstream", function() local res = assert(proxy_client:send { path = "/", headers = { ["Host"] = "example.com", } }) local body = assert.res_status(200, res) assert.equals("it works", body) end) it("remove client_certificate removes access", function() local res = assert(admin_client:patch("/services/" .. service.id, { body = { client_certificate = ngx.null, }, headers = { ["Content-Type"] = "application/json" }, })) assert.res_status(200, res) res = assert(proxy_client:send { path = "/", headers = { ["Host"] = "example.com", } }) local body = assert.res_status(400, res) assert.matches("400 No required SSL certificate was sent", body, nil, true) end) end) end) end
apache-2.0
nesstea/darkstar
scripts/zones/Dynamis-Beaucedine/Zone.lua
21
2557
----------------------------------- -- -- Zone: Dynamis-Beaucedine -- ----------------------------------- package.loaded["scripts/zones/Dynamis-Beaucedine/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Dynamis-Beaucedine/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-284.751,-39.923,-422.948,235); end if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaBeaucedine]UniqueID")) then if (player:isBcnmsFull() == 1) then if (player:hasStatusEffect(EFFECT_DYNAMIS, 0) == false) then inst = player:addPlayerToDynamis(1284); if (inst == 1) then player:bcnmEnter(1284); else cs = 0; end else player:bcnmEnter(1284); end else inst = player:bcnmRegister(1284); if (inst == 1) then player:bcnmEnter(1284); else cs = 0; end end else cs = 0; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0) then player:setPos(-284.751,-39.923,-422.948,235,0x6F); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Yuhtunga_Jungle/mobs/Rose_Garden.lua
7
1744
----------------------------------- -- Area: Yuhtunga Jungle -- MOB: Rose Garden ----------------------------------- ----------------------------------- function onMobSpawn(mob) local Voluptuous_Vilma = 17281358; GetMobByID(Voluptuous_Vilma):setLocalVar("1",os.time() + math.random((36000), (37800))); end; function onMobRoam(mob) local Voluptuous_Vilma = 17281358; local Voluptuous_Vilma_PH = 0; local Voluptuous_Vilma_PH_Table = { 17281357 }; local Voluptuous_Vilma_ToD = GetMobByID(Voluptuous_Vilma):getLocalVar("1"); if (Voluptuous_Vilma_ToD <= os.time()) then Voluptuous_Vilma_PH = math.random((0), (table.getn(Voluptuous_Vilma_PH_Table))); if (Voluptuous_Vilma_PH_Table[Voluptuous_Vilma_PH] ~= nil) then if (GetMobAction(Voluptuous_Vilma) == 0) then SetServerVariable("Voluptuous_Vilma_PH", Voluptuous_Vilma_PH_Table[Voluptuous_Vilma_PH]); DeterMob(Voluptuous_Vilma_PH_Table[Voluptuous_Vilma_PH], true); DeterMob(Voluptuous_Vilma, false); DespawnMob(Voluptuous_Vilma_PH_Table[Voluptuous_Vilma_PH]); SpawnMob(Voluptuous_Vilma, "", 0); end end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, ally) local Rose_Garden = 17281357; local Rose_Garden_PH = GetServerVariable("Rose_Garden_PH"); GetMobByID(Rose_Garden):setLocalVar("1",os.time() + math.random((36000), (37800))); SetServerVariable("Rose_Garden_PH", 0); DeterMob(Rose_Garden, true); DeterMob(Rose_Garden_PH, false); SpawnMob(Rose_Garden_PH, "", GetMobRespawnTime(Rose_Garden_PH)); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Port_Bastok/npcs/Dehlner.lua
13
1196
----------------------------------- -- Area: Port Bastok -- NPC: Dehlner -- Standard Info NPC -- Invlolved in Quest: A Foreman's Best Friend ----------------------------------- require("scripts/globals/quests"); package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) ForemansBestFriend = player:getQuestStatus(BASTOK,A_FOREMAN_S_BEST_FRIEND); if (ForemansBestFriend == QUEST_ACCEPTED) then player:startEvent(0x006f); else player:startEvent(0x002e); 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
nesstea/darkstar
scripts/globals/items/marron_glace.lua
18
1319
----------------------------------------- -- ID: 4502 -- Item: Marron Glace -- Food Effect: 180Min, All Races ----------------------------------------- -- Magic % 13 -- Magic Cap 85 -- Magic Regen While Healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4502); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_MPP, 13); target:addMod(MOD_FOOD_MP_CAP, 85); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_MPP, 13); target:delMod(MOD_FOOD_MP_CAP, 85); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Lower_Delkfutts_Tower/Zone.lua
13
3845
----------------------------------- -- -- Zone: Lower_Delkfutts_Tower (184) -- ----------------------------------- package.loaded["scripts/zones/Lower_Delkfutts_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/zone"); require("scripts/globals/missions"); require("scripts/zones/Lower_Delkfutts_Tower/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local tomes = {17531228,17531229,17531230}; SetGroundsTome(tomes); zone:registerRegion(1, 403, -34, 83, 409, -33, 89); -- Third Floor G-6 porter to Middle Delkfutt's Tower zone:registerRegion(2, 390, -34, -49, 397, -33, -43); -- Third Floor F-10 porter to Middle Delkfutt's Tower "1" end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(460.022,-1.77,-103.442,188); end if (player:getCurrentMission(ZILART) == RETURN_TO_DELKFUTTS_TOWER and player:getVar("ZilartStatus") <= 1) then cs = 0x000f; elseif (ENABLE_COP == 1 and prevZone == 126 and player:getCurrentMission(COP) == ANCIENT_FLAMES_BECKON) then cs = 0x0016; elseif (player:getCurrentMission(ACP) == BORN_OF_HER_NIGHTMARES and prevZone == 126) then cs = 0x0022; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { [1] = function (x) player:setVar("option",1); player:startEvent(4); end, [2] = function (x) player:setVar("option",2); player:startEvent(4); end, } end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x000f) then player:setVar("ZilartStatus",2); elseif (csid == 0x0004 and option == 1) then if (player:getVar("option") == 1) then player:setPos(-28, -48, 80, 111, 157); else player:setPos(-51, -48, -40, 246, 157); end player:setVar("option",0); elseif (csid == 0x0004 and (option == 0 or option >= 3)) then player:setVar("option",0); elseif (csid == 0x0016) then player:startEvent(0x0024); elseif (csid == 0x0022) then player:completeMission(ACP,BORN_OF_HER_NIGHTMARES); player:addMission(ACP,BANISHING_THE_ECHO); elseif (csid == 0x0024) then player:startEvent(0x0025); elseif (csid == 0x0025) then player:startEvent(0x0026); elseif (csid == 0x0026) then player:startEvent(0x0027); elseif (csid == 0x0027) then player:completeMission(COP,ANCIENT_FLAMES_BECKON); player:addMission(COP,THE_RITES_OF_LIFE); player:setVar("COP1",1); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/commands/givexp.lua
27
1213
--------------------------------------------------------------------------------------------------- -- func: @givexp <amount> <player> -- desc: Gives the GM or target player experience points. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "is" }; function onTrigger(player, amount, target) if (amount == nil or amount <= 0) then player:PrintToPlayer("You must enter a valid amount."); player:PrintToPlayer( "@givexp <amount> <player>" ); return; end if (target == nil) then player:addExp(amount); -- print( 'Exp amount: ' .. tostring( amount ) ); else local targ = GetPlayerByName(target); if (targ ~= nil) then targ:addExp(amount); -- print( 'Exp amount: ' .. tostring( amount ) ); player:PrintToPlayer( string.format( "Gave %i exp to player '%s' ", amount, target ) ); else player:PrintToPlayer( string.format( "Player named '%s' not found!", target ) ); player:PrintToPlayer( "@givexp <amount> <player>" ); end end end;
gpl-3.0
nesstea/darkstar
scripts/globals/items/bowl_of_ocean_soup.lua
18
1899
----------------------------------------- -- ID: 4285 -- Item: bowl_of_ocean_soup -- Food Effect: 4Hrs, All Races ----------------------------------------- -- HP % 5 -- MP 5 -- Dexterity 4 -- Mind -3 -- HP Recovered While Healing 9 -- Attack % 14 (cap 65) -- Ranged Attack % 14 (cap 65) ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4285); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 5); target:addMod(MOD_FOOD_HP_CAP, 999); target:addMod(MOD_MP, 5); target:addMod(MOD_DEX, 4); target:addMod(MOD_MND, -3); target:addMod(MOD_HPHEAL, 9); target:addMod(MOD_FOOD_ATTP, 14); target:addMod(MOD_FOOD_ATT_CAP, 65); target:addMod(MOD_FOOD_RATTP, 14); target:addMod(MOD_FOOD_RATT_CAP, 65); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 5); target:delMod(MOD_FOOD_HP_CAP, 999); target:delMod(MOD_MP, 5); target:delMod(MOD_DEX, 4); target:delMod(MOD_MND, -3); target:delMod(MOD_HPHEAL, 9); target:delMod(MOD_FOOD_ATTP, 14); target:delMod(MOD_FOOD_ATT_CAP, 65); target:delMod(MOD_FOOD_RATTP, 14); target:delMod(MOD_FOOD_RATT_CAP, 65); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Galzweesh.lua
34
1034
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Galzweesh -- Standard Info NPC ----------------------------------- 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:startEvent(0x0292); 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
UnfortunateFruit/darkstar
scripts/zones/Boneyard_Gully/bcnms/head_wind.lua
13
1700
----------------------------------- -- Area: Boneyard_Gully -- Name: head_wind -- BCNM: 672 ----------------------------------- package.loaded["scripts/zones/Boneyard_Gully/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Boneyard_Gully/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) if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if(player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 5) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); player:setVar("COP_Ulmia_s_Path",6); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1); 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(1000); end end;
gpl-3.0
nesstea/darkstar
scripts/globals/mobskills/Polar_Bulwark.lua
27
1037
--------------------------------------------- -- Polar Bulwark -- -- Description: Grants a Magic Shield effect for a time. -- Type: Enhancing -- -- Range: Self --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 316) then local mobSkin = mob:getModelId(); if (mobSkin == 1796) then return 0; else return 1; end end if (mob:AnimationSub() == 0) then return 0; else return 1; end end; function onMobWeaponSkill(target, mob, skill) -- addEx to pervent dispel mob:addStatusEffectEx(EFFECT_MAGIC_SHIELD,0,1,0,45) skill:setMsg(MSG_BUFF) if (mob:getFamily() == 313) then -- Tinnin follows this up immediately with Nerve Gas mob:useMobAbility(1580); end return EFFECT_MAGIC_SHIELD; end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/The_Eldieme_Necropolis_[S]/Zone.lua
28
1342
----------------------------------- -- -- Zone: The_Eldieme_Necropolis_[S] (175) -- ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/The_Eldieme_Necropolis_[S]/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(420.035,-58.114,-119.51,191); 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
akdor1154/awesome
lib/menubar/icon_theme.lua
4
8699
--------------------------------------------------------------------------- --- Class module for icon lookup for menubar -- -- @author Kazunobu Kuriyama -- @copyright 2015 Kazunobu Kuriyama -- @release @AWESOME_VERSION@ -- @classmod menubar.icon_theme --------------------------------------------------------------------------- -- This implementation is based on the specifications: -- Icon Theme Specification 0.12 -- http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-0.12.html local beautiful = require("beautiful") local awful_util = require("awful.util") local GLib = require("lgi").GLib local index_theme = require("menubar.index_theme") local ipairs = ipairs local setmetatable = setmetatable local string = string local table = table local math = math local get_pragmatic_base_directories = function() local dirs = {} local dir = GLib.build_filenamev({GLib.get_home_dir(), ".icons"}) if awful_util.dir_readable(dir) then table.insert(dirs, dir) end dir = GLib.build_filenamev({GLib.get_user_data_dir(), "icons"}) if awful_util.dir_readable(dir) then table.insert(dirs, dir) end for _, v in ipairs(GLib.get_system_data_dirs()) do dir = GLib.build_filenamev({v, "icons"}) if awful_util.dir_readable(dir) then table.insert(dirs, dir) end end local need_usr_share_pixmaps = true for _, v in ipairs(GLib.get_system_data_dirs()) do dir = GLib.build_filenamev({v, "pixmaps"}) if awful_util.dir_readable(dir) then table.insert(dirs, dir) end if dir == "/usr/share/pixmaps" then need_usr_share_pixmaps = false end end dir = "/usr/share/pixmaps" if need_usr_share_pixmaps and awful_util.dir_readable(dir) then table.insert(dirs, dir) end return dirs end local get_default_icon_theme_name = function() local icon_theme_names = { "Adwaita", "gnome", "hicolor" } for _, dir in ipairs(get_pragmatic_base_directories()) do for _, icon_theme_name in ipairs(icon_theme_names) do local filename = string.format("%s/%s/index.theme", dir, icon_theme_name) if awful_util.file_readable(filename) then return icon_theme_name end end end return nil end local icon_theme = { mt = {} } local index_theme_cache = {} --- Class constructor of `icon_theme` -- @tparam string icon_theme_name Internal name of icon theme -- @tparam table base_directories Paths used for lookup -- @treturn table An instance of the class `icon_theme` icon_theme.new = function(icon_theme_name, base_directories) icon_theme_name = icon_theme_name or beautiful.icon_theme or get_default_icon_theme_name() base_directories = base_directories or get_pragmatic_base_directories() local self = {} self.icon_theme_name = icon_theme_name self.base_directories = base_directories self.extensions = { "png", "svg", "xpm" } -- Instantiate index_theme (cached). if not index_theme_cache[self.icon_theme_name] then index_theme_cache[self.icon_theme_name] = {} end local cache_key = table.concat(self.base_directories, ':') if not index_theme_cache[self.icon_theme_name][cache_key] then index_theme_cache[self.icon_theme_name][cache_key] = index_theme( self.icon_theme_name, self.base_directories) end self.index_theme = index_theme_cache[self.icon_theme_name][cache_key] return setmetatable(self, { __index = icon_theme }) end local directory_matches_size = function(self, subdirectory, icon_size) local kind, size, min_size, max_size, threshold = self.index_theme:get_per_directory_keys(subdirectory) if kind == "Fixed" then return icon_size == size elseif kind == "Scalable" then return icon_size >= min_size and icon_size <= max_size elseif kind == "Threshold" then return icon_size >= size - threshold and icon_size <= size + threshold end return false end local directory_size_distance = function(self, subdirectory, icon_size) local kind, size, min_size, max_size, threshold = self.index_theme:get_per_directory_keys(subdirectory) if kind == "Fixed" then return math.abs(icon_size - size) elseif kind == "Scalable" then if icon_size < min_size then return min_size - icon_size elseif icon_size > max_size then return icon_size - max_size end return 0 elseif kind == "Threshold" then if icon_size < size - threshold then return min_size - icon_size elseif icon_size > size + threshold then return icon_size - max_size end return 0 end return 0xffffffff -- Any large number will do. end local lookup_icon = function(self, icon_name, icon_size) local checked_already = {} for _, subdir in ipairs(self.index_theme:get_subdirectories()) do for _, basedir in ipairs(self.base_directories) do for _, ext in ipairs(self.extensions) do if directory_matches_size(self, subdir, icon_size) then local filename = string.format("%s/%s/%s/%s.%s", basedir, self.icon_theme_name, subdir, icon_name, ext) if awful_util.file_readable(filename) then return filename else checked_already[filename] = true end end end end end local minimal_size = 0xffffffff -- Any large number will do. local closest_filename = nil for _, subdir in ipairs(self.index_theme:get_subdirectories()) do local dist = directory_size_distance(self, subdir, icon_size) if dist < minimal_size then for _, basedir in ipairs(self.base_directories) do for _, ext in ipairs(self.extensions) do local filename = string.format("%s/%s/%s/%s.%s", basedir, self.icon_theme_name, subdir, icon_name, ext) if not checked_already[filename] then if awful_util.file_readable(filename) then closest_filename = filename minimal_size = dist end end end end end end return closest_filename end local find_icon_path_helper -- Gets called recursively. find_icon_path_helper = function(self, icon_name, icon_size) local filename = lookup_icon(self, icon_name, icon_size) if filename then return filename end for _, parent in ipairs(self.index_theme:get_inherits()) do local parent_icon_theme = icon_theme(parent, self.base_directories) filename = find_icon_path_helper(parent_icon_theme, icon_name, icon_size) if filename then return filename end end return nil end local lookup_fallback_icon = function(self, icon_name) for _, dir in ipairs(self.base_directories) do for _, ext in ipairs(self.extensions) do local filename = string.format("%s/%s.%s", dir, icon_name, ext) if awful_util.file_readable(filename) then return filename end end end return nil end --- Look up an image file based on a given icon name and/or a preferable size. -- @tparam string icon_name Icon name to be looked up -- @tparam number icon_size Prefereable icon size -- @treturn string Absolute path to the icon file, or nil if not found function icon_theme:find_icon_path(icon_name, icon_size) icon_size = icon_size or 16 if not icon_name or icon_name == "" then return nil end local filename = find_icon_path_helper(self, icon_name, icon_size) if filename then return filename end if self.icon_theme_name ~= "hicolor" then filename = find_icon_path_helper(icon_theme("hicolor", self.base_directories), icon_name, icon_size) if filename then return filename end end return lookup_fallback_icon(self, icon_name) end icon_theme.mt.__call = function(_, ...) return icon_theme.new(...) end return setmetatable(icon_theme, icon_theme.mt) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
UnfortunateFruit/darkstar
scripts/zones/Kuftal_Tunnel/mobs/Phantom_Worm.lua
27
1396
----------------------------------- -- Area: Kuftal Tunnel (173) -- Mob: Phantom Worm ----------------------------------- ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local npc = GetNPCByID(17490254); npc:hideNPC(900); local randpos = math.random(1,16); switch (randpos): caseof { [1] = function (x) npc:setPos(75.943,29.969,118.854); end, [2] = function (x) npc:setPos(75.758,30.000,125.815); end, [3] = function (x) npc:setPos(65.222,29.364,131.645); end, [4] = function (x) npc:setPos(53.088,25.033,138.725); end, [5] = function (x) npc:setPos(85.658,30.155,123.941); end, [6] = function (x) npc:setPos(91.153,30.146,113.657); end, [7] = function (x) npc:setPos(86.549,29.875,107.232); end, [8] = function (x) npc:setPos(94.763,29.054,105.138); end, [9] = function (x) npc:setPos(102.719,26.751,102.816); end, [10] = function (x) npc:setPos(71.571,30.241,110.704); end, [11] = function (x) npc:setPos(65.642,28.018,99.2442); end, [12] = function (x) npc:setPos(62.090,25.421,93.4702); end, [13] = function (x) npc:setPos(60.740,22.638,86.1781); end, [14] = function (x) npc:setPos(80.460,30.293,112.721); end, [15] = function (x) npc:setPos(76.929,30.050,127.630); end, [16] = function (x) npc:setPos(68.810,30.175,123.516); end, } end;
gpl-3.0
ennis/autograph-pipelines
resources/scripts/pl/utils.lua
2
16579
--- Generally useful routines. -- See @{01-introduction.md.Generally_useful_functions|the Guide}. -- @module pl.utils local format,gsub,byte = string.format,string.gsub,string.byte local compat = require 'pl.compat' local clock = os.clock local stdout = io.stdout local append = table.insert local unpack = rawget(_G,'unpack') or rawget(table,'unpack') local collisions = {} local utils = { _VERSION = "1.4.0", lua51 = compat.lua51, setfenv = compat.setfenv, getfenv = compat.getfenv, load = compat.load, execute = compat.execute, dir_separator = _G.package.config:sub(1,1), unpack = unpack } --- end this program gracefully. -- @param code The exit code or a message to be printed -- @param ... extra arguments for message's format' -- @see utils.fprintf function utils.quit(code,...) if type(code) == 'string' then utils.fprintf(io.stderr,code,...) code = -1 else utils.fprintf(io.stderr,...) end io.stderr:write('\n') os.exit(code) end --- print an arbitrary number of arguments using a format. -- @param fmt The format (see string.format) -- @param ... Extra arguments for format function utils.printf(fmt,...) utils.assert_string(1,fmt) utils.fprintf(stdout,fmt,...) end --- write an arbitrary number of arguments to a file using a format. -- @param f File handle to write to. -- @param fmt The format (see string.format). -- @param ... Extra arguments for format function utils.fprintf(f,fmt,...) utils.assert_string(2,fmt) f:write(format(fmt,...)) end local function import_symbol(T,k,v,libname) local key = rawget(T,k) -- warn about collisions! if key and k ~= '_M' and k ~= '_NAME' and k ~= '_PACKAGE' and k ~= '_VERSION' then utils.fprintf(io.stderr,"warning: '%s.%s' will not override existing symbol\n",libname,k) return end rawset(T,k,v) end local function lookup_lib(T,t) for k,v in pairs(T) do if v == t then return k end end return '?' end local already_imported = {} --- take a table and 'inject' it into the local namespace. -- @param t The Table -- @param T An optional destination table (defaults to callers environment) function utils.import(t,T) T = T or _G t = t or utils if type(t) == 'string' then t = require (t) end local libname = lookup_lib(T,t) if already_imported[t] then return end already_imported[t] = libname for k,v in pairs(t) do import_symbol(T,k,v,libname) end end utils.patterns = { FLOAT = '[%+%-%d]%d*%.?%d*[eE]?[%+%-]?%d*', INTEGER = '[+%-%d]%d*', IDEN = '[%a_][%w_]*', FILE = '[%a%.\\][:%][%w%._%-\\]*' } --- escape any 'magic' characters in a string -- @param s The input string function utils.escape(s) utils.assert_string(1,s) return (s:gsub('[%-%.%+%[%]%(%)%$%^%%%?%*]','%%%1')) end --- return either of two values, depending on a condition. -- @param cond A condition -- @param value1 Value returned if cond is true -- @param value2 Value returned if cond is false (can be optional) function utils.choose(cond,value1,value2) if cond then return value1 else return value2 end end local raise --- return the contents of a file as a string -- @param filename The file path -- @param is_bin open in binary mode -- @return file contents function utils.readfile(filename,is_bin) local mode = is_bin and 'b' or '' utils.assert_string(1,filename) local f,open_err = io.open(filename,'r'..mode) if not f then return utils.raise (open_err) end local res,read_err = f:read('*a') f:close() if not res then -- Errors in io.open have "filename: " prefix, -- error in file:read don't, add it. return raise (filename..": "..read_err) end return res end --- write a string to a file -- @param filename The file path -- @param str The string -- @param is_bin open in binary mode -- @return true or nil -- @return error message -- @raise error if filename or str aren't strings function utils.writefile(filename,str,is_bin) local mode = is_bin and 'b' or '' utils.assert_string(1,filename) utils.assert_string(2,str) local f,err = io.open(filename,'w'..mode) if not f then return raise(err) end f:write(str) f:close() return true end --- return the contents of a file as a list of lines -- @param filename The file path -- @return file contents as a table -- @raise errror if filename is not a string function utils.readlines(filename) utils.assert_string(1,filename) local f,err = io.open(filename,'r') if not f then return raise(err) end local res = {} for line in f:lines() do append(res,line) end f:close() return res end --- split a string into a list of strings separated by a delimiter. -- @param s The input string -- @param re A Lua string pattern; defaults to '%s+' -- @param plain don't use Lua patterns -- @param n optional maximum number of splits -- @return a list-like table -- @raise error if s is not a string function utils.split(s,re,plain,n) utils.assert_string(1,s) local find,sub,append = string.find, string.sub, table.insert local i1,ls = 1,{} if not re then re = '%s+' end if re == '' then return {s} end while true do local i2,i3 = find(s,re,i1,plain) if not i2 then local last = sub(s,i1) if last ~= '' then append(ls,last) end if #ls == 1 and ls[1] == '' then return {} else return ls end end append(ls,sub(s,i1,i2-1)) if n and #ls == n then ls[#ls] = sub(s,i1) return ls end i1 = i3+1 end end --- split a string into a number of values. -- @param s the string -- @param re the delimiter, default space -- @return n values -- @usage first,next = splitv('jane:doe',':') -- @see split function utils.splitv (s,re) return unpack(utils.split(s,re)) end --- convert an array of values to strings. -- @param t a list-like table -- @param temp buffer to use, otherwise allocate -- @param tostr custom tostring function, called with (value,index). -- Otherwise use `tostring` -- @return the converted buffer function utils.array_tostring (t,temp,tostr) temp, tostr = temp or {}, tostr or tostring for i = 1,#t do temp[i] = tostr(t[i],i) end return temp end local is_windows = package.config:sub(1, 1) == "\\" --- Quote an argument of a command. -- Quotes a single argument of a command to be passed -- to `os.execute`, `pl.utils.execute` or `pl.utils.executeex`. -- @string argument the argument. -- @return quoted argument. function utils.quote_arg(argument) if is_windows then if argument == "" or argument:find('[ \f\t\v]') then -- Need to quote the argument. -- Quotes need to be escaped with backslashes; -- additionally, backslashes before a quote, escaped or not, -- need to be doubled. -- See documentation for CommandLineToArgvW Windows function. argument = '"' .. argument:gsub([[(\*)"]], [[%1%1\"]]):gsub([[\+$]], "%0%0") .. '"' end -- os.execute() uses system() C function, which on Windows passes command -- to cmd.exe. Escape its special characters. return (argument:gsub('["^<>!|&%%]', "^%0")) else if argument == "" or argument:find('[^a-zA-Z0-9_@%+=:,./-]') then -- To quote arguments on posix-like systems use single quotes. -- To represent an embedded single quote close quoted string ('), -- add escaped quote (\'), open quoted string again ('). argument = "'" .. argument:gsub("'", [['\'']]) .. "'" end return argument end end --- execute a shell command and return the output. -- This function redirects the output to tempfiles and returns the content of those files. -- @param cmd a shell command -- @param bin boolean, if true, read output as binary file -- @return true if successful -- @return actual return code -- @return stdout output (string) -- @return errout output (string) function utils.executeex(cmd, bin) local mode local outfile = os.tmpname() local errfile = os.tmpname() if is_windows and not outfile:find(':') then outfile = os.getenv('TEMP')..outfile errfile = os.getenv('TEMP')..errfile end cmd = cmd .. " > " .. utils.quote_arg(outfile) .. " 2> " .. utils.quote_arg(errfile) local success, retcode = utils.execute(cmd) local outcontent = utils.readfile(outfile, bin) local errcontent = utils.readfile(errfile, bin) os.remove(outfile) os.remove(errfile) return success, retcode, (outcontent or ""), (errcontent or "") end --- 'memoize' a function (cache returned value for next call). -- This is useful if you have a function which is relatively expensive, -- but you don't know in advance what values will be required, so -- building a table upfront is wasteful/impossible. -- @param func a function of at least one argument -- @return a function with at least one argument, which is used as the key. function utils.memoize(func) local cache = {} return function(k) local res = cache[k] if res == nil then res = func(k) cache[k] = res end return res end end utils.stdmt = { List = {_name='List'}, Map = {_name='Map'}, Set = {_name='Set'}, MultiMap = {_name='MultiMap'} } local _function_factories = {} --- associate a function factory with a type. -- A function factory takes an object of the given type and -- returns a function for evaluating it -- @tab mt metatable -- @func fun a callable that returns a function function utils.add_function_factory (mt,fun) _function_factories[mt] = fun end local function _string_lambda(f) local raise = utils.raise if f:find '^|' or f:find '_' then local args,body = f:match '|([^|]*)|(.+)' if f:find '_' then args = '_' body = f else if not args then return raise 'bad string lambda' end end local fstr = 'return function('..args..') return '..body..' end' local fn,err = utils.load(fstr) if not fn then return raise(err) end fn = fn() return fn else return raise 'not a string lambda' end end --- an anonymous function as a string. This string is either of the form -- '|args| expression' or is a function of one argument, '_' -- @param lf function as a string -- @return a function -- @usage string_lambda '|x|x+1' (2) == 3 -- @usage string_lambda '_+1 (2) == 3 -- @function utils.string_lambda utils.string_lambda = utils.memoize(_string_lambda) local ops --- process a function argument. -- This is used throughout Penlight and defines what is meant by a function: -- Something that is callable, or an operator string as defined by <code>pl.operator</code>, -- such as '>' or '#'. If a function factory has been registered for the type, it will -- be called to get the function. -- @param idx argument index -- @param f a function, operator string, or callable object -- @param msg optional error message -- @return a callable -- @raise if idx is not a number or if f is not callable function utils.function_arg (idx,f,msg) utils.assert_arg(1,idx,'number') local tp = type(f) if tp == 'function' then return f end -- no worries! -- ok, a string can correspond to an operator (like '==') if tp == 'string' then if not ops then ops = require 'pl.operator'.optable end local fn = ops[f] if fn then return fn end local fn, err = utils.string_lambda(f) if not fn then error(err..': '..f) end return fn elseif tp == 'table' or tp == 'userdata' then local mt = getmetatable(f) if not mt then error('not a callable object',2) end local ff = _function_factories[mt] if not ff then if not mt.__call then error('not a callable object',2) end return f else return ff(f) -- we have a function factory for this type! end end if not msg then msg = " must be callable" end if idx > 0 then error("argument "..idx..": "..msg,2) else error(msg,2) end end --- bind the first argument of the function to a value. -- @param fn a function of at least two values (may be an operator string) -- @param p a value -- @return a function such that f(x) is fn(p,x) -- @raise same as @{function_arg} -- @see func.bind1 function utils.bind1 (fn,p) fn = utils.function_arg(1,fn) return function(...) return fn(p,...) end end --- bind the second argument of the function to a value. -- @param fn a function of at least two values (may be an operator string) -- @param p a value -- @return a function such that f(x) is fn(x,p) -- @raise same as @{function_arg} function utils.bind2 (fn,p) fn = utils.function_arg(1,fn) return function(x,...) return fn(x,p,...) end end --- assert that the given argument is in fact of the correct type. -- @param n argument index -- @param val the value -- @param tp the type -- @param verify an optional verification function -- @param msg an optional custom message -- @param lev optional stack position for trace, default 2 -- @raise if the argument n is not the correct type -- @usage assert_arg(1,t,'table') -- @usage assert_arg(n,val,'string',path.isdir,'not a directory') function utils.assert_arg (n,val,tp,verify,msg,lev) if type(val) ~= tp then error(("argument %d expected a '%s', got a '%s'"):format(n,tp,type(val)),lev or 2) end if verify and not verify(val) then error(("argument %d: '%s' %s"):format(n,val,msg),lev or 2) end end --- assert the common case that the argument is a string. -- @param n argument index -- @param val a value that must be a string -- @raise val must be a string function utils.assert_string (n,val) utils.assert_arg(n,val,'string',nil,nil,3) end local err_mode = 'default' --- control the error strategy used by Penlight. -- Controls how <code>utils.raise</code> works; the default is for it -- to return nil and the error string, but if the mode is 'error' then -- it will throw an error. If mode is 'quit' it will immediately terminate -- the program. -- @param mode - either 'default', 'quit' or 'error' -- @see utils.raise function utils.on_error (mode) if ({['default'] = 1, ['quit'] = 2, ['error'] = 3})[mode] then err_mode = mode else -- fail loudly if err_mode == 'default' then err_mode = 'error' end utils.raise("Bad argument expected string; 'default', 'quit', or 'error'. Got '"..tostring(mode).."'") end end --- used by Penlight functions to return errors. Its global behaviour is controlled -- by <code>utils.on_error</code> -- @param err the error string. -- @see utils.on_error function utils.raise (err) if err_mode == 'default' then return nil,err elseif err_mode == 'quit' then utils.quit(err) else error(err,2) end end --- is the object of the specified type?. -- If the type is a string, then use type, otherwise compare with metatable -- @param obj An object to check -- @param tp String of what type it should be function utils.is_type (obj,tp) if type(tp) == 'string' then return type(obj) == tp end local mt = getmetatable(obj) return tp == mt end raise = utils.raise --- load a code string or bytecode chunk. -- @param code Lua code as a string or bytecode -- @param name for source errors -- @param mode kind of chunk, 't' for text, 'b' for bytecode, 'bt' for all (default) -- @param env the environment for the new chunk (default nil) -- @return compiled chunk -- @return error message (chunk is nil) -- @function utils.load --------------- -- Get environment of a function. -- With Lua 5.2, may return nil for a function with no global references! -- Based on code by [Sergey Rozhenko](http://lua-users.org/lists/lua-l/2010-06/msg00313.html) -- @param f a function or a call stack reference -- @function utils.getfenv --------------- -- Set environment of a function -- @param f a function or a call stack reference -- @param env a table that becomes the new environment of `f` -- @function utils.setfenv --- execute a shell command. -- This is a compatibility function that returns the same for Lua 5.1 and Lua 5.2 -- @param cmd a shell command -- @return true if successful -- @return actual return code -- @function utils.execute return utils
mit
Xileck/forgottenserver
data/global.lua
18
6348
dofile('data/lib/lib.lua') STORAGEVALUE_PROMOTION = 30018 ropeSpots = {384, 418, 8278, 8592, 13189, 14435, 14436, 15635, 19518} doors = {[1209] = 1211, [1210] = 1211, [1212] = 1214, [1213] = 1214, [1219] = 1220, [1221] = 1222, [1231] = 1233, [1232] = 1233, [1234] = 1236, [1235] = 1236, [1237] = 1238, [1239] = 1240, [1249] = 1251, [1250] = 1251, [1252] = 1254, [1253] = 1254, [1539] = 1540, [1541] = 1542, [3535] = 3537, [3536] = 3537, [3538] = 3539, [3544] = 3546, [3545] = 3546, [3547] = 3548, [4913] = 4915, [4914] = 4915, [4916] = 4918, [4917] = 4918, [5082] = 5083, [5084] = 5085, [5098] = 5100, [5099] = 5100, [5101] = 5102, [5107] = 5109, [5108] = 5109, [5110] = 5111, [5116] = 5118, [5117] = 5118, [5119] = 5120, [5125] = 5127, [5126] = 5127, [5128] = 5129, [5134] = 5136, [5135] = 5136, [5137] = 5139, [5138] = 5139, [5140] = 5142, [5141] = 5142, [5143] = 5145, [5144] = 5145, [5278] = 5280, [5279] = 5280, [5281] = 5283, [5282] = 5283, [5284] = 5285, [5286] = 5287, [5515] = 5516, [5517] = 5518, [5732] = 5734, [5733] = 5734, [5735] = 5737, [5736] = 5737, [6192] = 6194, [6193] = 6194, [6195] = 6197, [6196] = 6197, [6198] = 6199, [6200] = 6201, [6249] = 6251, [6250] = 6251, [6252] = 6254, [6253] = 6254, [6255] = 6256, [6257] = 6258, [6795] = 6796, [6797] = 6798, [6799] = 6800, [6801] = 6802, [6891] = 6893, [6892] = 6893, [6894] = 6895, [6900] = 6902, [6901] = 6902, [6903] = 6904, [7033] = 7035, [7034] = 7035, [7036] = 7037, [7042] = 7044, [7043] = 7044, [7045] = 7046, [7054] = 7055, [7056] = 7057, [8541] = 8543, [8542] = 8543, [8544] = 8546, [8545] = 8546, [8547] = 8548, [8549] = 8550, [9165] = 9167, [9166] = 9167, [9168] = 9170, [9169] = 9170, [9171] = 9172, [9173] = 9174, [9267] = 9269, [9268] = 9269, [9270] = 9272, [9271] = 9272, [9273] = 9274, [9275] = 9276, [10276] = 10277, [10274] = 10275, [10268] = 10270, [10269] = 10270, [10271] = 10273, [10272] = 10273, [10471] = 10472, [10480] = 10481, [10477] = 10479, [10478] = 10479, [10468] = 10470, [10469] = 10470, [10775] = 10777, [10776] = 10777, [12092] = 12094, [12093] = 12094, [12188] = 12190, [12189] = 12190, [19840] = 19842, [19841] = 19842, [19843] = 19844, [19980] = 19982, [19981] = 19982, [19983] = 19984, [20273] = 20275, [20274] = 20275, [20276] = 20277, [17235] = 17236, [18208] = 18209, [13022] = 13023, [10784] = 10786, [10785] = 10786, [12099] = 12101, [12100] = 12101, [12197] = 12199, [12198] = 12199, [19849] = 19851, [19850] = 19851, [19852] = 19853, [19989] = 19991, [19990] = 19991, [19992] = 19993, [20282] = 20284, [20283] = 20284, [20285] = 20286, [17237] = 17238, [13020] = 13021, [10780] = 10781, [12095] = 12096, [12195] = 12196, [19845] = 19846, [19985] = 19986, [20278] = 20279, [10789] = 10790, [12102] = 12103, [12204] = 12205, [19854] = 19855, [19994] = 19995, [20287] = 20288, [10782] = 10783, [12097] = 12098, [12193] = 12194, [19847] = 19848, [19987] = 19988, [20280] = 20281, [10791] = 10792, [12104] = 12105, [12202] = 12203, [19856] = 19857, [19996] = 19997, [20289] = 20290} verticalOpenDoors = {1211, 1220, 1224, 1228, 1233, 1238, 1242, 1246, 1251, 1256, 1260, 1540, 3546, 3548, 3550, 3552, 4915, 5083, 5109, 5111, 5113, 5115, 5127, 5129, 5131, 5133, 5142, 5145, 5283, 5285, 5289, 5293, 5516, 5737, 5749, 6194, 6199, 6203, 6207, 6251, 6256, 6260, 6264, 6798, 6802, 6902, 6904, 6906, 6908, 7044, 7046, 7048, 7050, 7055, 8543, 8548, 8552, 8556, 9167, 9172, 9269, 9274, 9274, 9269, 9278, 9282, 10270, 10275, 10279, 10283, 10479, 10481, 10485, 10483, 10786, 12101, 12199, 19851, 19853, 19991, 19993, 20284, 20286, 17238, 13021, 10790, 12103, 12205, 19855, 19995, 20288, 10792, 12105, 12203, 19857, 19997, 20290} horizontalOpenDoors = {1214, 1222, 1226, 1230, 1236, 1240, 1244, 1248, 1254, 1258, 1262, 1542, 3537, 3539, 3541, 3543, 4918, 5085, 5100, 5102, 5104, 5106, 5118, 5120, 5122, 5124, 5136, 5139, 5280, 5287, 5291, 5295, 5518, 5734, 5746, 6197, 6201, 6205, 6209, 6254, 6258, 6262, 6266, 6796, 6800, 6893, 6895, 6897, 6899, 7035, 7037, 7039, 7041, 7057, 8546, 8550, 8554, 8558, 9170, 9174, 9272, 9276, 9280, 9284, 10273, 10277, 10281, 10285, 10470, 10472, 10476, 10474, 10777, 12094, 12190, 19842, 19844, 19982, 19984, 20275, 20277, 17236, 18209, 13023, 10781, 12096, 12196, 19846, 19986, 20279, 10783, 12098, 12194, 19848, 19988, 20281} openSpecialDoors = {1224, 1226, 1228, 1230, 1242, 1244, 1246, 1248, 1256, 1258, 1260, 1262, 3541, 3543, 3550, 3552, 5104, 5106, 5113, 5115, 5122, 5124, 5131, 5133, 5289, 5291, 5293, 5295, 6203, 6205, 6207, 6209, 6260, 6262, 6264, 6266, 6897, 6899, 6906, 6908, 7039, 7041, 7048, 7050, 8552, 8554, 8556, 8558, 9176, 9178, 9180, 9182, 9278, 9280, 9282, 9284, 10279, 10281, 10283, 10285, 10474, 10476, 10483, 10485, 10781, 12096, 12196, 19846, 19986, 20279, 10783, 12098, 12194, 19848, 19988, 20281, 10790, 12103, 12205, 19855, 19995, 20288, 10792, 12105, 12203, 19857, 19997, 20290} questDoors = {1223, 1225, 1241, 1243, 1255, 1257, 3542, 3551, 5105, 5114, 5123, 5132, 5288, 5290, 5745, 5748, 6202, 6204, 6259, 6261, 6898, 6907, 7040, 7049, 8551, 8553, 9175, 9177, 9277, 9279, 10278, 10280, 10475, 10484, 10782, 12097, 12193, 19847, 19987, 20280, 10791, 12104, 12202, 19856, 19996, 20289} levelDoors = {1227, 1229, 1245, 1247, 1259, 1261, 3540, 3549, 5103, 5112, 5121, 5130, 5292, 5294, 6206, 6208, 6263, 6265, 6896, 6905, 7038, 7047, 8555, 8557, 9179, 9181, 9281, 9283, 10282, 10284, 10473, 10482, 10780, 10789, 10780, 12095, 12195, 19845, 19985, 20278, 10789, 12102, 12204, 19854, 19994, 20287} keys = {2086, 2087, 2088, 2089, 2090, 2091, 2092, 10032} function getDistanceBetween(firstPosition, secondPosition) local xDif = math.abs(firstPosition.x - secondPosition.x) local yDif = math.abs(firstPosition.y - secondPosition.y) local posDif = math.max(xDif, yDif) if firstPosition.z ~= secondPosition.z then posDif = posDif + 15 end return posDif end function getFormattedWorldTime() local worldTime = getWorldTime() local hours = math.floor(worldTime / 60) local minutes = worldTime % 60 if minutes < 10 then minutes = '0' .. minutes end return hours .. ':' .. minutes end string.split = function(str, sep) local res = {} for v in str:gmatch("([^" .. sep .. "]+)") do res[#res + 1] = v end return res end string.trim = function(str) return str:match'^()%s*$' and '' or str:match'^%s*(.*%S)' end if nextUseStaminaTime == nil then nextUseStaminaTime = {} end
gpl-2.0
ruisebastiao/nodemcu-firmware
tools/build.lua
48
28446
-- eLua build system module( ..., package.seeall ) local lfs = require "lfs" local sf = string.format utils = require "tools.utils" ------------------------------------------------------------------------------- -- Various helpers -- Return the time of the last modification of the file local function get_ftime( path ) local t = lfs.attributes( path, 'modification' ) return t or -1 end -- Check if a given target name is phony local function is_phony( target ) return target:find( "#phony" ) == 1 end -- Return a string with $(key) replaced with 'value' local function expand_key( s, key, value ) if not value then return s end local fmt = sf( "%%$%%(%s%%)", key ) return ( s:gsub( fmt, value ) ) end -- Return a target name considering phony targets local function get_target_name( s ) if not is_phony( s ) then return s end end -- 'Liniarize' a file name by replacing its path separators indicators with '_' local function linearize_fname( s ) return ( s:gsub( "[\\/]", "__" ) ) end -- Helper: transform a table into a string if needed local function table_to_string( t ) if not t then return nil end if type( t ) == "table" then t = table.concat( t, " " ) end return t end -- Helper: return the extended type of an object (takes into account __type) local function exttype( o ) local t = type( o ) if t == "table" and o.__type then t = o:__type() end return t end --------------------------------------- -- Table utils -- (from http://lua-users.org/wiki/TableUtils) function table.val_to_str( v ) if "string" == type( v ) then v = string.gsub( v, "\n", "\\n" ) if string.match( string.gsub(v,"[^'\"]",""), '^"+$' ) then return "'" .. v .. "'" end return '"' .. string.gsub(v,'"', '\\"' ) .. '"' else return "table" == type( v ) and table.tostring( v ) or tostring( v ) end end function table.key_to_str ( k ) if "string" == type( k ) and string.match( k, "^[_%a][_%a%d]*$" ) then return k else return "[" .. table.val_to_str( k ) .. "]" end end function table.tostring( tbl ) local result, done = {}, {} for k, v in ipairs( tbl ) do table.insert( result, table.val_to_str( v ) ) done[ k ] = true end for k, v in pairs( tbl ) do if not done[ k ] then table.insert( result, table.key_to_str( k ) .. "=" .. table.val_to_str( v ) ) end end return "{" .. table.concat( result, "," ) .. "}" end ------------------------------------------------------------------------------- -- Dummy 'builder': simply checks the date of a file local _fbuilder = {} _fbuilder.new = function( target, dep ) local self = {} setmetatable( self, { __index = _fbuilder } ) self.target = target self.dep = dep return self end _fbuilder.build = function( self ) -- Doesn't build anything but returns 'true' if the dependency is newer than -- the target if is_phony( self.target ) then return true else return get_ftime( self.dep ) > get_ftime( self.target ) end end _fbuilder.target_name = function( self ) return get_target_name( self.dep ) end -- Object type _fbuilder.__type = function() return "_fbuilder" end ------------------------------------------------------------------------------- -- Target object local _target = {} _target.new = function( target, dep, command, builder, ttype ) local self = {} setmetatable( self, { __index = _target } ) self.target = target self.command = command self.builder = builder builder:register_target( target, self ) self:set_dependencies( dep ) self.dep = self:_build_dependencies( self.origdep ) self.dont_clean = false self.can_substitute_cmdline = false self._force_rebuild = #self.dep == 0 builder.runlist[ target ] = false self:set_type( ttype ) return self end -- Set dependencies as a string; actual dependencies are computed by _build_dependencies -- (below) when 'build' is called _target.set_dependencies = function( self, dep ) self.origdep = dep end -- Set the target type -- This is only for displaying actions _target.set_type = function( self, ttype ) local atable = { comp = { "[COMPILE]", 'blue' } , dep = { "[DEPENDS]", 'magenta' }, link = { "[LINK]", 'yellow' }, asm = { "[ASM]", 'white' } } local tdata = atable[ ttype ] if not tdata then self.dispstr = is_phony( self.target ) and "[PHONY]" or "[TARGET]" self.dispcol = 'green' else self.dispstr = tdata[ 1 ] self.dispcol = tdata[ 2 ] end end -- Set dependencies -- This uses a proxy table and returns string deps dynamically according -- to the targets currently registered in the builder _target._build_dependencies = function( self, dep ) -- Step 1: start with an array if type( dep ) == "string" then dep = utils.string_to_table( dep ) end -- Step 2: linearize "dep" array keeping targets local filter = function( e ) local t = exttype( e ) return t ~= "_ftarget" and t ~= "_target" end dep = utils.linearize_array( dep, filter ) -- Step 3: strings are turned into _fbuilder objects if not found as targets; -- otherwise the corresponding target object is used for i = 1, #dep do if type( dep[ i ] ) == 'string' then local t = self.builder:get_registered_target( dep[ i ] ) dep[ i ] = t or _fbuilder.new( self.target, dep[ i ] ) end end return dep end -- Set pre-build function _target.set_pre_build_function = function( self, f ) self._pre_build_function = f end -- Set post-build function _target.set_post_build_function = function( self, f ) self._post_build_function = f end -- Force rebuild _target.force_rebuild = function( self, flag ) self._force_rebuild = flag end -- Set additional arguments to send to the builder function if it is a callable _target.set_target_args = function( self, args ) self._target_args = args end -- Function to execute in clean mode _target._cleaner = function( target, deps, tobj, disp_mode ) -- Clean the main target if it is not a phony target local dprint = function( ... ) if disp_mode ~= "minimal" then print( ... ) end end if not is_phony( target ) then if tobj.dont_clean then dprint( sf( "[builder] Target '%s' will not be deleted", target ) ) return 0 end if disp_mode ~= "minimal" then io.write( sf( "[builder] Removing %s ... ", target ) ) end if os.remove( target ) then dprint "done." else dprint "failed!" end end return 0 end -- Build the given target _target.build = function( self ) if self.builder.runlist[ self.target ] then return end local docmd = self:target_name() and lfs.attributes( self:target_name(), "mode" ) ~= "file" docmd = docmd or self.builder.global_force_rebuild local initdocmd = docmd self.dep = self:_build_dependencies( self.origdep ) local depends, dep, previnit = '', self.dep, self.origdep -- Iterate through all dependencies, execute each one in turn local deprunner = function() for i = 1, #dep do local res = dep[ i ]:build() docmd = docmd or res local t = dep[ i ]:target_name() if exttype( dep[ i ] ) == "_target" and t and not is_phony( self.target ) then docmd = docmd or get_ftime( t ) > get_ftime( self.target ) end if t then depends = depends .. t .. " " end end end deprunner() -- Execute the preb-build function if needed if self._pre_build_function then self._pre_build_function( self, docmd ) end -- If the dependencies changed as a result of running the pre-build function -- run through them again if previnit ~= self.origdep then self.dep = self:_build_dependencies( self.origdep ) depends, dep, docmd = '', self.dep, initdocmd deprunner() end -- If at least one dependency is new rebuild the target docmd = docmd or self._force_rebuild or self.builder.clean_mode local keep_flag = true if docmd and self.command then if self.builder.disp_mode ~= 'all' and self.builder.disp_mode ~= "minimal" and not self.builder.clean_mode then io.write( utils.col_funcs[ self.dispcol ]( self.dispstr ) .. " " ) end local cmd, code = self.command if self.builder.clean_mode then cmd = _target._cleaner end if type( cmd ) == 'string' then cmd = expand_key( cmd, "TARGET", self.target ) cmd = expand_key( cmd, "DEPENDS", depends ) cmd = expand_key( cmd, "FIRST", dep[ 1 ]:target_name() ) if self.builder.disp_mode == 'all' then print( cmd ) elseif self.builder.disp_mode ~= "minimal" then print( self.target ) end code = self:execute( cmd ) else if not self.builder.clean_mode and self.builder.disp_mode ~= "all" and self.builder.disp_mode ~= "minimal" then print( self.target ) end code = cmd( self.target, self.dep, self.builder.clean_mode and self or self._target_args, self.builder.disp_mode ) if code == 1 then -- this means "mark target as 'not executed'" keep_flag = false code = 0 end end if code ~= 0 then print( utils.col_red( "[builder] Error building target" ) ) if self.builder.disp_mode ~= 'all' and type( cmd ) == "string" then print( utils.col_red( "[builder] Last executed command was: " ) ) print( cmd ) end os.exit( 1 ) end end -- Execute the post-build function if needed if self._post_build_function then self._post_build_function( self, docmd ) end -- Marked target as "already ran" so it won't run again self.builder.runlist[ self.target ] = true return docmd and keep_flag end -- Return the actual target name (taking into account phony targets) _target.target_name = function( self ) return get_target_name( self.target ) end -- Restrict cleaning this target _target.prevent_clean = function( self, flag ) self.dont_clean = flag end -- Object type _target.__type = function() return "_target" end _target.execute = function( self, cmd ) local code if utils.is_windows() and #cmd > 8190 and self.can_substitute_cmdline then -- Avoid cmd's maximum command line length limitation local t = cmd:find( " " ) f = io.open( "tmpcmdline", "w" ) local rest = cmd:sub( t + 1 ) f:write( ( rest:gsub( "\\", "/" ) ) ) f:close() cmd = cmd:sub( 1, t - 1 ) .. " @tmpcmdline" end local code = os.execute( cmd ) os.remove( "tmpcmdline" ) return code end _target.set_substitute_cmdline = function( self, flag ) self.can_substitute_cmdline = flag end ------------------------------------------------------------------------------- -- Builder public interface builder = { KEEP_DIR = 0, BUILD_DIR_LINEARIZED = 1 } --------------------------------------- -- Initialization and option handling -- Create a new builder object with the output in 'build_dir' and with the -- specified compile, dependencies and link command builder.new = function( build_dir ) self = {} setmetatable( self, { __index = builder } ) self.build_dir = build_dir or ".build" self.exe_extension = utils.is_windows() and "exe" or "" self.clean_mode = false self.opts = utils.options_handler() self.args = {} self.user_args = {} self.build_mode = self.KEEP_DIR self.targets = {} self.targetargs = {} self._tlist = {} self.runlist = {} self.disp_mode = 'all' self.cmdline_macros = {} self.c_targets = {} self.preprocess_mode = false self.asm_mode = false return self end -- Helper: create the build output directory builder._create_build_dir = function( self ) if self.build_dir_created then return end if self.build_mode ~= self.KEEP_DIR then -- Create builds directory if needed local mode = lfs.attributes( self.build_dir, "mode" ) if not mode or mode ~= "directory" then if not utils.full_mkdir( self.build_dir ) then print( "[builder] Unable to create directory " .. self.build_dir ) os.exit( 1 ) end end end self.build_dir_created = true end -- Add an options to the builder builder.add_option = function( self, name, help, default, data ) self.opts:add_option( name, help, default, data ) end -- Initialize builder from the given command line builder.init = function( self, args ) -- Add the default options local opts = self.opts opts:add_option( "build_mode", 'choose location of the object files', self.KEEP_DIR, { keep_dir = self.KEEP_DIR, build_dir_linearized = self.BUILD_DIR_LINEARIZED } ) opts:add_option( "build_dir", 'choose build directory', self.build_dir ) opts:add_option( "disp_mode", 'set builder display mode', 'summary', { 'all', 'summary', 'minimal' } ) -- Apply default values to all options for i = 1, opts:get_num_opts() do local o = opts:get_option( i ) self.args[ o.name:upper() ] = o.default end -- Read and interpret command line for i = 1, #args do local a = args[ i ] if a:upper() == "-C" then -- clean option (-c) self.clean_mode = true elseif a:upper() == '-H' then -- help option (-h) self:_show_help() os.exit( 1 ) elseif a:upper() == "-E" then -- preprocess self.preprocess_mode = true elseif a:upper() == "-S" then -- generate assembler self.asm_mode = true elseif a:find( '-D' ) == 1 and #a > 2 then -- this is a macro definition that will be auomatically added to the compiler flags table.insert( self.cmdline_macros, a:sub( 3 ) ) elseif a:find( '=' ) then -- builder argument (key=value) local k, v = opts:handle_arg( a ) if not k then self:_show_help() os.exit( 1 ) end self.args[ k:upper() ] = v self.user_args[ k:upper() ] = true else -- this must be the target name / target arguments if self.targetname == nil then self.targetname = a else table.insert( self.targetargs, a ) end end end -- Read back the default options self.build_mode = self.args.BUILD_MODE self.build_dir = self.args.BUILD_DIR self.disp_mode = self.args.DISP_MODE end -- Return the value of the option with the given name builder.get_option = function( self, optname ) return self.args[ optname:upper() ] end -- Returns true if the given option was specified by the user on the command line, false otherwise builder.is_user_option = function( self, optname ) return self.user_args[ optname:upper() ] end -- Show builder help builder._show_help = function( self ) print( "[builder] Valid options:" ) print( " -h: help (this text)" ) print( " -c: clean target" ) print( " -E: generate preprocessed output for single file targets" ) print( " -S: generate assembler output for single file targets" ) self.opts:show_help() end --------------------------------------- -- Builder configuration -- Set the compile command builder.set_compile_cmd = function( self, cmd ) self.comp_cmd = cmd end -- Set the link command builder.set_link_cmd = function( self, cmd ) self.link_cmd = cmd end -- Set the assembler command builder.set_asm_cmd = function( self, cmd ) self._asm_cmd = cmd end -- Set (actually force) the object file extension builder.set_object_extension = function( self, ext ) self.obj_extension = ext end -- Set (actually force) the executable file extension builder.set_exe_extension = function( self, ext ) self.exe_extension = ext end -- Set the clean mode builder.set_clean_mode = function( self, isclean ) self.clean_mode = isclean end -- Sets the build mode builder.set_build_mode = function( self, mode ) self.build_mode = mode end -- Set the build directory builder.set_build_dir = function( self, dir ) if self.build_dir_created then print "[builder] Error: build directory already created" os.exit( 1 ) end self.build_dir = dir self:_create_build_dir() end -- Return the current build directory builder.get_build_dir = function( self ) return self.build_dir end -- Return the target arguments builder.get_target_args = function( self ) return self.targetargs end -- Set a specific dependency generation command for the assembler -- Pass 'false' to skip dependency generation for assembler files builder.set_asm_dep_cmd = function( self, asm_dep_cmd ) self.asm_dep_cmd = asm_dep_cmd end -- Set a specific dependency generation command for the compiler -- Pass 'false' to skip dependency generation for C files builder.set_c_dep_cmd = function( self, c_dep_cmd ) self.c_dep_cmd = c_dep_cmd end -- Save the builder configuration for a given component to a string builder._config_to_string = function( self, what ) local ctable = {} local state_fields if what == 'comp' then state_fields = { 'comp_cmd', '_asm_cmd', 'c_dep_cmd', 'asm_dep_cmd', 'obj_extension' } elseif what == 'link' then state_fields = { 'link_cmd' } else print( sf( "Invalid argument '%s' to _config_to_string", what ) ) os.exit( 1 ) end utils.foreach( state_fields, function( k, v ) ctable[ v ] = self[ v ] end ) return table.tostring( ctable ) end -- Check the configuration of the given component against the previous one -- Return true if the configuration has changed builder._compare_config = function( self, what ) local res = false local crtstate = self:_config_to_string( what ) if not self.clean_mode then local fconf = io.open( self.build_dir .. utils.dir_sep .. ".builddata." .. what, "rb" ) if fconf then local oldstate = fconf:read( "*a" ) fconf:close() if oldstate:lower() ~= crtstate:lower() then res = true end end end -- Write state to build dir fconf = io.open( self.build_dir .. utils.dir_sep .. ".builddata." .. what, "wb" ) if fconf then fconf:write( self:_config_to_string( what ) ) fconf:close() end return res end -- Sets the way commands are displayed builder.set_disp_mode = function( self, mode ) mode = mode:lower() if mode ~= 'all' and mode ~= 'summary' and mode ~= "minimal" then print( sf( "[builder] Invalid display mode '%s'", mode ) ) os.exit( 1 ) end self.disp_mode = mode end --------------------------------------- -- Command line builders -- Internal helper builder._generic_cmd = function( self, args ) local compcmd = args.compiler or "gcc" compcmd = compcmd .. " " local flags = type( args.flags ) == 'table' and table_to_string( utils.linearize_array( args.flags ) ) or args.flags local defines = type( args.defines ) == 'table' and table_to_string( utils.linearize_array( args.defines ) ) or args.defines local includes = type( args.includes ) == 'table' and table_to_string( utils.linearize_array( args.includes ) ) or args.includes local comptype = table_to_string( args.comptype ) or "-c" compcmd = compcmd .. utils.prepend_string( defines, "-D" ) compcmd = compcmd .. utils.prepend_string( includes, "-I" ) return compcmd .. flags .. " " .. comptype .. " -o $(TARGET) $(FIRST)" end -- Return a compile command based on the specified args builder.compile_cmd = function( self, args ) args.defines = { args.defines, self.cmdline_macros } if self.preprocess_mode then args.comptype = "-E" elseif self.asm_mode then args.comptype = "-S" else args.comptype = "-c" end return self:_generic_cmd( args ) end -- Return an assembler command based on the specified args builder.asm_cmd = function( self, args ) args.defines = { args.defines, self.cmdline_macros } args.compiler = args.assembler args.comptype = self.preprocess_mode and "-E" or "-c" return self:_generic_cmd( args ) end -- Return a link command based on the specified args builder.link_cmd = function( self, args ) local flags = type( args.flags ) == 'table' and table_to_string( utils.linearize_array( args.flags ) ) or args.flags local libraries = type( args.libraries ) == 'table' and table_to_string( utils.linearize_array( args.libraries ) ) or args.libraries local linkcmd = args.linker or "gcc" linkcmd = linkcmd .. " " .. flags .. " -o $(TARGET) $(DEPENDS)" linkcmd = linkcmd .. " " .. utils.prepend_string( libraries, "-l" ) return linkcmd end --------------------------------------- -- Target handling -- Create a return a new C to object target builder.c_target = function( self, target, deps, comp_cmd ) return _target.new( target, deps, comp_cmd or self.comp_cmd, self, 'comp' ) end -- Create a return a new ASM to object target builder.asm_target = function( self, target, deps, asm_cmd ) return _target.new( target, deps, asm_cmd or self._asm_cmd, self, 'asm' ) end -- Return the name of a dependency file name corresponding to a C source builder.get_dep_filename = function( self, srcname ) return utils.replace_extension( self.build_dir .. utils.dir_sep .. linearize_fname( srcname ), "d" ) end -- Create a return a new C dependency target builder.dep_target = function( self, dep, depdeps, dep_cmd ) local depname = self:get_dep_filename( dep ) return _target.new( depname, depdeps, dep_cmd, self, 'dep' ) end -- Create and return a new link target builder.link_target = function( self, out, dep, link_cmd ) local path, ext = utils.split_ext( out ) if not ext and self.exe_extension and #self.exe_extension > 0 then out = out .. self.exe_extension end local t = _target.new( out, dep, link_cmd or self.link_cmd, self, 'link' ) if self:_compare_config( 'link' ) then t:force_rebuild( true ) end t:set_substitute_cmdline( true ) return t end -- Create and return a new generic target builder.target = function( self, dest_target, deps, cmd ) return _target.new( dest_target, deps, cmd, self ) end -- Register a target (called from _target.new) builder.register_target = function( self, name, obj ) self._tlist[ name:gsub( "\\", "/" ) ] = obj end -- Returns a registered target (nil if not found) builder.get_registered_target = function( self, name ) return self._tlist[ name:gsub( "\\", "/" ) ] end --------------------------------------- -- Actual building functions -- Return the object name corresponding to a source file name builder.obj_name = function( self, name, ext ) local r = ext or self.obj_extension if not r then r = utils.is_windows() and "obj" or "o" end local objname = utils.replace_extension( name, r ) -- KEEP_DIR: object file in the same directory as source file -- BUILD_DIR_LINEARIZED: object file in the build directory, linearized filename if self.build_mode == self.KEEP_DIR then return objname elseif self.build_mode == self.BUILD_DIR_LINEARIZED then return self.build_dir .. utils.dir_sep .. linearize_fname( objname ) end end -- Read and interpret dependencies for each file specified in "ftable" -- "ftable" is either a space-separated string with all the source files or an array builder.read_depends = function( self, ftable ) if type( ftable ) == 'string' then ftable = utils.string_to_table( ftable ) end -- Read dependency data local dtable = {} for i = 1, #ftable do local f = io.open( self:get_dep_filename( ftable[ i ] ), "rb" ) local lines = ftable[ i ] if f then lines = f:read( "*a" ) f:close() lines = lines:gsub( "\n", " " ):gsub( "\\%s+", " " ):gsub( "%s+", " " ):gsub( "^.-: (.*)", "%1" ) end dtable[ ftable[ i ] ] = lines end return dtable end -- Create and return compile targets for the given sources builder.create_compile_targets = function( self, ftable, res ) if type( ftable ) == 'string' then ftable = utils.string_to_table( ftable ) end res = res or {} ccmd, oname = "-c", "o" if self.preprocess_mode then ccmd, oname = '-E', "pre" elseif self.asm_mode then ccmd, oname = '-S', 's' end -- Build dependencies for all targets for i = 1, #ftable do local isasm = ftable[ i ]:find( "%.c$" ) == nil -- Skip assembler targets if 'asm_dep_cmd' is set to 'false' -- Skip C targets if 'c_dep_cmd' is set to 'false' local skip = isasm and self.asm_dep_cmd == false skip = skip or ( not isasm and self.c_dep_cmd == false ) local deps = self:get_dep_filename( ftable[ i ] ) local target if not isasm then local depcmd = skip and self.comp_cmd or ( self.c_dep_cmd or self.comp_cmd:gsub( ccmd .. " ", sf( ccmd .. " -MD -MF %s ", deps ) ) ) target = self:c_target( self:obj_name( ftable[ i ], oname ), { self:get_registered_target( deps ) or ftable[ i ] }, depcmd ) else local depcmd = skip and self._asm_cmd or ( self.asm_dep_cmd or self._asm_cmd:gsub( ccmd .. " ", sf( ccmd .. " -MD -MF %s ", deps ) ) ) target = self:asm_target( self:obj_name( ftable[ i ], oname ), { self:get_registered_target( deps ) or ftable[ i ] }, depcmd ) end -- Pre build step: replace dependencies with the ones from the compiler generated dependency file local dprint = function( ... ) if self.disp_mode ~= "minimal" then print( ... ) end end if not skip then target:set_pre_build_function( function( t, _ ) if not self.clean_mode then local fres = self:read_depends( ftable[ i ] ) local fdeps = fres[ ftable[ i ] ] if #fdeps:gsub( "%s+", "" ) == 0 then fdeps = ftable[ i ] end t:set_dependencies( fdeps ) else if self.disp_mode ~= "minimal" then io.write( sf( "[builder] Removing %s ... ", deps ) ) end if os.remove( deps ) then dprint "done." else dprint "failed!" end end end ) end target.srcname = ftable[ i ] -- TODO: check clean mode? if not isasm then self.c_targets[ #self.c_targets + 1 ] = target end table.insert( res, target ) end return res end -- Add a target to the list of builder targets builder.add_target = function( self, target, help, alias ) self.targets[ target.target ] = { target = target, help = help } alias = alias or {} for _, v in ipairs( alias ) do self.targets[ v ] = { target = target, help = help } end return target end -- Make a target the default one builder.default = function( self, target ) self.deftarget = target.target self.targets.default = { target = target, help = "default target" } end -- Build everything builder.build = function( self, target ) local t = self.targetname or self.deftarget if not t then print( utils.col_red( "[builder] Error: build target not specified" ) ) os.exit( 1 ) end local trg -- Look for single targets (C source files) for _, ct in pairs( self.c_targets ) do if ct.srcname == t then trg = ct break end end if not trg then if not self.targets[ t ] then print( sf( "[builder] Error: target '%s' not found", t ) ) print( "Available targets: " ) print( " all source files" ) for k, v in pairs( self.targets ) do if not is_phony( k ) then print( sf( " %s - %s", k, v.help or "(no help available)" ) ) end end if self.deftarget and not is_phony( self.deftarget ) then print( sf( "Default target is '%s'", self.deftarget ) ) end os.exit( 1 ) else if self.preprocess_mode or self.asm_mode then print( "[builder] Error: preprocess (-E) or asm (-S) works only with single file targets." ) os.exit( 1 ) end trg = self.targets[ t ].target end end self:_create_build_dir() -- At this point check if we have a change in the state that would require a rebuild if self:_compare_config( 'comp' ) then print( utils.col_yellow( "[builder] Forcing rebuild due to configuration change." ) ) self.global_force_rebuild = true else self.global_force_rebuild = false end -- Do the actual build local res = trg:build() if not res then print( utils.col_yellow( sf( '[builder] %s: up to date', t ) ) ) end if self.clean_mode then os.remove( self.build_dir .. utils.dir_sep .. ".builddata.comp" ) os.remove( self.build_dir .. utils.dir_sep .. ".builddata.link" ) end print( utils.col_yellow( "[builder] Done building target." ) ) return res end -- Create dependencies, create object files, link final object builder.make_exe_target = function( self, target, file_list ) local odeps = self:create_compile_targets( file_list ) local exetarget = self:link_target( target, odeps ) self:default( self:add_target( exetarget ) ) return exetarget end ------------------------------------------------------------------------------- -- Other exported functions function new_builder( build_dir ) return builder.new( build_dir ) end
mit
UnfortunateFruit/darkstar
scripts/zones/Port_Bastok/npcs/Numa.lua
36
1824
----------------------------------- -- Area: Port Bastok -- NPC: Numa -- Standard Merchant NPC -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,NUMA_SHOP_DIALOG); stock = { 0x30A9, 5079,1, --Cotton Hachimaki 0x3129, 7654,1, --Cotton Dogi 0x31A9, 4212,1, --Cotton Tekko 0x3229, 6133,1, --Cotton Sitabaki 0x32A9, 3924,1, --Cotton Kyahan 0x3395, 3825,1, --Silver Obi 0x30A8, 759,2, --Hachimaki 0x3128, 1145,2, --Kenpogi 0x31A8, 630,2, --Tekko 0x3228, 915,2, --Sitabaki 0x32A8, 584,2, --Kyahan 0x02C0, 132,2, --Bamboo Stick 0x025D, 180,3, --Pickaxe 0x16EB, 13500,3, --Toolbag (Ino) 0x16EC, 18000,3, --Toolbag (Shika) 0x16ED, 18000,3 --Toolbag (Cho) } showNationShop(player, BASTOK, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
nesstea/darkstar
scripts/globals/porter_moogle_util.lua
13
27590
----------------------------------- -- Porter Moogle Utilities -- desc: Common functionality for Porter Moogles. ----------------------------------- require("scripts/globals/common"); -- Item IDs for all of the slips. local slipIds = { 29312, 29313, 29314, 29315, 29316, 29317, 29318, 29319, 29320, 29321, 29322, 29323, 29324, 29325, 29326, 29327, 29328, 29329, 29330, 29331, 29332 }; -- Item IDs for the items stored on each slip. Zero-based index in the table represents the bit indicating if the slip has the item stored. local slipItems = { [slipIds[1]] = { 16084, 14546, 14961, 15625, 15711, 16085, 14547, 14962, 15626, 15712, 16086, 14548, 14963, 15627, 15713, 16087, 14549, 14964, 15628, 15714, 16088, 14550, 14965, 15629, 15715, 16089, 14551, 14966, 15630, 15716, 16090, 14552, 14967, 15631, 15717, 16091, 14553, 14968, 15632, 15718, 16092, 14554, 14969, 15633, 15719, 16093, 14555, 14970, 15634, 15720, 16094, 14556, 14971, 15635, 15721, 16095, 14557, 14972, 15636, 15722, 16096, 14558, 14973, 15637, 15723, 16097, 14559, 14974, 15638, 15724, 16098, 14560, 14975, 15639, 15725, 16099, 14561, 14976, 15640, 15726, 16100, 14562, 14977, 15641, 15727, 16101, 14563, 14978, 15642, 15728, 16102, 14564, 14979, 15643, 15729, 16103, 14565, 14980, 15644, 15730, 16106, 14568, 14983, 15647, 15733, 16107, 14569, 14984, 15648, 15734, 16108, 14570, 14985, 15649, 15735, 16602, 17741, 18425, 18491, 18588, 18717, 18718, 18850, 18943, 16069, 14530, 14940, 15609, 15695, 16062, 14525, 14933, 15604, 15688, 16064, 14527, 14935, 15606, 15690, 18685, 18065, 17851, 18686, 18025, 18435, 18113, 17951, 17715, 18485, 18408, 18365, 18583, 18417, 18388, 16267, 16268, 16269, 16228, 16229, 15911, 15799, 15800, 15990, 17745, 18121, 16117, 14577, 17857 }, [slipIds[2]] = { 12421, 12549, 12677, 12805, 12933, 13911, 14370, 14061, 14283, 14163, 12429, 12557, 12685, 12813, 12941, 13924, 14371, 14816, 14296, 14175, 13934, 14387, 14821, 14303, 14184, 13935, 14388, 14822, 14304, 14185, 13876, 13787, 14006, 14247, 14123, 13877, 13788, 14007, 14248, 14124, 13908, 14367, 14058, 14280, 14160, 13909, 14368, 14059, 14281, 14161, 16113, 14573, 14995, 15655, 15740, 16115, 14575, 14997, 15657, 15742, 16114, 14574, 14996, 15656, 15741, 16116, 14576, 14998, 15658, 15743, 12818, 18198, 12946, 18043, 12690, 17659, 12296, 12434, 15471, 15472, 15473, 15508, 15509, 15510, 15511, 15512, 15513, 15514, 17710, 17595, 18397, 18360, 18222, 17948, 18100, 15475, 15476, 15477, 15488, 15961, 14815, 14812, 14813, 15244, 15240, 14488, 14905, 15576, 15661, 15241, 14489, 14906, 15577, 15662, 13927, 14378, 14076, 14308, 14180, 13928, 14379, 14077, 14309, 14181, 10438, 10276, 10320, 10326, 10367, 10439, 10277, 10321, 10327, 10368, 10440, 10278, 10322, 10328, 10369, 10441, 10279, 10323, 10329, 10370 }, [slipIds[3]] = { 16155, 11282, 15021, 16341, 11376, 16156, 11283, 15022, 16342, 11377, 16157, 11284, 15023, 16343, 11378, 16148, 14590, 15011, 16317, 15757, 16143, 14591, 15012, 16318, 15758, 16146, 14588, 15009, 16315, 15755, 16147, 14589, 15010, 16316, 15756, 15966, 15967, 19041, 17684, 17685, 11636, 15844, 15934, 16258, 18735, 18734, 16291, 16292, 19042, 15935, 16293, 16294, 15936, 18618, 11588, 11545, 16158, 16159, 16160, 16149, 14583, 15007, 16314, 15751, 16141, 14581, 15005, 16312, 15749, 16142, 14582, 15006, 16313, 15750, 10876, 10450, 10500, 11969, 10600, 10877, 10451, 10501, 11970, 10601, 10878, 10452, 10502, 11971, 10602, 19132, 18551, 11798, 11362, 11363, 11625, 15959, 16259 }, [slipIds[4]] = { 12511, 12638, 13961, 14214, 14089, 12512, 12639, 13962, 14215, 14090, 13855, 12640, 13963, 14216, 14091, 13856, 12641, 13964, 14217, 14092, 12513, 12642, 13965, 14218, 14093, 12514, 12643, 13966, 14219, 14094, 12515, 12644, 13967, 14220, 14095, 12516, 12645, 13968, 14221, 14096, 12517, 12646, 13969, 14222, 14097, 13857, 12647, 13970, 14223, 14098, 12518, 12648, 13971, 14099, 14224, 13868, 13781, 13972, 14225, 14100, 13869, 13782, 13973, 14226, 14101, 12519, 12649, 13974, 14227, 14102, 12520, 12650, 13975, 14228, 14103, 15265, 14521, 14928, 15600, 15684, 15266, 14522, 14929, 15601, 15685, 15267, 14523, 14930, 15602, 15686, 16138, 14578, 15002, 15659, 15746, 16139, 14579, 15003, 15660, 15747, 16140, 14580, 15004, 16311, 15748, 16678, 17478, 17422, 17423, 16829, 16764, 17643, 16798, 16680, 16766, 17188, 17812, 17771, 17772, 16887, 17532, 17717, 18702, 17858, 19203, 21461, 21124, 20776, 27786, 27926, 28066, 28206, 28346, 27787, 27927, 28067, 28207, 28347 }, [slipIds[5]] = { 15225, 14473, 14890, 15561, 15352, 15226, 14474, 14891, 15562, 15353, 15227, 14475, 14892, 15563, 15354, 15228, 14476, 14893, 15564, 15355, 15229, 14477, 14894, 15565, 15356, 15230, 14478, 14895, 15566, 15357, 15231, 14479, 14896, 15567, 15358, 15232, 14480, 14897, 15568, 15359, 15233, 14481, 14898, 15569, 15360, 15234, 14482, 14899, 15570, 15361, 15235, 14483, 14900, 15362, 15571, 15236, 14484, 14901, 15572, 15363, 15237, 14485, 14902, 15573, 15364, 15238, 14486, 14903, 15574, 15365, 15239, 14487, 14904, 15575, 15366, 11464, 11291, 15024, 16345, 11381, 11467, 11294, 15027, 16348, 11384, 11470, 11297, 15030, 16351, 11387, 11475, 11302, 15035, 16357, 11393, 11476, 11303, 15036, 16358, 11394, 11477, 11304, 15037, 16359, 11395 }, [slipIds[6]] = { 15072, 15087, 15102, 15117, 15132, 15871, 15073, 15088, 15103, 15118, 15133, 15478, 15074, 15089, 15104, 15119, 15134, 15872, 15075, 15090, 15105, 15120, 15135, 15874, 15076, 15091, 15106, 15121, 15136, 15873, 15077, 15092, 15107, 15122, 15137, 15480, 15078, 15093, 15108, 15123, 15138, 15481, 15079, 15094, 15109, 15124, 15139, 15479, 15080, 15095, 15110, 15125, 15140, 15875, 15081, 15096, 15111, 15126, 15141, 15482, 15082, 15097, 15112, 15127, 15142, 15876, 15083, 15098, 15113, 15128, 15143, 15879, 15084, 15099, 15114, 15129, 15144, 15877, 15085, 15100, 15115, 15130, 15145, 15878, 15086, 15101, 15116, 15131, 15146, 15484, 11465, 11292, 15025, 16346, 11382, 16244, 11468, 11295, 15028, 16349, 11385, 15920, 11471, 11298, 15031, 16352, 11388, 16245, 11478, 11305, 15038, 16360, 11396, 16248, 11480, 11307, 15040, 16362, 11398, 15925 }, [slipIds[7]] = { 15245, 14500, 14909, 15580, 15665, 15246, 14501, 14910, 15581, 15666, 15247, 14502, 14911, 15582, 15667, 15248, 14503, 14912, 15583, 15668, 15249, 14504, 14913, 15584, 15669, 15250, 14505, 14914, 15585, 15670, 15251, 14506, 14915, 15586, 15671, 15252, 14507, 14916, 15587, 15672, 15253, 14508, 14917, 15588, 15673, 15254, 14509, 14918, 15589, 15674, 15255, 14510, 14919, 15590, 15675, 15256, 14511, 14920, 15591, 15676, 15257, 14512, 14921, 15592, 15677, 15258, 14513, 14922, 15593, 15678, 15259, 14514, 14923, 15594, 15679, 11466, 11293, 15026, 16347, 11383, 11469, 11296, 15029, 16350, 11386, 11472, 11299, 15032, 16353, 11389, 11479, 11306, 15039, 16361, 11397, 11481, 11308, 15041, 16363, 11399 }, [slipIds[8]] = { 12008, 12028, 12048, 12068, 12088, 11591, 19253, 12009, 12029, 12049, 12069, 12089, 11592, 19254, 12010, 12030, 12050, 12070, 12090, 11615, 11554, 12011, 12031, 12051, 12071, 12091, 11593, 16203, 12012, 12032, 12052, 12072, 12092, 11594, 16204, 12013, 12033, 12053, 12073, 12093, 11736, 19260, 12014, 12034, 12054, 12074, 12094, 11595, 11750, 12015, 12035, 12055, 12075, 12095, 11616, 11737, 12016, 12036, 12056, 12076, 12096, 11617, 11555, 12017, 12037, 12057, 12077, 12097, 11618, 11738, 12018, 12038, 12058, 12078, 12098, 11596, 16205, 12019, 12039, 12059, 12079, 12099, 11597, 16206, 12020, 12040, 12060, 12080, 12100, 11598, 16207, 12021, 12041, 12061, 12081, 12101, 11599, 16208, 12022, 12042, 12062, 12082, 12102, 11619, 11739, 12023, 12043, 12063, 12083, 12103, 11600, 19255, 12024, 12044, 12064, 12084, 12104, 11601, 16209, 12025, 12045, 12065, 12085, 12105, 11602, 11751, 12026, 12046, 12066, 12086, 12106, 11603, 19256, 12027, 12047, 12067, 12087, 12107, 11620, 19247, 11703, 11704, 11705, 11706, 11707, 11708, 11709, 11710, 11711, 11712, 11713, 11714, 11715, 11716, 11717, 11718, 11719, 11720, 11721, 11722 }, [slipIds[9]] = { 11164, 11184, 11204, 11224, 11244, 11165, 11185, 11205, 11225, 11245, 11166, 11186, 11206, 11226, 11246, 11167, 11187, 11207, 11227, 11247, 11168, 11188, 11208, 11228, 11248, 11169, 11189, 11209, 11229, 11249, 11170, 11190, 11210, 11230, 11250, 11171, 11191, 11211, 11231, 11251, 11172, 11192, 11212, 11232, 11252, 11173, 11193, 11213, 11233, 11253, 11174, 11194, 11214, 11234, 11254, 11175, 11195, 11215, 11235, 11255, 11176, 11196, 11216, 11236, 11256, 11177, 11197, 11217, 11237, 11257, 11178, 11198, 11218, 11238, 11258, 11179, 11199, 11219, 11239, 11259, 11180, 11200, 11220, 11240, 11260, 11181, 11201, 11221, 11241, 11261, 11182, 11202, 11222, 11242, 11262, 11183, 11203, 11223, 11243, 11263 }, [slipIds[10]] = { 11064, 11084, 11104, 11124, 11144, 11065, 11085, 11105, 11125, 11145, 11066, 11086, 11106, 11126, 11146, 11067, 11087, 11107, 11127, 11147, 11068, 11088, 11108, 11128, 11148, 11069, 11089, 11109, 11129, 11149, 11070, 11090, 11110, 11130, 11150, 11071, 11091, 11111, 11131, 11151, 11072, 11092, 11112, 11132, 11152, 11073, 11093, 11113, 11133, 11153, 11074, 11094, 11114, 11134, 11154, 11075, 11095, 11115, 11135, 11155, 11076, 11096, 11116, 11136, 11156, 11077, 11097, 11117, 11137, 11157, 11078, 11098, 11118, 11138, 11158, 11079, 11099, 11119, 11139, 11159, 11080, 11100, 11120, 11140, 11160, 11081, 11101, 11121, 11141, 11161, 11082, 11102, 11122, 11142, 11162, 11083, 11103, 11123, 11143, 11163 }, [slipIds[11]] = { 15297, 15298, 15299, 15919, 15929, 15921, 18871, 16273, 18166, 18167, 18256, 13216, 13217, 13218, 15455, 15456, 181, 182, 183, 184, 129, 11499, 18502, 18855, 19274, 18763, 19110, 15008, 17764, 19101, 365, 366, 367, 15860, 272, 273, 274, 275, 276, 11853, 11956, 11854, 11957, 11811, 11812, 11861, 11862, 3676, 18879, 3647, 3648, 3649, 3677, 18880, 18863, 18864, 15178, 14519, 10382, 11965, 11967, 15752, 15179, 14520, 10383, 11966, 11968, 15753, 10875, 3619, 3620, 3621, 3650, 3652, 10430, 10251, 10593, 10431, 10252, 10594, 10432, 10253, 10595, 10433, 10254, 10596, 10429, 10250, 17031, 17032, 10807, 18881, 10256, 10330, 10257, 10331, 10258, 10332, 10259, 10333, 10260, 10334, 10261, 10335, 10262, 10336, 10263, 10337, 10264, 10338, 10265, 10339, 10266, 10340, 10267, 10341, 10268, 10342, 10269, 10343, 10270, 10344, 10271, 10345, 10446, 10447, 426, 10808, 3654, 265, 266, 267, 269, 270, 271, 18464, 18545, 18563, 18912, 18913, 10293, 10809, 10810, 10811, 10812, 27803, 28086, 27804, 28087, 27805, 28088, 27806, 28089, 27765, 27911, 27760, 27906, 27759, 28661, 286, 27757, 27758, 287, 27899, 28185, 28324, 27898, 28655, 27756, 28511, 21118, 27902, 100, 21117, 87, 20953, 21280, 28652, 28650, 27726, 28509, 28651, 27727, 28510, 27872, 21113, 27873, 21114, 20532, 20533, 27717, 27718 }, [slipIds[12]] = { 2033, 2034, 2035, 2036, 2037, 2038, 2039, 2040, 2041, 2042, 2043, 2044, 2045, 2046, 2047, 2048, 2049, 2050, 2051, 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070, 2071, 2072, 2073, 2074, 2075, 2076, 2077, 2078, 2079, 2080, 2081, 2082, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 2092, 2093, 2094, 2095, 2096, 2097, 2098, 2099, 2100, 2101, 2102, 2103, 2104, 2105, 2106, 2107, 2662, 2663, 2664, 2665, 2666, 2667, 2668, 2669, 2670, 2671, 2672, 2673, 2674, 2675, 2676, 2718, 2719, 2720, 2721, 2722, 2723, 2724, 2725, 2726, 2727 }, [slipIds[13]] = { 10650, 10670, 10690, 10710, 10730, 10651, 10671, 10691, 10711, 10731, 10652, 10672, 10692, 10712, 10732, 10653, 10673, 10693, 10713, 10733, 10654, 10674, 10694, 10714, 10734, 10655, 10675, 10695, 10715, 10735, 10656, 10676, 10696, 10716, 10736, 10657, 10677, 10697, 10717, 10737, 10658, 10678, 10698, 10718, 10738, 10659, 10679, 10699, 10719, 10739, 10660, 10680, 10700, 10720, 10740, 10661, 10681, 10701, 10721, 10741, 10662, 10682, 10702, 10722, 10742, 10663, 10683, 10703, 10723, 10743, 10664, 10684, 10704, 10724, 10744, 10665, 10685, 10705, 10725, 10745, 10666, 10686, 10706, 10726, 10746, 10667, 10687, 10707, 10727, 10747, 10668, 10688, 10708, 10728, 10748, 10669, 10689, 10709, 10729, 10749 }, [slipIds[14]] = { 10901, 10474, 10523, 10554, 10620, 10906, 10479, 10528, 10559, 10625, 10911, 10484, 10533, 10564, 10630, 19799, 18916, 10442, 10280, 16084, 27788, 27928, 28071, 28208, 27649, 27789, 27929, 28072, 28209, 27650, 27790, 27930, 28073, 28210, 27651, 27791, 27931, 28074, 28211, 27652, 27792, 27932, 28075, 28212, 27653, 27793, 27933, 28076, 28213, 27654, 27794, 27934, 28077, 28214, 27655, 27795, 27935, 28078, 28215, 27656, 27796, 27936, 28079, 28216, 27657, 27797, 27937, 28080, 28217, 27658, 27798, 27938, 28081, 28218, 27659, 27799, 27939, 28082, 28219, 27660, 27800, 27940, 28083, 28220, 27661, 27801, 27941, 28084, 28221, 27662, 27802, 27942, 28085, 28222 }, [slipIds[15]] = { 27663, 27807, 27943, 28090, 28223, 27664, 27808, 27944, 28091, 28224, 27665, 27809, 27945, 28092, 28225, 27666, 27810, 27946, 28093, 28226, 27667, 27811, 27947, 28094, 28227, 27668, 27812, 27948, 28095, 28228, 27669, 27813, 27949, 28096, 28229, 27670, 27814, 27950, 28097, 28230, 27671, 27815, 27951, 28098, 28231, 27672, 27816, 27952, 28099, 28232, 27673, 27817, 27953, 28100, 28233, 27674, 27818, 27954, 28101, 28234, 27675, 27819, 27955, 28102, 28235, 27676, 27820, 27956, 28103, 28236, 27677, 27821, 27957, 28104, 28237, 27678, 27822, 27958, 28105, 28238, 27679, 27823, 27959, 28106, 28239, 27680, 27824, 27960, 28107, 28240, 27681, 27825, 27961, 28108, 28241, 27682, 27826, 27962, 28109, 28242, 27683, 27827, 27963, 28110, 28243 }, [slipIds[16]] = { 27684, 27828, 27964, 28111, 28244, 27685, 27829, 27965, 28112, 28245, 27686, 27830, 27966, 28113, 28246, 28246, 27831, 27967, 28114, 28247, 27688, 27832, 27968, 28115, 28248, 27689, 27833, 27969, 28116, 28249, 27690, 27834, 27970, 28117, 28250, 27691, 27835, 27971, 28118, 28251, 27692, 27836, 27972, 28119, 28252, 27693, 27837, 27973, 28120, 28253, 27694, 27838, 27974, 28121, 28254, 27695, 27839, 27975, 28122, 28255, 27696, 27840, 27976, 28123, 28256, 27697, 27841, 27977, 28124, 28257, 27698, 27842, 27978, 28125, 28258, 27699, 27843, 27979, 28126, 28259, 27700, 27844, 27980, 28127, 28260, 27701, 27845, 27981, 28128, 28261, 27702, 27846, 27982, 28129, 28262, 27703, 27847, 27983, 28130, 28263, 27704, 27848, 27984, 28131, 28264, 27705, 27849, 27985, 28132, 28265, 27706, 27850, 27986, 28133, 28266 }, [slipIds[17]] = { 26624, 26800, 26976, 27152, 27328, 26626, 26802, 26978, 27154, 27330, 26628, 26804, 26980, 27156, 27332, 26630, 26806, 26982, 27158, 27334, 26632, 26808, 26984, 27160, 27336, 26634, 26810, 26986, 27162, 27338, 26636, 26812, 26988, 27164, 27340, 26638, 26814, 26990, 27166, 27342, 26640, 26816, 26992, 27168, 27344, 26642, 26818, 26994, 27170, 27346, 26644, 26820, 26996, 27172, 27348, 26646, 26822, 26998, 27174, 27350, 26648, 26824, 27000, 27176, 27352, 26650, 26826, 27002, 27178, 27354, 26652, 26828, 27004, 27180, 27356, 26654, 26830, 27006, 27182, 27358, 26656, 26832, 27008, 27184, 27360, 26658, 26834, 27010, 27186, 27362, 26660, 26836, 27012, 27188, 27364, 26662, 26838, 27014, 27190, 27366, 26664, 26840, 27016, 27192, 27368, 26666, 26842, 27018, 27194, 27370 }, [slipIds[18]] = { 26625, 26801, 26977, 27153, 27329, 26627, 26803, 26979, 27155, 27331, 26629, 26805, 26981, 27157, 27333, 26631, 26807, 26983, 27159, 27335, 26633, 26809, 26985, 27161, 27337, 26635, 26811, 26987, 27163, 27339, 26637, 26813, 26989, 27165, 27341, 26639, 26815, 26991, 27167, 27343, 26641, 26817, 26993, 27169, 27345, 26643, 26819, 26995, 27171, 27347, 26645, 26821, 26997, 27173, 27349, 26647, 26823, 26999, 27175, 27351, 26649, 26825, 27001, 27177, 27353, 26651, 26827, 27003, 27179, 27355, 26653, 26829, 27005, 27181, 27357, 26655, 26831, 27007, 27183, 27358, 26657, 26833, 27009, 27185, 27361, 26659, 26835, 27011, 27187, 27363, 26661, 26837, 27013, 27189, 27365, 26663, 26839, 27015, 27191, 27367, 26665, 26841, 27017, 27193, 27369, 26667, 26843, 27019, 27195, 27371 }, [slipIds[19]] = { 27715, 27866, 27716, 27867, 278, 281, 284, 3680, 3681, 27859, 28149, 27860, 28150, 21107, 21108, 27625, 27626, 26693, 26694, 26707, 26708, 27631, 27632, 26705, 26706, 27854, 27855, 26703, 26704, 3682, 3683, 3684, 3685, 3686, 3687, 3688, 3689, 3690, 3691, 3692, 3693, 3694, 3695, 21097, 21098, 26717, 26718, 26728,26719,26720,26889,26890, 21095, 21096, 26738, 26739, 26729, 26730, 26788, 26946, 27281, 27455, 26789 }, [slipIds[20]] = { 26740, 26898, 27052, 27237, 27411, 26742, 26900, 27054, 27239, 27413, 26744, 26902, 27056, 27241, 27415, 26746, 26904, 27058, 27243, 27417, 26748, 26906, 27060, 27245, 27419, 26750, 26908, 27062, 27247, 27421, 26752, 26910, 27064, 27249, 27423, 26754, 26912, 27066, 27251, 27425, 26756, 26914, 27068, 27253, 27427, 26758, 26916, 27070, 27255, 27429, 26760, 26918, 27072, 27257, 27431, 26762, 26920, 27074, 27259, 27433, 26764, 26922, 27076, 27261, 27435, 26766, 26924, 27078, 27263, 27437, 26768, 26926, 27080, 27265, 27439, 26770, 26928, 27082, 27267, 27441, 26772, 26930, 27084, 27269, 27443, 26774, 26932, 27086, 27271, 27445, 26776, 26934, 27088, 27273, 27447, 26778, 26936, 27090, 27275, 27449, 26780, 26938, 27092, 27277, 27451, 26782, 26940, 27094, 27279, 27453 }, [slipIds[21]] = { 26741, 26899, 27053, 27238, 27412, 26743, 26901, 27055, 27240, 27414, 26745, 26903, 27057, 27242, 27416, 26747, 26905, 27059, 27244, 27418, 26749, 26907, 27061, 27246, 27420, 26751, 26909, 27063, 27248, 27422, 26753, 26911, 27065, 27250, 27424, 26755, 26913, 27067, 27252, 27426, 26757, 26915, 27069, 27254, 27428, 26759, 26917, 27071, 27256, 27430, 26761, 26919, 27073, 27258, 27432, 26763, 26921, 27075, 27260, 27434, 26765, 26923, 27077, 27262, 27436, 26767, 26925, 27079, 27264, 27438, 26769, 26927, 27081, 27266, 27440, 26771, 26929, 27083, 27268, 27442, 26773, 26931, 27085, 27270, 27444, 26775, 26933, 27087, 27272, 27446, 26777, 26935, 27089, 27274, 27448, 26779, 26937, 27091, 27276, 27450, 26781, 26939, 27093, 27278, 27452, 26783, 26941, 27095, 27280, 27454 } }; ---------------------------------------------------------------------- -- desc : Checks if the supplied item is a Moogle Storage Slip. ---------------------------------------------------------------------- local function isSlip(itemId) return (slipItems[itemId] ~= nil); end ---------------------------------------------------------------------- -- desc : Checks if the supplied slip can store the supplied item. ---------------------------------------------------------------------- local function isStorableOn(slipId, itemId) for _, id in ipairs(slipItems[slipId]) do if (id == itemId) then return true; end end printf('Item %s is not storable on %s', itemId, slipId); return false; end ---------------------------------------------------------------------- -- desc : Gets IDs of retrievable items from the extra data on a slip. ---------------------------------------------------------------------- local function getItemsOnSlip(extra, slipId) local slip = slipItems[slipId]; local itemsOnSlip = {}; local x = 1; for k,v in ipairs(slip) do local byte = extra[math.floor((k - 1) / 8) + 1]; if byte < 0 then byte = byte + 256; end if (bit.band(bit.rshift(byte, (k - 1) % 8), 1) ~= 0) then itemsOnSlip[x] = v; x = x + 1; end end return itemsOnSlip; end ---------------------------------------------------------------------- -- desc : Finds the key in table t where the value equals i. ---------------------------------------------------------------------- local function find(t, i) for k, v in ipairs(t) do if v == i then return k end end return nil end ---------------------------------------------------------------------- -- desc : Converts the 8 bit extra data into 32 bit params for events. ---------------------------------------------------------------------- local function int8ToInt32(extra) local params = {}; local int32 = ''; for k,v in ipairs(extra) do int32 = string.format('%02x%s', v, int32); if (k % 4 == 0) then params[#params + 1] = tonumber(int32, 16); int32 = ''; end end if (int32 ~= '') then params[#params + 1] = tonumber(int32, 16); end return params; end ---------------------------------------------------------------------- -- desc : Gets Storage Slip ID from the trade window (does nothing -- if there are two or more Storage Slips in the trade and no -- storable items. ---------------------------------------------------------------------- local function getSlipId(trade) local slipId = 0; local slips = 0; for _, itemId in ipairs(slipIds) do if (trade:hasItemQty(itemId, 1)) then slips = slips + 1; if (slipId == 0) then slipId = itemId; end end end if (slips == trade:getItemCount() and slips > 1) then slipId = 0; end return slipId, slips; end ---------------------------------------------------------------------- -- desc : Gets all items in the trade window that are storable on the -- slip in the trade window. ---------------------------------------------------------------------- local function getStorableItems(player, trade, slipId) local storableItemIds = { }; for i = 0, 7 do local slotItemId = trade:getItem(i); if (slotItemId ~= 0 and isSlip(slotItemId) ~= true and player:hasItem(slotItemId)) then if (isStorableOn(slipId, slotItemId)) then storableItemIds[#storableItemIds+1] = slotItemId; end end end return storableItemIds; end ---------------------------------------------------------------------- -- desc : Stores the items on the Storage Slip extra data and starts -- the event indicating that the storage was successful. ---------------------------------------------------------------------- local function storeItems(player, storableItemIds, slipId, e) if (#storableItemIds > 0) then local param0 = 0x0; local param1 = 0x0; if (#storableItemIds == 1) then param0 = storableItemIds[1]; param1 = 0x00; else param0 = #storableItemIds; param1 = 0x01; end -- idk local extra = { }; for i = 0, 23 do extra[i] = 0; end for k, v in ipairs(slipItems[slipId]) do if find(storableItemIds, v) ~= nil then local bitmask = extra[math.floor((k - 1) / 8)]; if bitmask < 0 then bitmask = bitmask + 256; end extra[math.floor((k - 1) / 8)] = bit.bor(bitmask, bit.lshift(1, (k - 1) % 8)); end end local result = player:storeWithPorterMoogle(slipId, extra, storableItemIds); if (result == 0) then player:startEvent(e.STORE_EVENT_ID, param0, param1); elseif (result == 1) then player:startEvent(e.ALREADY_STORED_ID); elseif (result == 2) then player:startEvent(e.MAGIAN_TRIAL_ID); end end end ---------------------------------------------------------------------- -- desc : Returns a zero-based identifier for the slip (Storage Slip 1 -- is index 0, Storage Slip 2 is index 1, etc). ---------------------------------------------------------------------- local function getSlipIndex(slipId) return find(slipIds, slipId) - 1; end ---------------------------------------------------------------------- -- desc : Gets the extra data from the traded slip and starts the -- retrieval event. ---------------------------------------------------------------------- local function startRetrieveProcess(player, eventId, slipId) local extra = player:getRetrievableItemsForSlip(slipId); local params = int8ToInt32(extra); local slipIndex = getSlipIndex(slipId); player:setLocalVar('slipId', slipId); player:startEvent(eventId, params[1], params[2], params[3], params[4], params[5], params[6], nil, slipIndex); end ---------------------------------------------------------------------- -- desc : Begins the storage or retrieval process based on the items -- supplied in the trade. ---------------------------------------------------------------------- function porterMoogleTrade(player, trade, e) local slipId, slipCount = getSlipId(trade); if (slipId == 0 or slipCount > 1) then return; end; local storableItemIds = getStorableItems(player, trade, slipId); if (#storableItemIds > 0) then storeItems(player, storableItemIds, slipId, e); else startRetrieveProcess(player, e.RETRIEVE_EVENT_ID, slipId); end end ---------------------------------------------------------------------- -- desc : Retrieves the selected item from storage, removes it from -- the slip's extra data, displays a message to the user, and -- updates the user's event data. ---------------------------------------------------------------------- function porterEventUpdate(player, csid, option, RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED) local slipId = player:getLocalVar('slipId'); if (csid == RETRIEVE_EVENT_ID and slipId ~= 0 and slipId ~= nil) then local extra = player:getRetrievableItemsForSlip(slipId); local itemsOnSlip = getItemsOnSlip(extra, slipId); local retrievedItemId = itemsOnSlip[option + 1]; if (player:hasItem(retrievedItemId) or player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, retrievedItemId); else local k = find(slipItems[slipId], retrievedItemId); local extraId = math.floor((k - 1) / 8); local bitmask = extra[extraId + 1]; if bitmask < 0 then bitmask = bitmask + 256; end bitmask = bit.band(bitmask, bit.bnot(bit.lshift(1, (k - 1) % 8))); extra[extraId + 1] = bitmask; player:retrieveItemFromSlip(slipId, retrievedItemId, extraId, bitmask); player:messageSpecial(RETRIEVE_DIALOG_ID, retrievedItemId, nil, nil, retrievedItemId, false); end local params = int8ToInt32(extra); player:updateEvent(params[1], params[2], params[3], params[4], params[5], params[6], slipId); end end ---------------------------------------------------------------------- -- desc : Completes the event. ---------------------------------------------------------------------- function porterEventFinish(player, csid, option, TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL) if (csid == TALK_EVENT_ID and option < 1000) then -- This is just because hilarious. option = math.floor(option / 16) + (option % 16); local hasItem = player:hasItem(slipIds[option]); if (hasItem or player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, slipIds[option]); return; end if (player:delGil(1000)) then player:addItem(slipIds[option]); player:messageSpecial(ITEM_OBTAINED, slipIds[option]); else player:messageSpecial(NOT_HAVE_ENOUGH_GIL, slipIds[option]); return; end else player:setLocalVar('slipId', 0); end end
gpl-3.0
Xileck/forgottenserver
data/lib/compat/compat.lua
1
33274
TRUE = true FALSE = false result.getDataInt = result.getNumber result.getDataLong = result.getNumber result.getDataString = result.getString result.getDataStream = result.getStream LUA_ERROR = false LUA_NO_ERROR = true STACKPOS_GROUND = 0 STACKPOS_FIRST_ITEM_ABOVE_GROUNDTILE = 1 STACKPOS_SECOND_ITEM_ABOVE_GROUNDTILE = 2 STACKPOS_THIRD_ITEM_ABOVE_GROUNDTILE = 3 STACKPOS_FOURTH_ITEM_ABOVE_GROUNDTILE = 4 STACKPOS_FIFTH_ITEM_ABOVE_GROUNDTILE = 5 STACKPOS_TOP_CREATURE = 253 STACKPOS_TOP_FIELD = 254 STACKPOS_TOP_MOVEABLE_ITEM_OR_CREATURE = 255 THING_TYPE_PLAYER = CREATURETYPE_PLAYER + 1 THING_TYPE_MONSTER = CREATURETYPE_MONSTER + 1 THING_TYPE_NPC = CREATURETYPE_NPC + 1 COMBAT_POISONDAMAGE = COMBAT_EARTHDAMAGE CONDITION_EXHAUST = CONDITION_EXHAUST_WEAPON TALKTYPE_ORANGE_1 = TALKTYPE_MONSTER_SAY TALKTYPE_ORANGE_2 = TALKTYPE_MONSTER_YELL NORTH = DIRECTION_NORTH EAST = DIRECTION_EAST SOUTH = DIRECTION_SOUTH WEST = DIRECTION_WEST SOUTHWEST = DIRECTION_SOUTHWEST SOUTHEAST = DIRECTION_SOUTHEAST NORTHWEST = DIRECTION_NORTHWEST NORTHEAST = DIRECTION_NORTHEAST do local function CreatureIndex(self, key) local methods = getmetatable(self) if key == "uid" then return methods.getId(self) elseif key == "type" then local creatureType = 0 if methods.isPlayer(self) then creatureType = THING_TYPE_PLAYER elseif methods.isMonster(self) then creatureType = THING_TYPE_MONSTER elseif methods.isNpc(self) then creatureType = THING_TYPE_NPC end return creatureType elseif key == "itemid" then return 1 elseif key == "actionid" then return 0 end return methods[key] end rawgetmetatable("Player").__index = CreatureIndex rawgetmetatable("Monster").__index = CreatureIndex rawgetmetatable("Npc").__index = CreatureIndex end do local function ItemIndex(self, key) local methods = getmetatable(self) if key == "itemid" then return methods.getId(self) elseif key == "actionid" then return methods.getActionId(self) elseif key == "uid" then return methods.getUniqueId(self) elseif key == "type" then return methods.getSubType(self) end return methods[key] end rawgetmetatable("Item").__index = ItemIndex rawgetmetatable("Container").__index = ItemIndex rawgetmetatable("Teleport").__index = ItemIndex end function pushThing(thing) local t = {uid = 0, itemid = 0, type = 0, actionid = 0} if thing ~= nil then if thing:isItem() then t.uid = thing:getUniqueId() t.itemid = thing:getId() if ItemType(t.itemid):hasSubType() then t.type = thing:getSubType() end t.actionid = thing:getActionId() elseif thing:isCreature() then t.uid = thing:getId() t.itemid = 1 if thing:isPlayer() then t.type = THING_TYPE_PLAYER elseif thing:isMonster() then t.type = THING_TYPE_MONSTER else t.type = THING_TYPE_NPC end end end return t end createCombatObject = Combat setCombatArea = Combat.setArea setCombatCallback = Combat.setCallback setCombatCondition = Combat.setCondition setCombatFormula = Combat.setFormula setCombatParam = Combat.setParameter createConditionObject = Condition setConditionParam = Condition.setParameter setConditionFormula = Condition.setFormula addDamageCondition = Condition.addDamage addOutfitCondition = Condition.setOutfit function doCombat(cid, combat, var) return combat:execute(cid, var) end function isCreature(cid) return Creature(cid) ~= nil end function isPlayer(cid) return Player(cid) ~= nil end function isMonster(cid) return Monster(cid) ~= nil end function isSummon(cid) return Creature(cid):getMaster() ~= nil end function isNpc(cid) return Npc(cid) ~= nil end function isItem(uid) return Item(uid) ~= nil end function isContainer(uid) return Container(uid) ~= nil end function getCreatureName(cid) local c = Creature(cid) return c ~= nil and c:getName() or false end function getCreatureHealth(cid) local c = Creature(cid) return c ~= nil and c:getHealth() or false end function getCreatureMaxHealth(cid) local c = Creature(cid) return c ~= nil and c:getMaxHealth() or false end function getCreaturePosition(cid) local c = Creature(cid) return c ~= nil and c:getPosition() or false end function getCreatureOutfit(cid) local c = Creature(cid) return c ~= nil and c:getOutfit() or false end function getCreatureSpeed(cid) local c = Creature(cid) return c ~= nil and c:getSpeed() or false end function getCreatureBaseSpeed(cid) local c = Creature(cid) return c ~= nil and c:getBaseSpeed() or false end function getCreatureTarget(cid) local c = Creature(cid) if c ~= nil then local target = c:getTarget() return target ~= nil and target:getId() or 0 end return false end function getCreatureMaster(cid) local c = Creature(cid) if c ~= nil then local master = c:getMaster() return master ~= nil and master:getId() or c:getId() end return false end function getCreatureSummons(cid) local c = Creature(cid) if c == nil then return false end local result = {} for _, summon in ipairs(c:getSummons()) do result[#result + 1] = summon:getId() end return result end getCreaturePos = getCreaturePosition function doCreatureAddHealth(cid, health) local c = Creature(cid) return c ~= nil and c:addHealth(health) or false end function doRemoveCreature(cid) local c = Creature(cid) return c ~= nil and c:remove() or false end function doCreatureSetLookDir(cid, direction) local c = Creature(cid) return c ~= nil and c:setDirection(direction) or false end function doCreatureSay(cid, text, type, ...) local c = Creature(cid) return c ~= nil and c:say(text, type, ...) or false end function doCreatureChangeOutfit(cid, outfit) local c = Creature(cid) return c ~= nil and c:setOutfit(outfit) or false end function doSetCreatureDropLoot(cid, doDrop) local c = Creature(cid) return c ~= nil and c:setDropLoot(doDrop) or false end function doChangeSpeed(cid, delta) local c = Creature(cid) return c ~= nil and c:changeSpeed(delta) or false end function doAddCondition(cid, conditionId) local c = Creature(cid) return c ~= nil and c:addCondition(conditionId) or false end function doRemoveCondition(cid, conditionType, subId) local c = Creature(cid) return c ~= nil and (c:removeCondition(conditionType, CONDITIONID_COMBAT, subId) or c:removeCondition(conditionType, CONDITIONID_DEFAULT, subId) or true) end doSetCreatureDirection = doCreatureSetLookDir function registerCreatureEvent(cid, name) local c = Creature(cid) return c ~= nil and c:registerEvent(name) or false end function unregisterCreatureEvent(cid, name) local c = Creature(cid) return c ~= nil and c:unregisterEvent(name) or false end function getPlayerByName(name) local p = Player(name) return p ~= nil and p:getId() or false end function getIPByPlayerName(name) local p = Player(name) return p ~= nil and p:getIp() or false end function getPlayerGUID(cid) local p = Player(cid) return p ~= nil and p:getGuid() or false end function getPlayerIp(cid) local p = Player(cid) return p ~= nil and p:getIp() or false end function getPlayerAccountType(cid) local p = Player(cid) return p ~= nil and p:getAccountType() or false end function getPlayerLastLoginSaved(cid) local p = Player(cid) return p ~= nil and p:getLastLoginSaved() or false end function getPlayerName(cid) local p = Player(cid) return p ~= nil and p:getName() or false end function getPlayerFreeCap(cid) local p = Player(cid) return p ~= nil and (p:getFreeCapacity() / 100) or false end function getPlayerPosition(cid) local p = Player(cid) return p ~= nil and p:getPosition() or false end function getPlayerMagLevel(cid) local p = Player(cid) return p ~= nil and p:getMagicLevel() or false end function getPlayerAccess(cid) local player = Player(cid) if player == nil then return false end return player:getGroup():getAccess() and 1 or 0 end function getPlayerSkill(cid, skillId) local p = Player(cid) return p ~= nil and p:getSkillLevel(skillId) or false end function getPlayerMana(cid) local p = Player(cid) return p ~= nil and p:getMana() or false end function getPlayerMaxMana(cid) local p = Player(cid) return p ~= nil and p:getMaxMana() or false end function getPlayerLevel(cid) local p = Player(cid) return p ~= nil and p:getLevel() or false end function getPlayerTown(cid) local p = Player(cid) return p ~= nil and p:getTown():getId() or false end function getPlayerVocation(cid) local p = Player(cid) return p ~= nil and p:getVocation():getId() or false end function getPlayerSoul(cid) local p = Player(cid) return p ~= nil and p:getSoul() or false end function getPlayerSex(cid) local p = Player(cid) return p ~= nil and p:getSex() or false end function getPlayerStorageValue(cid, key) local p = Player(cid) return p ~= nil and p:getStorageValue(key) or false end function getPlayerBalance(cid) local p = Player(cid) return p ~= nil and p:getBankBalance() or false end function getPlayerMoney(cid) local p = Player(cid) return p ~= nil and p:getMoney() or false end function getPlayerGroupId(cid) local p = Player(cid) return p ~= nil and p:getGroup():getId() or false end function getPlayerLookDir(cid) local p = Player(cid) return p ~= nil and p:getDirection() or false end function getPlayerLight(cid) local p = Player(cid) return p ~= nil and p:getLight() or false end function getPlayerDepotItems(cid, depotId) local p = Player(cid) return p ~= nil and p:getDepotItems(depotId) or false end function getPlayerSkullType(cid) local p = Player(cid) return p ~= nil and p:getSkull() or false end function getPlayerLossPercent(cid) local p = Player(cid) return p ~= nil and p:getDeathPenalty() or false end function getPlayerMount(cid, mountId) local p = Player(cid) return p ~= nil and p:hasMount(mountId) or false end function getPlayerPremiumDays(cid) local p = Player(cid) return p ~= nil and p:getPremiumDays() or false end function getPlayerBlessing(cid, blessing) local p = Player(cid) return p ~= nil and p:hasBlessing(blessing) or false end function getPlayerParty(cid) local player = Player(cid) if player == nil then return false end local party = player:getParty() if party == nil then return nil end return party:getLeader():getId() end function getPlayerGuildId(cid) local player = Player(cid) if player == nil then return false end local guild = player:getGuild() if guild == nil then return false end return guild:getId() end function getPlayerGuildLevel(cid) local p = Player(cid) return p ~= nil and p:getGuildLevel() or false end function getPlayerGuildName(cid) local player = Player(cid) if player == nil then return false end local guild = player:getGuild() if guild == nil then return false end return guild:getName() end function getPlayerGuildRank(cid) local player = Player(cid) if player == nil then return false end local guild = player:getGuild() if guild == nil then return false end local rank = guild:getRankByLevel(player:getGuildLevel()) return rank ~= nil and rank.name or false end function getPlayerGuildNick(cid) local p = Player(cid) return p ~= nil and p:getGuildNick() or false end function getPlayerMasterPos(cid) local p = Player(cid) return p ~= nil and p:getTown():getTemplePosition() or false end function getPlayerItemCount(cid, itemId, ...) local p = Player(cid) return p ~= nil and p:getItemCount(itemId, ...) or false end function getPlayerSlotItem(cid, slot) local player = Player(cid) if player == nil then return pushThing(nil) end return pushThing(player:getSlotItem(slot)) end function getPlayerItemById(cid, deepSearch, itemId, ...) local player = Player(cid) if player == nil then return pushThing(nil) end return pushThing(player:getItemById(itemId, deepSearch, ...)) end function getPlayerFood(cid) local player = Player(cid) if player == nil then return false end local c = player:getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT) return c ~= nil and math.floor(c:getTicks() / 1000) or 0 end function canPlayerLearnInstantSpell(cid, name) local p = Player(cid) return p ~= nil and p:canLearnSpell(name) or false end function getPlayerLearnedInstantSpell(cid, name) local p = Player(cid) return p ~= nil and p:hasLearnedSpell(name) or false end function isPlayerGhost(cid) local p = Player(cid) return p ~= nil and p:isInGhostMode() or false end function isPlayerPzLocked(cid) local p = Player(cid) return p ~= nil and p:isPzLocked() or false end function isPremium(cid) local p = Player(cid) return p ~= nil and p:isPremium() or false end function getPlayersByIPAddress(ip, mask) if mask == nil then mask = 0xFFFFFFFF end local masked = bit.band(ip, mask) local result = {} for _, player in ipairs(Game.getPlayers()) do if bit.band(player:getIp(), mask) == masked then result[#result + 1] = player:getId() end end return result end function getOnlinePlayers() local result = {} for _, player in ipairs(Game.getPlayers()) do result[#result + 1] = player:getName() end return result end function getPlayersByAccountNumber(accountNumber) local result = {} for _, player in ipairs(Game.getPlayers()) do if player:getAccountId() == accountNumber then result[#result + 1] = player:getId() end end return result end function getPlayerGUIDByName(name) local player = Player(name) if player ~= nil then return player:getGuid() end local resultId = db.storeQuery("SELECT `id` FROM `players` WHERE `name` = " .. db.escapeString(name)) if resultId ~= false then local guid = result.getDataInt(resultId, "id") result.free(resultId) return guid end return 0 end function getAccountNumberByPlayerName(name) local player = Player(name) if player ~= nil then return player:getAccountId() end local resultId = db.storeQuery("SELECT `account_id` FROM `players` WHERE `name` = " .. db.escapeString(name)) if resultId ~= false then local accountId = result.getDataInt(resultId, "account_id") result.free(resultId) return accountId end return 0 end getPlayerAccountBalance = getPlayerBalance getIpByName = getIPByPlayerName function setPlayerStorageValue(cid, key, value) local p = Player(cid) return p ~= nil and p:setStorageValue(key, value) or false end function doPlayerSetBalance(cid, balance) local p = Player(cid) return p ~= nil and p:setBankBalance(balance) or false end function doPlayerAddMoney(cid, money) local p = Player(cid) return p ~= nil and p:addMoney(money) or false end function doPlayerRemoveMoney(cid, money) local p = Player(cid) return p ~= nil and p:removeMoney(money) or false end function doPlayerAddSoul(cid, soul) local p = Player(cid) return p ~= nil and p:addSoul(soul) or false end function doPlayerSetVocation(cid, vocation) local p = Player(cid) return p ~= nil and p:setVocation(Vocation(vocation)) or false end function doPlayerSetTown(cid, town) local p = Player(cid) return p ~= nil and p:setTown(Town(town)) or false end function setPlayerGroupId(cid, groupId) local p = Player(cid) return p ~= nil and p:setGroup(Group(groupId)) or false end function doPlayerSetSex(cid, sex) local p = Player(cid) return p ~= nil and p:setSex(sex) or false end function doPlayerSetGuildLevel(cid, level) local p = Player(cid) return p ~= nil and p:setGuildLevel(level) or false end function doPlayerSetGuildNick(cid, nick) local p = Player(cid) return p ~= nil and p:setGuildNick(nick) or false end function doShowTextDialog(cid, itemId, text) local p = Player(cid) return p ~= nil and p:showTextDialog(itemId, text) or false end function doPlayerAddItemEx(cid, uid, ...) local p = Player(cid) return p ~= nil and p:addItemEx(Item(uid), ...) or false end function doPlayerRemoveItem(cid, itemid, count, ...) local p = Player(cid) return p ~= nil and p:removeItem(itemid, count, ...) or false end function doPlayerAddPremiumDays(cid, days) local p = Player(cid) return p ~= nil and p:addPremiumDays(days) or false end function doPlayerRemovePremiumDays(cid, days) local p = Player(cid) return p ~= nil and p:removePremiumDays(days) or false end function doPlayerAddBlessing(cid, blessing) local p = Player(cid) return p ~= nil and p:addBlessing(blessing) or false end function doPlayerAddOutfit(cid, lookType, addons) local p = Player(cid) return p ~= nil and p:addOutfitAddon(lookType, addons) or false end function doPlayerRemOutfit(cid, lookType, addons) local player = Player(cid) if player == nil then return false end if addons == 255 then return player:removeOutfit(lookType) else return player:removeOutfitAddon(lookType, addons) end end function canPlayerWearOutfit(cid, lookType, addons) local p = Player(cid) return p ~= nil and p:hasOutfit(lookType, addons) or false end function doPlayerAddMount(cid, mountId) local p = Player(cid) return p ~= nil and p:addMount(mountId) or false end function doPlayerRemoveMount(cid, mountId) local p = Player(cid) return p ~= nil and p:removeMount(mountId) or false end function doPlayerSendCancel(cid, text) local p = Player(cid) return p ~= nil and p:sendCancelMessage(text) or false end function doPlayerFeed(cid, food) local p = Player(cid) return p ~= nil and p:feed(food) or false end function playerLearnInstantSpell(cid, name) local p = Player(cid) return p ~= nil and p:learnSpell(name) or false end function doPlayerPopupFYI(cid, message) local p = Player(cid) return p ~= nil and p:popupFYI(message) or false end function doSendTutorial(cid, tutorialId) local p = Player(cid) return p ~= nil and p:sendTutorial(tutorialId) or false end function doAddMapMark(cid, pos, type, description) local p = Player(cid) return p ~= nil and p:addMapMark(pos, type, description or "") or false end function doPlayerSendTextMessage(cid, type, text, ...) local p = Player(cid) return p ~= nil and p:sendTextMessage(type, text, ...) or false end function doSendAnimatedText() debugPrint("Deprecated function.") return true end function doPlayerAddExp(cid, exp, useMult, ...) local player = Player(cid) if player == nil then return false end if useMult then exp = exp * Game.getExperienceStage(player:getLevel()) end return player:addExperience(exp, ...) end function doPlayerAddManaSpent(cid, mana) local p = Player(cid) return p ~= nil and p:addManaSpent(mana * configManager.getNumber(configKeys.RATE_MAGIC)) or false end function doPlayerAddSkillTry(cid, skillid, n) local p = Player(cid) return p ~= nil and p:addSkillTries(skillid, n * configManager.getNumber(configKeys.RATE_SKILL)) or false end function doPlayerAddMana(cid, mana, ...) local p = Player(cid) return p ~= nil and p:addMana(mana, ...) or false end function doPlayerJoinParty(cid, leaderId) local player = Player(cid) if player == nil then return false end if player:getParty() ~= nil then player:sendTextMessage(MESSAGE_INFO_DESCR, "You are already in a party.") return true end local leader = Player(leaderId) if leader == nil then return false end local party = leader:getParty() if party == nil or party:getLeader() ~= leader then return true end for _, invitee in ipairs(party:getInvitees()) do if player ~= invitee then return true end end party:addMember(player) return true end function getPartyMembers(cid) local player = Player(cid) if player == nil then return false end local party = player:getParty() if party == nil then return false end local result = {party:getLeader():getId()} for _, member in ipairs(party:getMembers()) do result[#result + 1] = member:getId() end return result end doPlayerSendDefaultCancel = doPlayerSendCancel function getMonsterTargetList(cid) local monster = Monster(cid) if monster == nil then return false end local result = {} for _, creature in ipairs(monster:getTargetList()) do if monster:isTarget(creature) then result[#result + 1] = creature:getId() end end return result end function getMonsterFriendList(cid) local monster = Monster(cid) if monster == nil then return false end local z = monster:getPosition().z local result = {} for _, creature in ipairs(monster:getFriendList()) do if not creature:isRemoved() and creature:getPosition().z == z then result[#result + 1] = creature:getId() end end return result end function doSetMonsterTarget(cid, target) local monster = Monster(cid) if monster == nil then return false end if monster:getMaster() ~= nil then return true end local target = Creature(cid) if target == nil then return false end monster:selectTarget(target) return true end function doMonsterChangeTarget(cid) local monster = Monster(cid) if monster == nil then return false end if monster:getMaster() ~= nil then return true end monster:searchTarget(1) return true end function doCreateNpc(name, pos, ...) local npc = Game.createNpc(name, pos, ...) return npc ~= nil and npc:setMasterPos(pos) or false end function doSummonCreature(name, pos, ...) local m = Game.createMonster(name, pos, ...) return m ~= nil and m:getId() or false end function doConvinceCreature(cid, target) local creature = Creature(cid) if creature == nil then return false end local targetCreature = Creature(target) if targetCreature == nil then return false end targetCreature:setMaster(creature) return true end function getTownId(townName) local t = Town(townName) return t ~= nil and t:getId() or false end function getTownName(townId) local t = Town(townId) return t ~= nil and t:getName() or false end function getTownTemplePosition(townId) local t = Town(townId) return t ~= nil and t:getTemplePosition() or false end function doSetItemActionId(uid, actionId) local i = Item(uid) return i ~= nil and i:setActionId(actionId) or false end function doTransformItem(uid, newItemId, ...) local i = Item(uid) return i ~= nil and i:transform(newItemId, ...) or false end function doChangeTypeItem(uid, newType) local i = Item(uid) return i ~= nil and i:transform(i:getId(), newType) or false end function doRemoveItem(uid, ...) local i = Item(uid) return i ~= nil and i:remove(...) or false end function getContainerSize(uid) local c = Container(uid) return c ~= nil and c:getSize() or false end function getContainerCap(uid) local c = Container(uid) return c ~= nil and c:getCapacity() or false end function getContainerItem(uid, slot) local container = Container(uid) if container == nil then return pushThing(nil) end return pushThing(container:getItem(slot)) end function doAddContainerItemEx(uid, virtualId) local container = Container(uid) if container == nil then return false end local res = container:addItemEx(Item(virtualId)) if res == nil then return false end return res end function doSendMagicEffect(pos, magicEffect, ...) return Position(pos):sendMagicEffect(magicEffect, ...) end function doSendDistanceShoot(fromPos, toPos, distanceEffect, ...) return Position(fromPos):sendDistanceEffect(toPos, distanceEffect, ...) end function isSightClear(fromPos, toPos, floorCheck) return Position(fromPos):isSightClear(toPos, floorCheck) end function getPromotedVocation(vocationId) local vocation = Vocation(vocationId) if vocation == nil then return 0 end local promotedVocation = vocation:getPromotion() if promotedVocation == nil then return 0 end return promotedVocation:getId() end function getGuildId(guildName) local resultId = db.storeQuery("SELECT `id` FROM `guilds` WHERE `name` = " .. db.escapeString(guildName)) if resultId == false then return false end local guildId = result.getDataInt(resultId, "id") result.free(resultId) return guildId end function getHouseName(houseId) local h = House(houseId) return h ~= nil and h:getName() or false end function getHouseOwner(houseId) local h = House(houseId) return h ~= nil and h:getOwnerGuid() or false end function getHouseEntry(houseId) local h = House(houseId) return h ~= nil and h:getExitPosition() or false end function getHouseTown(houseId) local h = House(houseId) if h == nil then return false end local t = h:getTown() return t ~= nil and t:getId() or false end function getHouseTilesSize(houseId) local h = House(houseId) return h ~= nil and h:getTileCount() or false end function isItemStackable(itemId) return ItemType(itemId):isStackable() end function isItemRune(itemId) return ItemType(itemId):isRune() end function isItemDoor(itemId) return ItemType(itemId):isDoor() end function isItemContainer(itemId) return ItemType(itemId):isContainer() end function isItemFluidContainer(itemId) return ItemType(itemId):isFluidContainer() end function isItemMovable(itemId) return ItemType(itemId):isMovable() end function isCorpse(uid) local i = Item(uid) return i ~= nil and ItemType(i:getId()):isCorpse() or false end isItemMoveable = isItemMovable isMoveable = isMovable function getItemName(itemId) return ItemType(itemId):getName() end function getItemWeight(itemId, ...) return ItemType(itemId):getWeight(...) / 100 end function getItemDescriptions(itemId) local itemType = ItemType(itemId) return { name = itemType:getName(), plural = itemType:getPluralName(), article = itemType:getArticle(), description = itemType:getDescription() } end function getItemIdByName(name) local id = ItemType(name):getId() if id == 0 then return false end return id end function getItemWeightByUID(uid, ...) local item = Item(uid) if item == nil then return false end local itemType = ItemType(item:getId()) return itemType:isStackable() and (itemType:getWeight(item:getCount(), ...) / 100) or (itemType:getWeight(1, ...) / 100) end function getItemRWInfo(uid) local item = Item(uid) if item == nil then return false end local rwFlags = 0 local itemType = ItemType(item:getId()) if itemType:isReadable() then rwFlags = bit.bor(rwFlags, 1) end if itemType:isWritable() then rwFlags = bit.bor(rwFlags, 2) end return rwFlags end function getContainerCapById(itemId) return ItemType(itemId):getCapacity() end function getFluidSourceType(itemId) local it = ItemType(itemId) return it.id ~= 0 and it:getFluidSource() or false end function hasProperty(uid, prop) local item = Item(uid) if item == nil then return false end local parent = item:getParent() if parent:isTile() and item == parent:getGround() then return parent:hasProperty(prop) else return item:hasProperty(prop) end end function doSetItemText(uid, text) local item = Item(uid) if item == nil then return false end if text ~= "" then item:setAttribute(ITEM_ATTRIBUTE_TEXT, text) else item:removeAttribute(ITEM_ATTRIBUTE_TEXT) end return true end function doSetItemSpecialDescription(uid, desc) local item = Item(uid) if item == nil then return false end if desc ~= "" then item:setAttribute(ITEM_ATTRIBUTE_DESCRIPTION, desc) else item:removeAttribute(ITEM_ATTRIBUTE_DESCRIPTION) end return true end function doDecayItem(uid) local i = Item(uid) return i ~= nil and i:decay() or false end function setHouseOwner(id, guid) local h = House(id) return h ~= nil and h:setOwnerGuid(guid) or false end function getHouseRent(id) local h = House(id) return h ~= nil and h:getRent() or nil end function getHouseAccessList(id, listId) local h = House(id) return h ~= nil and h:getAccessList(listId) or nil end function setHouseAccessList(id, listId, listText) local h = House(id) return h ~= nil and h:setAccessList(listId, listText) or false end function getHouseByPlayerGUID(playerGUID) for _, house in ipairs(Game.getHouses()) do if house:getOwnerGuid() == playerGUID then return house:getId() end end return nil end function getTileHouseInfo(pos) local t = Tile(pos) if t == nil then return false end local h = t:getHouse() return h ~= nil and h:getId() or false end function getTilePzInfo(position) local t = Tile(position) if t == nil then return false end return t:hasFlag(TILESTATE_PROTECTIONZONE) end function getTileInfo(position) local t = Tile(position) if t == nil then return false end local ret = pushThing(t:getGround()) ret.protection = t:hasFlag(TILESTATE_PROTECTIONZONE) ret.nopz = ret.protection ret.nologout = t:hasFlag(TILESTATE_NOLOGOUT) ret.refresh = t:hasFlag(TILESTATE_REFRESH) ret.house = t:hasFlag(TILESTATE_HOUSE) ret.bed = t:hasFlag(TILESTATE_BED) ret.depot = t:hasFlag(TILESTATE_DEPOT) ret.things = t:getThingCount() ret.creatures = t:getCreatureCount() ret.items = t:getItemCount() ret.topItems = t:getTopItemCount() ret.downItems = t:getDownItemCount() return ret end function getTileItemByType(position, itemType) local t = Tile(position) if t == nil then return pushThing(nil) end return pushThing(t:getItemByType(itemType)) end function getTileItemById(position, itemId, ...) local t = Tile(position) if t == nil then return pushThing(nil) end return pushThing(t:getItemById(itemId, ...)) end function getTileThingByPos(position) local t = Tile(position) if t == nil then if position.stackpos == -1 then return -1 end return pushThing(nil) end if position.stackpos == -1 then return t:getThingCount() end return pushThing(t:getThing(position.stackpos)) end function getTileThingByTopOrder(position, topOrder) local t = Tile(position) if t == nil then return pushThing(nil) end return pushThing(t:getItemByTopOrder(topOrder)) end function getTopCreature(position) local t = Tile(position) if t == nil then return pushThing(nil) end return pushThing(t:getTopCreature()) end function queryTileAddThing(thing, position, ...) local t = Tile(position) return t ~= nil and t:queryAdd(thing, ...) or false end function doTeleportThing(uid, dest, pushMovement) if type(uid) == "userdata" then if uid:isCreature() then return uid:teleportTo(dest, pushMovement or false) else return uid:moveTo(dest) end else if uid >= 0x10000000 then local creature = Creature(uid) if creature ~= nil then return creature:teleportTo(dest, pushMovement or false) end else local item = Item(uid) if item ~= nil then return item:moveTo(dest) end end end return false end function getThingPos(uid) local thing if uid >= 0x10000000 then thing = Creature(uid) else thing = Item(uid) end if thing == nil then return false end local stackpos = 0 local tile = thing:getTile() if tile ~= nil then stackpos = tile:getThingIndex(thing) end local position = thing:getPosition() position.stackpos = stackpos return position end function getThingfromPos(pos) local tile = Tile(pos) if tile == nil then return pushThing(nil) end local thing if stackpos == STACKPOS_TOP_MOVEABLE_ITEM_OR_CREATURE then thing = tile:getTopCreature() if thing == nil then local item = tile:getTopDownItem() if item ~= nil and item:getType():isMovable() then thing = item end end elseif stackpos == STACKPOS_TOP_FIELD then thing = tile:getFieldItem() elseif stackpos == STACKPOS_TOP_CREATURE then thing = tile:getTopCreature() else thing = tile:getThing(pos.stackpos) end return pushThing(thing) end function doRelocate(fromPos, toPos) if fromPos == toPos then return false end local fromTile = Tile(fromPos) if fromTile == nil then return false end if Tile(toPos) == nil then return false end for i = fromTile:getThingCount() - 1, 0, -1 do local thing = fromTile:getThing(i) if thing ~= nil then if thing:isItem() then if ItemType(thing:getId()):isMovable() then thing:moveTo(toPos) end elseif thing:isCreature() then thing:teleportTo(toPos) end end end return true end function getThing(uid) return uid >= 0x10000000 and pushThing(Creature(uid)) or pushThing(Item(uid)) end function getConfigInfo(info) if type(info) ~= "string" then return nil end dofile('config.lua') return _G[info] end function getWorldCreatures(type) if type == 0 then return Game.getPlayerCount() elseif type == 1 then return Game.getMonsterCount() elseif type == 2 then return Game.getNpcCount() end return Game.getPlayerCount() + Game.getMonsterCount() + Game.getNpcCount() end saveData = saveServer function getGlobalStorageValue(key) return Game.getStorageValue(key) or -1 end function setGlobalStorageValue(key, value) Game.setStorageValue(key, value) return true end getWorldType = Game.getWorldType numberToVariant = Variant stringToVariant = Variant positionToVariant = Variant function targetPositionToVariant(position) local variant = Variant(position) variant.type = VARIANT_TARGETPOSITION return variant end variantToNumber = Variant.getNumber variantToString = Variant.getString variantToPosition = Variant.getPosition function doCreateTeleport(itemId, destination, position) local item = Game.createItem(itemId, 1, position) if not item:isTeleport() then item:remove() return false end item:setDestination(destination) return item:getUniqueId() end function getSpectators(centerPos, rangex, rangey, multifloor, onlyPlayers) local result = Game.getSpectators(centerPos, multifloor, onlyPlayers or false, rangex, rangex, rangey, rangey) if #result == 0 then return nil end for index, spectator in ipairs(result) do result[index] = spectator:getId() end return result end function broadcastMessage(message, messageType) Game.broadcastMessage(message, messageType) print("> Broadcasted message: \"" .. message .. "\".") end function Guild.addMember(self, player) return player:setGuild(guild) end function Guild.removeMember(self, player) return player:getGuild() == self and player:setGuild(nil) end
gpl-2.0
heyuqi/wxFormBuilder
build/premake/4.3/src/actions/xcode/_xcode.lua
7
1428
-- -- _xcode.lua -- Define the Apple XCode action and support functions. -- Copyright (c) 2009 Jason Perkins and the Premake project -- premake.xcode = { } newaction { trigger = "xcode3", shortname = "Xcode 3", description = "Generate Apple Xcode 3 project files (experimental)", os = "macosx", valid_kinds = { "ConsoleApp", "WindowedApp", "SharedLib", "StaticLib" }, valid_languages = { "C", "C++" }, valid_tools = { cc = { "gcc" }, }, valid_platforms = { Native = "Native", x32 = "Native 32-bit", x64 = "Native 64-bit", Universal32 = "32-bit Universal", Universal64 = "64-bit Universal", Universal = "Universal", }, default_platform = "Universal", onsolution = function(sln) -- Assign IDs needed for inter-project dependencies premake.xcode.preparesolution(sln) end, onproject = function(prj) premake.generate(prj, "%%.xcodeproj/project.pbxproj", premake.xcode.project) end, oncleanproject = function(prj) premake.clean.directory(prj, "%%.xcodeproj") end, oncheckproject = function(prj) -- Xcode can't mix target kinds within a project local last for cfg in premake.eachconfig(prj) do if last and last ~= cfg.kind then error("Project '" .. prj.name .. "' uses more than one target kind; not supported by Xcode", 0) end last = cfg.kind end end, }
gpl-2.0
UnfortunateFruit/darkstar
scripts/zones/Bastok_Mines/npcs/Griselda.lua
34
1892
----------------------------------- -- Area: Bastok Mines -- NPC: Griselda -- Standard Merchant NPC -- @pos -25.749 -0.044 52.360 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatBastok = player:getVar("WildcatBastok"); if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,15) == false) then player:startEvent(0x01fb); else player:showText(npc,GRISELDA_SHOP_DIALOG); stock = { 0x115A, 360,1, --Bottle of pineapple juice 0x1127, 21,2, --Bretzel 0x118A, 432,2, --Pickled herring 0x1148, 990,2, --Bottle of melon juice 0x1193, 90,3, --Loaf of iron bread 0x1118, 108,3, --Strip of meat jerky 0x119D, 10,3 --Flask of distilled water } showNationShop(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); if (csid == 0x01fb) then player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",15,true); end end;
gpl-3.0
hhrhhr/Lua-utils-for-X-Rebirth
lua/xmlhandler/tree.lua
1
5067
local function init() local obj = { root = {}, options = {noreduce = {}} } obj._stack = {obj.root, n=1} return obj end --- @module XML Tree Handler. -- Generates a lua table from an XML content string. -- It is a simplified handler which attempts -- to generate a more 'natural' table based structure which -- supports many common XML formats. -- -- The XML tree structure is mapped directly into a recursive -- table structure with node names as keys and child elements -- as either a table of values or directly as a string value -- for text. Where there is only a single child element this -- is inserted as a named key - if there are multiple -- elements these are inserted as a vector (in some cases it -- may be preferable to always insert elements as a vector -- which can be specified on a per element basis in the -- options). Attributes are inserted as a child element with -- a key of '_attr'. -- -- Only Tag/Text & CDATA elements are processed - all others -- are ignored. -- -- This format has some limitations - primarily -- -- * Mixed-Content behaves unpredictably - the relationship -- between text elements and embedded tags is lost and -- multiple levels of mixed content does not work -- * If a leaf element has both a text element and attributes -- then the text must be accessed through a vector (to -- provide a container for the attribute) -- -- In general however this format is relatively useful. -- -- It is much easier to understand by running some test -- data through 'textxml.lua -simpletree' than to read this) -- -- Options -- ======= -- options.noreduce = { <tag> = bool,.. } -- - Nodes not to reduce children vector even if only -- one child -- -- License: -- ======== -- -- This code is freely distributable under the terms of the [MIT license](LICENSE). -- --@author Paul Chakravarti (paulc@passtheaardvark.com) --@author Manoel Campos da Silva Filho local tree = init() ---Instantiates a new handler object. --Each instance can handle a single XML. --By using such a constructor, you can parse --multiple XML files in the same application. --@return the handler instance function tree:new() local obj = init() obj.__index = self setmetatable(obj, self) return obj end --Gets the first key of a table --@param tb table to get its first key --@return the table's first key, nil if the table is empty --or the given parameter if it isn't a table local function getFirstKey(tb) if type(tb) == "table" then for k, v in pairs(tb) do return k end return nil end return tb end --- Recursively removes redundant vectors for nodes -- with single child elements function tree:reduce(node, key, parent) for k,v in pairs(node) do if type(v) == 'table' then self:reduce(v,k,node) end end if #node == 1 and not self.options.noreduce[key] and node._attr == nil then parent[key] = node[1] else node.n = nil end end ---Parses a start tag. -- @param tag a {name, attrs} table -- where name is the name of the tag and attrs -- is a table containing the atributtes of the tag function tree:starttag(tag) local node = {} if self.parseAttributes == true then node._attr=tag.attrs end local current = self._stack[#self._stack] if current[tag.name] then table.insert(current[tag.name], node) else current[tag.name] = {node; n=1} end table.insert(self._stack, node) end ---Parses an end tag. -- @param tag a {name, attrs} table -- where name is the name of the tag and attrs -- is a table containing the atributtes of the tag function tree:endtag(tag, s) --Tabela que representa a tag atualmente sendo processada local current = self._stack[#self._stack] --Tabela que representa a tag na qual a tag --atual está contida. local prev = self._stack[#self._stack-1] if not prev[tag.name] then error("XML Error - Unmatched Tag ["..s..":"..tag.name.."]\n") end if prev == self.root then -- Once parsing complete recursively reduce tree self:reduce(prev, nil, nil) end local firstKey = getFirstKey(current) --Se a primeira chave da tabela que representa --a tag atual não possui nenhum elemento, --é porque não há nenhum valor associado à tag -- (como nos casos de tags automaticamente fechadas como <senha />). --Assim, atribui uma string vazia a mesma para --que seja retornado vazio no lugar da tag e não --uma tabela. Retornando uma string vazia --simplifica para as aplicações NCLua --para imprimir tal valor. if firstKey == nil then current[tag.name] = "" prev[tag.name] = "" end table.remove(self._stack) end ---Parses a tag content. -- @param t text to process function tree:text(t) local current = self._stack[#self._stack] table.insert(current, t) end ---Parses CDATA tag content. tree.cdata = tree.text tree.__index = tree return tree
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/La_Theine_Plateau/Zone.lua
6
5851
----------------------------------- -- -- Zone: La_Theine_Plateau (102) -- ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; package.loaded["scripts/globals/chocobo_digging"] = nil; ----------------------------------- require("scripts/zones/La_Theine_Plateau/TextIDs"); require("scripts/globals/zone"); require("scripts/globals/icanheararainbow"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/weather"); require("scripts/globals/chocobo_digging"); ----------------------------------- -- Chocobo Digging vars ----------------------------------- local itemMap = { -- itemid, abundance, requirement { 688, 153, DIGREQ_NONE }, { 17396, 155, DIGREQ_NONE }, { 17296, 134, DIGREQ_NONE }, { 641, 103, DIGREQ_NONE }, { 840, 56, DIGREQ_NONE }, { 642, 49, DIGREQ_NONE }, { 696, 57, DIGREQ_NONE }, { 694, 40, DIGREQ_NONE }, { 622, 28, DIGREQ_NONE }, { 700, 3, DIGREQ_NONE }, { 4096, 100, DIGREQ_NONE }, -- all crystals { 4545, 34, DIGREQ_BURROW }, { 636, 20, DIGREQ_BURROW }, { 616, 8, DIGREQ_BURROW }, { 5235, 2, DIGREQ_BURROW }, { 2364, 139, DIGREQ_BORE }, { 2235, 44, DIGREQ_BORE }, { 617, 6, DIGREQ_BORE }, { 4570, 10, DIGREQ_MODIFIER }, { 4487, 11, DIGREQ_MODIFIER }, { 4409, 12, DIGREQ_MODIFIER }, { 1188, 10, DIGREQ_MODIFIER }, { 1237, 12, DIGREQ_MODIFIER }, }; local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED }; ----------------------------------- -- onChocoboDig ----------------------------------- function onChocoboDig(player, precheck) return chocoboDig(player, itemMap, precheck, messageArray); end; ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17195678,17195679}; SetFieldManual(manuals); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos( -272.118, 21.715, 98.859, 243); end if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow cs = 0x007b; elseif ( prevZone == 193 and player:getVar( "darkPuppetCS") == 5 and player:getFreeSlotsCount() >= 1) then cs = 0x007a; elseif(player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1)then cs = 0x007d; end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter( player, region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x007b) then lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow elseif (csid == 0x007d) then player:updateEvent(0,0,0,0,0,2); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x007b) then lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow elseif (csid == 0x007a) then player:addItem( 14096); player:messageSpecial( ITEM_OBTAINED, 14096); -- Chaos Sollerets player:setVar( "darkPuppetCS", 0); player:addFame( BASTOK, AF2_FAME); player:completeQuest( BASTOK,DARK_PUPPET); end end; ----------------------------------- -- onZoneWeatherChange ----------------------------------- function onZoneWeatherChange(weather) local _2u0 = GetNPCByID(17195607); local VanadielTOTD = VanadielTOTD(); local I_Can_Hear_a_Rainbow = GetServerVariable("I_Can_Hear_a_Rainbow"); if (I_Can_Hear_a_Rainbow == 1 and weather ~= WEATHER_RAIN and VanadielTOTD >= TIME_DAWN and VanadielTOTD <= TIME_EVENING and _2u0:getAnimation() == 9) then _2u0:setAnimation(8); elseif (I_Can_Hear_a_Rainbow == 1 and weather == WEATHER_RAIN and _2u0:getAnimation() == 8) then _2u0:setAnimation(9); SetServerVariable("I_Can_Hear_a_Rainbow", 0); end end; ----------------------------------- -- onTOTDChange ----------------------------------- function onTOTDChange(TOTD) local _2u0 = GetNPCByID(17195607); local I_Can_Hear_a_Rainbow = GetServerVariable("I_Can_Hear_a_Rainbow"); if (I_Can_Hear_a_Rainbow == 1 and TOTD >= TIME_DAWN and TOTD <= TIME_EVENING and _2u0:getAnimation() == 9) then _2u0:setAnimation(8); elseif (I_Can_Hear_a_Rainbow == 1 and TOTD < TIME_DAWN or TOTD > TIME_EVENING and _2u0:getAnimation() == 8) then _2u0:setAnimation(9); SetServerVariable("I_Can_Hear_a_Rainbow", 0); end end;
gpl-3.0
NezzKryptic/Wire-Extras
lua/entities/gmod_wire_expression2/core/custom/tracesystem.lua
2
45389
/*********************************************************************************************************************** Credits Feha - I am coding the stuff gmod lua wiki - they got a list of functions you can use. Inspired by the e2 extensions: holo, datasignals, gvars, entity and ranger. ***********************************************************************************************************************/ E2Lib.RegisterExtension("tracesystem", false) /**************************** ***** Helper functions ***** ****************************/ --[ local v = debug.getregistry().Vector local Length = v.Length local Dot = v.Dot local Cross = v.Cross local Distance = v.Distance local sqrt = math.sqrt --]] local function E2VecToLuaVec( Vec ) return Vector(Vec[1],Vec[2],Vec[3]) end local function LuaVecToE2Vec( Vec ) if (Vec) then return {Vec.x,Vec.y,Vec.z} end return {0,0,0} end local function E2AngToLuaAng( Ang ) return Angle(Ang[1],Ang[2],Ang[3]) end local function LuaAngToE2Ang( Ang ) if (Ang) then return {Ang.p,Ang.y,Ang.r} end return {0,0,0} end //Default function make 1,0,0 have a length below 1, use this instead. local function Norm( Vec ) return Vec / Length(Vec) end /********************************* ***** Intersection functions ***** *********************************/ local function RayPlaneIntersection( Start, Dir, Pos, Normal ) local A = Dot(Normal, Dir) //Check if the ray is aiming towards the plane (fail if it origin behind the plane, but that is checked later) if (A < 0) then local B = Dot(Normal, Pos-Start) //Check if the ray origin in front of plane if (B < 0) then return (Start + Dir * (B/A)) end //Check if the ray is parallel to the plane elseif (A == 0) then //Check if the ray origin inside the plane if (Dot(Normal, Pos-Start) == 0) then return Start end end return false end local function RayFaceIntersection( Start, Dir, Pos, Normal, Size, Rotation ) local hitPos = RayPlaneIntersection( Start, Dir, Pos, Normal ) if (hitPos) then faceAngle = Normal:Angle()+Angle(0,0,Rotation) local localHitPos = WorldToLocal( hitPos, Angle(0,0,0), Pos, faceAngle ) local min = Size/-2 local max = Size/2 //Because using Normal:Angle() for WorldToLocal() makes it think that axis is x, we need to use the local hitpos z as x. if (localHitPos.z >= min.x and localHitPos.z <= max.x) then if (localHitPos.y >= min.y and localHitPos.y <= max.y) then return hitPos end end end return false end local function RayPolygonIntersection( Start, Dir, Vertices ) local Vertex1 = Vertices[1] local Vertex2 = Vertices[2] local Vertex3 = Vertices[3] local V1V2 = Norm(Vertex2 - Vertex1) local V1V3 = Norm(Vertex3 - Vertex1) local normal = Cross(V1V2, V1V3) if Dot( Dir, normal ) > 0 then normal:Mul(-1) end local hitPos = RayPlaneIntersection( Start, Dir, Vertex1, normal ) if (hitPos) then local V1Hit = Norm(hitPos - Vertex1) if Dot( V1V2, V1V3 ) < Dot( V1V2, V1Hit ) and Dot( V1V3, V1V2 ) < Dot( V1V3, V1Hit ) and Dot( V1V2, Norm(Vertex3 - Vertex2) ) > Dot( V1V2, Norm(hitPos - Vertex2) ) then return hitPos end end return false end local boxNormals = { Vector(1,0,0), Vector(0,1,0), Vector(0,0,1), Vector(-1,0,0), Vector(0,-1,0), Vector(0,0,-1) } local function RayAABBoxIntersection( Start, Dir, Pos, Size ) //Getting the sizes for the faces let us scale the box a lil. local boxSizes = { Vector(Size.z,Size.y,0), Vector(Size.z,Size.x,0), Vector(Size.x,Size.y,0), Vector(Size.z,Size.y,0), Vector(Size.z,Size.x,0), Vector(Size.x,Size.y,0) } local closestDist local closestHitPos local closestNormal for i=1,6 do local normal = boxNormals[i] local faceSize = boxSizes[i] if (Dot(normal, Dir) < 0) then local planePos = Pos + normal * (Size/2) local HitPos = RayFaceIntersection( Start, Dir, planePos, normal, faceSize, 0 ) if (HitPos) then local dist = Distance(HitPos, Start) if (!closestDist or dist < closestDist) then closestDist = dist closestHitPos = HitPos closestNormal = normal end end end end if (closestHitPos) then return closestHitPos, closestNormal end return false end local function RayOBBoxIntersection( Start, Dir, Pos, Size, Ang ) //To use an oriented-bounding-box we make the ray local (so we can use the AABB code) local localRayStart = WorldToLocal( Start, Angle(0,0,0), Pos, Ang ) //The direction need to be local to 0,0,0 though local localRayDir = WorldToLocal( Dir, Angle(0,0,0), Vector(0,0,0), Ang ) //Use AABB code as that is easyer than calculating the normals of the faces and their angle aroudn that axis local localHitPos, localHitNormal = RayAABBoxIntersection( localRayStart, localRayDir, Vector(0,0,0), Size ) //But we want the returned hitpos to be a world coord if (localHitPos) then local hitPos = LocalToWorld( localHitPos, Angle(0,0,0), Pos, Ang ) local hitNormal = LocalToWorld( localHitNormal, Angle(0,0,0), Vector(0,0,0), Ang ) return hitPos, hitNormal end return false end local function RayCircleIntersection( Start, Dir, Pos, Normal, Radius ) local HitPos = RayPlaneIntersection( Start, Dir, Pos, Normal ) if (HitPos) then local Dist = Distance(Pos, HitPos) if (Dist < Radius) then return HitPos, Dist end end return false end local function RaySphereIntersection( Start, Dir, Pos, Radius ) //New ray-sphere intersection code --[ local A = 2 * Length(Dir)^2 local B = 2 * Dot(Dir,Start - Pos) local C = Length(Pos)^2 + Length(Start)^2 - 2 * Dot(Pos,Start) - Radius^2 local BAC4 = B^2-(2*A*C) if (BAC4 >= 0 and B < 0) then //Enter sphere return Start + ((-sqrt(BAC4) - B) / A)*Dir //Exits sphere //return Start + ((sqrt(BAC4) - B) / A)*Dir end --]] //Old ray-sphere intersection code (slower) --[[ local Normal = Dir * -1 local B = Normal:Dot(Pos-Start) / Normal:Dot(Dir) //It is a ray, not line, for a line segment, just add a distance chek. if (B >= 0) then local HitPos = Start + Dir * B local Dist = Distance(Pos, HitPos) if (Dist < Radius) then HitPos = HitPos - Dir * sqrt(Radius ^ 2 - Dist ^ 2) return HitPos end end --]] return false end local function RayAAEllipsoidIntersection( Start, Dir, Pos, Size ) local RayPos = Start - Pos local RayDir = Norm(Dir) --This boosts my performance by only having to do ^2 once per variable, instead of 3. local ElipsoidRadiusX2 = Size.x^2 local ElipsoidRadiusY2 = Size.y^2 local ElipsoidRadiusZ2 = Size.z^2 local A = RayDir.x^2 / ElipsoidRadiusX2 + RayDir.y^2 / ElipsoidRadiusY2 + RayDir.z^2 / ElipsoidRadiusZ2 local B = (2 * RayPos.x * RayDir.x) / ElipsoidRadiusX2 + (2 * RayPos.y * RayDir.y) / ElipsoidRadiusY2 + (2 * RayPos.z * RayDir.z) / ElipsoidRadiusZ2 local C = RayPos.x^2 / ElipsoidRadiusX2 + RayPos.y^2 / ElipsoidRadiusY2 + RayPos.z^2 / ElipsoidRadiusZ2 - 1 local D = (B^2) - (4 * A * C) if (D >= 0) then D = sqrt(D) local Hit1 = (-B + D) / (2 * A) local Hit2 = (-B - D) / (2 * A) if (Hit1 < Hit2) then return Start + RayDir * Hit1 else return Start + RayDir * Hit2 end end return false end local function RayOEllipsoidIntersection( Start, Dir, Pos, Size, Ang ) //To use an oriented-bounding-box we make the ray local (so we can use the AABB code) local localRayStart = WorldToLocal( Start, Angle(0,0,0), Pos, Ang ) //The direction need to be local to 0,0,0 though local localRayDir = WorldToLocal( Dir, Angle(0,0,0), Vector(0,0,0), Ang ) //Use AABB code as that is easyer than calculating the normals of the faces and their angle aroudn that axis local localHitPos = RayAAEllipsoidIntersection( localRayStart, localRayDir, Vector(0,0,0), Size ) //But we want the returned hitpos to be a world coord if (localHitPos) then local hitPos = LocalToWorld( localHitPos, Angle(0,0,0), Pos, Ang ) return hitPos end return false end local function ConeSphereIntersection( Start, Dir, Pos, Radius, Ang ) local HitPos = RaySphereIntersection( Start, Dir, Pos, Radius ) //If we hit with a normal trace we dont need to calculate for a cone if (HitPos) then return HitPos, 0 end if (Ang == 0) then return false end //Normal of the plane is -Dir because that makes the face perfectly perpendicular to the trace, and facing towards the origin HitPos = RayPlaneIntersection( Start, Dir, Pos, Dir * -1 ) if (!HitPos) then return false end //Calculate where on a circle would be closest to the plane hitpos HitPos = Pos + Norm(HitPos-Pos) * Radius //Get angle between the vector we aim and vector to the circle "hitpos" VecAng = math.deg( math.acos( Dot( Norm(Dir), Norm(HitPos-Start) ) ) ) if (VecAng <= Ang) then return HitPos, VecAng end return false end /************************ ***** * functions ***** *************************/ local playerAmount = {} local shapes = {} local sharing = {} CreateConVar("wire_shapes_max","50") local function ShapeCanCreate( ply ) if (playerAmount[ply] < GetConVar("wire_shapes_max"):GetInt()) then return true end end local function ShapeShare( share, self ) if (share) then sharing[self.player][self.entity] = math.Clamp(share,0,2) end end local models = { "", "plane", "face", "box", "circle", "sphere", "ellipsoid", "polygon" } local function ShapeCreate( index, model, radius, rotation, pos, normal, size, ang, vertices, self ) if (!table.HasValue( models, model )) then return "Invalid model." end if (model == "polygon") then return ShapeCreatePolygon( index, vertices, self ) end if (!shapes[self.player][self.entity][index]) then playerAmount[self.player] = playerAmount[self.player]+1 end local shape = {} //Unmodifiable shape.Index = index shape.Entity = self.entity shape.Owner = self.player //Modifiable shape.Model = model shape.Radius = radius shape.Rotation = rotation shape.Pos = pos shape.Normal = normal shape.Size = size shape.Ang = ang shape.Vertices = nil shapes[self.player][self.entity][index] = shape return "" end local function ShapeCreatePolygon( index, vertices, self ) if (!shapes[self.player][self.entity][index]) then playerAmount[self.player] = playerAmount[self.player]+1 end local shape = {} //Unmodifiable shape.Index = index shape.Entity = self.entity shape.Owner = self.player //Modifiable shape.Model = "polygon" shape.Vertices = vertices shape.Pos = (vertices[1] + vertices[2] + vertices[3]) / 3 shape.Radius = 0 shape.Rotation = 0 shape.Normal = Vector(0,0,0) shape.Size = Vector(0,0,0) shape.Ang = Angle(0,0,0) shapes[self.player][self.entity][index] = shape return "" end local function ShapeModel( index, model, self ) if (!table.HasValue( models, model )) then return "Invalid model." end local shape = shapes[self.player][self.entity][index] if (!shape) then return "Invalid index." end shape.Model = model return "" end local function ShapeRadius( index, radius, self ) local shape = shapes[self.player][self.entity][index] if (!shape) then return "Invalid index." end shape.Radius = radius return "" end local function ShapeRotation( index, rotation, self ) local shape = shapes[self.player][self.entity][index] if (!shape) then return "Invalid index." end shape.Rotation = rotation return "" end local function ShapePos( index, pos, self ) local shape = shapes[self.player][self.entity][index] if (!shape) then return "Invalid index." end if (shape.Parent) then shape.Pos = shape.Parent:WorldToLocal(pos) else shape.Pos = pos end return "" end local function ShapeVertices( index, vertices, self ) local shape = shapes[self.player][self.entity][index] if (!shape) then return "Invalid index." end if (shape.Parent) then vertices[1] = shape.Parent:WorldToLocal(vertices[1]) vertices[2] = shape.Parent:WorldToLocal(vertices[2]) vertices[3] = shape.Parent:WorldToLocal(vertices[3]) shape.Vertices = vertices else shape.Vertices = vertices end return "" end local function ShapeAng( index, ang, self ) local shape = shapes[self.player][self.entity][index] if (!shape) then return "Invalid index." end if (shape.Parent) then shape.Ang = shape.Parent:WorldToLocal(ang) else shape.Ang = ang end return "" end local function ShapeNormal( index, normal, self ) local shape = shapes[self.player][self.entity][index] if (!shape) then return "Invalid index." end if (shape.Parent) then shape.Normal = WorldToLocal( normal, Angle(0,0,0), Vector(0,0,0), shape.Parent:GetAngles() ) else shape.Normal = normal end return "" end local function ShapeSize( index, size, self ) local shape = shapes[self.player][self.entity][index] if (!shape) then return "Invalid index." end shape.Size = size return "" end local function ShapeParent( index, parent, self ) local shape = shapes[self.player][self.entity][index] if (!shape) then return "Invalid index." end if (parent) then local pos, ang, normal, rotation, vertices if (shape.Parent) then pos, ang, normal, rotation, vertices = GetWorldData(shape) else pos, ang, normal, rotation = shape.Pos, shape.Ang, shape.Normal, shape.Rotation local vertices = shape.Vertices end shape.Pos = parent:WorldToLocal(pos) shape.Ang = parent:WorldToLocalAngles(ang) shape.Normal = WorldToLocal( normal, Angle(0,0,0), Vector(0,0,0), parent:GetAngles() ) shape.Rotation = rotation //Work on if vertices then shape.Vertices[1] = parent:WorldToLocal(vertices[1]) shape.Vertices[2] = parent:WorldToLocal(vertices[2]) shape.Vertices[3] = parent:WorldToLocal(vertices[3]) else shape.Vertices = nil end end shape.Parent = parent return "" end local function ShapeRemove( index, self ) local shape = shapes[self.player][self.entity][index] if (!shape) then return "Invalid index." end playerAmount[self.player] = playerAmount[self.player]-1 shapes[self.player][self.entity][index] = nil return "" end local function ShapeClear( self ) for index,shape in pairs(shapes[self.player][self.entity]) do playerAmount[self.player] = playerAmount[self.player]-1 shapes[self.player][self.entity][index] = nil end end /*********************************** ***** Ts intersection functions ***** ***********************************/ local function GetWorldData(shape) local parent = shape.Parent local pos = parent:LocalToWorld(shape.Pos) local ang = parent:LocalToWorldAngles(shape.Ang) local normal = LocalToWorld( shape.Normal, Angle(0,0,0), Vector(0,0,0), shape.Parent:GetAngles() ) local rotation = shape.Rotation //Work On local vertices = shape.Vertices if vertices then vertices[1] = parent:LocalToWorld(vertices[1]) vertices[2] = parent:LocalToWorld(vertices[2]) vertices[3] = parent:LocalToWorld(vertices[3]) end return pos, ang, normal, rotation, vertices end local function FillTraceData( trace, shape ) local pos, ang, normal, rotation, vertices if (shape.Parent) then pos, ang, normal, rotation, vertices = GetWorldData(shape) else pos, ang, normal, rotation = shape.Pos, shape.Ang, shape.Normal, shape.Rotation vertices = shape.Vertices end trace.Hit = 1 trace.Index = shape.Index trace.Radius = shape.Radius trace.Rotation = rotation trace.Model = shape.Model trace.HitNormal = normal trace.Size = shape.Size trace.Pos = pos trace.Vertices = vertices trace.Ang = ang trace.Parent = shape.Parent trace.HitEntity = shape.Entity trace.HitOwner = shape.Owner end local function TsRayPlaneIntersection( start, dir, self ) local traces = {} for ply,plyGates in pairs(shapes) do for gate,gateShapes in pairs(plyGates) do local cont = false //If player is not same player who trace and e2's does not share with other players e2 if (ply ~= self.player and (sharing[ply][gate] ~= 2 or sharing[self.player][self.entity] ~= 2)) then cont = true end //If e2 is not same as e2 that trace and e2 does not share at all if (gate ~= self.entity and (sharing[ply][gate] == 0 or sharing[self.player][self.entity] == 0)) then cont = true end if (!cont) then for k,shape in pairs(gateShapes) do if (shape.Model == "plane") then local pos, ang, normal, rotation if (shape.Parent) then pos, ang, normal, rotation = GetWorldData(shape) else pos, ang, normal, rotation = shape.Pos, shape.Ang, shape.Normal, shape.Rotation end local hitPos = RayPlaneIntersection( start, dir, pos, normal ) if (hitPos) then local trace = {} FillTraceData( trace, shape ) trace.HitAngle = 0 trace.StartPos = start trace.HitPos = hitPos table.insert( traces, trace ) end end end end end end return traces end local function TsRayFaceIntersection( start, dir, self ) local traces = {} for ply,plyGates in pairs(shapes) do for gate,gateShapes in pairs(plyGates) do local cont = false //If player is not same player who trace and e2's does not share with other players e2 if (ply ~= self.player and (sharing[ply][gate] ~= 2 or sharing[self.player][self.entity] ~= 2)) then cont = true end //If e2 is not same as e2 that trace and e2 does not share at all if (gate ~= self.entity and (sharing[ply][gate] == 0 or sharing[self.player][self.entity] == 0)) then cont = true end if (!cont) then for k,shape in pairs(gateShapes) do if (shape.Model == "face") then local pos, ang, normal, rotation if (shape.Parent) then pos, ang, normal, rotation = GetWorldData(shape) else pos, ang, normal, rotation = shape.Pos, shape.Ang, shape.Normal, shape.Rotation end local hitPos = RayFaceIntersection( start, dir, pos, normal, shape.Size, rotation ) if (hitPos) then local trace = {} FillTraceData( trace, shape ) trace.HitAngle = 0 trace.StartPos = start trace.HitPos = hitPos table.insert( traces, trace ) end end end end end end return traces end local function TsRayPolygonIntersection( start, dir, self ) local traces = {} for ply,plyGates in pairs(shapes) do for gate,gateShapes in pairs(plyGates) do local cont = false //If player is not same player who trace and e2's does not share with other players e2 if (ply ~= self.player and (sharing[ply][gate] ~= 2 or sharing[self.player][self.entity] ~= 2)) then cont = true end //If e2 is not same as e2 that trace and e2 does not share at all if (gate ~= self.entity and (sharing[ply][gate] == 0 or sharing[self.player][self.entity] == 0)) then cont = true end if (!cont) then for k,shape in pairs(gateShapes) do if (shape.Model == "polygon") then local pos, ang, normal, rotation, vertices if (shape.Parent) then pos, ang, normal, rotation, vertices = GetWorldData(shape) else pos, ang, normal, rotation, vertices = shape.Pos, shape.Ang, shape.Normal, shape.Rotation, shape.Vertices end local hitPos = RayPolygonIntersection( start, dir, vertices ) if (hitPos) then local trace = {} FillTraceData( trace, shape ) trace.HitAngle = 0 trace.StartPos = start trace.HitPos = hitPos table.insert( traces, trace ) end end end end end end return traces end local function TsRayBoxIntersection( start, dir, self ) local traces = {} for ply,plyGates in pairs(shapes) do for gate,gateShapes in pairs(plyGates) do local cont = false //If player is not same player who trace and e2's does not share with other players e2 if (ply ~= self.player and (sharing[ply][gate] ~= 2 or sharing[self.player][self.entity] ~= 2)) then cont = true end //If e2 is not same as e2 that trace and e2 does not share at all if (gate ~= self.entity and (sharing[ply][gate] == 0 or sharing[self.player][self.entity] == 0)) then cont = true end if (!cont) then for k,shape in pairs(gateShapes) do if (shape.Model == "box") then local pos, ang, normal, rotation if (shape.Parent) then pos, ang, normal, rotation = GetWorldData(shape) else pos, ang, normal, rotation = shape.Pos, shape.Ang, shape.Normal, shape.Rotation end local hitPos, hitNormal = RayOBBoxIntersection( start, dir, pos, shape.Size, ang ) if (hitPos) then local trace = {} FillTraceData( trace, shape ) trace.HitAngle = 0 trace.StartPos = start trace.HitPos = hitPos trace.HitNormal = hitNormal table.insert( traces, trace ) end end end end end end return traces end local function TsRayCircleIntersection( start, dir, self ) local traces = {} for ply,plyGates in pairs(shapes) do for gate,gateShapes in pairs(plyGates) do local cont = false //If player is not same player who trace and e2's does not share with other players e2 if (ply ~= self.player and (sharing[ply][gate] ~= 2 or sharing[self.player][self.entity] ~= 2)) then cont = true end //If e2 is not same as e2 that trace and e2 does not share at all if (gate ~= self.entity and (sharing[ply][gate] == 0 or sharing[self.player][self.entity] == 0)) then cont = true end if (!cont) then for k,shape in pairs(gateShapes) do if (shape.Model == "circle") then local pos, ang, normal, rotation if (shape.Parent) then pos, ang, normal, rotation = GetWorldData(shape) else pos, ang, normal, rotation = shape.Pos, shape.Ang, shape.Normal, shape.Rotation end local hitPos = RayCircleIntersection( start, dir, pos, normal, shape.Radius ) if (hitPos) then local trace = {} FillTraceData( trace, shape ) trace.HitAngle = 0 trace.StartPos = start trace.HitPos = hitPos table.insert( traces, trace ) end end end end end end return traces end local function TsRaySphereIntersection( start, dir, self ) local traces = {} for ply,plyGates in pairs(shapes) do for gate,gateShapes in pairs(plyGates) do local cont = false //If player is not same player who trace and e2's does not share with other players e2 if (ply ~= self.player and (sharing[ply][gate] ~= 2 or sharing[self.player][self.entity] ~= 2)) then cont = true end //If e2 is not same as e2 that trace and e2 does not share at all if (gate ~= self.entity and (sharing[ply][gate] == 0 or sharing[self.player][self.entity] == 0)) then cont = true end if (!cont) then for k,shape in pairs(gateShapes) do if (shape.Model == "sphere") then local pos, ang, normal, rotation if (shape.Parent) then pos, ang, normal, rotation = GetWorldData(shape) else pos, ang, normal, rotation = shape.Pos, shape.Ang, shape.Normal, shape.Rotation end local hitPos = RaySphereIntersection( start, dir, pos, shape.Radius ) if (hitPos) then local trace = {} FillTraceData( trace, shape ) trace.HitAngle = 0 trace.StartPos = start trace.HitPos = hitPos trace.HitNormal = Norm(hitPos - pos) table.insert( traces, trace ) end end end end end end return traces end local function TsRayEllipsoidIntersection( start, dir, self ) local traces = {} for ply, plyGates in pairs(shapes) do for gate, gateShapes in pairs(plyGates) do local cont = false //If player is not same player who trace and e2's does not share with other players e2 if (ply ~= self.player and (sharing[ply][gate] ~= 2 or sharing[self.player][self.entity] ~= 2)) then cont = true end //If e2 is not same as e2 that trace and e2 does not share at all if (gate ~= self.entity and (sharing[ply][gate] == 0 or sharing[self.player][self.entity] == 0)) then cont = true end if (!cont) then for k,shape in pairs(gateShapes) do if (shape.Model == "ellipsoid") then local pos, ang, normal, rotation if (shape.Parent) then pos, ang, normal, rotation = GetWorldData(shape) else pos, ang, normal, rotation = shape.Pos, shape.Ang, shape.Normal, shape.Rotation end local hitPos = RayOEllipsoidIntersection( start, dir, pos, shape.Size, ang ) if (hitPos) then local trace = {} FillTraceData( trace, shape ) trace.HitAngle = 0 trace.StartPos = start trace.HitPos = hitPos trace.HitNormal = Norm(hitPos - pos) table.insert( traces, trace ) end end end end end end return traces end local function TsRayIntersection( start, dir, self ) local traces = {} local rayPlane = TsRayPlaneIntersection( start, dir, self ) local rayFace = TsRayFaceIntersection( start, dir, self ) local rayPolygon = TsRayPolygonIntersection( start, dir, self ) local rayBox = TsRayBoxIntersection( start, dir, self) local rayCircle = TsRayCircleIntersection( start, dir, self ) local raySphere = TsRaySphereIntersection( start, dir, self ) local rayEllipsoid = TsRayEllipsoidIntersection( start, dir, self ) table.Add(traces,rayPlane) table.Add(traces,rayFace) table.Add(traces,rayPolygon) table.Add(traces,rayBox) table.Add(traces,rayCircle) table.Add(traces,raySphere) table.Add(traces,rayEllipsoid) return traces end local function TsConeSphereIntersection( start, dir, angle, self ) local traces = {} for ply,plyGates in pairs(shapes) do for gate,gateShapes in pairs(plyGates) do local cont = false //If player is not same player who trace and e2's does not share with other players e2 if (ply ~= self.player and (sharing[ply][gate] ~= 2 or sharing[self.player][self.entity] ~= 2)) then cont = true end //If e2 is not same as e2 that trace and e2 does not share at all if (gate ~= self.entity and (sharing[ply][gate] == 0 or sharing[self.player][self.entity] == 0)) then cont = true end if (!cont) then for k,shape in pairs(gateShapes) do if (shape.Model == "sphere") then local pos, ang, normal, rotation if (shape.Parent) then pos, ang, normal, rotation = GetWorldData(shape) else pos, ang, normal, rotation = shape.Pos, shape.Ang, shape.Normal, shape.Rotation end local hitPos, hitAngle = ConeSphereIntersection( start, dir, pos, shape.Radius, angle ) if (hitPos) then local trace = {} FillTraceData( trace, shape ) trace.HitAngle = hitAngle trace.StartPos = start trace.HitPos = hitPos trace.HitNormal = Norm(hitPos - pos) table.insert( traces, trace ) end end end end end end return traces end /****************************** ***** Retrieval functions ***** ******************************/ local function SortByDistance( traces, pos ) table.sort(traces, function(a, b) return Distance(pos, a.HitPos) < Distance(pos, b.HitPos) end) return #traces end local function Count( traces ) return #traces end local function GetHit( traces, index ) if (traces[index]) then return traces[index].Hit end return 0 end local function GetHitAngle( traces, index ) if (traces[index]) then return traces[index].HitAngle end return 0 end local function GetHitIndex( traces, index ) if (traces[index]) then return traces[index].Index end return 0 end local function GetHitDistance( traces, index ) if (traces[index]) then local trace = traces[index] return Distance(trace.StartPos, trace.HitPos) end return 0 end local function GetHitRadius( traces, index ) if (traces[index]) then return traces[index].Radius end return 0 end local function GetHitRotation( traces, index ) if (traces[index]) then return traces[index].Rotation end return 0 end local function GetHitModel( traces, index ) if (traces[index]) then return traces[index].Model end return "" end local function GetHitPos( traces, index ) if (traces[index]) then return traces[index].HitPos end end local function GetHitOrigin( traces, index ) if (traces[index]) then return traces[index].Pos end end local function GetHitVertices( traces, index ) if (traces[index]) then return traces[index].Vertices end end local function GetHitAng( traces, index ) if (traces[index]) then return traces[index].Ang end end local function GetHitNormal( traces, index ) if (traces[index]) then return traces[index].HitNormal end end local function GetHitSize( traces, index ) if (traces[index]) then return traces[index].Size end end local function GetHitParent( traces, index ) if (traces[index]) then return traces[index].Parent end end local function GetHitEntity( traces, index ) if (traces[index]) then return traces[index].HitEntity end end local function GetHitOwner( traces, index ) if (traces[index]) then return traces[index].HitOwner end end /************************ ***** E2 Datatype ***** *************************/ registerType("tracedata", "xtd", {}, nil, nil, function(retval) if retval == nil then return end if type(retval) ~= "table" then error("Return value is not a table, but a "..type(retval).."!",0) end end, function(v) return type(v) ~= "table" end ) e2function tracedata operator=(tracedata lhs, tracedata rhs) local scope = self.Scopes[ args[4] ] scope[lhs] = rhs scope.vclk[lhs] = true return rhs end e2function number operator_is(tracedata walker) if walker then return 1 else return 0 end end /************************************ ***** E2 Intersection functions ***** ************************************/ e2function vector rayPlaneIntersection( vector start, vector dir, vector pos, vector normal ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) pos = E2VecToLuaVec( pos ) normal = E2VecToLuaVec( normal ) local hitPos = RayPlaneIntersection( start, dir, pos, normal ) return LuaVecToE2Vec( hitPos ) end e2function vector rayFaceIntersection( vector start, vector dir, vector pos, vector normal, vector size, number ang ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) pos = E2VecToLuaVec( pos ) normal = E2VecToLuaVec( normal ) size = E2VecToLuaVec( size ) local hitPos = RayFaceIntersection( start, dir, pos, normal, size, ang ) return LuaVecToE2Vec( hitPos ) end e2function vector rayPolygonIntersection( vector start, vector dir, vector vertex1, vector vertex2, vector vertex3 ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) vertex1 = E2VecToLuaVec( vertex1 ) vertex2 = E2VecToLuaVec( vertex2 ) vertex3 = E2VecToLuaVec( vertex3 ) local hitPos = RayPolygonIntersection( start, dir, {vertex1, vertex2, vertex3} ) return LuaVecToE2Vec( hitPos ) end e2function vector rayAABBoxIntersection( vector start, vector dir, vector pos, vector size ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) pos = E2VecToLuaVec( pos ) size = E2VecToLuaVec( size ) local hitPos = RayAABBoxIntersection( start, dir, pos, size ) return LuaVecToE2Vec( hitPos ) end e2function vector rayOBBoxIntersection( vector start, vector dir, vector pos, vector size, angle ang ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) pos = E2VecToLuaVec( pos ) size = E2VecToLuaVec( size ) ang = E2AngToLuaAng( ang ) local hitPos = RayOBBoxIntersection( start, dir, pos, size, ang ) return LuaVecToE2Vec( hitPos ) end e2function vector rayCircleIntersection( vector start, vector dir, vector pos, vector normal, number radius ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) pos = E2VecToLuaVec( pos ) normal = E2VecToLuaVec( normal ) local hitPos = RayCircleIntersection( start, dir, pos, normal, radius ) return LuaVecToE2Vec( hitPos ) end e2function vector raySphereIntersection( vector start, vector dir, vector pos, number radius ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) pos = E2VecToLuaVec( pos ) local hitPos = RaySphereIntersection( start, dir, pos, radius ) return LuaVecToE2Vec( hitPos ) end e2function vector rayAAEllipsoidIntersection( vector start, vector dir, vector pos, vector size ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) pos = E2VecToLuaVec( pos ) size = E2VecToLuaVec( size ) local hitPos = RayAAEllipsoidIntersection( start, dir, pos, size ) return LuaVecToE2Vec( hitPos ) end e2function vector rayOEllipsoidIntersection( vector start, vector dir, vector pos, vector size, angle ang ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) pos = E2VecToLuaVec( pos ) size = E2VecToLuaVec( size ) ang = E2AngToLuaAng( ang ) local hitPos = RayOEllipsoidIntersection( start, dir, pos, size, ang ) return LuaVecToE2Vec( hitPos ) end e2function vector coneSphereIntersection( vector start, vector dir, vector pos, number radius, number ang ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) pos = E2VecToLuaVec( pos ) local hitPos = ConeSphereIntersection( start, dir, pos, radius, ang ) return LuaVecToE2Vec( hitPos ) end /************************** ***** E2 * functions ***** **************************/ e2function number tsShapeCanCreate( ) return GetConVar("wire_shapes_max"):GetInt() - playerAmount[self.player] end e2function void tsShapeShare( number share ) return ShapeShare( share, self ) end e2function string tsShapeCreate( number index, string model, number radius, rotation, vector pos, vector normal, vector size, angle ang, vector vertex1, vector vertex2, vector vertex3 ) if (!ShapeCanCreate( self.player )) then return "Limit reached" end pos = E2VecToLuaVec( pos ) normal = E2VecToLuaVec( normal ) size = E2VecToLuaVec( size ) ang = E2AngToLuaAng( ang ) vertex1 = E2VecToLuaVec( vertex1 ) vertex2 = E2VecToLuaVec( vertex2 ) vertex3 = E2VecToLuaVec( vertex3 ) return ShapeCreate( index, model, radius, rotation, pos, normal, size, ang, vertices, self ) end e2function string tsShapeCreate( number index ) if (!ShapeCanCreate( self.player )) then return "Limit reached" end return ShapeCreate( index, "", 0, 0, Vector(0,0,0), Vector(0,0,0), Vector(0,0,0), Angle(0,0,0), {}, self ) end e2function string tsShapePolygon( number index, vector vertex1, vector vertex2, vector vertex3 ) if (!ShapeCanCreate( self.player )) then return "Limit reached" end vertex1 = E2VecToLuaVec( vertex1 ) vertex2 = E2VecToLuaVec( vertex2 ) vertex3 = E2VecToLuaVec( vertex3 ) return ShapeCreatePolygon( index, {vertex1, vertex2, vertex3}, self ) end e2function string tsShapeModel( number index, string model ) return ShapeModel( index, model, self ) end e2function string tsShapeRadius( number index, number radius ) return ShapeRadius( index, radius, self ) end e2function string tsShapeRotation( number index, number rotation ) return ShapeRotation( index, rotation, self ) end e2function string tsShapePos( number index, vector pos ) pos = E2VecToLuaVec( pos ) return ShapePos( index, pos, self ) end e2function string tsShapeVertices( number index, vector vertex1, vector vertex2, vector vertex3 ) vertex1 = E2VecToLuaVec( vertex1 ) vertex2 = E2VecToLuaVec( vertex2 ) vertex3 = E2VecToLuaVec( vertex3 ) return ShapeVertices( index, {vertex1, vertex2, vertex3}, self ) end e2function string tsShapeAng( number index, angle ang ) ang = E2AngToLuaAng( ang ) return ShapeAng( index, ang, self ) end e2function string tsShapeNormal( number index, vector normal ) normal = E2VecToLuaVec( normal ) return ShapeNormal( index, normal, self ) end e2function string tsShapeSize( number index, vector size ) size = E2VecToLuaVec( size ) return ShapeSize( index, size, self ) end e2function string tsShapeParent( number index, entity parent ) return ShapeParent( index, parent, self ) end e2function string tsShapeRemove( number index ) return ShapeRemove( index, self ) end e2function void tsShapeClear( ) return ShapeClear( self ) end /************************************** ***** E2 ts intersection functions ***** **************************************/ e2function tracedata tsRayPlaneIntersection( vector start, vector dir ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) local traces = TsRayPlaneIntersection( start, dir, self ) SortByDistance( traces, start ) return traces end e2function tracedata tsRayFaceIntersection( vector start, vector dir ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) local traces = TsRayFaceIntersection( start, dir, self ) SortByDistance( traces, start ) return traces end e2function tracedata tsRayPolygonIntersection( vector start, vector dir ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) local traces = TsRayPolygonIntersection( start, dir, self ) SortByDistance( traces, start ) return traces end e2function tracedata tsRayBoxIntersection( vector start, vector dir ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) local traces = TsRayBoxIntersection( start, dir, self ) SortByDistance( traces, start ) return traces end e2function tracedata tsRayCircleIntersection( vector start, vector dir ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) local traces = TsRayCircleIntersection( start, dir, self ) SortByDistance( traces, start ) return traces end e2function tracedata tsRaySphereIntersection( vector start, vector dir ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) local traces = TsRaySphereIntersection( start, dir, self ) SortByDistance( traces, start ) return traces end e2function tracedata tsRayEllipsoidIntersection( vector start, vector dir ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) local traces = TsRayEllipsoidIntersection( start, dir, self ) SortByDistance( traces, start ) return traces end e2function tracedata tsRayIntersection( vector start, vector dir ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) local traces = TsRayIntersection( start, dir, self ) SortByDistance( traces, start ) return traces end e2function tracedata tsConeSphereIntersection( vector start, vector dir, number angle ) start = E2VecToLuaVec( start ) dir = E2VecToLuaVec( dir ) local traces = TsConeSphereIntersection( start, dir, angle, self ) SortByDistance( traces, start ) return traces end /********************************* ***** E2 Retrieval functions ***** *********************************/ e2function number tracedata:sortByDistance( vector pos ) pos = E2VecToLuaVec( pos ) return SortByDistance( this, pos ) end e2function number tracedata:count( ) return Count( this ) end e2function number tracedata:hit( ) return GetHit( this, 1 ) end e2function number tracedata:hit( number index ) return GetHit( this, index ) end e2function number tracedata:hitAngle( ) return GetHitAngle( this, 1 ) end e2function number tracedata:hitAngle( number index ) return GetHitAngle( this, index ) end e2function number tracedata:index( ) return GetHitIndex( this, 1 ) end e2function number tracedata:index( number index ) return GetHitIndex( this, index ) end e2function number tracedata:distance( ) return GetHitDistance( this, 1 ) end e2function number tracedata:distance( number index ) return GetHitDistance( this, index ) end e2function number tracedata:radius( ) return GetHitRadius( this, 1 ) end e2function number tracedata:radius( number index ) return GetHitRadius( this, index ) end e2function number tracedata:rotation( ) return GetHitRotation( this, 1 ) end e2function number tracedata:rotation( number index ) return GetHitRotation( this, index ) end e2function string tracedata:model( ) return GetHitModel( this, 1 ) end e2function string tracedata:model( number index ) return GetHitModel( this, index ) end e2function vector tracedata:hitPos( ) local hitPos = GetHitPos( this, 1 ) return LuaVecToE2Vec(hitPos) end e2function vector tracedata:hitPos( number index ) local hitPos = GetHitPos( this, index ) return LuaVecToE2Vec(hitPos) end e2function vector tracedata:pos( ) local pos = GetHitOrigin( this, 1 ) return LuaVecToE2Vec(pos) end e2function vector tracedata:pos( number index ) local pos = GetHitOrigin( this, index ) return LuaVecToE2Vec(pos) end e2function vector tracedata:vertices( ) return GetHitVertices( this, 1 ) end e2function vector tracedata:vertices( number index ) return GetHitVertices( this, index ) end e2function angle tracedata:ang( ) local ang = GetHitAng( this, 1 ) return LuaAngToE2Ang(ang) end e2function angle tracedata:ang( number index ) local ang = GetHitAng( this, index ) return LuaAngToE2Ang(ang) end e2function vector tracedata:hitNormal( ) local hitNormal = GetHitNormal( this, 1 ) return LuaVecToE2Vec(hitNormal) end e2function vector tracedata:hitNormal( number index ) local hitNormal = GetHitNormal( this, index ) return LuaVecToE2Vec(hitNormal) end e2function vector tracedata:size( ) local size = GetHitSize( this, 1 ) return LuaVecToE2Vec(size) end e2function vector tracedata:size( number index ) local size = GetHitSize( this, index ) return LuaVecToE2Vec(size) end e2function entity tracedata:parent( ) return GetHitParent( this, 1 ) end e2function entity tracedata:parent( number index ) return GetHitParent( this, index ) end e2function entity tracedata:entity( ) return GetHitEntity( this, 1 ) end e2function entity tracedata:entity( number index ) return GetHitEntity( this, index ) end e2function entity tracedata:owner( ) return GetHitOwner( this, 1 ) end e2function entity tracedata:owner( number index ) return GetHitOwner( this, index ) end /******************* ***** Hooks ***** *******************/ //When an e2 is spawned registerCallback("construct",function(self) if (!sharing[self.player]) then shapes[self.player] = {} sharing[self.player] = {} playerAmount[self.player] = 0 end shapes[self.player][self.entity] = {} sharing[self.player][self.entity] = 0 end) //When an e2 is removed registerCallback("destruct",function(self) if sharing[self.player] and sharing[self.player][self.entity] then ShapeClear( self ) shapes[self.player][self.entity] = nil sharing[self.player][self.entity] = nil end end) //When player leaves, remove his shapes. hook.Add("PlayerDisconnected","playerdisconnected",function(ply) if (ply:IsValid() and ply:IsPlayer()) then shapes[ply] = nil sharing[ply] = nil playerAmount[ply] = nil end end)
gpl-3.0
nesstea/darkstar
scripts/globals/effects/addendum_black.lua
65
2045
----------------------------------- -- -- -- ----------------------------------- ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:recalculateAbilitiesTable(); local bonus = effect:getPower(); local helix = effect:getSubPower(); target:addMod(MOD_BLACK_MAGIC_COST, -bonus); target:addMod(MOD_BLACK_MAGIC_CAST, -bonus); target:addMod(MOD_BLACK_MAGIC_RECAST, -bonus); if not (target:hasStatusEffect(EFFECT_TABULA_RASA)) then target:addMod(MOD_BLACK_MAGIC_COST, -10); target:addMod(MOD_BLACK_MAGIC_CAST, -10); target:addMod(MOD_BLACK_MAGIC_RECAST, -10); target:addMod(MOD_WHITE_MAGIC_COST, 20); target:addMod(MOD_WHITE_MAGIC_CAST, 20); target:addMod(MOD_WHITE_MAGIC_RECAST, 20); target:addMod(MOD_HELIX_EFFECT, helix); target:addMod(MOD_HELIX_DURATION, 72); end target:recalculateSkillsTable(); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:recalculateAbilitiesTable(); local bonus = effect:getPower(); local helix = effect:getSubPower(); target:delMod(MOD_BLACK_MAGIC_COST, -bonus); target:delMod(MOD_BLACK_MAGIC_CAST, -bonus); target:delMod(MOD_BLACK_MAGIC_RECAST, -bonus); if not (target:hasStatusEffect(EFFECT_TABULA_RASA)) then target:delMod(MOD_BLACK_MAGIC_COST, -10); target:delMod(MOD_BLACK_MAGIC_CAST, -10); target:delMod(MOD_BLACK_MAGIC_RECAST, -10); target:delMod(MOD_WHITE_MAGIC_COST, 20); target:delMod(MOD_WHITE_MAGIC_CAST, 20); target:delMod(MOD_WHITE_MAGIC_RECAST, 20); target:delMod(MOD_HELIX_EFFECT, helix); target:delMod(MOD_HELIX_DURATION, 72); end target:recalculateSkillsTable(); end;
gpl-3.0
nesstea/darkstar
scripts/globals/effects/dark_arts.lua
65
2045
----------------------------------- -- -- -- ----------------------------------- ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:recalculateAbilitiesTable(); local bonus = effect:getPower(); local helix = effect:getSubPower(); target:addMod(MOD_BLACK_MAGIC_COST, -bonus); target:addMod(MOD_BLACK_MAGIC_CAST, -bonus); target:addMod(MOD_BLACK_MAGIC_RECAST, -bonus); if not (target:hasStatusEffect(EFFECT_TABULA_RASA)) then target:addMod(MOD_BLACK_MAGIC_COST, -10); target:addMod(MOD_BLACK_MAGIC_CAST, -10); target:addMod(MOD_BLACK_MAGIC_RECAST, -10); target:addMod(MOD_WHITE_MAGIC_COST, 20); target:addMod(MOD_WHITE_MAGIC_CAST, 20); target:addMod(MOD_WHITE_MAGIC_RECAST, 20); target:addMod(MOD_HELIX_EFFECT, helix); target:addMod(MOD_HELIX_DURATION, 72); end target:recalculateSkillsTable(); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:recalculateAbilitiesTable(); local bonus = effect:getPower(); local helix = effect:getSubPower(); target:delMod(MOD_BLACK_MAGIC_COST, -bonus); target:delMod(MOD_BLACK_MAGIC_CAST, -bonus); target:delMod(MOD_BLACK_MAGIC_RECAST, -bonus); if not (target:hasStatusEffect(EFFECT_TABULA_RASA)) then target:delMod(MOD_BLACK_MAGIC_COST, -10); target:delMod(MOD_BLACK_MAGIC_CAST, -10); target:delMod(MOD_BLACK_MAGIC_RECAST, -10); target:delMod(MOD_WHITE_MAGIC_COST, 20); target:delMod(MOD_WHITE_MAGIC_CAST, 20); target:delMod(MOD_WHITE_MAGIC_RECAST, 20); target:delMod(MOD_HELIX_EFFECT, helix); target:delMod(MOD_HELIX_DURATION, 72); end target:recalculateSkillsTable(); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Mhoti_Pyiahrs.lua
13
1060
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Mhoti Pyiahrs -- Type: Allegiance -- @zone: 94 -- @pos 6.356 -2 26.677 -- -- 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(0x0002); 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
nesstea/darkstar
scripts/globals/weaponskills/hot_shot.lua
11
1351
----------------------------------- -- Hot Shot -- Marksmanship weapon skill -- Skill Level: 5 -- Deals fire elemental damage to enemy. -- Aligned with the Flame Gorget & Light Gorget. -- Aligned with the Flame Belt & Light Belt. -- Element: Fire -- Modifiers: AGI:30% -- 100%TP 200%TP 300%TP -- 0.50 0.75 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary) local params = {}; params.numHits = 1; params.ftp100 = 0.5; params.ftp200 = 0.75; params.ftp300 = 1; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp200 = 1.55; params.ftp300 = 2.1; params.agi_wsc = 0.7; end local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
nesstea/darkstar
scripts/zones/Cloister_of_Frost/bcnms/class_reunion.lua
30
1515
----------------------------------- -- Area: Cloister of Tremors -- BCNM: Class Reunion ----------------------------------- package.loaded["scripts/zones/Cloister_of_Frost/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Cloister_of_Frost/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 player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,2); 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 and player:getVar("ClassReunionProgress") == 5) then player:setVar("ClassReunionProgress",6); end; end;
gpl-3.0
nesstea/darkstar
scripts/globals/spells/bluemagic/saline_coat.lua
26
1336
----------------------------------------- -- Spell: Saline Coat -- Enhances magic defense -- Spell cost: 66 MP -- Monster Type: Luminians -- Spell Type: Magical (Light) -- Blue Magic Points: 3 -- Stat Bonus: VIT+2, AGI+2, MP+10 -- Level: 72 -- Casting Time: 3 seconds -- Recast Time: 60 seconds -- Duration: 60 seconds -- -- Combos: Defense Bonus ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_MAGIC_DEF_BOOST; local power = 40; local duration = 60; 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
magnetophon/.dot
common/.config/mpv/scripts/reload.lua
1
4509
-- reload.lua -- -- When an online video is stuck buffering or got very slow CDN -- source, restarting often helps. This script provides automatic -- reloading of videos that doesn't have buffering progress for some -- time while keeping the current time position. It also adds `Ctrl+r` -- keybinding to reload video manually. -- -- SETTINGS -- -- To override default setting put `lua-settings/reload.conf` file in -- mpv user folder, on linux it is `~/.config/mpv`. NOTE: config file -- name should match the name of the script. -- -- Default `reload.conf` settings: -- -- ``` -- # enable automatic reload on timeout -- paused_for_cache_timer_enabled=yes -- # checking paused_for_cache property interval in seconds, -- # can not be less than 0.05 (50 ms) -- paused_for_cache_timer_interval=1 -- # time in seconds to wait until reload -- paused_for_cache_timer_timeout=10 -- -- # keybinding to reload stream from current time position -- # you can disable keybinding by setting it to empty value -- # reload_key_binding= -- reload_key_binding=Ctrl+r -- ``` -- -- DEBUGGING -- -- Debug messages will be printed to stdout with mpv command line option -- `--msg-level='reload=debug'` local msg = require 'mp.msg' local options = require 'mp.options' local utils = require 'mp.utils' local settings = { paused_for_cache_timer_enabled = true, paused_for_cache_timer_interval = 1, paused_for_cache_timer_timeout = 10, reload_key_binding = "Ctrl+r", } local paused_for_cache_seconds = 0 local paused_for_cache_timer = nil function read_settings() options.read_options(settings, mp.get_script_name()) msg.debug(utils.to_string(settings)) end function debug_info(event) msg.debug("event =", utils.to_string(event)) msg.debug("path =", mp.get_property("path")) msg.debug("time-pos =", mp.get_property("time-pos")) msg.debug("paused-for-cache =", mp.get_property("paused-for-cache")) msg.debug("stream-path =", mp.get_property("stream-path")) msg.debug("stream-pos =", mp.get_property("stream-pos")) msg.debug("stream-end =", mp.get_property("stream-end")) msg.debug("duration =", mp.get_property("duration")) msg.debug("seekable =", mp.get_property("seekable")) end function reload_time_pos(path, time_pos) msg.debug("reload_time_pos; time_pos = ", time_pos) mp.commandv("loadfile", path, "replace", "start=+" .. time_pos) end function reload(path) msg.debug("reload") mp.commandv("loadfile", path, "replace") end function reload_resume() local path = mp.get_property("path") local time_pos = mp.get_property("time-pos") -- Tries to determine live stream vs. pre-recordered VOD. -- VOD has fixed start position. When reloading vod, to keep current -- time position we should provide offset from the start. -- Stream doesn't have fixed start. Decent choice would be to reload -- stream from it's current 'live' positon. So we don't pass the offset when -- reloading streams. if mp.get_property_native("duration") then msg.info("reloading video from", time_pos, "second") reload_time_pos(path, time_pos) else msg.info("reloading stream") reload(path) end end function reset_timer() msg.debug("reset_timer; paused_for_cache_seconds =", paused_for_cache_seconds) if paused_for_cache_timer then paused_for_cache_timer:kill() paused_for_cache_timer = nil paused_for_cache_seconds = 0 end end function start_timer(interval_seconds, timeout_seconds) msg.debug("start_timer") paused_for_cache_timer = mp.add_periodic_timer( interval_seconds, function() paused_for_cache_seconds = paused_for_cache_seconds + interval_seconds if paused_for_cache_seconds >= timeout_seconds then reset_timer() reload_resume() end end) end function paused_for_cache_handler(property, is_paused) if is_paused then if not paused_for_cache_timer then start_timer( settings.paused_for_cache_timer_interval, settings.paused_for_cache_timer_timeout) end else if paused_for_cache_timer then reset_timer() end end end -- main read_settings() if settings.reload_key_binding ~= "" then mp.add_key_binding(settings.reload_key_binding, "reload_resume", reload_resume) end if settings.paused_for_cache_timer_enabled then mp.observe_property("paused-for-cache", "bool", paused_for_cache_handler) end -- mp.register_event("file-loaded", debug_info)
gpl-2.0
FailcoderAddons/supervillain-ui
SVUI_Auras/Loader.lua
2
8121
--[[ ########################################################## S V U I By: Failcoder ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --GLOBAL NAMESPACE local _G = _G; --LUA local unpack = _G.unpack; local select = _G.select; local assert = _G.assert; local SV = _G["SVUI"]; local L = SV.L local MOD = SV:NewModule(...); local Schema = MOD.Schema; MOD.media = {} MOD.media.hyperAuraIcons = { [[Interface\Addons\SVUI_Auras\assets\AURA-STATS]], [[Interface\Addons\SVUI_Auras\assets\AURA-HEART]], [[Interface\Addons\SVUI_Auras\assets\AURA-POWER]], [[Interface\Addons\SVUI_Auras\assets\AURA-HASTE]], [[Interface\Addons\SVUI_Auras\assets\AURA-SPELL]], [[Interface\Addons\SVUI_Auras\assets\AURA-CRIT]], [[Interface\Addons\SVUI_Auras\assets\AURA-MASTERY]], [[Interface\Addons\SVUI_Auras\assets\AURA-MULTISTRIKE]], [[Interface\Addons\SVUI_Auras\assets\AURA-VERSATILITY]] }; -- local GENERAL_PROCS = {10060,119032,121557,6346,114255}; -- local DISC_PROCS = {81700,109964,81782,33206}; -- local HOLY_PROCS = {20711,47788,63735}; -- local SHADOW_PROCS = {47585,15286,132573,158831}; SV.defaults.Filters["Procs"] = {}; SV.defaults[Schema] = { ["aurasEnabled"] = true, ["hyperBuffsEnabled"] = true, ["hyperBuffsFiltered"] = true, ["font"] = "SVUI Number Font", ["fontSize"] = 12, ["fontOutline"] = "THINOUTLINE", ["countOffsetV"] = 0, ["countOffsetH"] = 0, ["timeOffsetV"] = -4, ["timeOffsetH"] = 0, ["fadeBy"] = 5, ["procsEnabled"] = true, ["procSize"] = 40, ["buffs"] = { ["showBy"] = "LEFT_DOWN", ["wrapAfter"] = 12, ["maxWraps"] = 3, ["wrapXOffset"] = 6, ["wrapYOffset"] = 16, ["sortMethod"] = "TIME", ["sortDir"] = "-", ["isolate"] = 1, ["size"] = 32, }, ["debuffs"] = { ["showBy"] = "LEFT_DOWN", ["wrapAfter"] = 12, ["maxWraps"] = 1, ["wrapXOffset"] = 6, ["wrapYOffset"] = 16, ["sortMethod"] = "TIME", ["sortDir"] = "-", ["isolate"] = 1, ["size"] = 32, }, }; local auraOptionsTemplate = { scaleGroup = { order = 1, guiInline = true, type = "group", name = L["Scale Options"], args = { size = { type = "range", name = L["Size"], desc = L["Set the size of the individual auras."], min = 16, max = 60, step = 2, order = 1 }, wrapXOffset = { order = 2, type = "range", name = L["Horizontal Spacing"], min = 0, max = 50, step = 1 }, wrapYOffset = { order = 3, type = "range", name = L["Vertical Spacing"], min = 0, max = 50, step = 1 }, } }, layoutGroup = { order = 2, guiInline = true, type = "group", name = L["Directional Options"], args = { showBy = { type = "select", order = 1, name = L["Growth Direction"], desc = L["The direction the auras will grow and then the direction they will grow after they reach the wrap after limit."], values = { DOWN_RIGHT = format(L["%s and then %s"], L["Down"], L["Right"]), DOWN_LEFT = format(L["%s and then %s"], L["Down"], L["Left"]), UP_RIGHT = format(L["%s and then %s"], L["Up"], L["Right"]), UP_LEFT = format(L["%s and then %s"], L["Up"], L["Left"]), RIGHT_DOWN = format(L["%s and then %s"], L["Right"], L["Down"]), RIGHT_UP = format(L["%s and then %s"], L["Right"], L["Up"]), LEFT_DOWN = format(L["%s and then %s"], L["Left"], L["Down"]), LEFT_UP = format(L["%s and then %s"], L["Left"], L["Up"]) } }, wrapAfter = { type = "range", order = 2, name = L["Wrap After"], desc = L["Begin a new row or column after this many auras."], min = 1, max = 32, step = 1 }, maxWraps = { name = L["Max Wraps"], order = 3, desc = L["Limit the number of rows or columns."], type = "range", min = 1, max = 32, step = 1 }, } }, sortGroup = { order = 1, guiInline = true, type = "group", name = L["Sorting Options"], args = { sortMethod = { order = 1, name = L["Sort Method"], desc = L["Defines how the group is sorted."], type = "select", values = { ["INDEX"] = L["Index"], ["TIME"] = L["Time"], ["NAME"] = L["Name"] } }, sortDir = { order = 2, name = L["Sort Direction"], desc = L["Defines the sort order of the selected sort method."], type = "select", values = { ["+"] = L["Ascending"], ["-"] = L["Descending"] } }, isolate = { order = 3, name = L["Seperate"], desc = L["Indicate whether buffs you cast yourself should be separated before or after."], type = "select", values = { [-1] = L["Other's First"], [0] = L["No Sorting"], [1] = L["Your Auras First"] } } } }, } function MOD:LoadOptions() SV.Options.args[Schema] = { type = "group", name = Schema, childGroups = "tab", get = function(a)return SV.db[Schema][a[#a]] end, set = function(a,b) MOD:ChangeDBVar(b,a[#a]); MOD:UpdateAuraHeader(SVUI_PlayerBuffs, "buffs") MOD:UpdateAuraHeader(SVUI_PlayerDebuffs, "debuffs") end, args = { intro = { order = 1, width = 'full', type = "description", name = L["AURAS_DESC"] }, aurasEnabled = { order = 2, type = "toggle", name = L["Auras Enabled"], get = function(a) return SV.db[Schema].aurasEnabled end, set = function(a,b)SV.db[Schema].aurasEnabled = b;SV:StaticPopup_Show("RL_CLIENT") end }, hyperBuffsEnabled = { order = 3, type = "toggle", name = L["Hyper Auras Enabled"], get = function(a)return SV.db[Schema].hyperBuffsEnabled end, set = function(a,b)SV.db[Schema].hyperBuffsEnabled = b;SV:StaticPopup_Show("RL_CLIENT")end }, hyperBuffsFiltered = { order = 4, type = "toggle", name = L["Hyper Auras Filtered"], get = function(a)return SV.db[Schema].hyperBuffsFiltered end, set = function(a,b)SV.db[Schema].hyperBuffsFiltered = b;SV:StaticPopup_Show("RL_CLIENT")end }, procsEnabled = { order = 5, type = "toggle", name = L["Proc Watch Enabled"], get = function(a) return SV.db[Schema].procsEnabled end, set = function(a,b)SV.db[Schema].procsEnabled = b;SV:StaticPopup_Show("RL_CLIENT") end }, auraGroups = { order = 6, type = "group", name = L["Options"], childGroups = "tree", disabled = function() return not SV.db[Schema].aurasEnabled end, args = { common = { order = 10, type = "group", name = L["General"], args = { fadeBy = { type = "range", name = L["Fade Threshold"], desc = L["Threshold before text changes red, goes into decimal form, and the icon will fade. Set to -1 to disable."], min = -1, max = 30, step = 1, order = 1 }, timeOffsetH = { order = 2, name = L["Time xOffset"], type = "range", min = -60, max = 60, step = 1 }, timeOffsetV = { order = 3, name = L["Time yOffset"], type = "range", min = -60, max = 60, step = 1 }, countOffsetH = { order = 4, name = L["Count xOffset"], type = "range", min = -60, max = 60, step = 1 }, countOffsetV = { order = 5, name = L["Count yOffset"], type = "range", min = -60, max = 60, step = 1 } } }, buffs = { order = 30, type = "group", name = L["Buffs"], get = function(b)return SV.db[Schema].buffs[b[#b]]end, set = function(a,b)MOD:ChangeDBVar(b,a[#a],"buffs");MOD:UpdateAuraHeader(SVUI_PlayerBuffs, "buffs")end, args = auraOptionsTemplate }, debuffs = { order = 40, type = "group", name = L["Debuffs"], get = function(b)return SV.db[Schema].debuffs[b[#b]]end, set = function(a,b)MOD:ChangeDBVar(b,a[#a],"debuffs");MOD:UpdateAuraHeader(SVUI_PlayerDebuffs, "debuffs")end, args = auraOptionsTemplate } } }, } } end
mit
UnfortunateFruit/darkstar
scripts/globals/items/strip_of_smoked_mackerel.lua
36
1154
----------------------------------------- -- ID: 5943 -- Item: Strip of Smoked Mackerel -- Food Effect: 30Min, All Races ----------------------------------------- -- Agility 4 -- Vitality -3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5943); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 4); target:addMod(MOD_VIT, -3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 4); target:delMod(MOD_VIT, -3); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Lufaise_Meadows/mobs/Colorful_Leshy.lua
8
1886
----------------------------------- -- Area: Lufaise Meadows -- MOB: Colorful Leshy ----------------------------------- ----------------------------------- -- onMobSpawn ----------------------------------- function onMobSpawn(mob) local Defoliate_Leshy = 16875763; GetMobByID(Defoliate_Leshy):setLocalVar("1", os.time() + math.random((43200), (86400))); end; ----------------------------------- -- onMobRoam ----------------------------------- function onMobRoam(mob) local Defoliate_Leshy = 16875763; local Defoliate_Leshy_PH = 0; local Defoliate_Leshy_PH_Table = { 16875762 }; local Defoliate_Leshy_ToD = GetMobByID(Defoliate_Leshy):getLocalVar("1"); if (Defoliate_Leshy_ToD <= os.time()) then Defoliate_Leshy_PH = math.random((0), (table.getn(Defoliate_Leshy_PH_Table))); if (Defoliate_Leshy_PH_Table[Defoliate_Leshy_PH] ~= nil) then if (GetMobAction(Defoliate_Leshy) == 0) then SetServerVariable("Defoliate_Leshy_PH", Defoliate_Leshy_PH_Table[Defoliate_Leshy_PH]); DeterMob(Defoliate_Leshy_PH_Table[Defoliate_Leshy_PH], true); DeterMob(Defoliate_Leshy, false); DespawnMob(Defoliate_Leshy_PH_Table[Defoliate_Leshy_PH]); SpawnMob(Defoliate_Leshy, "", 0); end end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, ally) local Colorful_Leshy = 16875762; local Colorful_Leshy_PH = GetServerVariable("Colorful_Leshy_PH"); GetMobByID(Colorful_Leshy):setLocalVar("1", os.time() + math.random((43200), (86400))); SetServerVariable("Colorful_Leshy_PH", 0); DeterMob(Colorful_Leshy, true); DeterMob(Colorful_Leshy_PH, false); SpawnMob(Colorful_Leshy_PH, "", GetMobRespawnTime(Colorful_Leshy_PH)); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/shiranui.lua
15
1514
----------------------------------------- -- ID: 17774 -- Item: Shiranui -- Additional Effect: Light Damage (night time only) ----------------------------------------- require("scripts/globals/status"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 35; if (VanadielHour()>=18 or VanadielHour()<7) then if (target:getMainLvl() > player:getMainLvl()) then chance = chance - 5 * (target:getMainLvl() - player:getMainLvl()) chance = utils.clamp(chance, 5, 95); end if (math.random(0,99) >= chance) then return 0,0,0; else local diff = player:getStat(MOD_INT) - target:getStat(MOD_INT); if (diff > 20) then diff = 20 + (diff - 20) / 2; end local lightDamage = diff + (player:getMainLvl() - target:getMainLvl()) + damage/2; local params = {}; params.bonusmab = 0; params.includemab = true; lightDamage = addBonusesAbility(player, ELE_LIGHT, target, lightDamage, params); lightDamage = lightDamage * applyResistanceAddEffect(player,target,ELE_LIGHT,0); lightDamage = adjustForTarget(target,lightDamage,ELE_LIGHT); if (lightDamage < 0) then lightDamage = 0 end lightDamage = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,lightDamage); if (lightDamage >35) then lightDamage = 35; end return SUBEFFECT_LIGHT_DAMAGE, 163, lightDamage; end end return 0,0,0; end;
gpl-3.0
Mashape/kong
kong/api/endpoints.lua
1
21702
local Errors = require "kong.db.errors" local utils = require "kong.tools.utils" local arguments = require "kong.api.arguments" local app_helpers = require "lapis.application" local kong = kong local escape_uri = ngx.escape_uri local unescape_uri = ngx.unescape_uri local tonumber = tonumber local tostring = tostring local select = select local pairs = pairs local null = ngx.null local type = type local fmt = string.format local concat = table.concat local re_match = ngx.re.match local split = utils.split -- error codes http status codes local ERRORS_HTTP_CODES = { [Errors.codes.INVALID_PRIMARY_KEY] = 400, [Errors.codes.SCHEMA_VIOLATION] = 400, [Errors.codes.PRIMARY_KEY_VIOLATION] = 400, [Errors.codes.FOREIGN_KEY_VIOLATION] = 400, [Errors.codes.UNIQUE_VIOLATION] = 409, [Errors.codes.NOT_FOUND] = 404, [Errors.codes.INVALID_OFFSET] = 400, [Errors.codes.DATABASE_ERROR] = 500, [Errors.codes.INVALID_SIZE] = 400, [Errors.codes.INVALID_UNIQUE] = 400, [Errors.codes.INVALID_OPTIONS] = 400, [Errors.codes.OPERATION_UNSUPPORTED] = 405, [Errors.codes.FOREIGN_KEYS_UNRESOLVED] = 400, } local function get_message(default, ...) local message local n = select("#", ...) if n > 0 then if n == 1 then local arg = select(1, ...) if type(arg) == "table" then message = arg elseif arg ~= nil then message = tostring(arg) end else message = {} for i = 1, n do local arg = select(i, ...) message[i] = tostring(arg) end message = concat(message) end end if not message then message = default end if type(message) == "string" then message = { message = message } end return message end local function ok(...) return kong.response.exit(200, get_message(nil, ...)) end local function created(...) return kong.response.exit(201, get_message(nil, ...)) end local function no_content() return kong.response.exit(204) end local function not_found(...) return kong.response.exit(404, get_message("Not found", ...)) end local function method_not_allowed(...) return kong.response.exit(405, get_message("Method not allowed", ...)) end local function unexpected(...) return kong.response.exit(500, get_message("An unexpected error occurred", ...)) end local function handle_error(err_t) if type(err_t) ~= "table" then kong.log.err(err_t) return unexpected() end if err_t.strategy then err_t.strategy = nil end local status = ERRORS_HTTP_CODES[err_t.code] if not status or status == 500 then return app_helpers.yield_error(err_t) end if err_t.code == Errors.codes.OPERATION_UNSUPPORTED then return kong.response.exit(status, err_t) end return kong.response.exit(status, utils.get_default_exit_body(status, err_t)) end local function extract_options(args, schema, context) local options = { nulls = true, } if args and schema and context then if schema.ttl == true and args.ttl ~= nil and (context == "insert" or context == "update" or context == "upsert") then options.ttl = args.ttl args.ttl = nil end if schema.fields.tags and args.tags ~= nil and context == "page" then local tags = args.tags if type(tags) == "table" then tags = tags[1] end if re_match(tags, [=[^([a-zA-Z0-9\.\-\_~]+(?:,|$))+$]=], 'jo') then -- 'a,b,c' or 'a' options.tags_cond = 'and' options.tags = split(tags, ',') elseif re_match(tags, [=[^([a-zA-Z0-9\.\-\_~]+(?:/|$))+$]=], 'jo') then -- 'a/b/c' options.tags_cond = 'or' options.tags = split(tags, '/') else options.tags = tags -- not setting tags_cond since we can't determine the cond -- will raise an error in db/dao/init.lua:validate_options_value end args.tags = nil end end return options end local function get_page_size(args) local size = args.size if size ~= nil then size = tonumber(size) if size == nil then return nil, "size must be a number" end return size end end local function query_entity(context, self, db, schema, method) local is_insert = context == "insert" local is_update = context == "update" or context == "upsert" local args if is_update or is_insert then args = self.args.post else args = self.args.uri end local opts = extract_options(args, schema, context) local dao = db[schema.name] if is_insert then return dao[method or context](dao, args, opts) end if context == "page" then local size, err = get_page_size(args) if err then return nil, err, db[schema.name].errors:invalid_size(err) end if not method then return dao[context](dao, size, args.offset, opts) end return dao[method](dao, self.params[schema.name], size, args.offset, opts) end local key = self.params[schema.name] if key then if type(key) ~= "table" then if type(key) == "string" then key = { id = unescape_uri(key) } else key = { id = key } end end if key.id and not utils.is_valid_uuid(key.id) then local endpoint_key = schema.endpoint_key if endpoint_key then local field = schema.fields[endpoint_key] local inferred_value = arguments.infer_value(key.id, field) if is_update then return dao[method or context .. "_by_" .. endpoint_key](dao, inferred_value, args, opts) end return dao[method or context .. "_by_" .. endpoint_key](dao, inferred_value, opts) end end end if is_update then return dao[method or context](dao, key, args, opts) end return dao[method or context](dao, key, opts) end local function select_entity(...) return query_entity("select", ...) end local function update_entity(...) return query_entity("update", ...) end local function upsert_entity(...) return query_entity("upsert", ...) end local function delete_entity(...) return query_entity("delete", ...) end local function insert_entity(...) return query_entity("insert", ...) end local function page_collection(...) return query_entity("page", ...) end -- Generates admin api get collection endpoint functions -- -- Examples: -- -- /routes -- /services/:services/routes -- -- and -- -- /services local function get_collection_endpoint(schema, foreign_schema, foreign_field_name, method) return not foreign_schema and function(self, db, helpers) local next_page_tags = "" local args = self.args.uri if args.tags then next_page_tags = "&tags=" .. (type(args.tags) == "table" and args.tags[1] or args.tags) end local data, _, err_t, offset = page_collection(self, db, schema, method) if err_t then return handle_error(err_t) end local next_page = offset and fmt("/%s?offset=%s%s", schema.admin_api_name or schema.name, escape_uri(offset), next_page_tags) or null return ok { data = data, offset = offset, next = next_page, } end or function(self, db, helpers) local foreign_entity, _, err_t = select_entity(self, db, foreign_schema) if err_t then return handle_error(err_t) end if not foreign_entity then return not_found() end self.params[schema.name] = foreign_schema:extract_pk_values(foreign_entity) local method = method or "page_for_" .. foreign_field_name local data, _, err_t, offset = page_collection(self, db, schema, method) if err_t then return handle_error(err_t) end local foreign_key = self.params[foreign_schema.name] local next_page = offset and fmt("/%s/%s/%s?offset=%s", foreign_schema.admin_api_name or foreign_schema.name, foreign_key, schema.admin_api_nested_name or schema.admin_api_name or schema.name, escape_uri(offset)) or null return ok { data = data, offset = offset, next = next_page, } end end -- Generates admin api post collection endpoint functions -- -- Examples: -- -- /routes -- /services/:services/routes -- -- and -- -- /services local function post_collection_endpoint(schema, foreign_schema, foreign_field_name, method) return function(self, db, helpers, post_process) if foreign_schema then local foreign_entity, _, err_t = select_entity(self, db, foreign_schema) if err_t then return handle_error(err_t) end if not foreign_entity then return not_found() end self.args.post[foreign_field_name] = foreign_schema:extract_pk_values(foreign_entity) end local entity, _, err_t = insert_entity(self, db, schema, method) if err_t then return handle_error(err_t) end if post_process then entity, _, err_t = post_process(entity) if err_t then return handle_error(err_t) end end return created(entity) end end -- Generates admin api get entity endpoint functions -- -- Examples: -- -- /routes/:routes -- /routes/:routes/service -- -- and -- -- /services/:services -- /services/:services/routes/:routes local function get_entity_endpoint(schema, foreign_schema, foreign_field_name, method, is_foreign_entity_endpoint) return function(self, db, helpers) local entity, _, err_t if foreign_schema then entity, _, err_t = select_entity(self, db, schema) else entity, _, err_t = select_entity(self, db, schema, method) end if err_t then return handle_error(err_t) end if not entity then return not_found() end if foreign_schema then local pk if is_foreign_entity_endpoint then pk = entity[foreign_field_name] if not pk or pk == null then return not_found() end self.params[foreign_schema.name] = pk else pk = schema:extract_pk_values(entity) end entity, _, err_t = select_entity(self, db, foreign_schema, method) if err_t then return handle_error(err_t) end if not entity then return not_found() end if not is_foreign_entity_endpoint then local fk = entity[foreign_field_name] if not fk or fk == null then return not_found() end fk = schema:extract_pk_values(fk) for k, v in pairs(pk) do if fk[k] ~= v then return not_found() end end end end return ok(entity) end end -- Generates admin api put entity endpoint functions -- -- Examples: -- -- /routes/:routes -- /routes/:routes/service -- -- and -- -- /services/:services -- /services/:services/routes/:routes local function put_entity_endpoint(schema, foreign_schema, foreign_field_name, method, is_foreign_entity_endpoint) return not foreign_schema and function(self, db, helpers) local entity, _, err_t = upsert_entity(self, db, schema, method) if err_t then return handle_error(err_t) end if not entity then return not_found() end return ok(entity) end or function(self, db, helpers) local entity, _, err_t = select_entity(self, db, schema) if err_t then return handle_error(err_t) end if not entity then return not_found() end local associate if is_foreign_entity_endpoint then local pk = entity[foreign_field_name] if pk and pk ~= null then self.params[foreign_schema.name] = pk else associate = true self.params[foreign_schema.name] = utils.uuid() end else self.args.post[foreign_field_name] = schema:extract_pk_values(entity) end local foreign_entity foreign_entity, _, err_t = upsert_entity(self, db, foreign_schema, method) if err_t then return handle_error(err_t) end if not foreign_entity then return not_found() end if associate then local pk = schema:extract_pk_values(entity) local data = { [foreign_field_name] = foreign_schema:extract_pk_values(foreign_entity) } _, _, err_t = db[schema.name]:update(pk, data) if err_t then return handle_error(err_t) end --if not entity then -- route was deleted after service was created, -- so we cannot associate anymore. perhaps not -- worth it to handle, the service on the other -- hand was updates just fine. --end end return ok(foreign_entity) end end -- Generates admin api patch entity endpoint functions -- -- Examples: -- -- /routes/:routes -- /routes/:routes/service -- -- and -- -- /services/:services -- /services/:services/routes/:routes local function patch_entity_endpoint(schema, foreign_schema, foreign_field_name, method, is_foreign_entity_endpoint) return not foreign_schema and function(self, db, helpers) local entity, _, err_t = update_entity(self, db, schema, method) if err_t then return handle_error(err_t) end if not entity then return not_found() end return ok(entity) end or function(self, db, helpers) local entity, _, err_t = select_entity(self, db, schema) if err_t then return handle_error(err_t) end if not entity then return not_found() end if is_foreign_entity_endpoint then local pk = entity[foreign_field_name] if not pk or pk == null then return not_found() end self.params[foreign_schema.name] = pk else if not self.args.post[foreign_field_name] then self.args.post[foreign_field_name] = schema:extract_pk_values(entity) end local pk = schema:extract_pk_values(entity) entity, _, err_t = select_entity(self, db, foreign_schema) if err_t then return handle_error(err_t) end if not entity then return not_found() end local fk = entity[foreign_field_name] if not fk or fk == null then return not_found() end fk = schema:extract_pk_values(fk) for k, v in pairs(pk) do if fk[k] ~= v then return not_found() end end end entity, _, err_t = update_entity(self, db, foreign_schema, method) if err_t then return handle_error(err_t) end if not entity then return not_found() end return ok(entity) end end -- Generates admin api delete entity endpoint functions -- -- Examples: -- -- /routes/:routes -- /routes/:routes/service -- -- and -- -- /services/:services -- /services/:services/routes/:routes local function delete_entity_endpoint(schema, foreign_schema, foreign_field_name, method, is_foreign_entity_endpoint) return not foreign_schema and function(self, db, helpers) local _, _, err_t = delete_entity(self, db, schema, method) if err_t then return handle_error(err_t) end return no_content() end or function(self, db, helpers) local entity, _, err_t = select_entity(self, db, schema) if err_t then return handle_error(err_t) end if is_foreign_entity_endpoint then local id = entity and entity[foreign_field_name] if not id or id == null then return not_found() end return method_not_allowed() end local pk = schema:extract_pk_values(entity) entity, _, err_t = select_entity(self, db, foreign_schema) if err_t then return handle_error(err_t) end if not entity then return not_found() end local fk = entity[foreign_field_name] if not fk or fk == null then return not_found() end fk = schema:extract_pk_values(fk) for k, v in pairs(pk) do if fk[k] ~= v then return not_found() end end local _, _, err_t = delete_entity(self, db, foreign_schema, method) if err_t then return handle_error(err_t) end return no_content() end end -- Generates admin api collection endpoint functions -- -- Examples: -- -- /routes -- /services/:services/routes -- -- and -- -- /services local function generate_collection_endpoints(endpoints, schema, foreign_schema, foreign_field_name) local collection_path if foreign_schema then collection_path = fmt("/%s/:%s/%s", foreign_schema.admin_api_name or foreign_schema.name, foreign_schema.name, schema.admin_api_nested_name or schema.admin_api_name or schema.name) else collection_path = fmt("/%s", schema.admin_api_name or schema.name) end endpoints[collection_path] = { schema = schema, methods = { --OPTIONS = method_not_allowed, --HEAD = method_not_allowed, GET = get_collection_endpoint(schema, foreign_schema, foreign_field_name), POST = post_collection_endpoint(schema, foreign_schema, foreign_field_name), --PUT = method_not_allowed, --PATCH = method_not_allowed, --DELETE = method_not_allowed, }, } end -- Generates admin api entity endpoint functions -- -- Examples: -- -- /routes/:routes -- /routes/:routes/service -- -- and -- -- /services/:services -- /services/:services/routes/:routes local function generate_entity_endpoints(endpoints, schema, foreign_schema, foreign_field_name, is_foreign_entity_endpoint) local entity_path if foreign_schema then if is_foreign_entity_endpoint then entity_path = fmt("/%s/:%s/%s", schema.admin_api_name or schema.name, schema.name, foreign_field_name) else entity_path = fmt("/%s/:%s/%s/:%s", schema.admin_api_name or schema.name, schema.name, foreign_schema.admin_api_nested_name or foreign_schema.admin_api_name or foreign_schema.name, foreign_schema.name) end else entity_path = fmt("/%s/:%s", schema.admin_api_name or schema.name, schema.name) end endpoints[entity_path] = { schema = foreign_schema or schema, methods = { --OPTIONS = method_not_allowed, --HEAD = method_not_allowed, GET = get_entity_endpoint(schema, foreign_schema, foreign_field_name, nil, is_foreign_entity_endpoint), --POST = method_not_allowed, PUT = put_entity_endpoint(schema, foreign_schema, foreign_field_name, nil, is_foreign_entity_endpoint), PATCH = patch_entity_endpoint(schema, foreign_schema, foreign_field_name, nil, is_foreign_entity_endpoint), DELETE = delete_entity_endpoint(schema, foreign_schema, foreign_field_name, nil, is_foreign_entity_endpoint), }, } end -- Generates admin api endpoint functions -- -- Examples: -- -- /routes -- /routes/:routes -- /routes/:routes/service -- /services/:services/routes -- -- and -- -- /services -- /services/:services -- /services/:services/routes/:routes local function generate_endpoints(schema, endpoints) -- e.g. /routes generate_collection_endpoints(endpoints, schema) -- e.g. /routes/:routes generate_entity_endpoints(endpoints, schema) for foreign_field_name, foreign_field in schema:each_field() do if foreign_field.type == "foreign" and not foreign_field.schema.legacy then -- e.g. /routes/:routes/service generate_entity_endpoints(endpoints, schema, foreign_field.schema, foreign_field_name, true) -- e.g. /services/:services/routes generate_collection_endpoints(endpoints, schema, foreign_field.schema, foreign_field_name) -- e.g. /services/:services/routes/:routes generate_entity_endpoints(endpoints, foreign_field.schema, schema, foreign_field_name) end end return endpoints end -- A reusable handler for endpoints that are deactivated -- (e.g. /targets/:targets) local disable = { before = function() return not_found() end } local Endpoints = { disable = disable, handle_error = handle_error, get_page_size = get_page_size, extract_options = extract_options, select_entity = select_entity, update_entity = update_entity, upsert_entity = upsert_entity, delete_entity = delete_entity, insert_entity = insert_entity, page_collection = page_collection, get_entity_endpoint = get_entity_endpoint, put_entity_endpoint = put_entity_endpoint, patch_entity_endpoint = patch_entity_endpoint, delete_entity_endpoint = delete_entity_endpoint, get_collection_endpoint = get_collection_endpoint, post_collection_endpoint = post_collection_endpoint, } function Endpoints.new(schema, endpoints) return generate_endpoints(schema, endpoints) end return Endpoints
apache-2.0
UnfortunateFruit/darkstar
scripts/zones/Bastok_Mines/npcs/HomePoint#3.lua
11
1186
----------------------------------- -- Area: Bastok Mines -- NPC: HomePoint#3 -- @pos 87 7 1 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Bastok_Mines/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fe, 99); 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 == 0x21fe) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/slice_of_lynx_meat.lua
18
1292
----------------------------------------- -- ID: 5667 -- Item: Slice of Lynx Meat -- Food Effect: 5 Min, Galka only ----------------------------------------- -- Strength 5 -- Intelligence -7 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 8) then result = 247; end if(target:getMod(MOD_EAT_RAW_MEAT) == 1) then result = 0; end 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,5667); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 5); target:addMod(MOD_INT, -7); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 5); target:delMod(MOD_INT, -7); end;
gpl-3.0
plajjan/snabbswitch
lib/pflua/tests/pfquickcheck/pflang_math.lua
25
2387
#!/usr/bin/env luajit module(..., package.seeall) local io = require("io") local codegen = require("pf.backend") local expand = require("pf.expand") local parse = require("pf.parse") local pfcompile = require("pfquickcheck.pfcompile") local libpcap = require("pf.libpcap") local bpf = require("pf.bpf") local utils = require("pf.utils") -- Generate pflang arithmetic local PflangNumber, PflangSmallNumber, PflangOp function PflangNumber() return math.random(0, 2^32-1) end function PflangOp() return utils.choose({ '+', '-', '*', '/' }) end function PflangArithmetic() return { PflangNumber(), PflangOp(), PflangNumber() } end -- Evaluate math expressions with libpcap and pflang's IR -- Pflang allows arithmetic as part of larger expressions. -- This tool uses len < arbitrary_arithmetic_here as a scaffold function libpcap_eval(str_expr) local expr = "len < " .. str_expr local asm = libpcap.compile(expr, 'RAW') local asm_str = bpf.disassemble(asm) local template = "^000: A = length\ 001: if %(A >= (%d+)%) goto 2 else goto 3\ 002: return 0\ 003: return 65535\ $" local constant_str = asm_str:match(template) if not constant_str then error ("unexpected bpf: "..asm_str) end local constant = assert(tonumber(constant_str), constant_str) assert(0 <= constant and constant < 2^32, constant) return constant end -- Here is an example of the pflua output that is parsed --return function(P,length) -- return length < ((519317859 + 63231) % 4294967296) --end -- Old style: -- return function(P,length) -- local v1 = 3204555350 * 122882 -- local v2 = v1 % 4294967296 -- do return length < v2 end -- end function pflua_eval(str_expr) local expr = "len < " .. str_expr local ir = expand.expand(parse.parse(expr)) local filter = pfcompile.compile_lua_ast(ir, "Arithmetic check") -- Old style: -- local math_string = string.match(filter, "v1 = [%d-+/*()%a. ]*") local math_str = string.match(filter, "return length < ([%d%a %%-+/*()]*)") math_str = "v1 = " .. math_str -- Loadstring has a different env, so floor doesn't resolve; use math.floor math_str = math_str:gsub('floor', 'math.floor') v1 = nil loadstring(math_str)() -- v1 must not be local, or this approach will fail -- v1 should always be within [0..2^32-1] assert(v1 >= 0) assert (v1 < 2^32) assert(v1 == math.floor(v1)) return v1 end
apache-2.0
dpino/snabbswitch
lib/pflua/tests/pfquickcheck/pflang_math.lua
25
2387
#!/usr/bin/env luajit module(..., package.seeall) local io = require("io") local codegen = require("pf.backend") local expand = require("pf.expand") local parse = require("pf.parse") local pfcompile = require("pfquickcheck.pfcompile") local libpcap = require("pf.libpcap") local bpf = require("pf.bpf") local utils = require("pf.utils") -- Generate pflang arithmetic local PflangNumber, PflangSmallNumber, PflangOp function PflangNumber() return math.random(0, 2^32-1) end function PflangOp() return utils.choose({ '+', '-', '*', '/' }) end function PflangArithmetic() return { PflangNumber(), PflangOp(), PflangNumber() } end -- Evaluate math expressions with libpcap and pflang's IR -- Pflang allows arithmetic as part of larger expressions. -- This tool uses len < arbitrary_arithmetic_here as a scaffold function libpcap_eval(str_expr) local expr = "len < " .. str_expr local asm = libpcap.compile(expr, 'RAW') local asm_str = bpf.disassemble(asm) local template = "^000: A = length\ 001: if %(A >= (%d+)%) goto 2 else goto 3\ 002: return 0\ 003: return 65535\ $" local constant_str = asm_str:match(template) if not constant_str then error ("unexpected bpf: "..asm_str) end local constant = assert(tonumber(constant_str), constant_str) assert(0 <= constant and constant < 2^32, constant) return constant end -- Here is an example of the pflua output that is parsed --return function(P,length) -- return length < ((519317859 + 63231) % 4294967296) --end -- Old style: -- return function(P,length) -- local v1 = 3204555350 * 122882 -- local v2 = v1 % 4294967296 -- do return length < v2 end -- end function pflua_eval(str_expr) local expr = "len < " .. str_expr local ir = expand.expand(parse.parse(expr)) local filter = pfcompile.compile_lua_ast(ir, "Arithmetic check") -- Old style: -- local math_string = string.match(filter, "v1 = [%d-+/*()%a. ]*") local math_str = string.match(filter, "return length < ([%d%a %%-+/*()]*)") math_str = "v1 = " .. math_str -- Loadstring has a different env, so floor doesn't resolve; use math.floor math_str = math_str:gsub('floor', 'math.floor') v1 = nil loadstring(math_str)() -- v1 must not be local, or this approach will fail -- v1 should always be within [0..2^32-1] assert(v1 >= 0) assert (v1 < 2^32) assert(v1 == math.floor(v1)) return v1 end
apache-2.0
nesstea/darkstar
scripts/zones/Korroloka_Tunnel/npcs/Excavation_Point.lua
13
1081
----------------------------------- -- Area: Korroloka Tunnel -- NPC: Excavation Point ----------------------------------- package.loaded["scripts/zones/Korroloka_Tunnel/TextIDs"] = nil; ------------------------------------- require("scripts/globals/excavation"); require("scripts/zones/Korroloka_Tunnel/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startExcavation(player,player:getZoneID(),npc,trade,0x0000); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(MINING_IS_POSSIBLE_HERE,605); 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
UnfortunateFruit/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Naja_Salaheem.lua
8
2579
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Naja Salaheem -- Type: Standard NPC -- @pos 22.700 -8.804 -45.591 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TOAUM3_DAY = player:getVar("TOAUM3_STARTDAY"); local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day local needToZone = player:needToZone(); if(player:getCurrentMission(TOAU) == IMMORTAL_SENTRIES)then if(player:getVar("TOAUM2") == 1 or player:getVar("TOAUM2") == 2) then player:startEvent(0x0BBA,0,0,0,0,0,0,0,0,0); end elseif(player:getCurrentMission(TOAU) == PRESIDENT_SALAHEEM and player:getVar("TOAUM3") == 1)then player:startEvent(0x0049,0,0,0,0,0,0,0,0,0); elseif(player:getCurrentMission(TOAU) == PRESIDENT_SALAHEEM and player:getVar("TOAUM3") == 2 and TOAUM3_DAY ~= realday and needToZone == true) then player:startEvent(0x0BCC,0,0,0,0,0,0,0,0,0); else player:messageSpecial(0);-- need to find correct normal chat CS.. 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 == 0x0BBA)then player:setVar("TOAUM2",0); player:completeMission(TOAU,IMMORTAL_SENTRIES); player:addMission(TOAU,PRESIDENT_SALAHEEM); player:addCurrency("imperial_standing", 150); player:addTitle(PRIVATE_SECOND_CLASS); player:addKeyItem(PSC_WILDCAT_BADGE); player:messageSpecial(KEYITEM_OBTAINED,PSC_WILDCAT_BADGE); elseif(csid == 0x0BCC)then player:completeMission(TOAU,PRESIDENT_SALAHEEM); player:addMission(TOAU,KNIGHT_OF_GOLD); player:setVar("TOAUM3",0); player:setVar("TOAUM3_DAY", 0); elseif(csid == 0x0049)then player:setVar("TOAUM3",2); player:setVar("TOAUM3_DAY", os.date("%j")); -- %M for next minute, %j for next day end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Northern_San_dOria/npcs/Olbergieut.lua
19
2257
----------------------------------- -- Area: Northern San d'Oria -- NPC: Olbergieut -- Type: Quest NPC -- @zone 231 -- @pos 91 0 121 -- -- Starts and Finishes Quest: Gates of Paradise ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) gates = player:getQuestStatus(SANDORIA,GATES_TO_PARADISE); if (player:hasKeyItem(SCRIPTURE_OF_WATER) == true) then player:startEvent(0x026c); elseif (gates == QUEST_ACCEPTED) then player:showText(npc, OLBERGIEUT_DIALOG, SCRIPTURE_OF_WIND); elseif (player:getFameLevel(SANDORIA) >= 2 and gates == QUEST_AVAILABLE) then player:startEvent(0x026b); else player:startEvent(0x0264); 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 == 0x026b and option == 0) then player:addQuest(SANDORIA, GATES_TO_PARADISE); player:addKeyItem(SCRIPTURE_OF_WIND); player:messageSpecial(KEYITEM_OBTAINED, SCRIPTURE_OF_WIND); elseif (csid == 0x026c) then if(player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 13584); else player:completeQuest(SANDORIA,GATES_TO_PARADISE); player:addFame(SANDORIA,SAN_FAME*30); player:addTitle(THE_PIOUS_ONE); player:delKeyItem(SCRIPTURE_OF_WATER); player:addItem(13584,1); player:messageSpecial(ITEM_OBTAINED,13584); end; end; end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Windurst_Waters/npcs/Aramu-Paramu.lua
36
1648
----------------------------------- -- Area: Windurst Waters -- NPC: Aramu-Paramu -- Involved In Quest: Wondering Minstrel -- Working 100% -- @zone = 238 -- @pos = -63 -4 27 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- 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) wonderingstatus = player:getQuestStatus(WINDURST,WONDERING_MINSTREL); if (wonderingstatus == QUEST_ACCEPTED) then player:startEvent(0x027e); -- WONDERING_MINSTREL: Quest Available / Quest Accepted elseif (wonderingstatus == QUEST_COMPLETED and player:needToZone()) then player:startEvent(0x0281); -- WONDERING_MINSTREL: Quest After else player:startEvent(0x261); -- Standard Conversation end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Temenos/mobs/Praetorian_Guard_CCCXI.lua
17
1194
----------------------------------- -- Area: Temenos N T -- NPC: Praetorian_Guard ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) if(IsMobDead(16928809)==true and IsMobDead(16928810)==true and IsMobDead(16928811)==true and IsMobDead(16928812)==true )then GetNPCByID(16928768+28):setPos(-311,80,419); GetNPCByID(16928768+28):setStatus(STATUS_NORMAL); GetNPCByID(16928768+162):setPos(-311,80,417); GetNPCByID(16928768+162):setStatus(STATUS_NORMAL); GetNPCByID(16928768+213):setPos(-311,80,421); GetNPCByID(16928768+213):setStatus(STATUS_NORMAL); GetNPCByID(16928770+454):setStatus(STATUS_NORMAL); end end;
gpl-3.0
vonflynee/opencomputersserver
world/opencomputers/4f2775bd-9dcb-42e6-8318-1837ede27e76/bin/pastebin.lua
7
4234
--[[ This program allows downloading and uploading from and to pastebin.com. Authors: Sangar, Vexatos ]] local component = require("component") local fs = require("filesystem") local internet = require("internet") local shell = require("shell") if not component.isAvailable("internet") then io.stderr:write("This program requires an internet card to run.") return end local args, options = shell.parse(...) -- This gets code from the website and stores it in the specified file. local function get(pasteId, filename) local f, reason = io.open(filename, "w") if not f then io.stderr:write("Failed opening file for writing: " .. reason) return end io.write("Downloading from pastebin.com... ") local url = "http://pastebin.com/raw.php?i=" .. pasteId local result, response = pcall(internet.request, url) if result then io.write("success.\n") for chunk in response do if not options.k then string.gsub(chunk, "\r\n", "\n") end f:write(chunk) end f:close() io.write("Saved data to " .. filename .. "\n") else io.write("failed.\n") f:close() fs.remove(filename) io.stderr:write("HTTP request failed: " .. response .. "\n") end end -- This makes a string safe for being used in a URL. function encode(code) if code then code = string.gsub(code, "([^%w ])", function (c) return string.format("%%%02X", string.byte(c)) end) code = string.gsub(code, " ", "+") end return code end -- This stores the program in a temporary file, which it will -- delete after the program was executed. function run(pasteId, ...) local tmpFile = os.tmpname() get(pasteId, tmpFile) io.write("Running...\n") local success, reason = shell.execute(tmpFile, nil, ...) if not success then io.stderr:write(reason) end fs.remove(tmpFile) end -- Uploads the specified file as a new paste to pastebin.com. function put(path) local config = {} local configFile = loadfile("/etc/pastebin.conf", "t", config) if configFile then local result, reason = pcall(configFile) if not result then io.stderr:write("Failed loading config: " .. reason) end end config.key = config.key or "fd92bd40a84c127eeb6804b146793c97" local file, reason = io.open(path, "r") if not file then io.stderr:write("Failed opening file for reading: " .. reason) return end local data = file:read("*a") file:close() io.write("Uploading to pastebin.com... ") local result, response = pcall(internet.request, "http://pastebin.com/api/api_post.php", "api_option=paste&" .. "api_dev_key=" .. config.key .. "&" .. "api_paste_format=lua&" .. "api_paste_expire_date=N&" .. "api_paste_name=" .. encode(fs.name(path)) .. "&" .. "api_paste_code=" .. encode(data)) if result then local info = "" for chunk in response do info = info .. chunk end if string.match(info, "^Bad API request, ") then io.write("failed.\n") io.write(info) else io.write("success.\n") local pasteId = string.match(info, "[^/]+$") io.write("Uploaded as " .. info .. "\n") io.write('Run "pastebin get ' .. pasteId .. '" to download anywhere.') end else io.write("failed.\n") io.stderr:write(response) end end local command = args[1] if command == "put" then if #args == 2 then put(shell.resolve(args[2])) return end elseif command == "get" then if #args == 3 then local path = shell.resolve(args[3]) if fs.exists(path) then if not options.f or not os.remove(path) then io.stderr:write("file already exists") return end end get(args[2], path) return end elseif command == "run" then if #args >= 2 then run(args[2], table.unpack(args, 3)) return end end -- If we come here there was some invalid input. io.write("Usages:\n") io.write("pastebin put [-f] <file>\n") io.write("pastebin get [-f] <id> <file>\n") io.write("pastebin run [-f] <id> [<arguments...>]\n") io.write(" -f: Force overwriting existing files.\n") io.write(" -k: keep line endings as-is (will convert\n") io.write(" Windows line endings to Unix otherwise).")
mit
vonflynee/opencomputersserver
world/opencomputers/05fe03dc-84c6-416b-a304-6f79787f6411/bin/pastebin.lua
7
4234
--[[ This program allows downloading and uploading from and to pastebin.com. Authors: Sangar, Vexatos ]] local component = require("component") local fs = require("filesystem") local internet = require("internet") local shell = require("shell") if not component.isAvailable("internet") then io.stderr:write("This program requires an internet card to run.") return end local args, options = shell.parse(...) -- This gets code from the website and stores it in the specified file. local function get(pasteId, filename) local f, reason = io.open(filename, "w") if not f then io.stderr:write("Failed opening file for writing: " .. reason) return end io.write("Downloading from pastebin.com... ") local url = "http://pastebin.com/raw.php?i=" .. pasteId local result, response = pcall(internet.request, url) if result then io.write("success.\n") for chunk in response do if not options.k then string.gsub(chunk, "\r\n", "\n") end f:write(chunk) end f:close() io.write("Saved data to " .. filename .. "\n") else io.write("failed.\n") f:close() fs.remove(filename) io.stderr:write("HTTP request failed: " .. response .. "\n") end end -- This makes a string safe for being used in a URL. function encode(code) if code then code = string.gsub(code, "([^%w ])", function (c) return string.format("%%%02X", string.byte(c)) end) code = string.gsub(code, " ", "+") end return code end -- This stores the program in a temporary file, which it will -- delete after the program was executed. function run(pasteId, ...) local tmpFile = os.tmpname() get(pasteId, tmpFile) io.write("Running...\n") local success, reason = shell.execute(tmpFile, nil, ...) if not success then io.stderr:write(reason) end fs.remove(tmpFile) end -- Uploads the specified file as a new paste to pastebin.com. function put(path) local config = {} local configFile = loadfile("/etc/pastebin.conf", "t", config) if configFile then local result, reason = pcall(configFile) if not result then io.stderr:write("Failed loading config: " .. reason) end end config.key = config.key or "fd92bd40a84c127eeb6804b146793c97" local file, reason = io.open(path, "r") if not file then io.stderr:write("Failed opening file for reading: " .. reason) return end local data = file:read("*a") file:close() io.write("Uploading to pastebin.com... ") local result, response = pcall(internet.request, "http://pastebin.com/api/api_post.php", "api_option=paste&" .. "api_dev_key=" .. config.key .. "&" .. "api_paste_format=lua&" .. "api_paste_expire_date=N&" .. "api_paste_name=" .. encode(fs.name(path)) .. "&" .. "api_paste_code=" .. encode(data)) if result then local info = "" for chunk in response do info = info .. chunk end if string.match(info, "^Bad API request, ") then io.write("failed.\n") io.write(info) else io.write("success.\n") local pasteId = string.match(info, "[^/]+$") io.write("Uploaded as " .. info .. "\n") io.write('Run "pastebin get ' .. pasteId .. '" to download anywhere.') end else io.write("failed.\n") io.stderr:write(response) end end local command = args[1] if command == "put" then if #args == 2 then put(shell.resolve(args[2])) return end elseif command == "get" then if #args == 3 then local path = shell.resolve(args[3]) if fs.exists(path) then if not options.f or not os.remove(path) then io.stderr:write("file already exists") return end end get(args[2], path) return end elseif command == "run" then if #args >= 2 then run(args[2], table.unpack(args, 3)) return end end -- If we come here there was some invalid input. io.write("Usages:\n") io.write("pastebin put [-f] <file>\n") io.write("pastebin get [-f] <id> <file>\n") io.write("pastebin run [-f] <id> [<arguments...>]\n") io.write(" -f: Force overwriting existing files.\n") io.write(" -k: keep line endings as-is (will convert\n") io.write(" Windows line endings to Unix otherwise).")
mit
jj918160/cocos2d-x-samples
samples/KillBug/src/cocos/framework/extends/UIListView.lua
55
2358
--[[ Copyright (c) 2011-2014 chukong-inc.com 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 ListView = ccui.ListView function ListView:onEvent(callback) self:addEventListener(function(sender, eventType) local event = {} if eventType == 0 then event.name = "ON_SELECTED_ITEM_START" else event.name = "ON_SELECTED_ITEM_END" end event.target = sender callback(event) end) return self end function ListView:onScroll(callback) self:addScrollViewEventListener(function(sender, eventType) local event = {} if eventType == 0 then event.name = "SCROLL_TO_TOP" elseif eventType == 1 then event.name = "SCROLL_TO_BOTTOM" elseif eventType == 2 then event.name = "SCROLL_TO_LEFT" elseif eventType == 3 then event.name = "SCROLL_TO_RIGHT" elseif eventType == 4 then event.name = "SCROLLING" elseif eventType == 5 then event.name = "BOUNCE_TOP" elseif eventType == 6 then event.name = "BOUNCE_BOTTOM" elseif eventType == 7 then event.name = "BOUNCE_LEFT" elseif eventType == 8 then event.name = "BOUNCE_RIGHT" end event.target = sender callback(event) end) return self end
mit
jj918160/cocos2d-x-samples
samples/KillBug/src/cocos/cocos2d/Cocos2dConstants.lua
15
16056
cc = cc or {} cc.SPRITE_INDEX_NOT_INITIALIZED = 0xffffffff cc.TMX_ORIENTATION_HEX = 0x1 cc.TMX_ORIENTATION_ISO = 0x2 cc.TMX_ORIENTATION_ORTHO = 0x0 cc.Z_COMPRESSION_BZIP2 = 0x1 cc.Z_COMPRESSION_GZIP = 0x2 cc.Z_COMPRESSION_NONE = 0x3 cc.Z_COMPRESSION_ZLIB = 0x0 cc.BLEND_DST = 0x303 cc.BLEND_SRC = 0x1 cc.DIRECTOR_IOS_USE_BACKGROUND_THREAD = 0x0 cc.DIRECTOR_MAC_THREAD = 0x0 cc.DIRECTOR_STATS_INTERVAL = 0.1 cc.ENABLE_BOX2_D_INTEGRATION = 0x0 cc.ENABLE_DEPRECATED = 0x1 cc.ENABLE_GL_STATE_CACHE = 0x1 cc.ENABLE_PROFILERS = 0x0 cc.ENABLE_STACKABLE_ACTIONS = 0x1 cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0x0 cc.GL_ALL = 0x0 cc.LABELATLAS_DEBUG_DRAW = 0x0 cc.LABELBMFONT_DEBUG_DRAW = 0x0 cc.MAC_USE_DISPLAY_LINK_THREAD = 0x0 cc.MAC_USE_MAIN_THREAD = 0x2 cc.MAC_USE_OWN_THREAD = 0x1 cc.NODE_RENDER_SUBPIXEL = 0x1 cc.PVRMIPMAP_MAX = 0x10 cc.SPRITEBATCHNODE_RENDER_SUBPIXEL = 0x1 cc.SPRITE_DEBUG_DRAW = 0x0 cc.TEXTURE_ATLAS_USE_TRIANGLE_STRIP = 0x0 cc.TEXTURE_ATLAS_USE_VAO = 0x1 cc.USE_L_A88_LABELS = 0x1 cc.ACTION_TAG_INVALID = -1 cc.DEVICE_MAC = 0x6 cc.DEVICE_MAC_RETINA_DISPLAY = 0x7 cc.DEVICEI_PAD = 0x4 cc.DEVICEI_PAD_RETINA_DISPLAY = 0x5 cc.DEVICEI_PHONE = 0x0 cc.DEVICEI_PHONE5 = 0x2 cc.DEVICEI_PHONE5_RETINA_DISPLAY = 0x3 cc.DEVICEI_PHONE_RETINA_DISPLAY = 0x1 cc.DIRECTOR_PROJECTION2_D = 0x0 cc.DIRECTOR_PROJECTION3_D = 0x1 cc.DIRECTOR_PROJECTION_CUSTOM = 0x2 cc.DIRECTOR_PROJECTION_DEFAULT = 0x1 cc.FILE_UTILS_SEARCH_DIRECTORY_MODE = 0x1 cc.FILE_UTILS_SEARCH_SUFFIX_MODE = 0x0 cc.FLIPED_ALL = 0xe0000000 cc.FLIPPED_MASK = 0x1fffffff cc.IMAGE_FORMAT_JPEG = 0x0 cc.IMAGE_FORMAT_PNG = 0x1 cc.ITEM_SIZE = 0x20 cc.LABEL_AUTOMATIC_WIDTH = -1 cc.LINE_BREAK_MODE_CHARACTER_WRAP = 0x1 cc.LINE_BREAK_MODE_CLIP = 0x2 cc.LINE_BREAK_MODE_HEAD_TRUNCATION = 0x3 cc.LINE_BREAK_MODE_MIDDLE_TRUNCATION = 0x5 cc.LINE_BREAK_MODE_TAIL_TRUNCATION = 0x4 cc.LINE_BREAK_MODE_WORD_WRAP = 0x0 cc.MAC_VERSION_10_6 = 0xa060000 cc.MAC_VERSION_10_7 = 0xa070000 cc.MAC_VERSION_10_8 = 0xa080000 cc.MENU_HANDLER_PRIORITY = -128 cc.MENU_STATE_TRACKING_TOUCH = 0x1 cc.MENU_STATE_WAITING = 0x0 cc.NODE_TAG_INVALID = -1 cc.PARTICLE_DURATION_INFINITY = -1 cc.PARTICLE_MODE_GRAVITY = 0x0 cc.PARTICLE_MODE_RADIUS = 0x1 cc.PARTICLE_START_RADIUS_EQUAL_TO_END_RADIUS = -1 cc.PARTICLE_START_SIZE_EQUAL_TO_END_SIZE = -1 cc.POSITION_TYPE_FREE = 0x0 cc.POSITION_TYPE_GROUPED = 0x2 cc.POSITION_TYPE_RELATIVE = 0x1 cc.PRIORITY_NON_SYSTEM_MIN = -2147483647 cc.PRIORITY_SYSTEM = -2147483648 cc.PROGRESS_TIMER_TYPE_BAR = 0x1 cc.PROGRESS_TIMER_TYPE_RADIAL = 0x0 cc.REPEAT_FOREVER = 0xfffffffe cc.RESOLUTION_MAC = 0x1 cc.RESOLUTION_MAC_RETINA_DISPLAY = 0x2 cc.RESOLUTION_UNKNOWN = 0x0 cc.TMX_TILE_DIAGONAL_FLAG = 0x20000000 cc.TMX_TILE_HORIZONTAL_FLAG = 0x80000000 cc.TMX_TILE_VERTICAL_FLAG = 0x40000000 cc.TEXT_ALIGNMENT_CENTER = 0x1 cc.TEXT_ALIGNMENT_LEFT = 0x0 cc.TEXT_ALIGNMENT_RIGHT = 0x2 cc.TEXTURE2_D_PIXEL_FORMAT_AUTO = 0x0 cc.TEXTURE2_D_PIXEL_FORMAT_BGR_A8888 = 0x1 cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888 = 0x2 cc.TEXTURE2_D_PIXEL_FORMAT_RG_B888 = 0x3 cc.TEXTURE2_D_PIXEL_FORMAT_RG_B565 = 0x4 cc.TEXTURE2_D_PIXEL_FORMAT_A8 = 0x5 cc.TEXTURE2_D_PIXEL_FORMAT_I8 = 0x6 cc.TEXTURE2_D_PIXEL_FORMAT_A_I88 = 0x7 cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A4444 = 0x8 cc.TEXTURE2_D_PIXEL_FORMAT_RGB5_A1 = 0x9 cc.TEXTURE2_D_PIXEL_FORMAT_PVRTC4 = 0xa cc.TEXTURE2_D_PIXEL_FORMAT_PVRTC4A = 0xb cc.TEXTURE2_D_PIXEL_FORMAT_PVRTC2 = 0xc cc.TEXTURE2_D_PIXEL_FORMAT_PVRTC2A = 0xd cc.TEXTURE2_D_PIXEL_FORMAT_ETC = 0xe cc.TEXTURE2_D_PIXEL_FORMAT_S3TC_DXT1 = 0xf cc.TEXTURE2_D_PIXEL_FORMAT_S3TC_DXT3 = 0x10 cc.TEXTURE2_D_PIXEL_FORMAT_S3TC_DXT5 = 0x11 cc.TEXTURE2_D_PIXEL_FORMAT_DEFAULT = 0x0 cc.TOUCHES_ALL_AT_ONCE = 0x0 cc.TOUCHES_ONE_BY_ONE = 0x1 cc.TRANSITION_ORIENTATION_DOWN_OVER = 0x1 cc.TRANSITION_ORIENTATION_LEFT_OVER = 0x0 cc.TRANSITION_ORIENTATION_RIGHT_OVER = 0x1 cc.TRANSITION_ORIENTATION_UP_OVER = 0x0 cc.UNIFORM_COS_TIME = 0x5 cc.UNIFORM_MV_MATRIX = 0x1 cc.UNIFORM_MVP_MATRIX = 0x2 cc.UNIFORM_P_MATRIX = 0x0 cc.UNIFORM_RANDOM01 = 0x6 cc.UNIFORM_SAMPLER = 0x7 cc.UNIFORM_SIN_TIME = 0x4 cc.UNIFORM_TIME = 0x3 cc.UNIFORM_MAX = 0x8 cc.VERTEX_ATTRIB_FLAG_COLOR = 0x2 cc.VERTEX_ATTRIB_FLAG_NONE = 0x0 cc.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX = 0x7 cc.VERTEX_ATTRIB_FLAG_POSITION = 0x1 cc.VERTEX_ATTRIB_FLAG_TEX_COORDS = 0x4 cc.VERTEX_ATTRIB_COLOR = 0x1 cc.VERTEX_ATTRIB_MAX = 0x3 cc.VERTEX_ATTRIB_POSITION = 0x0 cc.VERTEX_ATTRIB_TEX_COORD = 0x2 cc.VERTEX_ATTRIB_TEX_COORDS = 0x2 cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM = 0x2 cc.VERTICAL_TEXT_ALIGNMENT_CENTER = 0x1 cc.VERTICAL_TEXT_ALIGNMENT_TOP = 0x0 cc.OS_VERSION_4_0 = 0x4000000 cc.OS_VERSION_4_0_1 = 0x4000100 cc.OS_VERSION_4_1 = 0x4010000 cc.OS_VERSION_4_2 = 0x4020000 cc.OS_VERSION_4_2_1 = 0x4020100 cc.OS_VERSION_4_3 = 0x4030000 cc.OS_VERSION_4_3_1 = 0x4030100 cc.OS_VERSION_4_3_2 = 0x4030200 cc.OS_VERSION_4_3_3 = 0x4030300 cc.OS_VERSION_4_3_4 = 0x4030400 cc.OS_VERSION_4_3_5 = 0x4030500 cc.OS_VERSION_5_0 = 0x5000000 cc.OS_VERSION_5_0_1 = 0x5000100 cc.OS_VERSION_5_1_0 = 0x5010000 cc.OS_VERSION_6_0_0 = 0x6000000 cc.ANIMATION_FRAME_DISPLAYED_NOTIFICATION = 'CCAnimationFrameDisplayedNotification' cc.CHIPMUNK_IMPORT = 'chipmunk.h' cc.ATTRIBUTE_NAME_COLOR = 'a_color' cc.ATTRIBUTE_NAME_POSITION = 'a_position' cc.ATTRIBUTE_NAME_TEX_COORD = 'a_texCoord' cc.SHADER_POSITION_COLOR = 'ShaderPositionColor' cc.SHADER_POSITION_LENGTH_TEXURE_COLOR = 'ShaderPositionLengthTextureColor' cc.SHADER_POSITION_TEXTURE = 'ShaderPositionTexture' cc.SHADER_POSITION_TEXTURE_A8_COLOR = 'ShaderPositionTextureA8Color' cc.SHADER_POSITION_TEXTURE_COLOR = 'ShaderPositionTextureColor' cc.SHADER_POSITION_TEXTURE_COLOR_ALPHA_TEST = 'ShaderPositionTextureColorAlphaTest' cc.SHADER_POSITION_TEXTURE_U_COLOR = 'ShaderPositionTexture_uColor' cc.SHADER_POSITION_U_COLOR = 'ShaderPosition_uColor' cc.UNIFORM_ALPHA_TEST_VALUE_S = 'CC_AlphaValue' cc.UNIFORM_COS_TIME_S = 'CC_CosTime' cc.UNIFORM_MV_MATRIX_S = 'CC_MVMatrix' cc.UNIFORM_MVP_MATRIX_S = 'CC_MVPMatrix' cc.UNIFORM_P_MATRIX_S = 'CC_PMatrix' cc.UNIFORM_RANDOM01_S = 'CC_Random01' cc.UNIFORM_SAMPLER_S = 'CC_Texture0' cc.UNIFORM_SIN_TIME_S = 'CC_SinTime' cc.UNIFORM_TIME_S = 'CC_Time' cc.PLATFORM_OS_WINDOWS = 0 cc.PLATFORM_OS_LINUX = 1 cc.PLATFORM_OS_MAC = 2 cc.PLATFORM_OS_ANDROID = 3 cc.PLATFORM_OS_IPHONE = 4 cc.PLATFORM_OS_IPAD = 5 cc.PLATFORM_OS_BLACKBERRY = 6 cc.PLATFORM_OS_NACL = 7 cc.PLATFORM_OS_EMSCRIPTEN = 8 cc.PLATFORM_OS_TIZEN = 9 cc.PLATFORM_OS_WINRT = 10 cc.PLATFORM_OS_WP8 = 11 cc.LANGUAGE_ENGLISH = 0 cc.LANGUAGE_CHINESE = 1 cc.LANGUAGE_FRENCH = 2 cc.LANGUAGE_ITALIAN = 3 cc.LANGUAGE_GERMAN = 4 cc.LANGUAGE_SPANISH = 5 cc.LANGUAGE_RUSSIAN = 6 cc.LANGUAGE_KOREAN = 7 cc.LANGUAGE_JAPANESE = 8 cc.LANGUAGE_HUNGARIAN = 9 cc.LANGUAGE_PORTUGUESE = 10 cc.LANGUAGE_ARABIC = 11 cc.NODE_ON_ENTER = 0 cc.NODE_ON_EXIT = 1 cc.NODE_ON_ENTER_TRANSITION_DID_FINISH = 2 cc.NODE_ON_EXIT_TRANSITION_DID_START = 3 cc.NODE_ON_CLEAN_UP = 4 cc.Handler = cc.Handler or {} cc.Handler.NODE = 0 cc.Handler.MENU_CLICKED = 1 cc.Handler.CALLFUNC = 2 cc.Handler.SCHEDULE = 3 cc.Handler.TOUCHES = 4 cc.Handler.KEYPAD = 5 cc.Handler.ACCELEROMETER = 6 cc.Handler.CONTROL_TOUCH_DOWN = 7 cc.Handler.CONTROL_TOUCH_DRAG_INSIDE = 8 cc.Handler.CONTROL_TOUCH_DRAG_OUTSIDE = 9 cc.Handler.CONTROL_TOUCH_DRAG_ENTER = 10 cc.Handler.CONTROL_TOUCH_DRAG_EXIT = 11 cc.Handler.CONTROL_TOUCH_UP_INSIDE = 12 cc.Handler.CONTROL_TOUCH_UP_OUTSIDE = 13 cc.Handler.CONTROL_TOUCH_UP_CANCEL = 14 cc.Handler.CONTROL_VALUE_CHANGED = 15 cc.Handler.WEBSOCKET_OPEN = 16 cc.Handler.WEBSOCKET_MESSAGE = 17 cc.Handler.WEBSOCKET_CLOSE = 18 cc.Handler.WEBSOCKET_ERROR = 19 cc.Handler.GL_NODE_DRAW = 20 cc.Handler.SCROLLVIEW_SCROLL = 21 cc.Handler.SCROLLVIEW_ZOOM = 22 cc.Handler.TABLECELL_TOUCHED = 23 cc.Handler.TABLECELL_HIGHLIGHT = 24 cc.Handler.TABLECELL_UNHIGHLIGHT = 25 cc.Handler.TABLECELL_WILL_RECYCLE = 26 cc.Handler.TABLECELL_SIZE_FOR_INDEX = 27 cc.Handler.TABLECELL_AT_INDEX = 28 cc.Handler.TABLEVIEW_NUMS_OF_CELLS = 29 cc.Handler.HTTPREQUEST_STATE_CHANGE = 30 cc.Handler.ASSETSMANAGER_PROGRESS = 31 cc.Handler.ASSETSMANAGER_SUCCESS = 32 cc.Handler.ASSETSMANAGER_ERROR = 33 cc.Handler.STUDIO_EVENT_LISTENER = 34 cc.Handler.ARMATURE_EVENT = 35 cc.Handler.EVENT_ACC = 36 cc.Handler.EVENT_CUSTIOM = 37 cc.Handler.EVENT_KEYBOARD_PRESSED = 38 cc.Handler.EVENT_KEYBOARD_RELEASED = 39 cc.Handler.EVENT_TOUCH_BEGAN = 40 cc.Handler.EVENT_TOUCH_MOVED = 41 cc.Handler.EVENT_TOUCH_ENDED = 42 cc.Handler.EVENT_TOUCH_CANCELLED = 43 cc.Handler.EVENT_TOUCHES_BEGAN = 44 cc.Handler.EVENT_TOUCHES_MOVED = 45 cc.Handler.EVENT_TOUCHES_ENDED = 46 cc.Handler.EVENT_TOUCHES_CANCELLED = 47 cc.Handler.EVENT_MOUSE_DOWN = 48 cc.Handler.EVENT_MOUSE_UP = 49 cc.Handler.EVENT_MOUSE_MOVE = 50 cc.Handler.EVENT_MOUSE_SCROLL = 51 cc.Handler.EVENT_SPINE = 52 cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN = 53 cc.Handler.EVENT_PHYSICS_CONTACT_PRESOLVE = 54 cc.Handler.EVENT_PHYSICS_CONTACT_POSTSOLVE = 55 cc.Handler.EVENT_PHYSICS_CONTACT_SEPARATE = 56 cc.Handler.EVENT_FOCUS = 57 cc.Handler.EVENT_CONTROLLER_CONNECTED = 58 cc.Handler.EVENT_CONTROLLER_DISCONNECTED = 59 cc.Handler.EVENT_CONTROLLER_KEYDOWN = 60 cc.Handler.EVENT_CONTROLLER_KEYUP = 61 cc.Handler.EVENT_CONTROLLER_KEYREPEAT = 62 cc.Handler.EVENT_CONTROLLER_AXIS = 63 cc.Handler.EVENT_SPINE_ANIMATION_START = 64 cc.Handler.EVENT_SPINE_ANIMATION_END = 65 cc.Handler.EVENT_SPINE_ANIMATION_COMPLETE = 66 cc.Handler.EVENT_SPINE_ANIMATION_EVENT = 67 cc.EVENT_UNKNOWN = 0 cc.EVENT_TOUCH_ONE_BY_ONE = 1 cc.EVENT_TOUCH_ALL_AT_ONCE = 2 cc.EVENT_KEYBOARD = 3 cc.EVENT_MOUSE = 4 cc.EVENT_ACCELERATION = 5 cc.EVENT_CUSTOM = 6 cc.PHYSICSSHAPE_MATERIAL_DEFAULT = {density = 0.0, restitution = 0.5, friction = 0.5} cc.PHYSICSBODY_MATERIAL_DEFAULT = {density = 0.1, restitution = 0.5, friction = 0.5} cc.GLYPHCOLLECTION_DYNAMIC = 0 cc.GLYPHCOLLECTION_NEHE = 1 cc.GLYPHCOLLECTION_ASCII = 2 cc.GLYPHCOLLECTION_CUSTOM = 3 cc.ResolutionPolicy = { EXACT_FIT = 0, NO_BORDER = 1, SHOW_ALL = 2, FIXED_HEIGHT = 3, FIXED_WIDTH = 4, UNKNOWN = 5, } cc.LabelEffect = { NORMAL = 0, OUTLINE = 1, SHADOW = 2, GLOW = 3, } cc.KeyCodeKey = { "KEY_NONE", "KEY_PAUSE", "KEY_SCROLL_LOCK", "KEY_PRINT", "KEY_SYSREQ", "KEY_BREAK", "KEY_ESCAPE", "KEY_BACKSPACE", "KEY_TAB", "KEY_BACK_TAB", "KEY_RETURN", "KEY_CAPS_LOCK", "KEY_SHIFT", "KEY_RIGHT_SHIFT", "KEY_CTRL", "KEY_RIGHT_CTRL", "KEY_ALT", "KEY_RIGHT_ALT", "KEY_MENU", "KEY_HYPER", "KEY_INSERT", "KEY_HOME", "KEY_PG_UP", "KEY_DELETE", "KEY_END", "KEY_PG_DOWN", "KEY_LEFT_ARROW", "KEY_RIGHT_ARROW", "KEY_UP_ARROW", "KEY_DOWN_ARROW", "KEY_NUM_LOCK", "KEY_KP_PLUS", "KEY_KP_MINUS", "KEY_KP_MULTIPLY", "KEY_KP_DIVIDE", "KEY_KP_ENTER", "KEY_KP_HOME", "KEY_KP_UP", "KEY_KP_PG_UP", "KEY_KP_LEFT", "KEY_KP_FIVE", "KEY_KP_RIGHT", "KEY_KP_END", "KEY_KP_DOWN", "KEY_KP_PG_DOWN", "KEY_KP_INSERT", "KEY_KP_DELETE", "KEY_F1", "KEY_F2", "KEY_F3", "KEY_F4", "KEY_F5", "KEY_F6", "KEY_F7", "KEY_F8", "KEY_F9", "KEY_F10", "KEY_F11", "KEY_F12", "KEY_SPACE", "KEY_EXCLAM", "KEY_QUOTE", "KEY_NUMBER", "KEY_DOLLAR", "KEY_PERCENT", "KEY_CIRCUMFLEX", "KEY_AMPERSAND", "KEY_APOSTROPHE", "KEY_LEFT_PARENTHESIS", "KEY_RIGHT_PARENTHESIS", "KEY_ASTERISK", "KEY_PLUS", "KEY_COMMA", "KEY_MINUS", "KEY_PERIOD", "KEY_SLASH", "KEY_0", "KEY_1", "KEY_2", "KEY_3", "KEY_4", "KEY_5", "KEY_6", "KEY_7", "KEY_8", "KEY_9", "KEY_COLON", "KEY_SEMICOLON", "KEY_LESS_THAN", "KEY_EQUAL", "KEY_GREATER_THAN", "KEY_QUESTION", "KEY_AT", "KEY_CAPITAL_A", "KEY_CAPITAL_B", "KEY_CAPITAL_C", "KEY_CAPITAL_D", "KEY_CAPITAL_E", "KEY_CAPITAL_F", "KEY_CAPITAL_G", "KEY_CAPITAL_H", "KEY_CAPITAL_I", "KEY_CAPITAL_J", "KEY_CAPITAL_K", "KEY_CAPITAL_L", "KEY_CAPITAL_M", "KEY_CAPITAL_N", "KEY_CAPITAL_O", "KEY_CAPITAL_P", "KEY_CAPITAL_Q", "KEY_CAPITAL_R", "KEY_CAPITAL_S", "KEY_CAPITAL_T", "KEY_CAPITAL_U", "KEY_CAPITAL_V", "KEY_CAPITAL_W", "KEY_CAPITAL_X", "KEY_CAPITAL_Y", "KEY_CAPITAL_Z", "KEY_LEFT_BRACKET", "KEY_BACK_SLASH", "KEY_RIGHT_BRACKET", "KEY_UNDERSCORE", "KEY_GRAVE", "KEY_A", "KEY_B", "KEY_C", "KEY_D", "KEY_E", "KEY_F", "KEY_G", "KEY_H", "KEY_I", "KEY_J", "KEY_K", "KEY_L", "KEY_M", "KEY_N", "KEY_O", "KEY_P", "KEY_Q", "KEY_R", "KEY_S", "KEY_T", "KEY_U", "KEY_V", "KEY_W", "KEY_X", "KEY_Y", "KEY_Z", "KEY_LEFT_BRACE", "KEY_BAR", "KEY_RIGHT_BRACE", "KEY_TILDE", "KEY_EURO", "KEY_POUND", "KEY_YEN", "KEY_MIDDLE_DOT", "KEY_SEARCH", "KEY_DPAD_LEFT", "KEY_DPAD_RIGHT", "KEY_DPAD_UP", "KEY_DPAD_DOWN", "KEY_DPAD_CENTER", "KEY_ENTER", "KEY_PLAY", } cc.KeyCode = { } for k,v in ipairs(cc.KeyCodeKey) do cc.KeyCode[v] = k - 1 end cc.KeyCode.KEY_BACK = cc.KeyCode.KEY_ESCAPE cc.KeyCode.KEY_LEFT_SHIFT = cc.KeyCode.KEY_SHIFT cc.KeyCode.KEY_LEFT_CTRL = cc.KeyCode.KEY_CTRL cc.KeyCode.KEY_LEFT_ALT = cc.KeyCode.KEY_ALT cc.EventAssetsManagerEx = { EventCode = { ERROR_NO_LOCAL_MANIFEST = 0, ERROR_DOWNLOAD_MANIFEST = 1, ERROR_PARSE_MANIFEST = 2, NEW_VERSION_FOUND = 3, ALREADY_UP_TO_DATE = 4, UPDATE_PROGRESSION = 5, ASSET_UPDATED = 6, ERROR_UPDATING = 7, UPDATE_FINISHED = 8, }, } cc.AssetsManagerExStatic = { VERSION_ID = "@version", MANIFEST_ID = "@manifest", } cc.EventCode = { BEGAN = 0, MOVED = 1, ENDED = 2, CANCELLED = 3, } cc.DIRECTOR_PROJECTION_2D = 0 cc.DIRECTOR_PROJECTION_3D = 1 cc.ConfigType = { NONE = 0, COCOSTUDIO = 1, } cc.AUDIO_INVAILD_ID = -1 cc.AUDIO_TIME_UNKNOWN = -1.0 cc.CameraFlag = { DEFAULT = 1, USER1 = 2, USER2 = 4, USER3 = 8, USER4 = 16, USER5 = 32, USER6 = 64, USER7 = 128, USER8 = 256, } cc.BillBoard_Mode = { VIEW_POINT_ORIENTED = 0, VIEW_PLANE_ORIENTED = 1, } cc.GLProgram_VERTEX_ATTRIB = { POSITION = 0, COLOR = 1, TEX_COORD = 2, TEX_COORD1 = 3, TEX_COORD2 = 4, TEX_COORD3 = 5, TEX_COORD4 = 6, TEX_COORD5 = 7, TEX_COORD6 = 8, TEX_COORD7 = 9, NORMAL = 10, BLEND_WEIGHT = 11, BLEND_INDEX =12, MAX = 13, --backward compatibility TEX_COORDS = 2, } cc.MATRIX_STACK_TYPE = { MODELVIEW = 0, PROJECTION = 1, TEXTURE = 2, } cc.LightType = { DIRECTIONAL = 0, POINT = 1, SPOT = 2, AMBIENT = 3, } cc.LightFlag = { LIGHT0 = math.pow(2,0), LIGHT1 = math.pow(2,1), LIGHT2 = math.pow(2,2), LIGHT3 = math.pow(2,3), LIGHT4 = math.pow(2,4), LIGHT5 = math.pow(2,5), LIGHT6 = math.pow(2,6), LIGHT7 = math.pow(2,7), LIGHT8 = math.pow(2,8), LIGHT9 = math.pow(2,9), LIGHT10 = math.pow(2,10), LIGHT11 = math.pow(2,11), LIGHT12 = math.pow(2,12), LIGHT13 = math.pow(2,13), LIGHT14 = math.pow(2,14), LIGHT15 = math.pow(2,15), } cc.AsyncTaskPool.TaskType = { TASK_IO = 0, TASK_NETWORK = 1, TASK_OTHER = 2, TASK_MAX_TYPE = 3, }
mit
UnfortunateFruit/darkstar
scripts/globals/items/plate_of_squid_sushi.lua
35
1598
----------------------------------------- -- ID: 5148 -- Item: plate_of_squid_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 30 -- Dexterity 6 -- Agility 5 -- Mind -1 -- Accuracy % 15 -- Ranged ACC % 15 -- Sleep Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5148); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 30); target:addMod(MOD_DEX, 6); target:addMod(MOD_AGI, 5); target:addMod(MOD_MND, -1); target:addMod(MOD_ACCP, 15); target:addMod(MOD_RACCP, 15); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 30); target:delMod(MOD_DEX, 6); target:delMod(MOD_AGI, 5); target:delMod(MOD_MND, -1); target:delMod(MOD_ACCP, 15); target:delMod(MOD_RACCP, 15); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Rolanberry_Fields/Zone.lua
6
4757
----------------------------------- -- -- Zone: Rolanberry_Fields (110) -- ----------------------------------- package.loaded["scripts/zones/Rolanberry_Fields/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Rolanberry_Fields/TextIDs"); require("scripts/globals/icanheararainbow"); require("scripts/globals/zone"); require("scripts/globals/chocobo_digging"); ----------------------------------- -- Chocobo Digging vars ----------------------------------- local itemMap = { -- itemid, abundance, requirement { 4450, 30, DIGREQ_NONE }, { 4566, 7, DIGREQ_NONE }, { 768, 164, DIGREQ_NONE }, { 748, 15, DIGREQ_NONE }, { 846, 97, DIGREQ_NONE }, { 17396, 75, DIGREQ_NONE }, { 749, 45, DIGREQ_NONE }, { 739, 3, DIGREQ_NONE }, { 17296, 216, DIGREQ_NONE }, { 4448, 15, DIGREQ_NONE }, { 638, 82, DIGREQ_NONE }, { 106, 37, DIGREQ_NONE }, { 4096, 100, DIGREQ_NONE }, -- all crystals { 656, 200, DIGREQ_BURROW }, { 750, 100, DIGREQ_BURROW }, { 4375, 60, DIGREQ_BORE }, { 4449, 15, DIGREQ_BORE }, { 4374, 52, DIGREQ_BORE }, { 4373, 10, DIGREQ_BORE }, { 4570, 10, DIGREQ_MODIFIER }, { 4487, 11, DIGREQ_MODIFIER }, { 4409, 12, DIGREQ_MODIFIER }, { 1188, 10, DIGREQ_MODIFIER }, { 4532, 12, DIGREQ_MODIFIER }, }; local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED }; ----------------------------------- -- onChocoboDig ----------------------------------- function onChocoboDig(player, precheck) return chocoboDig(player, itemMap, precheck, messageArray); end; ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17228375,17228376}; local book = GetNPCByID(17228375); local rift = GetNPCByID(17228385) book:setPos(-98,-9,-655,216) rift:setPos(-90.707,-7.899,-663.99,216) SetFieldManual(manuals); -- Simurgh SetRespawnTime(17228242, 900, 10800); -- Spawns Silk Caterpillar (temporary until someone implements a way to make it spawn properly) SpawnMob(17227782,300,660); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; if( player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos( -381.747, -31.068, -788.092, 211); end if( triggerLightCutscene( player)) then -- Quest: I Can Hear A Rainbow cs = 0x0002; elseif(player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1)then cs = 0x0004; end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter( player, region) end; ----------------------------------- -- onGameHour ----------------------------------- function onGameHour() local VanadielHour = VanadielHour(); local SilkCaterpillar = 17227782; if(VanadielHour % 1 == 0 and GetMobAction( SilkCaterpillar ) == 16) then DespawnMob( SilkCaterpillar ); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if ( csid == 0x0002) then lightCutsceneUpdate( player); -- Quest: I Can Hear A Rainbow elseif (csid == 0x0004) then if(player:getZPos() < 75) then player:updateEvent(0,0,0,0,0,1); else player:updateEvent(0,0,0,0,0,2); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if( csid == 0x0002) then lightCutsceneFinish( player); -- Quest: I Can Hear A Rainbow end end;
gpl-3.0
milkmanjack/lama
src/global/Nanny.lua
1
7274
--[[ lama is a MUD server made in Lua. Copyright (C) 2013 Curtis Erickson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --- Singleton that contains necessary processes for connecting new players, -- as well as processing their input during these stages. -- @author milkmanjack local md5 = require("md5") local Mob = require("obj.Mob") local Race = require("obj.Race") local Class = require("obj.Class") --- Singleton that contains necessary processes for connecting new players, -- as well as processing their input during these stages. -- @class table -- @name Nanny Nanny = {} --- Processes input from a player. -- @param player The player to process. -- @param input The input to process. function Nanny.process(player, input) if player:getState() == PlayerState.NAME then local name = DatabaseManager.legalizeName(input) if string.len(input) < 3 or string.len(input) > 12 then Nanny.messageNameLengthLimit(player) Nanny.askForName(player) else if DatabaseManager.characterNameTaken(input) then local mob, location = DatabaseManager.loadCharacter(input) player.nanny.mob = mob player.nanny.location = location player:setState(PlayerState.OLD_CHAR_PASSWORD) Nanny.askForOldPassword(player) else local mob = Mob:new() player:setMob(mob) mob:setName(name) mob:setKeywords(name) player:setState(PlayerState.NEW_CHAR_PASSWORD) Nanny.askForNewPassword(player, false) end end elseif player:getState() == PlayerState.OLD_CHAR_PASSWORD then if md5.sumhexa(input) ~= player.nanny.mob:getPassword() then player:sendMessage("That password doesn't match the old password!", MessageMode.FAILURE) player.nanny.mob = nil player.nanny.location = nil player:setState(PlayerState.NAME) Nanny.askForName(player) else player:setMob(player.nanny.mob) player:setState(PlayerState.MOTD) Nanny.MOTD(player) end elseif player:getState() == PlayerState.NEW_CHAR_PASSWORD then player.nanny.password = input player:setState(PlayerState.NEW_CHAR_PASSWORD_CONFIRM) Nanny.askForNewPassword(player, true) elseif player:getState() == PlayerState.NEW_CHAR_PASSWORD_CONFIRM then if input ~= player.nanny.password then player:sendMessage("Those passwords don't match!") Nanny.askForNewPassword(player, false) player:setState(PlayerState.NEW_CHAR_PASSWORD) else player.mob:setPassword(md5.sumhexa(player.nanny.password)) player.mob.race = DatabaseManager.getRaceByName("human") player.mob.class = DatabaseManager.getClassByName("warrior") player:setState(PlayerState.MOTD) Nanny.MOTD(player) end elseif player:getState() == PlayerState.MOTD then Nanny.login(player) end end --- Transitions from "logging in" to being "logged in." -- Assigns a player ID, introduces the player to the world, and so on. -- @param player Player that is logging in. function Nanny.login(player) local mob = player:getMob() player:setID(Game.getNextPlayerID()) -- now that they're finally playing Nanny.introduce(player) Game.info(string.format("%s has joined.", tostring(player), tostring(mob))) -- move our mob to starting point mob:moveToMap(Game.map) if player.nanny.location then mob:move(player.nanny.location) else mob:setXYZLoc(1,1,1) end player:getMob():showRoom() -- introduce us player:setState(PlayerState.PLAYING) -- we're playing end --- Transitions from being "logged in" to being "logged out." -- Announces the player's exit, removes the mob from the map, and so on. -- @param player Player that is logging out. function Nanny.logout(player) player:setState(PlayerState.DISCONNECTING) -- we are disconnecting local mob = player:getMob() Nanny.sendOff(player) Game.info(string.format("%s has left.", tostring(player), tostring(mob))) -- remove their mob from the map mob:moveToMap(nil) end --- Introduce the player to the world. -- @param player Player to introduce. function Nanny.introduce(player) player:sendMessage(string.format("\nWelcome to %s, %s!", tostring(Game.getName()), tostring(player:getMob()))) Game.announce(string.format("%s has joined!", tostring(player:getMob())), MessageMode.INFO, PlayerState.PLAYING) end --- Send the player off, announcing their departure. -- @param player Player that is departing. function Nanny.sendOff(player) player:sendMessage("Goodbye!") Game.announce(string.format("%s has left!", tostring(player:getMob())), MessageMode.INFO, PlayerState.PLAYING) end --- Greets a connecting player and begins the logging in.<br/> -- In the case of a hotboot greeting, merely puts the player back -- in the game. -- @param player Player to be greeted. -- @param hotboot If true, greeting after a hotboot. function Nanny.greet(player, hotboot) if hotboot then player:sendMessage("Welcome back!") player:setState(PlayerState.PLAYING) else player:sendMessage(Nanny.getGreeting()) player:setState(PlayerState.NAME) Nanny.askForName(player) end end --- Asks for a name. -- @param player Player to ask. function Nanny.askForName(player) player:askQuestion("What is your name? ") end --- Ask for a new password. -- @param player Player to ask. function Nanny.askForNewPassword(player, confirm) if not confirm then player:askQuestion("New password: ") else player:askQuestion("Repeat password: ") end end --- Ask for the old password. -- @param player Player to ask. function Nanny.askForOldPassword(player) player:askQuestion("Password: ") end --- Tell the player the name length limits. -- @param player Player to inform. function Nanny.messageNameLengthLimit(player) player:sendMessage("Your name must be between 3 and 12 characters.", MessageMode.FAILURE) end --- Send the MOTD to the player. -- @param player Player to be MOTDed. function Nanny.MOTD(player) player:sendMessage("\n" .. Nanny.getMOTD()) player:sendMessage("< PRESS ENTER >", nil, false) end --- Retreive the text to be used as the MOTD. -- @return The MOTD! function Nanny.getMOTD() return "\[THIS IS THE MESSAGE OF THE DAY\]" end --- Get the greeting message. By default, refers to "txt/GREETING". If not found, returns generic credits. -- @return The message. function Nanny.getGreeting() -- use contents of txt/GREETING for our greeting, if available. local file = io.open("txt/GREETING", "r") if file then local txt = file:read("*a") local formatted = string.format(txt, Game.getName(), Game.getVersion(), table.concat(Game.getDevelopers(), ", ")) return formatted end -- generic greeting return string.format([[%s (%s) by %s Developed in Lua 5.2]], Game.getName(), Game.getVersion(), Game.getDevelopers()) end _G.Nanny = Nanny return Nanny
gpl-3.0
plntyk/packages
utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/wifi_stations.lua
58
2753
local ubus = require "ubus" local iwinfo = require "iwinfo" local function scrape() local metric_wifi_stations = metric("wifi_stations", "gauge") local metric_wifi_station_signal = metric("wifi_station_signal_dbm","gauge") local metric_wifi_station_inactive = metric('wifi_station_inactive_milliseconds', 'gauge') local metric_wifi_station_exp_thr = metric('wifi_station_expected_throughput_kilobits_per_second', 'gauge') local metric_wifi_station_tx_bitrate = metric('wifi_station_transmit_kilobits_per_second', 'gauge') local metric_wifi_station_rx_bitrate = metric('wifi_station_receive_kilobits_per_second', 'gauge') local metric_wifi_station_tx_packets = metric("wifi_station_transmit_packets_total","counter") local metric_wifi_station_rx_packets = metric("wifi_station_receive_packets_total","counter") local metric_wifi_station_tx_bytes = metric('wifi_station_transmit_bytes_total', 'counter') local metric_wifi_station_rx_bytes = metric('wifi_station_receive_bytes_total', 'counter') local u = ubus.connect() local status = u:call("network.wireless", "status", {}) for dev, dev_table in pairs(status) do for _, intf in ipairs(dev_table['interfaces']) do local ifname = intf['ifname'] if ifname ~= nil then local iw = iwinfo[iwinfo.type(ifname)] local count = 0 local assoclist = iw.assoclist(ifname) for mac, station in pairs(assoclist) do local labels = { ifname = ifname, mac = mac, } if station.signal and station.signal ~= 0 then metric_wifi_station_signal(labels, station.signal) end if station.inactive then metric_wifi_station_inactive(labels, station.inactive) end if station.expected_throughput and station.expected_throughput ~= 0 then metric_wifi_station_exp_thr(labels, station.expected_throughput) end if station.tx_rate and station.tx_rate ~= 0 then metric_wifi_station_tx_bitrate(labels, station.tx_rate) end if station.rx_rate and station.rx_rate ~= 0 then metric_wifi_station_rx_bitrate(labels, station.rx_rate) end metric_wifi_station_tx_packets(labels, station.tx_packets) metric_wifi_station_rx_packets(labels, station.rx_packets) if station.tx_bytes then metric_wifi_station_tx_bytes(labels, station.tx_bytes) end if station.rx_bytes then metric_wifi_station_rx_bytes(labels, station.rx_bytes) end count = count + 1 end metric_wifi_stations({ifname = ifname}, count) end end end end return { scrape = scrape }
gpl-2.0
zuzuf/TA3D
src/ta3d/src/luajit/dynasm/dynasm.lua
73
30945
------------------------------------------------------------------------------ -- DynASM. A dynamic assembler for code generation engines. -- Originally designed and implemented for LuaJIT. -- -- Copyright (C) 2005-2013 Mike Pall. All rights reserved. -- See below for full copyright notice. ------------------------------------------------------------------------------ -- Application information. local _info = { name = "DynASM", description = "A dynamic assembler for code generation engines", version = "1.3.0", vernum = 10300, release = "2011-05-05", author = "Mike Pall", url = "http://luajit.org/dynasm.html", license = "MIT", copyright = [[ Copyright (C) 2005-2013 Mike Pall. All rights reserved. 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. [ MIT license: http://www.opensource.org/licenses/mit-license.php ] ]], } -- Cache library functions. local type, pairs, ipairs = type, pairs, ipairs local pcall, error, assert = pcall, error, assert local _s = string local sub, match, gmatch, gsub = _s.sub, _s.match, _s.gmatch, _s.gsub local format, rep, upper = _s.format, _s.rep, _s.upper local _t = table local insert, remove, concat, sort = _t.insert, _t.remove, _t.concat, _t.sort local exit = os.exit local io = io local stdin, stdout, stderr = io.stdin, io.stdout, io.stderr ------------------------------------------------------------------------------ -- Program options. local g_opt = {} -- Global state for current file. local g_fname, g_curline, g_indent, g_lineno, g_synclineno, g_arch local g_errcount = 0 -- Write buffer for output file. local g_wbuffer, g_capbuffer ------------------------------------------------------------------------------ -- Write an output line (or callback function) to the buffer. local function wline(line, needindent) local buf = g_capbuffer or g_wbuffer buf[#buf+1] = needindent and g_indent..line or line g_synclineno = g_synclineno + 1 end -- Write assembler line as a comment, if requestd. local function wcomment(aline) if g_opt.comment then wline(g_opt.comment..aline..g_opt.endcomment, true) end end -- Resync CPP line numbers. local function wsync() if g_synclineno ~= g_lineno and g_opt.cpp then wline("# "..g_lineno..' "'..g_fname..'"') g_synclineno = g_lineno end end -- Dummy action flush function. Replaced with arch-specific function later. local function wflush(term) end -- Dump all buffered output lines. local function wdumplines(out, buf) for _,line in ipairs(buf) do if type(line) == "string" then assert(out:write(line, "\n")) else -- Special callback to dynamically insert lines after end of processing. line(out) end end end ------------------------------------------------------------------------------ -- Emit an error. Processing continues with next statement. local function werror(msg) error(format("%s:%s: error: %s:\n%s", g_fname, g_lineno, msg, g_curline), 0) end -- Emit a fatal error. Processing stops. local function wfatal(msg) g_errcount = "fatal" werror(msg) end -- Print a warning. Processing continues. local function wwarn(msg) stderr:write(format("%s:%s: warning: %s:\n%s\n", g_fname, g_lineno, msg, g_curline)) end -- Print caught error message. But suppress excessive errors. local function wprinterr(...) if type(g_errcount) == "number" then -- Regular error. g_errcount = g_errcount + 1 if g_errcount < 21 then -- Seems to be a reasonable limit. stderr:write(...) elseif g_errcount == 21 then stderr:write(g_fname, ":*: warning: too many errors (suppressed further messages).\n") end else -- Fatal error. stderr:write(...) return true -- Stop processing. end end ------------------------------------------------------------------------------ -- Map holding all option handlers. local opt_map = {} local opt_current -- Print error and exit with error status. local function opterror(...) stderr:write("dynasm.lua: ERROR: ", ...) stderr:write("\n") exit(1) end -- Get option parameter. local function optparam(args) local argn = args.argn local p = args[argn] if not p then opterror("missing parameter for option `", opt_current, "'.") end args.argn = argn + 1 return p end ------------------------------------------------------------------------------ -- Core pseudo-opcodes. local map_coreop = {} -- Dummy opcode map. Replaced by arch-specific map. local map_op = {} -- Forward declarations. local dostmt local readfile ------------------------------------------------------------------------------ -- Map for defines (initially empty, chains to arch-specific map). local map_def = {} -- Pseudo-opcode to define a substitution. map_coreop[".define_2"] = function(params, nparams) if not params then return nparams == 1 and "name" or "name, subst" end local name, def = params[1], params[2] or "1" if not match(name, "^[%a_][%w_]*$") then werror("bad or duplicate define") end map_def[name] = def end map_coreop[".define_1"] = map_coreop[".define_2"] -- Define a substitution on the command line. function opt_map.D(args) local namesubst = optparam(args) local name, subst = match(namesubst, "^([%a_][%w_]*)=(.*)$") if name then map_def[name] = subst elseif match(namesubst, "^[%a_][%w_]*$") then map_def[namesubst] = "1" else opterror("bad define") end end -- Undefine a substitution on the command line. function opt_map.U(args) local name = optparam(args) if match(name, "^[%a_][%w_]*$") then map_def[name] = nil else opterror("bad define") end end -- Helper for definesubst. local gotsubst local function definesubst_one(word) local subst = map_def[word] if subst then gotsubst = word; return subst else return word end end -- Iteratively substitute defines. local function definesubst(stmt) -- Limit number of iterations. for i=1,100 do gotsubst = false stmt = gsub(stmt, "#?[%w_]+", definesubst_one) if not gotsubst then break end end if gotsubst then wfatal("recursive define involving `"..gotsubst.."'") end return stmt end -- Dump all defines. local function dumpdefines(out, lvl) local t = {} for name in pairs(map_def) do t[#t+1] = name end sort(t) out:write("Defines:\n") for _,name in ipairs(t) do local subst = map_def[name] if g_arch then subst = g_arch.revdef(subst) end out:write(format(" %-20s %s\n", name, subst)) end out:write("\n") end ------------------------------------------------------------------------------ -- Support variables for conditional assembly. local condlevel = 0 local condstack = {} -- Evaluate condition with a Lua expression. Substitutions already performed. local function cond_eval(cond) local func, err if setfenv then func, err = loadstring("return "..cond, "=expr") else -- No globals. All unknown identifiers evaluate to nil. func, err = load("return "..cond, "=expr", "t", {}) end if func then if setfenv then setfenv(func, {}) -- No globals. All unknown identifiers evaluate to nil. end local ok, res = pcall(func) if ok then if res == 0 then return false end -- Oh well. return not not res end err = res end wfatal("bad condition: "..err) end -- Skip statements until next conditional pseudo-opcode at the same level. local function stmtskip() local dostmt_save = dostmt local lvl = 0 dostmt = function(stmt) local op = match(stmt, "^%s*(%S+)") if op == ".if" then lvl = lvl + 1 elseif lvl ~= 0 then if op == ".endif" then lvl = lvl - 1 end elseif op == ".elif" or op == ".else" or op == ".endif" then dostmt = dostmt_save dostmt(stmt) end end end -- Pseudo-opcodes for conditional assembly. map_coreop[".if_1"] = function(params) if not params then return "condition" end local lvl = condlevel + 1 local res = cond_eval(params[1]) condlevel = lvl condstack[lvl] = res if not res then stmtskip() end end map_coreop[".elif_1"] = function(params) if not params then return "condition" end if condlevel == 0 then wfatal(".elif without .if") end local lvl = condlevel local res = condstack[lvl] if res then if res == "else" then wfatal(".elif after .else") end else res = cond_eval(params[1]) if res then condstack[lvl] = res return end end stmtskip() end map_coreop[".else_0"] = function(params) if condlevel == 0 then wfatal(".else without .if") end local lvl = condlevel local res = condstack[lvl] condstack[lvl] = "else" if res then if res == "else" then wfatal(".else after .else") end stmtskip() end end map_coreop[".endif_0"] = function(params) local lvl = condlevel if lvl == 0 then wfatal(".endif without .if") end condlevel = lvl - 1 end -- Check for unfinished conditionals. local function checkconds() if g_errcount ~= "fatal" and condlevel ~= 0 then wprinterr(g_fname, ":*: error: unbalanced conditional\n") end end ------------------------------------------------------------------------------ -- Search for a file in the given path and open it for reading. local function pathopen(path, name) local dirsep = package and match(package.path, "\\") and "\\" or "/" for _,p in ipairs(path) do local fullname = p == "" and name or p..dirsep..name local fin = io.open(fullname, "r") if fin then g_fname = fullname return fin end end end -- Include a file. map_coreop[".include_1"] = function(params) if not params then return "filename" end local name = params[1] -- Save state. Ugly, I know. but upvalues are fast. local gf, gl, gcl, gi = g_fname, g_lineno, g_curline, g_indent -- Read the included file. local fatal = readfile(pathopen(g_opt.include, name) or wfatal("include file `"..name.."' not found")) -- Restore state. g_synclineno = -1 g_fname, g_lineno, g_curline, g_indent = gf, gl, gcl, gi if fatal then wfatal("in include file") end end -- Make .include and conditionals initially available, too. map_op[".include_1"] = map_coreop[".include_1"] map_op[".if_1"] = map_coreop[".if_1"] map_op[".elif_1"] = map_coreop[".elif_1"] map_op[".else_0"] = map_coreop[".else_0"] map_op[".endif_0"] = map_coreop[".endif_0"] ------------------------------------------------------------------------------ -- Support variables for macros. local mac_capture, mac_lineno, mac_name local mac_active = {} local mac_list = {} -- Pseudo-opcode to define a macro. map_coreop[".macro_*"] = function(mparams) if not mparams then return "name [, params...]" end -- Split off and validate macro name. local name = remove(mparams, 1) if not name then werror("missing macro name") end if not (match(name, "^[%a_][%w_%.]*$") or match(name, "^%.[%w_%.]*$")) then wfatal("bad macro name `"..name.."'") end -- Validate macro parameter names. local mdup = {} for _,mp in ipairs(mparams) do if not match(mp, "^[%a_][%w_]*$") then wfatal("bad macro parameter name `"..mp.."'") end if mdup[mp] then wfatal("duplicate macro parameter name `"..mp.."'") end mdup[mp] = true end -- Check for duplicate or recursive macro definitions. local opname = name.."_"..#mparams if map_op[opname] or map_op[name.."_*"] then wfatal("duplicate macro `"..name.."' ("..#mparams.." parameters)") end if mac_capture then wfatal("recursive macro definition") end -- Enable statement capture. local lines = {} mac_lineno = g_lineno mac_name = name mac_capture = function(stmt) -- Statement capture function. -- Stop macro definition with .endmacro pseudo-opcode. if not match(stmt, "^%s*.endmacro%s*$") then lines[#lines+1] = stmt return end mac_capture = nil mac_lineno = nil mac_name = nil mac_list[#mac_list+1] = opname -- Add macro-op definition. map_op[opname] = function(params) if not params then return mparams, lines end -- Protect against recursive macro invocation. if mac_active[opname] then wfatal("recursive macro invocation") end mac_active[opname] = true -- Setup substitution map. local subst = {} for i,mp in ipairs(mparams) do subst[mp] = params[i] end local mcom if g_opt.maccomment and g_opt.comment then mcom = " MACRO "..name.." ("..#mparams..")" wcomment("{"..mcom) end -- Loop through all captured statements for _,stmt in ipairs(lines) do -- Substitute macro parameters. local st = gsub(stmt, "[%w_]+", subst) st = definesubst(st) st = gsub(st, "%s*%.%.%s*", "") -- Token paste a..b. if mcom and sub(st, 1, 1) ~= "|" then wcomment(st) end -- Emit statement. Use a protected call for better diagnostics. local ok, err = pcall(dostmt, st) if not ok then -- Add the captured statement to the error. wprinterr(err, "\n", g_indent, "| ", stmt, "\t[MACRO ", name, " (", #mparams, ")]\n") end end if mcom then wcomment("}"..mcom) end mac_active[opname] = nil end end end -- An .endmacro pseudo-opcode outside of a macro definition is an error. map_coreop[".endmacro_0"] = function(params) wfatal(".endmacro without .macro") end -- Dump all macros and their contents (with -PP only). local function dumpmacros(out, lvl) sort(mac_list) out:write("Macros:\n") for _,opname in ipairs(mac_list) do local name = sub(opname, 1, -3) local params, lines = map_op[opname]() out:write(format(" %-20s %s\n", name, concat(params, ", "))) if lvl > 1 then for _,line in ipairs(lines) do out:write(" |", line, "\n") end out:write("\n") end end out:write("\n") end -- Check for unfinished macro definitions. local function checkmacros() if mac_capture then wprinterr(g_fname, ":", mac_lineno, ": error: unfinished .macro `", mac_name ,"'\n") end end ------------------------------------------------------------------------------ -- Support variables for captures. local cap_lineno, cap_name local cap_buffers = {} local cap_used = {} -- Start a capture. map_coreop[".capture_1"] = function(params) if not params then return "name" end wflush() local name = params[1] if not match(name, "^[%a_][%w_]*$") then wfatal("bad capture name `"..name.."'") end if cap_name then wfatal("already capturing to `"..cap_name.."' since line "..cap_lineno) end cap_name = name cap_lineno = g_lineno -- Create or continue a capture buffer and start the output line capture. local buf = cap_buffers[name] if not buf then buf = {}; cap_buffers[name] = buf end g_capbuffer = buf g_synclineno = 0 end -- Stop a capture. map_coreop[".endcapture_0"] = function(params) wflush() if not cap_name then wfatal(".endcapture without a valid .capture") end cap_name = nil cap_lineno = nil g_capbuffer = nil g_synclineno = 0 end -- Dump a capture buffer. map_coreop[".dumpcapture_1"] = function(params) if not params then return "name" end wflush() local name = params[1] if not match(name, "^[%a_][%w_]*$") then wfatal("bad capture name `"..name.."'") end cap_used[name] = true wline(function(out) local buf = cap_buffers[name] if buf then wdumplines(out, buf) end end) g_synclineno = 0 end -- Dump all captures and their buffers (with -PP only). local function dumpcaptures(out, lvl) out:write("Captures:\n") for name,buf in pairs(cap_buffers) do out:write(format(" %-20s %4s)\n", name, "("..#buf)) if lvl > 1 then local bar = rep("=", 76) out:write(" ", bar, "\n") for _,line in ipairs(buf) do out:write(" ", line, "\n") end out:write(" ", bar, "\n\n") end end out:write("\n") end -- Check for unfinished or unused captures. local function checkcaptures() if cap_name then wprinterr(g_fname, ":", cap_lineno, ": error: unfinished .capture `", cap_name,"'\n") return end for name in pairs(cap_buffers) do if not cap_used[name] then wprinterr(g_fname, ":*: error: missing .dumpcapture ", name ,"\n") end end end ------------------------------------------------------------------------------ -- Sections names. local map_sections = {} -- Pseudo-opcode to define code sections. -- TODO: Data sections, BSS sections. Needs extra C code and API. map_coreop[".section_*"] = function(params) if not params then return "name..." end if #map_sections > 0 then werror("duplicate section definition") end wflush() for sn,name in ipairs(params) do local opname = "."..name.."_0" if not match(name, "^[%a][%w_]*$") or map_op[opname] or map_op["."..name.."_*"] then werror("bad section name `"..name.."'") end map_sections[#map_sections+1] = name wline(format("#define DASM_SECTION_%s\t%d", upper(name), sn-1)) map_op[opname] = function(params) g_arch.section(sn-1) end end wline(format("#define DASM_MAXSECTION\t\t%d", #map_sections)) end -- Dump all sections. local function dumpsections(out, lvl) out:write("Sections:\n") for _,name in ipairs(map_sections) do out:write(format(" %s\n", name)) end out:write("\n") end ------------------------------------------------------------------------------ -- Replacement for customized Lua, which lacks the package library. local prefix = "" if not require then function require(name) local fp = assert(io.open(prefix..name..".lua")) local s = fp:read("*a") assert(fp:close()) return assert(loadstring(s, "@"..name..".lua"))() end end -- Load architecture-specific module. local function loadarch(arch) if not match(arch, "^[%w_]+$") then return "bad arch name" end local ok, m_arch = pcall(require, "dasm_"..arch) if not ok then return "cannot load module: "..m_arch end g_arch = m_arch wflush = m_arch.passcb(wline, werror, wfatal, wwarn) m_arch.setup(arch, g_opt) map_op, map_def = m_arch.mergemaps(map_coreop, map_def) end -- Dump architecture description. function opt_map.dumparch(args) local name = optparam(args) if not g_arch then local err = loadarch(name) if err then opterror(err) end end local t = {} for name in pairs(map_coreop) do t[#t+1] = name end for name in pairs(map_op) do t[#t+1] = name end sort(t) local out = stdout local _arch = g_arch._info out:write(format("%s version %s, released %s, %s\n", _info.name, _info.version, _info.release, _info.url)) g_arch.dumparch(out) local pseudo = true out:write("Pseudo-Opcodes:\n") for _,sname in ipairs(t) do local name, nparam = match(sname, "^(.+)_([0-9%*])$") if name then if pseudo and sub(name, 1, 1) ~= "." then out:write("\nOpcodes:\n") pseudo = false end local f = map_op[sname] local s if nparam ~= "*" then nparam = nparam + 0 end if nparam == 0 then s = "" elseif type(f) == "string" then s = map_op[".template__"](nil, f, nparam) else s = f(nil, nparam) end if type(s) == "table" then for _,s2 in ipairs(s) do out:write(format(" %-12s %s\n", name, s2)) end else out:write(format(" %-12s %s\n", name, s)) end end end out:write("\n") exit(0) end -- Pseudo-opcode to set the architecture. -- Only initially available (map_op is replaced when called). map_op[".arch_1"] = function(params) if not params then return "name" end local err = loadarch(params[1]) if err then wfatal(err) end end -- Dummy .arch pseudo-opcode to improve the error report. map_coreop[".arch_1"] = function(params) if not params then return "name" end wfatal("duplicate .arch statement") end ------------------------------------------------------------------------------ -- Dummy pseudo-opcode. Don't confuse '.nop' with 'nop'. map_coreop[".nop_*"] = function(params) if not params then return "[ignored...]" end end -- Pseudo-opcodes to raise errors. map_coreop[".error_1"] = function(params) if not params then return "message" end werror(params[1]) end map_coreop[".fatal_1"] = function(params) if not params then return "message" end wfatal(params[1]) end -- Dump all user defined elements. local function dumpdef(out) local lvl = g_opt.dumpdef if lvl == 0 then return end dumpsections(out, lvl) dumpdefines(out, lvl) if g_arch then g_arch.dumpdef(out, lvl) end dumpmacros(out, lvl) dumpcaptures(out, lvl) end ------------------------------------------------------------------------------ -- Helper for splitstmt. local splitlvl local function splitstmt_one(c) if c == "(" then splitlvl = ")"..splitlvl elseif c == "[" then splitlvl = "]"..splitlvl elseif c == "{" then splitlvl = "}"..splitlvl elseif c == ")" or c == "]" or c == "}" then if sub(splitlvl, 1, 1) ~= c then werror("unbalanced (), [] or {}") end splitlvl = sub(splitlvl, 2) elseif splitlvl == "" then return " \0 " end return c end -- Split statement into (pseudo-)opcode and params. local function splitstmt(stmt) -- Convert label with trailing-colon into .label statement. local label = match(stmt, "^%s*(.+):%s*$") if label then return ".label", {label} end -- Split at commas and equal signs, but obey parentheses and brackets. splitlvl = "" stmt = gsub(stmt, "[,%(%)%[%]{}]", splitstmt_one) if splitlvl ~= "" then werror("unbalanced () or []") end -- Split off opcode. local op, other = match(stmt, "^%s*([^%s%z]+)%s*(.*)$") if not op then werror("bad statement syntax") end -- Split parameters. local params = {} for p in gmatch(other, "%s*(%Z+)%z?") do params[#params+1] = gsub(p, "%s+$", "") end if #params > 16 then werror("too many parameters") end params.op = op return op, params end -- Process a single statement. dostmt = function(stmt) -- Ignore empty statements. if match(stmt, "^%s*$") then return end -- Capture macro defs before substitution. if mac_capture then return mac_capture(stmt) end stmt = definesubst(stmt) -- Emit C code without parsing the line. if sub(stmt, 1, 1) == "|" then local tail = sub(stmt, 2) wflush() if sub(tail, 1, 2) == "//" then wcomment(tail) else wline(tail, true) end return end -- Split into (pseudo-)opcode and params. local op, params = splitstmt(stmt) -- Get opcode handler (matching # of parameters or generic handler). local f = map_op[op.."_"..#params] or map_op[op.."_*"] if not f then if not g_arch then wfatal("first statement must be .arch") end -- Improve error report. for i=0,9 do if map_op[op.."_"..i] then werror("wrong number of parameters for `"..op.."'") end end werror("unknown statement `"..op.."'") end -- Call opcode handler or special handler for template strings. if type(f) == "string" then map_op[".template__"](params, f) else f(params) end end -- Process a single line. local function doline(line) if g_opt.flushline then wflush() end -- Assembler line? local indent, aline = match(line, "^(%s*)%|(.*)$") if not aline then -- No, plain C code line, need to flush first. wflush() wsync() wline(line, false) return end g_indent = indent -- Remember current line indentation. -- Emit C code (even from macros). Avoids echo and line parsing. if sub(aline, 1, 1) == "|" then if not mac_capture then wsync() elseif g_opt.comment then wsync() wcomment(aline) end dostmt(aline) return end -- Echo assembler line as a comment. if g_opt.comment then wsync() wcomment(aline) end -- Strip assembler comments. aline = gsub(aline, "//.*$", "") -- Split line into statements at semicolons. if match(aline, ";") then for stmt in gmatch(aline, "[^;]+") do dostmt(stmt) end else dostmt(aline) end end ------------------------------------------------------------------------------ -- Write DynASM header. local function dasmhead(out) out:write(format([[ /* ** This file has been pre-processed with DynASM. ** %s ** DynASM version %s, DynASM %s version %s ** DO NOT EDIT! The original file is in "%s". */ #if DASM_VERSION != %d #error "Version mismatch between DynASM and included encoding engine" #endif ]], _info.url, _info.version, g_arch._info.arch, g_arch._info.version, g_fname, _info.vernum)) end -- Read input file. readfile = function(fin) g_indent = "" g_lineno = 0 g_synclineno = -1 -- Process all lines. for line in fin:lines() do g_lineno = g_lineno + 1 g_curline = line local ok, err = pcall(doline, line) if not ok and wprinterr(err, "\n") then return true end end wflush() -- Close input file. assert(fin == stdin or fin:close()) end -- Write output file. local function writefile(outfile) local fout -- Open output file. if outfile == nil or outfile == "-" then fout = stdout else fout = assert(io.open(outfile, "w")) end -- Write all buffered lines wdumplines(fout, g_wbuffer) -- Close output file. assert(fout == stdout or fout:close()) -- Optionally dump definitions. dumpdef(fout == stdout and stderr or stdout) end -- Translate an input file to an output file. local function translate(infile, outfile) g_wbuffer = {} g_indent = "" g_lineno = 0 g_synclineno = -1 -- Put header. wline(dasmhead) -- Read input file. local fin if infile == "-" then g_fname = "(stdin)" fin = stdin else g_fname = infile fin = assert(io.open(infile, "r")) end readfile(fin) -- Check for errors. if not g_arch then wprinterr(g_fname, ":*: error: missing .arch directive\n") end checkconds() checkmacros() checkcaptures() if g_errcount ~= 0 then stderr:write(g_fname, ":*: info: ", g_errcount, " error", (type(g_errcount) == "number" and g_errcount > 1) and "s" or "", " in input file -- no output file generated.\n") dumpdef(stderr) exit(1) end -- Write output file. writefile(outfile) end ------------------------------------------------------------------------------ -- Print help text. function opt_map.help() stdout:write("DynASM -- ", _info.description, ".\n") stdout:write("DynASM ", _info.version, " ", _info.release, " ", _info.url, "\n") stdout:write[[ Usage: dynasm [OPTION]... INFILE.dasc|- -h, --help Display this help text. -V, --version Display version and copyright information. -o, --outfile FILE Output file name (default is stdout). -I, --include DIR Add directory to the include search path. -c, --ccomment Use /* */ comments for assembler lines. -C, --cppcomment Use // comments for assembler lines (default). -N, --nocomment Suppress assembler lines in output. -M, --maccomment Show macro expansions as comments (default off). -L, --nolineno Suppress CPP line number information in output. -F, --flushline Flush action list for every line. -D NAME[=SUBST] Define a substitution. -U NAME Undefine a substitution. -P, --dumpdef Dump defines, macros, etc. Repeat for more output. -A, --dumparch ARCH Load architecture ARCH and dump description. ]] exit(0) end -- Print version information. function opt_map.version() stdout:write(format("%s version %s, released %s\n%s\n\n%s", _info.name, _info.version, _info.release, _info.url, _info.copyright)) exit(0) end -- Misc. options. function opt_map.outfile(args) g_opt.outfile = optparam(args) end function opt_map.include(args) insert(g_opt.include, 1, optparam(args)) end function opt_map.ccomment() g_opt.comment = "/*|"; g_opt.endcomment = " */" end function opt_map.cppcomment() g_opt.comment = "//|"; g_opt.endcomment = "" end function opt_map.nocomment() g_opt.comment = false end function opt_map.maccomment() g_opt.maccomment = true end function opt_map.nolineno() g_opt.cpp = false end function opt_map.flushline() g_opt.flushline = true end function opt_map.dumpdef() g_opt.dumpdef = g_opt.dumpdef + 1 end ------------------------------------------------------------------------------ -- Short aliases for long options. local opt_alias = { h = "help", ["?"] = "help", V = "version", o = "outfile", I = "include", c = "ccomment", C = "cppcomment", N = "nocomment", M = "maccomment", L = "nolineno", F = "flushline", P = "dumpdef", A = "dumparch", } -- Parse single option. local function parseopt(opt, args) opt_current = #opt == 1 and "-"..opt or "--"..opt local f = opt_map[opt] or opt_map[opt_alias[opt]] if not f then opterror("unrecognized option `", opt_current, "'. Try `--help'.\n") end f(args) end -- Parse arguments. local function parseargs(args) -- Default options. g_opt.comment = "//|" g_opt.endcomment = "" g_opt.cpp = true g_opt.dumpdef = 0 g_opt.include = { "" } -- Process all option arguments. args.argn = 1 repeat local a = args[args.argn] if not a then break end local lopt, opt = match(a, "^%-(%-?)(.+)") if not opt then break end args.argn = args.argn + 1 if lopt == "" then -- Loop through short options. for o in gmatch(opt, ".") do parseopt(o, args) end else -- Long option. parseopt(opt, args) end until false -- Check for proper number of arguments. local nargs = #args - args.argn + 1 if nargs ~= 1 then if nargs == 0 then if g_opt.dumpdef > 0 then return dumpdef(stdout) end end opt_map.help() end -- Translate a single input file to a single output file -- TODO: Handle multiple files? translate(args[args.argn], g_opt.outfile) end ------------------------------------------------------------------------------ -- Add the directory dynasm.lua resides in to the Lua module search path. local arg = arg if arg and arg[0] then prefix = match(arg[0], "^(.*[/\\])") if package and prefix then package.path = prefix.."?.lua;"..package.path end end -- Start DynASM. parseargs{...} ------------------------------------------------------------------------------
gpl-2.0
nesstea/darkstar
scripts/zones/Windurst_Waters/npcs/Kyume-Romeh.lua
13
3411
----------------------------------- -- Area: Windurst Waters -- NPC: Kyume-Romeh -- Involved In Quest: Making Headlines, Hat in Hand -- @pos -58 -4 23 238 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) function testflag(set,flag) return (set % (2*flag) >= flag) end local hatstatus = player:getQuestStatus(WINDURST,HAT_IN_HAND); local MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES); local WildcatWindurst = player:getVar("WildcatWindurst"); if (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("MEMORIES_OF_A_MAIDEN_Status")==4) then player:startEvent(0x0369); elseif (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,14) == false) then player:startEvent(0x03ab); elseif ((hatstatus == 1 or player:getVar("QuestHatInHand_var2") == 1) and testflag(tonumber(player:getVar("QuestHatInHand_var")),16) == false) then player:startEvent(0x003c); -- Show Off Hat elseif (MakingHeadlines == 1) then local prog = player:getVar("QuestMakingHeadlines_var"); -- Variable to track if player has talked to 4 NPCs and a door -- 1 = Kyume -- 2 = Yujuju -- 4 = Hiwom -- 8 = Umumu -- 16 = Mahogany Door if (testflag(tonumber(prog),1) == false) then player:startEvent(0x029c); -- Quest progress else player:startEvent(0x029d); -- Quest not furthered end else local rand = math.random(1,2); if (rand == 1) then player:startEvent(0x025c); -- Standard Conversation else player:startEvent(0x0189); -- Standard Conversation end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x029c) then prog = player:getVar("QuestMakingHeadlines_var"); player:addKeyItem(WINDURST_WATERS_SCOOP); player:messageSpecial(KEYITEM_OBTAINED,WINDURST_WATERS_SCOOP); player:setVar("QuestMakingHeadlines_var",prog+1); elseif (csid == 0x003c) then -- Show Off Hat player:setVar("QuestHatInHand_var",player:getVar("QuestHatInHand_var")+16); player:setVar("QuestHatInHand_count",player:getVar("QuestHatInHand_count")+1); elseif (csid == 0x0369) then player:setVar("MEMORIES_OF_A_MAIDEN_Status",5); elseif (csid == 0x03ab) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",14,true); end end;
gpl-3.0
NezzKryptic/Wire-Extras
lua/autorun/widgets/list.lua
1
4416
------------------------------------------------- List ---------------------------------------------------------- panelWidget["list"] = { name = "list", realName = "List Box", wireType = 2, paramTable = { fontSize = {index = 1, default = 2, realName = "Font Size:", stool = {stype = 1, smin = 1, smax = 15, ntype = 1} }, list = {index = 2, default = "", realName = "List (seperate with |):", stool = {stype = 2}}}, modInit = function (widget) widget.selected = 0 if widget.paramTable[1] then widget.oSpacing = tonumber(widget.paramTable[1]) * 5 widget.size = tonumber(widget.paramTable[1]) else widget.oSpacing = widget.modType.paramTable.fontSize.default * 5 widget.size = 1 end if widget.paramTable[2] then widget.options = string.Explode("|", widget.paramTable[2]) widget.numOptions = table.getn(widget.options) - 1 else widget.options = {} widget.numOptions = 0 end end, modDraw = function (ent, widget) surface.SetDrawColor(ent.currentScheme.outline.r, ent.currentScheme.outline.g, ent.currentScheme.outline.b, 255) local x1 = (widget.X * ent.XdrawCoef) + ent.XdrawOffs local y1 = (widget.Y * ent.YdrawCoef) + ent.YdrawOffs local w = widget.W * ent.XdrawCoef local h = widget.H * ent.YdrawCoef surface.DrawRect(x1, y1, w, h) surface.SetDrawColor(ent.currentScheme.foreground.r, ent.currentScheme.foreground.g, ent.currentScheme.foreground.b, 255) local x1 = ((widget.X + 1) * ent.XdrawCoef) + ent.XdrawOffs local y1 = ((widget.Y + 1) * ent.YdrawCoef) + ent.YdrawOffs local w = (widget.W - 2) * ent.XdrawCoef local h = (widget.H - 2) * ent.YdrawCoef surface.DrawRect(x1, y1, w, h) surface.SetDrawColor(ent.currentScheme.foregroundb.r, ent.currentScheme.foregroundb.g, ent.currentScheme.foregroundb.b, 255) local x1 = ((widget.X + 1) * ent.XdrawCoef) + ent.XdrawOffs local w = (widget.W - 2) * ent.XdrawCoef local h = 1 * ent.YdrawCoef for offs=0, widget.numOptions, 1 do local y1 = ((widget.Y + 1 + (offs * widget.oSpacing)) * ent.YdrawCoef) + ent.YdrawOffs surface.DrawRect(x1, y1, w, h) end surface.SetDrawColor(ent.currentScheme.highlight.r, ent.currentScheme.highlight.g, ent.currentScheme.highlight.b, 255) local x1 = ((widget.X + 1) * ent.XdrawCoef) + ent.XdrawOffs local y1 = ((widget.Y + (widget.selected * widget.oSpacing) + 1) * ent.YdrawCoef) + ent.YdrawOffs local w = (widget.W - 2) * ent.XdrawCoef local h = (widget.oSpacing + 2) * ent.YdrawCoef surface.DrawRect(x1, y1, w, h) local x1 = ((widget.X + 2) * ent.XdrawCoef) + ent.XdrawOffs for k, text in ipairs(widget.options) do local y1 = ((widget.Y + ((k - 1) * widget.oSpacing)) * ent.YdrawCoef) + ent.YdrawOffs draw.DrawText(text, "guipfont"..16 - widget.size, x1, y1, Color(ent.currentScheme.text.r, ent.currentScheme.text.g, ent.currentScheme.text.b, 255), 0) end end, modClicked = function (ply, widget, Xpos, Ypos) widget.selected = math.Min(math.Round((Ypos - (widget.oSpacing / 2)) / widget.oSpacing), widget.numOptions) --clientSendOutput(widget, 1, widget.selected + 1) widget.parent:widgetOutput(ply, widget.modName, "selected", widget.selected + 1) guiP_cl_drawUpdate(widget, 1, widget.selected) --print ("sent "..widget.selected.."\n") end, modThink = nil, triggerInput = function (widget, inIndex, value) if (inIndex == "options") then --clientSendOutput(widget, 1, widget.selected + 1) widget.parent:widgetOutput(nil, widget.modName, "selected", widget.selected + 1) widget.options = string.Explode("|", value) widget.numOptions = table.getn(widget.options) - 1 widget.selected = 0 guiP_cl_drawUpdate(widget, 2, value) --print ("sent "..value.."\n") end end, drawUpdate = function (widget, paramNum, value) --print ("recieved "..value.."\n") if (paramNum == 1) then widget.selected = value elseif (paramNum == 2) then widget.options = string.Explode("|", value) widget.numOptions = table.getn(widget.options) - 1 widget.selected = 0 end end, inputs = {options = {index = 1, msgType = 2}}, outputs = {"selected"} }
gpl-3.0
nesstea/darkstar
scripts/zones/Bastok_Mines/npcs/Sieglinde.lua
32
1749
----------------------------------- -- Area: Bastok Mines -- NPC: Sieglinde -- Alchemy Synthesis Image Support ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,1); local SkillCap = getCraftSkillCap(player,SKILL_SMITHING); local SkillLevel = player:getSkillLevel(SKILL_SMITHING); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_ALCHEMY_IMAGERY) == false) then player:startEvent(0x007C,SkillCap,SkillLevel,2,201,player:getGil(),0,4095,0); else player:startEvent(0x007C,SkillCap,SkillLevel,2,201,player:getGil(),7009,4095,0); end else player:startEvent(0x007C); 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 == 0x007C and option == 1) then player:messageSpecial(ALCHEMY_SUPPORT,0,7,2); player:addStatusEffect(EFFECT_ALCHEMY_IMAGERY,1,0,120); end end;
gpl-3.0
NezzKryptic/Wire-Extras
lua/weapons/gmod_tool/stools/dscale.lua
4
3313
TOOL.Category = "Wire Extras/Obsolete" TOOL.Name = "Damage Scale" TOOL.Tab = "Wire" TOOL.Command = nil TOOL.ConfigName = "" if ( CLIENT ) then language.Add( "Tool.dscale.name", "Damage Scale Tool (Wire)" ) language.Add( "Tool.dscale.desc", "Spawns a Scale" ) language.Add( "Tool.dscale.0", "Primary: Create Scale, Secondary: Change model" ) language.Add( "Undone_wire damage scale", "Undone Wired Damage Scale" )//Typo end TOOL.ClientConVar["Model"] = "models/kobilica/wiremonitorrtbig.mdl" cleanup.Register("wire_dm_scale") function TOOL:LeftClick( trace ) if (!trace.HitPos) then return false end if (trace.Entity:IsPlayer()) then return false end if ( CLIENT ) then return true end local ply = self:GetOwner() local Ang = trace.HitNormal:Angle() Ang.pitch = Ang.pitch + 90 local s = MakeScaleEnt( ply, trace.HitPos, Ang , self:GetClientInfo("model")) local min = s:OBBMins() s:SetPos( trace.HitPos - trace.HitNormal * min.z ) local const = WireLib.Weld(s, trace.Entity, trace.PhysicsBone, true) undo.Create("Wire Damage Scale") undo.AddEntity( s ) undo.AddEntity( const ) undo.SetPlayer( ply ) undo.Finish() ply:AddCleanup( "dscale", s ) ply:AddCleanup( "dscale", const ) return true end function TOOL:RightClick( trace ) local ply = self:GetOwner() if (CLIENT) then return true end if (trace.Entity and trace.Entity:IsValid()) then if (trace.Entity:GetClass() == "prop_physics") then ply:ConCommand('dscale_Model "'..trace.Entity:GetModel()..'"\n') Msg("Damage Scale model set to "..trace.Entity:GetModel().."\n") else ply:PrintMessage(3,"Damage Scales only accept physics models!") end end return true end function TOOL:Reload( trace ) end if (SERVER) then function MakeScaleEnt( pl, Pos, Ang, Model ) local w = ents.Create( "damage_scaler" ) if (!w:IsValid()) then return false end w:SetAngles( Ang ) w:SetPos( Pos ) w:SetModel( Model )//Changed here w:Spawn() w:SetPlayer( pl ) w.pl = pl pl:AddCount("dscale", w) return w end //duplicator.RegisterEntityClass("damage_scaler", MakeScaleEnt, "pl", "Pos", "Model", "frozen") //Changed to match duplicator.RegisterEntityClass("Pos", "Ang", "Model", "Vel", "aVel", "frozen") end function TOOL:UpdateGhostW( ent, player ) if ( !ent || !ent:IsValid() ) then return end local tr = util.GetPlayerTrace( player, player:GetAimVector() ) local trace = util.TraceLine( tr ) if (!trace.Hit || trace.Entity:IsPlayer() || trace.Entity:GetClass() == "damage_scaler" ) then ent:SetNoDraw( true ) return end local Ang = trace.HitNormal:Angle() Ang.pitch = Ang.pitch + 90 local min = ent:OBBMins() ent:SetPos( trace.HitPos - trace.HitNormal * min.z ) ent:SetAngles( Ang ) ent:SetNoDraw( false ) end function TOOL:Think() if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != self.Model ) then self:MakeGhostEntity( self:GetClientInfo("Model"), Vector(0,0,0), Angle(0,0,0) ) end self:UpdateGhostW( self.GhostEntity, self:GetOwner() ) end function TOOL.BuildCPanel(panel) panel:AddControl("Header", { Text = "#Tool.dscale.name", Description = "#Tool.dscale.desc" }) end
gpl-3.0
nesstea/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Rasdinice.lua
19
1072
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Rasdinice -- @zone 80 -- @pos -8 1 35 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, 11637); -- (Couldn't find default text so i threw this in) Perhaps you should first attend to more pressing matters... 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
milkmanjack/lama
src/obj/Map.lua
1
5289
--[[ lama is a MUD server made in Lua. Copyright (C) 2013 Curtis Erickson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --- Cloneable that handles map data and processing. -- @author milkmanjack module("obj.Map", package.seeall) local Cloneable = require("obj.Cloneable") local MapTile = require("obj.MapTile") --- Cloneable that handles map data and processing. -- @class table -- @name Map -- @field width Horizontal width if the map. -- @field height Vertical height of the map. -- @field layers 3D height of the map. local Map = Cloneable.clone() -- runtime data Map.width = 0 Map.height = 0 Map.layers = 0 --- A 3D grid containing all of the MapTiles within a Map. -- The matrix is ordered in a layer->column->row format. Essentially, z->y->x. -- @class table -- @name Map.tiles Map.tiles = nil --- Contains every MapObject within the Map, including MapTiles. -- @class table -- @name Map.contents Map.contents = nil --- Creates a unique contents table for each Map. function Map:initialize() self.contents = {} end --- Set proportions of the map. function Map:setProportions(width,height,layers) self.width = width self.height = height self.layers = layers -- generate tables self.tiles = {} for x=1, width do self.tiles[x] = {} for y=1, height do self.tiles[x][y] = {} for z=1, layers do end end end end --- Adds a MapObject to our contents. -- MapObjects and Maps share mutual references to each other. -- If a MapObject is added to a Map's contents, the MapObject's -- map is set to it, and it is removed from whatever map it was in -- previously. -- @param mapObject MapObject to be added. function Map:addToContents(mapObject) table.insert(self.contents, mapObject) self.contents[mapObject] = true -- mutuality if mapObject:getMap() ~= self then mapObject:moveToMap(self) end end --- Removes a MapObject from our contents. -- MapObjects and Maps share mutual references to each other. -- If a MapObject is removed from a Map's contents, the MapObject's -- map is set to nil, and it is removed from any location in that map. -- @param mapObject MapObject to be removed. function Map:removeFromContents(mapObject) table.removeValue(self.contents, mapObject) self.contents[mapObject] = nil -- mutuality if mapObject:getMap() == self then mapObject:moveToMap(nil) mapObject:setLoc(nil) end end --- Assign a MapTile to a given XYZ location. -- @param tile The tile to be assigned. -- @param x The X location. -- @param y The Y location. -- @param z The Z location. function Map:setTile(tile, x, y, z) if tile:getMap() ~= self then tile:moveToMap(self) end tile:setXYZLoc(x,y,z) self.tiles[x][y][z] = tile end --- Gets the tile in the given direction from a MapObject. -- @param mapObject A MapObject on the Map. -- @param direction A direction. Always a member of the Direction table. -- @param The MapTile in the given direction.<br/>nil if none is found. function Map:getStep(mapObject, direction) local x,y,z = mapObject:getX(), mapObject:getY(), mapObject:getZ() -- update new xyz location if direction == Direction.NORTH or direction == Direction.NORTHEAST or direction == Direction.NORTHWEST then y = y + 1 elseif direction == Direction.SOUTH or direction == Direction.SOUTHEAST or direction == Direction.SOUTHWEST then y = y - 1 end if direction == Direction.EAST or direction == NORTHEAST or direction == NORTHWEST then x = x + 1 elseif direction == Direction.WEST or direction == Direction.NORTHWEST or direction == Direction.SOUTHWEST then x = x - 1 end return self:getTile(x,y,z) end --- Check if a Map contains a MapObject. -- @param mapObject The MapObject to check for. -- @return true if the Map contains it.<br/>false otherwise. function Map:contains(mapObject) return self.contents[mapObject] == true end --- Gets contents list. -- @return Contents list. function Map:getContents() return self.contents end --- Gets width of map. -- @return Width of map. function Map:getWidth() return self.width end --- Gets height of map. -- @return Height of map. function Map:getHeight() return self.height end --- Gets layer count of map. -- @return Layer count of map. function Map:getLayers() return self.layers end --- Gets tile list. -- @return Tile list. function Map:getTiles() return self.tiles end --- Get a tile at the given XYZ location. -- @param x X to check. -- @param y Y to check. -- @param z Z to check. -- @return MapTile if tile is found.<br/>nil otherwise. function Map:getTile(x,y,z) if x < 1 or x > self.width or y < 1 or y > self.height or z < 1 or z > self.layers then return nil end return self.tiles[x][y][z] end return Map
gpl-3.0
nesstea/darkstar
scripts/zones/Castle_Oztroja/npcs/_m74.lua
13
2224
----------------------------------- -- Area: Castle Oztroja -- NPC: _m74 (Torch Stand) -- Notes: Opens door _477 when _m72 to _m75 are lit -- @pos -59.525 -72.320 -62.379 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) DoorID = npc:getID() - 4; Torch1 = npc:getID() - 2; Torch2 = npc:getID() - 1; Torch3 = npc:getID(); Torch4 = npc:getID() + 1; DoorA = GetNPCByID(DoorID):getAnimation(); TorchStand1A = GetNPCByID(Torch1):getAnimation(); TorchStand2A = GetNPCByID(Torch2):getAnimation(); TorchStand3A = npc:getAnimation(); TorchStand4A = GetNPCByID(Torch4):getAnimation(); if (DoorA == 9 and TorchStand3A == 9) then player:startEvent(0x000a); else player:messageSpecial(TORCH_LIT); 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 (option == 1) then GetNPCByID(Torch3):openDoor(55); if ((DoorA == 9)) then GetNPCByID(DoorID):openDoor(35); -- The lamps shouldn't go off here, but I couldn't get the torches to update animation times without turning them off first -- They need to be reset to the door open time(35s) + 4s (39 seconds) GetNPCByID(Torch1):setAnimation(9); GetNPCByID(Torch2):setAnimation(9); GetNPCByID(Torch3):setAnimation(9); GetNPCByID(Torch4):setAnimation(9); GetNPCByID(Torch1):openDoor(39); GetNPCByID(Torch2):openDoor(39); GetNPCByID(Torch3):openDoor(39); GetNPCByID(Torch4):openDoor(39); end end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Southern_San_dOria/npcs/Nokkhi_Jinjahl.lua
13
13181
----------------------------------- -- Area: Southern San d'Oria -- NPC: Nokkhi Jinjahl -- Type: Travelling Merchant NPC / NPC Quiver Maker / San d'Oria 1st Place -- @zone: 230 -- @pos 24.829 0.978 -13.110 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local count = trade:getItemCount(); local carnation = trade:getItemQty(948) ----------------ARROWS---------------------------- local antlion = (trade:getItemQty(19195) / 99) local beetle = (trade:getItemQty(18154) / 99) local demon = (trade:getItemQty(18159) / 99) local gargou = (trade:getItemQty(19800) / 99) local horn = (trade:getItemQty(18156) / 99) local irona = (trade:getItemQty(17320) / 99) local kabura = (trade:getItemQty(17325) / 99) local ruszor = (trade:getItemQty(19182) / 99) local scorpion = (trade:getItemQty(18155) / 99) local silvera = (trade:getItemQty(17321) / 99) local sleepa = (trade:getItemQty(18158) / 99) ----------------BOLTS----------------------------- local acid = (trade:getItemQty(18148) / 99) local adamana = (trade:getItemQty(19801) / 99) local blind = (trade:getItemQty(18150) / 99) local bloody = (trade:getItemQty(18151) / 99) local darka = (trade:getItemQty(19183) / 99) local darkling = (trade:getItemQty(19196) / 99) local darksteel = (trade:getItemQty(17338) / 99) local fusion = (trade:getItemQty(19197) / 99) local holy = (trade:getItemQty(18153) / 99) local mythril = (trade:getItemQty(17337) / 99) local sleepb = (trade:getItemQty(18149) / 99) local venom = (trade:getItemQty(18152) / 99) ----------------BULLETS--------------------------- local adamanb = (trade:getItemQty(19803) / 99) local bullet = (trade:getItemQty(17340) / 99) local bronze = (trade:getItemQty(17343) / 99) local darkb = (trade:getItemQty(19184) / 99) local dweomer = (trade:getItemQty(19198) / 99) local ironb = (trade:getItemQty(17312) / 99) local oberons = (trade:getItemQty(19199) / 99) local orichalcum= (trade:getItemQty(19802) / 99) local silverb = (trade:getItemQty(17341) / 99) local steel = (trade:getItemQty(18723) / 99) local spartan = (trade:getItemQty(18160) / 99) ----------------CARDS----------------------------- local fire = (trade:getItemQty(2176) / 99) local ice = (trade:getItemQty(2177) / 99) local wind = (trade:getItemQty(2178) / 99) local earth = (trade:getItemQty(2179) / 99) local thunder = (trade:getItemQty(2180) / 99) local water = (trade:getItemQty(2181) / 99) local light = (trade:getItemQty(2182) / 99) local dark = (trade:getItemQty(2183) / 99) ----------------------------------------------------- local quiver = (antlion + beetle + demon + gargou + horn + irona + kabura + ruszor + scorpion + silvera + sleepa + acid + adamana + blind + bloody + darka + darkling + darksteel + fusion + holy + mythril + sleepb + venom + adamanb + bullet + bronze + darkb + dweomer + ironb + oberons + orichalcum + silverb + steel + spartan + fire + ice + wind + earth + thunder + water + light + dark) if (((quiver * 99) + carnation) == count) then if ((quiver == math.floor(quiver)) and (quiver == carnation) and (player:getFreeSlotsCount() >= carnation)) then player:tradeComplete(); ----------------ARROWS---------------------------- if (antlion > 0) then player:addItem(5819,antlion); player:messageSpecial(ITEM_OBTAINED,5819); end if (beetle > 0) then player:addItem(4221,beetle); player:messageSpecial(ITEM_OBTAINED,4221); end if (demon > 0) then player:addItem(4224,demon); player:messageSpecial(ITEM_OBTAINED,4224); end if (gargou > 0) then player:addItem(5912,gargouille); player:messageSpecial(ITEM_OBTAINED,5912); end if (horn > 0) then player:addItem(4222,horn); player:messageSpecial(ITEM_OBTAINED,4222); end if (irona > 0) then player:addItem(4225,irona); player:messageSpecial(ITEM_OBTAINED,4225); end if (kabura > 0) then player:addItem(5332,kabura); player:messageSpecial(ITEM_OBTAINED,5332); end if (ruszor > 0) then player:addItem(5871,ruszor); player:messageSpecial(ITEM_OBTAINED,5871); end if (scorpion > 0) then player:addItem(4223,scorpion); player:messageSpecial(ITEM_OBTAINED,4223); end if (silvera > 0) then player:addItem(4226,silvera); player:messageSpecial(ITEM_OBTAINED,4226); end if (sleepa > 0) then player:addItem(5333,sleepa); player:messageSpecial(ITEM_OBTAINED,5333); end ----------------BOLTS----------------------------- if (acid > 0) then player:addItem(5335,acid); player:messageSpecial(ITEM_OBTAINED,5335); end if (adamana > 0) then player:addItem(5913,adamana); player:messageSpecial(ITEM_OBTAINED,5913); end if (blind > 0) then player:addItem(5334,blind); player:messageSpecial(ITEM_OBTAINED,5334); end if (bloody > 0) then player:addItem(5339,bloody); player:messageSpecial(ITEM_OBTAINED,5339); end if (darka > 0) then player:addItem(5872,darka); player:messageSpecial(ITEM_OBTAINED,5872); end if (darkling > 0) then player:addItem(5820,darkling); player:messageSpecial(ITEM_OBTAINED,5820); end if (darksteel > 0) then player:addItem(4229,darksteel); player:messageSpecial(ITEM_OBTAINED,4229); end if (fusion > 0) then player:addItem(5821,fusion); player:messageSpecial(ITEM_OBTAINED,5821); end if (holy > 0) then player:addItem(5336,holy); player:messageSpecial(ITEM_OBTAINED,5336); end if (mythril > 0) then player:addItem(4228,mythril); player:messageSpecial(ITEM_OBTAINED,4228); end if (sleepb > 0) then player:addItem(5337,sleepb); player:messageSpecial(ITEM_OBTAINED,5337); end if (venom > 0) then player:addItem(5338,venom); player:messageSpecial(ITEM_OBTAINED,5338); end ----------------BULLETS--------------------------- if (adamanb > 0) then player:addItem(5915,adamanb); player:messageSpecial(ITEM_OBTAINED,5915); end if (bullet > 0) then player:addItem(5363,bullet); player:messageSpecial(ITEM_OBTAINED,5363); end if (bronze > 0) then player:addItem(5359,bronze); player:messageSpecial(ITEM_OBTAINED,5359); end if (darkb > 0) then player:addItem(5873,darkb); player:messageSpecial(ITEM_OBTAINED,5873); end if (dweomer > 0) then player:addItem(5822,dweomer); player:messageSpecial(ITEM_OBTAINED,5822); end if (ironb > 0) then player:addItem(5353,ironb); player:messageSpecial(ITEM_OBTAINED,5353); end if (oberons > 0) then player:addItem(5823,oberons); player:messageSpecial(ITEM_OBTAINED,5823); end if (orichalcum > 0) then player:addItem(5914,orichalcum); player:messageSpecial(ITEM_OBTAINED,5914); end if (silverb > 0) then player:addItem(5340,silverb); player:messageSpecial(ITEM_OBTAINED,5340); end if (steel > 0) then player:addItem(5416,steel); player:messageSpecial(ITEM_OBTAINED,5416); end if (spartan > 0) then player:addItem(5341,spartan); player:messageSpecial(ITEM_OBTAINED,5341); end ----------------CARDS----------------------------- if (fire > 0) then player:addItem(5402,fire); player:messageSpecial(ITEM_OBTAINED,5402); end if (ice > 0) then player:addItem(5403,ice); player:messageSpecial(ITEM_OBTAINED,5403); end if (wind > 0) then player:addItem(5404,wind); player:messageSpecial(ITEM_OBTAINED,5404); end if (earth > 0) then player:addItem(5405,earth); player:messageSpecial(ITEM_OBTAINED,5405); end if (thunder > 0) then player:addItem(5406,thunder); player:messageSpecial(ITEM_OBTAINED,5406); end if (water > 0) then player:addItem(5407,water); player:messageSpecial(ITEM_OBTAINED,5407); end if (light > 0) then player:addItem(5408,light); player:messageSpecial(ITEM_OBTAINED,5408); end if (dark > 0) then player:addItem(5409,dark); player:messageSpecial(ITEM_OBTAINED,5409); end end end --948 - carnation --SINGLE--ARROWS----------------STACK --19195 - antlion arrow - 5819 --18154 - beetle arrow - 4221 --18159 - demon arrow - 4224 --19800 - gargouille arrow - 5912 --18156 - horn arrow - 4222 --17320 - iron arrow - 4225 --17325 - kabura arrow - 5332 --19182 - ruszor arrow - 5871 --18155 - scorpion arrow - 4223 --17321 - silver arrow - 4226 --18158 - sleep arrow - 5333 ----------BOLTS----------------------- --18148 - acid bolt - 5335 --19801 - adaman bolt - 5913 --18150 - blind bolt - 5334 --18151 - bloody bolt - 5339 --19183 - dark adaman bolt - 5872 --19196 - darkling bolt - 5820 --17338 - darksteel bolt - 4229 --19197 - fusion bolt - 5821 --18153 - holy bolt - 5336 --17337 - mythril bolt - 4228 --18149 - sleep bolt - 5337 --18152 - venom bolt - 5338 ----------BULLETS--------------------- --19803 - adaman bullet - 5915 --17340 - bullet - 5363 --17343 - bronze bullet - 5359 --19184 - dark adaman bullet- 5873 --19198 - dweomer bullet - 5822 --17312 - iron bullet - 5353 --19199 - oberon's bullet - 5823 --19802 - orichalcum bullet - 5914 --17341 - silver bullet - 5340 --18723 - steel bullet - 5416 --18160 - spartan bullet - 5341 ----------CARDS----------------------- --2176 - fire card - 5402 --2177 - ice card - 5403 --2178 - wind card - 5404 --2179 - earth card - 5405 --2180 - thunder card - 5406 --2181 - water card - 5407 --2182 - light card - 5408 --2183 - dark card - 5409 -------------------------------------- end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02ab,npc:getID()); 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
FailcoderAddons/supervillain-ui
SVUI_!Core/libs/AceGUI-3.0/widgets/AceGUIWidget-Keybinding.lua
25
6806
--[[----------------------------------------------------------------------------- Keybinding Widget Set Keybindings in the Config UI. -------------------------------------------------------------------------------]] local Type, Version = "Keybinding", 25 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local pairs = pairs -- WoW APIs local IsShiftKeyDown, IsControlKeyDown, IsAltKeyDown = IsShiftKeyDown, IsControlKeyDown, IsAltKeyDown local CreateFrame, UIParent = CreateFrame, UIParent -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: NOT_BOUND --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function Control_OnEnter(frame) frame.obj:Fire("OnEnter") end local function Control_OnLeave(frame) frame.obj:Fire("OnLeave") end local function Keybinding_OnClick(frame, button) if button == "LeftButton" or button == "RightButton" then local self = frame.obj if self.waitingForKey then frame:EnableKeyboard(false) frame:EnableMouseWheel(false) self.msgframe:Hide() frame:UnlockHighlight() self.waitingForKey = nil else frame:EnableKeyboard(true) frame:EnableMouseWheel(true) self.msgframe:Show() frame:LockHighlight() self.waitingForKey = true end end AceGUI:ClearFocus() end local ignoreKeys = { ["BUTTON1"] = true, ["BUTTON2"] = true, ["UNKNOWN"] = true, ["LSHIFT"] = true, ["LCTRL"] = true, ["LALT"] = true, ["RSHIFT"] = true, ["RCTRL"] = true, ["RALT"] = true, } local function Keybinding_OnKeyDown(frame, key) local self = frame.obj if self.waitingForKey then local keyPressed = key if keyPressed == "ESCAPE" then keyPressed = "" else if ignoreKeys[keyPressed] then return end if IsShiftKeyDown() then keyPressed = "SHIFT-"..keyPressed end if IsControlKeyDown() then keyPressed = "CTRL-"..keyPressed end if IsAltKeyDown() then keyPressed = "ALT-"..keyPressed end end frame:EnableKeyboard(false) frame:EnableMouseWheel(false) self.msgframe:Hide() frame:UnlockHighlight() self.waitingForKey = nil if not self.disabled then self:SetKey(keyPressed) self:Fire("OnKeyChanged", keyPressed) end end end local function Keybinding_OnMouseDown(frame, button) if button == "LeftButton" or button == "RightButton" then return elseif button == "MiddleButton" then button = "BUTTON3" elseif button == "Button4" then button = "BUTTON4" elseif button == "Button5" then button = "BUTTON5" end Keybinding_OnKeyDown(frame, button) end local function Keybinding_OnMouseWheel(frame, direction) local button if direction >= 0 then button = "MOUSEWHEELUP" else button = "MOUSEWHEELDOWN" end Keybinding_OnKeyDown(frame, button) end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self:SetWidth(200) self:SetLabel("") self:SetKey("") self.waitingForKey = nil self.msgframe:Hide() self:SetDisabled(false) self.button:EnableKeyboard(false) self.button:EnableMouseWheel(false) end, -- ["OnRelease"] = nil, ["SetDisabled"] = function(self, disabled) self.disabled = disabled if disabled then self.button:Disable() self.label:SetTextColor(0.5,0.5,0.5) else self.button:Enable() self.label:SetTextColor(1,1,1) end end, ["SetKey"] = function(self, key) if (key or "") == "" then self.button:SetText(NOT_BOUND) self.button:SetNormalFontObject("GameFontNormal") else self.button:SetText(key) self.button:SetNormalFontObject("GameFontHighlight") end end, ["GetKey"] = function(self) local key = self.button:GetText() if key == NOT_BOUND then key = nil end return key end, ["SetLabel"] = function(self, label) self.label:SetText(label or "") if (label or "") == "" then self.alignoffset = nil self:SetHeight(24) else self.alignoffset = 30 self:SetHeight(44) end end, } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local ControlBackdrop = { bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", tile = true, tileSize = 16, edgeSize = 16, insets = { left = 3, right = 3, top = 3, bottom = 3 } } local function keybindingMsgFixWidth(frame) frame:SetWidth(frame.msg:GetWidth() + 10) frame:SetScript("OnUpdate", nil) end local function Constructor() local name = "AceGUI30KeybindingButton" .. AceGUI:GetNextWidgetNum(Type) local frame = CreateFrame("Frame", nil, UIParent) local button = CreateFrame("Button", name, frame, "UIPanelButtonTemplate") button:EnableMouse(true) button:EnableMouseWheel(false) button:RegisterForClicks("AnyDown") button:SetScript("OnEnter", Control_OnEnter) button:SetScript("OnLeave", Control_OnLeave) button:SetScript("OnClick", Keybinding_OnClick) button:SetScript("OnKeyDown", Keybinding_OnKeyDown) button:SetScript("OnMouseDown", Keybinding_OnMouseDown) button:SetScript("OnMouseWheel", Keybinding_OnMouseWheel) button:SetPoint("BOTTOMLEFT") button:SetPoint("BOTTOMRIGHT") button:SetHeight(24) button:EnableKeyboard(false) local text = button:GetFontString() text:SetPoint("LEFT", 7, 0) text:SetPoint("RIGHT", -7, 0) local label = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlight") label:SetPoint("TOPLEFT") label:SetPoint("TOPRIGHT") label:SetJustifyH("CENTER") label:SetHeight(18) local msgframe = CreateFrame("Frame", nil, UIParent) msgframe:SetHeight(30) msgframe:SetBackdrop(ControlBackdrop) msgframe:SetBackdropColor(0,0,0) msgframe:SetFrameStrata("FULLSCREEN_DIALOG") msgframe:SetFrameLevel(1000) msgframe:SetToplevel(true) local msg = msgframe:CreateFontString(nil, "OVERLAY", "GameFontNormal") msg:SetText("Press a key to bind, ESC to clear the binding or click the button again to cancel.") msgframe.msg = msg msg:SetPoint("TOPLEFT", 5, -5) msgframe:SetScript("OnUpdate", keybindingMsgFixWidth) msgframe:SetPoint("BOTTOM", button, "TOP") msgframe:Hide() local widget = { button = button, label = label, msgframe = msgframe, frame = frame, alignoffset = 30, type = Type } for method, func in pairs(methods) do widget[method] = func end button.obj = widget return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
mit
nesstea/darkstar
scripts/zones/Windurst_Woods/npcs/Forine.lua
27
1121
----------------------------------- -- Area: Windurst Woods -- NPC: Forine -- Involved In Mission: Journey Abroad -- @zone 241 -- @pos -52.677 -0.501 -26.299 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01bd); 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
malortie/gmod-addons
th_weapons/lua/entities/ent_weapon_th_glock/init.lua
1
1178
-- Only enable this addon if HL:S is mounted. if !IsHL1Mounted() then return end ------------------------------------- -- Weapon Glock spawning. ------------------------------------- AddCSLuaFile('cl_init.lua') AddCSLuaFile('shared.lua') include('shared.lua') -- Define a global variable to ease calling base class methods. DEFINE_BASECLASS( 'base_point' ) --[[--------------------------------------------------------- Called to spawn this entity. @param ply The player spawner. @param tr The trace result from player's eye to the spawn point. @param ClassName The entity's class name. @return true on success. @return false on failure. -----------------------------------------------------------]] function ENT:SpawnFunction( ply, tr, ClassName ) -- Do not spawn at an invalid position. if ( !tr.Hit ) then return end -- Spawn the entity at the hit position, -- facing toward the player. local SpawnPos = tr.HitPos + tr.HitNormal local SpawnAng = ply:EyeAngles() SpawnAng.p = 0 SpawnAng.y = SpawnAng.y + 180 local ent = ents.Create( 'weapon_th_glock' ) ent:SetPos( SpawnPos ) ent:SetAngles( SpawnAng ) ent:Spawn() ent:Activate() return ent end
gpl-3.0
johnmccabe/dockercraft
world/Plugins/APIDump/Hooks/OnPlayerPlacedBlock.lua
36
1637
return { HOOK_PLAYER_PLACED_BLOCK = { CalledWhen = "After a player has placed a block. Notification only.", DefaultFnName = "OnPlayerPlacedBlock", -- also used as pagename Desc = [[ This hook is called after a {{cPlayer|player}} has placed a block in the {{cWorld|world}}. The block is already added to the world and the corresponding item removed from player's {{cInventory|inventory}}.</p> <p> Use the {{cPlayer}}:GetWorld() function to get the world to which the block belongs.</p> <p> See also the {{OnPlayerPlacingBlock|HOOK_PLAYER_PLACING_BLOCK}} hook for a similar hook called before the placement.</p> <p> If the client action results in multiple blocks being placed (such as a bed or a door), each separate block is reported through this hook. All the blocks are already present in the world before the first instance of this hook is called. ]], Params = { { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who placed the block" }, { Name = "BlockX", Type = "number", Notes = "X-coord of the block" }, { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" }, { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" }, { Name = "BlockType", Type = "BLOCKTYPE", Notes = "The block type of the block" }, { Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "The block meta of the block" }, }, Returns = [[ If this function returns false or no value, Cuberite calls other plugins with the same event. If this function returns true, no other plugin is called for this event. ]], }, -- HOOK_PLAYER_PLACED_BLOCK }
apache-2.0
UnfortunateFruit/darkstar
scripts/zones/Windurst_Waters/npcs/Lumomo.lua
12
2828
----------------------------------- -- Area: Windurst Waters -- NPC: Lumomo -- Type: Standard NPC -- @zone: 238 -- @pos -55.770 -5.499 18.914 -- 0x027e 0x0332 0x0334 0x0336 0x0337 -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ecoWarWindurst = player:getQuestStatus(WINDURST,ECO_WARRIOR_WIN); local ecoWarActiveNation = player:getVar("ECO_WARRIOR_ACTIVE"); if(player:hasKeyItem(INDIGESTED_MEAT) and ecoWarActiveNation == 238) then player:startEvent(0x0336); -- quest done elseif(ecoWarActiveNation < 1 and player:getFameLevel(WINDURST) >= 1 and player:getVar("ECO-WAR_ConquestWeek") ~= getConquestTally()) then player:startEvent(0x0332); -- Start CS elseif(ecoWarActiveNation ~= 238 and ecoWarActiveNation > 1) then player:startEvent(0x0337); elseif(ecoWarWindurst ~= QUEST_AVAILABLE and ecoWarActiveNation == 238 and player:getVar("ECO-WAR_ConquestWeek") ~= getConquestTally()) then player:startEvent(0x0334); -- reminder else player:startEvent(0x0335); -- Default chit-chat 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 == 0x0332 and option == 1) then if(player:getQuestStatus(WINDURST,ECO_WARRIOR_WIN) == QUEST_AVAILABLE) then player:addQuest(WINDURST,ECO_WARRIOR_WIN); end player:setVar("ECO_WARRIOR_ACTIVE",player:getZoneID()); player:setVar("ECO-WAR_ConquestWeek",0); elseif(csid == 0x0336) then if(player:getFreeSlotsCount() >= 1) then player:completeQuest(WINDURST,ECO_WARRIOR_WIN); player:delKeyItem(INDIGESTED_MEAT); player:addGil(GIL_RATE * 5000); player:messageSpecial(GIL_OBTAINED,GIL_RATE * 5000); player:addItem(4198); player:messageSpecial(ITEM_OBTAINED,4198); player:addTitle(EMERALD_EXTERMINATOR); player:addFame(WINDURST,WIN_FAME * 80); player:setVar("ECO-WAR_ConquestWeek",getConquestTally()) player:setVar("ECO_WARRIOR_ACTIVE",0); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4198); end end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Windurst_Waters/npcs/Yung_Yaam.lua
12
1770
----------------------------------- -- Area: Windurst Waters -- NPC: Yung Yaam -- Involved In Quest: Wondering Minstrel -- Working 100% -- @zone = 238 -- @pos = -63 -4 27 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- 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) --player:addFame(WINDURST,100) wonderingstatus = player:getQuestStatus(WINDURST,WONDERING_MINSTREL); fame = player:getFameLevel(WINDURST) if (wonderingstatus <= 1 and fame >= 5) then player:startEvent(0x027d); -- WONDERING_MINSTREL: Quest Available / Quest Accepted elseif (wonderingstatus == QUEST_COMPLETED and player:needToZone()) then player:startEvent(0x0283); -- WONDERING_MINSTREL: Quest After else player:startEvent(0x0261); -- Standard Conversation end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Windurst_Walls/npcs/_6n2.lua
12
5603
----------------------------------- -- Area: Windurst Walls -- Door: House of the Hero -- Involved in Mission 2-1 -- Involved In Quest: Know One's Onions, Onion Rings, The Puppet Master, Class Reunion -- @pos -26 -13 260 239 ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Windurst_Walls/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ThePuppetMaster = player:getQuestStatus(WINDURST,THE_PUPPET_MASTER); local ClassReunion = player:getQuestStatus(WINDURST,CLASS_REUNION); local CarbuncleDebacle = player:getQuestStatus(WINDURST,CARBUNCLE_DEBACLE); -- Check for Missions first (priority?) if (player:getCurrentMission(WINDURST) == LOST_FOR_WORDS and player:getVar("MissionStatus") == 5) then player:startEvent(0x0151); else ---------------------------------------------------- -- Carbuncle Debacle if (player:getMainLvl() >= AF2_QUEST_LEVEL and player:getMainJob() == 15 and ClassReunion == QUEST_COMPLETED and CarbuncleDebacle == QUEST_AVAILABLE and player:needToZone() == false) then player:startEvent(0x019f); -- Carby begs for your help ---------------------------------------------------- -- Class Reunion elseif (player:getMainLvl() >= AF2_QUEST_LEVEL and player:getMainJob() == 15 and ThePuppetMaster == QUEST_COMPLETED and ClassReunion == QUEST_AVAILABLE and player:needToZone() == false) then player:startEvent(0x019d); -- Carby asks for your help again. ---------------------------------------------------- -- The Puppet Master elseif (player:getMainLvl() >= AF1_QUEST_LEVEL and player:getMainJob() == 15 and ThePuppetMaster ~= QUEST_ACCEPTED and player:needToZone() == false and ClassReunion ~= QUEST_ACCEPTED and CarbuncleDebacle ~= QUEST_ACCEPTED) then -- you need to be on SMN as well to repeat the quest player:startEvent(0x0192); -- Carby asks for your help, visit Juroro elseif (player:getQuestStatus(WINDURST,THE_PUPPET_MASTER) == QUEST_ACCEPTED and player:getVar("ThePuppetMasterProgress") == 1) then player:startEvent(0x0193); -- reminder to visit Juroro ---------------------------------------------------- elseif (player:hasKeyItem(JOKER_CARD)) then player:startEvent(0x0183,0,JOKER_CARD); elseif (player:getVar("WildCard") == 1) then player:startEvent(0x0182); elseif (player:getVar("OnionRings") == 1) then player:startEvent(0x0121); elseif (player:getVar("KnowOnesOnions") == 1) then player:startEvent(0x0120,0,4387); elseif (player:getQuestStatus(WINDURST,I_CAN_HEAR_A_RAINBOW) == QUEST_AVAILABLE and player:getMainLvl() >= 30 and player:hasItem(1125)) then player:startEvent(0x0180,1125,1125,1125,1125,1125,1125,1125,1125); elseif (player:getQuestStatus(WINDURST,I_CAN_HEAR_A_RAINBOW) == QUEST_ACCEPTED) then player:startEvent(0x0181,1125,1125,1125,1125,1125,1125,1125,1125); else player:messageSpecial(7532); -- "The doors are firmly sealed shut." end; end; return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0120) then player:setVar("KnowOnesOnions",2); elseif (csid == 0x0121) then player:completeQuest(WINDURST,ONION_RINGS); player:addFame(WINDURST,100); player:addTitle(STAR_ONION_BRIGADIER); player:delKeyItem(OLD_RING); player:setVar("OnionRingsTime",0); player:setVar("OnionRings",2); elseif (csid == 0x0180) then player:addQuest(WINDURST, I_CAN_HEAR_A_RAINBOW); elseif (csid == 0x0182) then player:setVar("WildCard",2); elseif (csid == 0x0183) then player:delKeyItem(JOKER_CARD); player:addGil(GIL_RATE*8000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*8000); elseif (csid == 0x0151) then -- Mark the progress player:setVar("MissionStatus",6); elseif (csid == 0x0192) then if (player:getQuestStatus(WINDURST,THE_PUPPET_MASTER) == QUEST_COMPLETED) then player:delQuest(WINDURST,THE_PUPPET_MASTER); player:addQuest(WINDURST,THE_PUPPET_MASTER); -- this needs only if you repeat this quest end; player:setVar("ThePuppetMasterProgress",1); player:addQuest(WINDURST,THE_PUPPET_MASTER); elseif (csid == 0x019d) then player:setVar("ClassReunionProgress",1); player:addQuest(WINDURST,CLASS_REUNION); player:addKeyItem(CARBUNCLES_TEAR); player:messageSpecial(KEYITEM_OBTAINED,CARBUNCLES_TEAR); elseif (csid == 0x019f) then player:addQuest(WINDURST,CARBUNCLE_DEBACLE); player:setVar("CarbuncleDebacleProgress",1); end; end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Carpenters_Landing/npcs/Logging_Point.lua
29
1116
----------------------------------- -- Area: Carpenters Landing -- NPC: Logging Point ----------------------------------- package.loaded["scripts/zones/Carpenters_Landing/TextIDs"] = nil; ------------------------------------- require("scripts/globals/logging"); require("scripts/zones/Carpenters_Landing/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startLogging(player,player:getZoneID(),npc,trade,0x001E); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(LOGGING_IS_POSSIBLE_HERE,1021); 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
nesstea/darkstar
scripts/zones/Lower_Jeuno/npcs/Kurou-Morou.lua
25
5570
----------------------------------- -- Area: Lower Jeuno -- Starts and Finishes Quest: Your Crystal Ball & Never to return -- @pos -4 -6 -28 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,YOUR_CRYSTAL_BALL) == QUEST_ACCEPTED and trade:getItemCount() == 1) then if (trade:hasItemQty(557,1) == true) then player:startEvent(0x00C0); -- CS for ahriman lens trade; Trading the lens to Kurou-Morou is optional elseif (trade:hasItemQty(556,1) == true) then player:startEvent(0x00C4); -- Trade divination sphere, finish quest end elseif (player:getQuestStatus(JEUNO,NEVER_TO_RETURN) == QUEST_ACCEPTED and trade:hasItemQty(12507,1) == true and trade:getItemCount() == 1) then player:startEvent(0x00Cb); -- Finish "Never to return" quest end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) printf("Ontrigger completed"); local YourCrystalBall = player:getQuestStatus(JEUNO,YOUR_CRYSTAL_BALL); local SearchingForTheRightWords = player:getQuestStatus(JEUNO,SEARCHING_FOR_THE_RIGHT_WORDS); local ACandlelightVigil = player:getQuestStatus(JEUNO,A_CANDLELIGHT_VIGIL); local RubbishDay = player:getQuestStatus(JEUNO,RUBBISH_DAY); local NeverToReturn = player:getQuestStatus(JEUNO,NEVER_TO_RETURN); local JFame = player:getFameLevel(JEUNO); local SearchingForWords_prereq = player:getVar("QuestSearchRightWords_prereq"); if (JFame >= 2 and YourCrystalBall == QUEST_AVAILABLE) then player:startEvent(0x00C2); -- Start "Your Crystal Ball" quest elseif (JFame >= 5 and YourCrystalBall == QUEST_COMPLETED and player:getQuestStatus(JEUNO,NEVER_TO_RETURN) == QUEST_AVAILABLE and player:getVar("QuestNeverToReturn_day") ~= VanadielDayOfTheYear()) then prog = player:getVar("QuestNeverToReturn_prog"); if (prog <= 2) then fortune = math.random(1,99); player:startEvent(0x00Cc,fortune); -- Required to get fortune read 3x on 3 diff game days before quest is kicked off elseif (prog == 3) then player:startEvent(0x00Ca); -- Start "Never to return" quest end --if searching for right words *prereq* CS has been activated elseif (SearchingForWords_prereq == 1) then player:startEvent(0x0026); elseif (player:getVar("QuestSearchRightWords_denied") == 1) then player:startEvent(0x0024); elseif (SearchingForTheRightWords == QUEST_ACCEPTED) then player:startEvent(0x0027); elseif (player:getVar("SearchingForRightWords_postcs") == -2) then player:startEvent(0x009a); elseif (SearchingForTheRightWords == QUEST_COMPLETED) then --final state, after all quests complete player:startEvent(0x0025); --conditions for searching for the right words elseif (ACandlelightVigil == QUEST_COMPLETED and RubbishDay == QUEST_COMPLETED and NeverToReturn == QUEST_COMPLETED and SearchingForTheRightWords == QUEST_AVAILABLE) then player:startEvent(0x0011); else player:startEvent(0x00C1); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00C2 and option == 0) then player:addQuest(JEUNO,YOUR_CRYSTAL_BALL); elseif (csid == 0x00C4) then player:addTitle(FORTUNETELLER_IN_TRAINING); player:addFame(JEUNO, 30); player:tradeComplete(trade); player:completeQuest(JEUNO,YOUR_CRYSTAL_BALL); elseif (csid == 0x00Cc and option == 0) then player:setVar("QuestNeverToReturn_prog", player:getVar("QuestNeverToReturn_prog") + 1); -- Keep track of how many times the players fortune has been read player:setVar("QuestNeverToReturn_day", VanadielDayOfTheYear()); -- new vanadiel day elseif (csid == 0x00Ca and option == 0) then player:addQuest(JEUNO,NEVER_TO_RETURN); player:setVar("QuestNeverToReturn_prog", 0); player:setVar("QuestNeverToReturn_day", 0); elseif (csid == 0x00Cb) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13477); else player:addGil(GIL_RATE*1200); player:messageSpecial(GIL_OBTAINED,GIL_RATE*1200); player:addItem(13477); player:messageSpecial(ITEM_OBTAINED,13477); player:addFame(JEUNO, 30); player:tradeComplete(trade); player:completeQuest(JEUNO,NEVER_TO_RETURN); end elseif (csid == 0x0011) then player:setVar("QuestSearchRightWords_prereq", 1); elseif (csid == 0x009a) then player:setVar("SearchingForRightWords_postcs", -1); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Dynamis-Xarcabard/bcnms/dynamis_xarcabard.lua
21
1443
----------------------------------- -- Area: Dynamis Xarcabard -- Name: Dynamis Xarcabard ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[DynaXarcabard]UniqueID",player:getDynamisUniqueID(1285)); SetServerVariable("[DynaXarcabard]TE43_Trigger",0); SetServerVariable("[DynaXarcabard]TE60_Trigger",0); SetServerVariable("[DynaXarcabard]TE150_Trigger",0); SetServerVariable("[DynaXarcabard]Boss_Trigger",0); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("DynamisID",GetServerVariable("[DynaXarcabard]UniqueID")); local realDay = os.time(); if (DYNA_MIDNIGHT_RESET == true) then realDay = getMidnight() - 86400; end local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay) then player:setVar("dynaWaitxDay",realDay); end end; -- Leaving the Dynamis by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 4) then GetNPCByID(17330778):setStatus(2); SetServerVariable("[DynaXarcabard]UniqueID",0); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Port_Bastok/npcs/Raifa.lua
38
1026
----------------------------------- -- Area: Port Bastok -- NPC: Raifa -- Type: Quest Giver -- @zone: 236 -- @pos -166.416 -8.48 7.153 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0116); 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
nesstea/darkstar
scripts/zones/Buburimu_Peninsula/npcs/Cavernous_Maw.lua
58
1890
----------------------------------- -- Area: Buburimu Peninsula -- NPC: Cavernous Maw -- @pos -334 -24 52 -- Teleports Players to Abyssea - Attohwa ----------------------------------- package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/abyssea"); require("scripts/zones/Buburimu_Peninsula/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_ABYSSEA == 1 and player:getMainLvl() >= 30) then local HasStone = getTravStonesTotal(player); if (HasStone >= 1 and player:getQuestStatus(ABYSSEA, DAWN_OF_DEATH) == QUEST_ACCEPTED and player:getQuestStatus(ABYSSEA, A_FLUTTERY_FIEND) == QUEST_AVAILABLE) then player:startEvent(62); else player:startEvent(61,0,1); -- No param = no entry. end 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 == 62) then player:addQuest(ABYSSEA, A_FLUTTERY_FIEND); elseif (csid == 63) then -- Killed Itzpapalotl elseif (csid == 61 and option == 1) then player:setPos(-140, 20, -181, 131, 215); end end;
gpl-3.0
Cyumus/NutScript
gamemode/core/sh_util.lua
1
24654
-- Includes a file from the prefix. function nut.util.include(fileName, state) if (!fileName) then error("[NutScript] No file name specified for including.") end -- Only include server-side if we're on the server. if ((state == "server" or fileName:find("sv_")) and SERVER) then include(fileName) -- Shared is included by both server and client. elseif (state == "shared" or fileName:find("sh_")) then if (SERVER) then -- Send the file to the client if shared so they can run it. AddCSLuaFile(fileName) end include(fileName) -- File is sent to client, included on client. elseif (state == "client" or fileName:find("cl_")) then if (SERVER) then AddCSLuaFile(fileName) else include(fileName) end end end -- Include files based off the prefix within a directory. function nut.util.includeDir(directory, fromLua) -- By default, we include relatively to NutScript. local baseDir = "nutscript" -- If we're in a schema, include relative to the schema. if (SCHEMA and SCHEMA.folder and SCHEMA.loading) then baseDir = SCHEMA.folder.."/schema/" else baseDir = baseDir.."/gamemode/" end -- Find all of the files within the directory. for k, v in ipairs(file.Find((fromLua and "" or baseDir)..directory.."/*.lua", "LUA")) do -- Include the file from the prefix. nut.util.include(directory.."/"..v) end end -- Returns the address:port of the server. function nut.util.getAddress() local address = tonumber(GetConVarString("hostip")) if (!address) then return "127.0.0.1"..":"..GetConVarString("hostport") end local ip = {} ip[1] = bit.rshift(bit.band(address, 0xFF000000), 24) ip[2] = bit.rshift(bit.band(address, 0x00FF0000), 16) ip[3] = bit.rshift(bit.band(address, 0x0000FF00), 8) ip[4] = bit.band(address, 0x000000FF) return table.concat(ip, ".")..":"..GetConVarString("hostport") end -- Returns a table of admin players function nut.util.getAdmins(isSuper) local admins = {} for k, v in ipairs(player.GetAll()) do if (isSuper) then if (v:IsSuperAdmin()) then table.insert(admins, v) end else if (v:IsAdmin()) then table.insert(admins, v) end end end return admins end -- Returns a single cached copy of a material or creates it if it doesn't exist. function nut.util.getMaterial(materialPath) -- Cache the material. nut.util.cachedMaterials = nut.util.cachedMaterials or {} nut.util.cachedMaterials[materialPath] = nut.util.cachedMaterials[materialPath] or Material(materialPath) return nut.util.cachedMaterials[materialPath] end -- Finds a player by matching their names. function nut.util.findPlayer(name, allowPatterns) if (!allowPatterns) then name = string.PatternSafe(name) end for k, v in ipairs(player.GetAll()) do if (nut.util.stringMatches(v:Name(), name)) then return v end end end -- Returns whether or a not a string matches. function nut.util.stringMatches(a, b) if (a and b) then local a2, b2 = a:lower(), b:lower() -- Check if the actual letters match. if (a == b) then return true end if (a2 == b2) then return true end -- Be less strict and search. if (a:find(b)) then return true end if (a2:find(b2)) then return true end end return false end local ADJUST_SOUND = SoundDuration("npc/metropolice/pain1.wav") > 0 and "" or "../../hl2/sound/" -- Emits sounds one after the other from an entity. function nut.util.emitQueuedSounds(entity, sounds, delay, spacing, volume, pitch) -- Let there be a delay before any sound is played. delay = delay or 0 spacing = spacing or 0.1 -- Loop through all of the sounds. for k, v in ipairs(sounds) do local postSet, preSet = 0, 0 -- Determine if this sound has special time offsets. if (type(v) == "table") then postSet, preSet = v[2] or 0, v[3] or 0 v = v[1] end -- Get the length of the sound. local length = SoundDuration(ADJUST_SOUND..v) -- If the sound has a pause before it is played, add it here. delay = delay + preSet -- Have the sound play in the future. timer.Simple(delay, function() -- Check if the entity still exists and play the sound. if (IsValid(entity)) then entity:EmitSound(v, volume, pitch) end end) -- Add the delay for the next sound. delay = delay + length + postSet + spacing end -- Return how long it took for the whole thing. return delay end function nut.util.gridVector(vec, gridSize) if (gridSize <= 0) then gridSize = 1 end for i = 1, 3 do vec[i] = vec[i] / gridSize vec[i] = math.Round(vec[i]) vec[i] = vec[i] * gridSize end return vec end function nut.util.getAllChar() local charTable = {} for k, v in ipairs(player.GetAll()) do if (v:getChar()) then table.insert(charTable, v:getChar():getID()) end end return charTable end if (CLIENT) then NUT_CVAR_CHEAP = CreateClientConVar("nut_cheapblur", 0, true) local useCheapBlur = NUT_CVAR_CHEAP:GetBool() local blur = nut.util.getMaterial("pp/blurscreen") cvars.AddChangeCallback("nut_cheapblur", function(name, old, new) useCheapBlur = (tonumber(new) or 0) > 0 end) -- Draws a blurred material over the screen, to blur things. function nut.util.drawBlur(panel, amount, passes) -- Intensity of the blur. amount = amount or 5 if (useCheapBlur) then surface.SetDrawColor(50, 50, 50, amount * 20) surface.DrawRect(0, 0, panel:GetWide(), panel:GetTall()) else surface.SetMaterial(blur) surface.SetDrawColor(255, 255, 255) local x, y = panel:LocalToScreen(0, 0) for i = -(passes or 0.2), 1, 0.2 do -- Do things to the blur material to make it blurry. blur:SetFloat("$blur", i * amount) blur:Recompute() -- Draw the blur material over the screen. render.UpdateScreenEffectTexture() surface.DrawTexturedRect(x * -1, y * -1, ScrW(), ScrH()) end end end function nut.util.drawBlurAt(x, y, w, h, amount, passes) -- Intensity of the blur. amount = amount or 5 if (useCheapBlur) then surface.SetDrawColor(30, 30, 30, amount * 20) surface.DrawRect(x, y, w, h) else surface.SetMaterial(blur) surface.SetDrawColor(255, 255, 255) local scrW, scrH = ScrW(), ScrH() local x2, y2 = x / scrW, y / scrH local w2, h2 = (x + w) / scrW, (y + h) / scrH for i = -(passes or 0.2), 1, 0.2 do blur:SetFloat("$blur", i * amount) blur:Recompute() render.UpdateScreenEffectTexture() surface.DrawTexturedRectUV(x, y, w, h, x2, y2, w2, h2) end end end -- Draw a text with a shadow. function nut.util.drawText(text, x, y, color, alignX, alignY, font, alpha) color = color or color_white return draw.TextShadow({ text = text, font = font or "nutGenericFont", pos = {x, y}, color = color, xalign = alignX or 0, yalign = alignY or 0 }, 1, alpha or (color.a * 0.575)) end -- Wraps text so it does not pass a certain width. function nut.util.wrapText(text, width, font) font = font or "nutChatFont" surface.SetFont(font) local exploded = string.Explode("%s", text, true) local line = "" local lines = {} local w = surface.GetTextSize(text) local maxW = 0 if (w <= width) then return {(text:gsub("%s", " "))}, w end for i = 1, #exploded do local word = exploded[i] line = line.." "..word w = surface.GetTextSize(line) if (w > width) then lines[#lines + 1] = line line = "" if (w > maxW) then maxW = w end end end if (line != "") then lines[#lines + 1] = line end return lines, maxW end local LAST_WIDTH = ScrW() local LAST_HEIGHT = ScrH() timer.Create("nutResolutionMonitor", 1, 0, function() local scrW, scrH = ScrW(), ScrH() if (scrW != LAST_WIDTH or scrH != LAST_HEIGHT) then hook.Run("ScreenResolutionChanged", LAST_WIDTH, LAST_HEIGHT) LAST_WIDTH = scrW LAST_HEIGHT = scrH end end) end -- Utility entity extensions. do local entityMeta = FindMetaTable("Entity") -- Checks if an entity is a door by comparing its class. function entityMeta:isDoor() return self:GetClass():find("door") end -- Make a cache of chairs on start. local CHAIR_CACHE = {} -- Add chair models to the cache by checking if its vehicle category is a class. for k, v in pairs(list.Get("Vehicles")) do if (v.Category == "Chairs") then CHAIR_CACHE[v.Model] = true end end -- Whether or not a vehicle is a chair by checking its model with the chair list. function entityMeta:isChair() -- Micro-optimization in-case this gets used a lot. return CHAIR_CACHE[self.GetModel(self)] end if (SERVER) then -- Returns the door's slave entity. function entityMeta:getDoorPartner() return self.nutPartner end -- Returns whether door/button is locked or not. function entityMeta:isLocked() if (self:IsVehicle()) then local datatable = self:GetSaveTable() if (datatable) then return (datatable.VehicleLocked) end else local datatable = self:GetSaveTable() if (datatable) then return (datatable.m_bLocked) end end return end -- Returns the entity that blocking door's sequence. function entityMeta:getBlocker() local datatable = self:GetSaveTable() return (datatable.pBlocker) end else -- Returns the door's slave entity. function entityMeta:getDoorPartner() local owner = self:GetOwner() or self.nutDoorOwner if (IsValid(owner) and owner:isDoor()) then return owner end for k, v in ipairs(ents.FindByClass("prop_door_rotating")) do if (v:GetOwner() == self) then self.nutDoorOwner = v return v end end end end -- Makes a fake door to replace it. function entityMeta:blastDoor(velocity, lifeTime, ignorePartner) if (!self:isDoor()) then return end if (IsValid(self.nutDummy)) then self.nutDummy:Remove() end velocity = velocity or VectorRand()*100 lifeTime = lifeTime or 120 local partner = self:getDoorPartner() if (IsValid(partner) and !ignorePartner) then partner:blastDoor(velocity, lifeTime, true) end local color = self:GetColor() local dummy = ents.Create("prop_physics") dummy:SetModel(self:GetModel()) dummy:SetPos(self:GetPos()) dummy:SetAngles(self:GetAngles()) dummy:Spawn() dummy:SetColor(color) dummy:SetMaterial(self:GetMaterial()) dummy:SetSkin(self:GetSkin() or 0) dummy:SetRenderMode(RENDERMODE_TRANSALPHA) dummy:CallOnRemove("restoreDoor", function() if (IsValid(self)) then self:SetNotSolid(false) self:SetNoDraw(false) self:DrawShadow(true) self.ignoreUse = false self.nutIsMuted = false for k, v in ipairs(ents.GetAll()) do if (v:GetParent() == self) then v:SetNotSolid(false) v:SetNoDraw(false) if (v.onDoorRestored) then v:onDoorRestored(self) end end end end end) dummy:SetOwner(self) dummy:SetCollisionGroup(COLLISION_GROUP_WEAPON) self:Fire("unlock") self:Fire("open") self:SetNotSolid(true) self:SetNoDraw(true) self:DrawShadow(false) self.ignoreUse = true self.nutDummy = dummy self.nutIsMuted = true self:DeleteOnRemove(dummy) for k, v in ipairs(self:GetBodyGroups()) do dummy:SetBodygroup(v.id, self:GetBodygroup(v.id)) end for k, v in ipairs(ents.GetAll()) do if (v:GetParent() == self) then v:SetNotSolid(true) v:SetNoDraw(true) if (v.onDoorBlasted) then v:onDoorBlasted(self) end end end dummy:GetPhysicsObject():SetVelocity(velocity) local uniqueID = "doorRestore"..self:EntIndex() local uniqueID2 = "doorOpener"..self:EntIndex() timer.Create(uniqueID2, 1, 0, function() if (IsValid(self) and IsValid(self.nutDummy)) then self:Fire("open") else timer.Remove(uniqueID2) end end) timer.Create(uniqueID, lifeTime, 1, function() if (IsValid(self) and IsValid(dummy)) then uniqueID = "dummyFade"..dummy:EntIndex() local alpha = 255 timer.Create(uniqueID, 0.1, 255, function() if (IsValid(dummy)) then alpha = alpha - 1 dummy:SetColor(ColorAlpha(color, alpha)) if (alpha <= 0) then dummy:Remove() end else timer.Remove(uniqueID) end end) end end) return dummy end end -- Misc. player stuff. do local playerMeta = FindMetaTable("Player") ALWAYS_RAISED = {} ALWAYS_RAISED["weapon_physgun"] = true ALWAYS_RAISED["gmod_tool"] = true ALWAYS_RAISED["nut_poshelper"] = true -- Returns how many seconds the player has played on the server in total. if (SERVER) then function playerMeta:getPlayTime() return self.nutPlayTime + (RealTime() - (self.nutJoinTime or RealTime())) end else nut.playTime = nut.playTime or 0 function playerMeta:getPlayTime() return nut.playTime + (RealTime() - nut.joinTime) end end -- Returns whether or not the player has their weapon raised. function playerMeta:isWepRaised() local weapon = self.GetActiveWeapon(self) local override = hook.Run("ShouldWeaponBeRaised", self, weapon) -- Allow the hook to check first. if (override != nil) then return override end -- Some weapons may have their own properties. if (IsValid(weapon)) then -- If their weapon is always raised, return true. if (weapon.IsAlwaysRaised or ALWAYS_RAISED[weapon.GetClass(weapon)]) then return true -- Return false if always lowered. elseif (weapon.IsAlwaysLowered or weapon.NeverRaised) then return false end end -- If the player has been forced to have their weapon lowered. if (self.getNetVar(self, "restricted")) then return false end -- Let the config decide before actual results. if (nut.config.get("wepAlwaysRaised")) then return true end -- Returns what the gamemode decides. return self.getNetVar(self, "raised", false) end local vectorLength2D = FindMetaTable("Vector").Length2D -- Checks if the player is running by seeing if the speed is faster than walking. function playerMeta:isRunning() return vectorLength2D(self.GetVelocity(self)) > (self.GetWalkSpeed(self) + 10) end -- Checks if the player has a female model. function playerMeta:isFemale() local model = self:GetModel():lower() return model:find("female") or model:find("alyx") or model:find("mossman") or nut.anim.getModelClass(model) == "citizen_female" end -- Returns a good position in front of the player for an entity. function playerMeta:getItemDropPos() -- Start a trace. local data = {} -- The trace starts behind the player in case they are looking at a wall. data.start = self:GetShootPos() - self:GetAimVector()*64 -- The trace finishes 86 units infront of the player. data.endpos = self:GetShootPos() + self:GetAimVector()*86 -- Ignore the actual player. data.filter = self -- Get the end position of the trace. local trace = util.TraceLine(data) return trace.HitPos + trace.HitNormal*36 end -- Do an action that requires the player to stare at something. function playerMeta:doStaredAction(entity, callback, time, onCancel, distance) local uniqueID = "nutStare"..self:UniqueID() local data = {} data.filter = self timer.Create(uniqueID, 0.1, time / 0.1, function() if (IsValid(self) and IsValid(entity)) then data.start = self:GetShootPos() data.endpos = data.start + self:GetAimVector()*(distance or 96) if (util.TraceLine(data).Entity != entity) then timer.Remove(uniqueID) if (onCancel) then onCancel() end elseif (callback and timer.RepsLeft(uniqueID) == 0) then callback() end else timer.Remove(uniqueID) if (onCancel) then onCancel() end end end) end if (SERVER) then -- Sets whether or not the weapon is raised. function playerMeta:setWepRaised(state) -- Sets the networked variable for being raised. self:setNetVar("raised", state) -- Delays any weapon shooting. local weapon = self:GetActiveWeapon() if (IsValid(weapon)) then weapon:SetNextPrimaryFire(CurTime() + 1) weapon:SetNextSecondaryFire(CurTime() + 1) end end -- Inverts whether or not the weapon is raised. function playerMeta:toggleWepRaised() self:setWepRaised(!self:isWepRaised()) local weapon = self:GetActiveWeapon() if (IsValid(weapon)) then if (self:isWepRaised() and weapon.OnRaised) then weapon:OnRaised() elseif (!self:isWepRaised() and weapon.OnLowered) then weapon:OnLowered() end end end -- Performs a delayed action on a player. function playerMeta:setAction(text, time, callback, startTime, finishTime) if (time and time <= 0) then if (callback) then callback(self) end return end -- Default the time to five seconds. time = time or 5 startTime = startTime or CurTime() finishTime = finishTime or (startTime + time) if (text == false) then timer.Remove("nutAct"..self:UniqueID()) netstream.Start(self, "actBar") return end -- Tell the player to draw a bar for the action. netstream.Start(self, "actBar", startTime, finishTime, text) -- If we have provided a callback, run it delayed. if (callback) then -- Create a timer that runs once with a delay. timer.Create("nutAct"..self:UniqueID(), time, 1, function() -- Call the callback if the player is still valid. if (IsValid(self)) then callback(self) end end) end end -- Sends a Derma string request to the client. function playerMeta:requestString(title, subTitle, callback, default) local time = math.floor(os.time()) self.nutStrReqs = self.nutStrReqs or {} self.nutStrReqs[time] = callback netstream.Start(self, "strReq", time, title, subTitle, default) end -- Removes a player's weapon and restricts interactivity. function playerMeta:setRestricted(state, noMessage) if (state) then self:setNetVar("restricted", true) if (noMessage) then self:setLocalVar("restrictNoMsg", true) end self.nutRestrictWeps = self.nutRestrictWeps or {} for k, v in ipairs(self:GetWeapons()) do self.nutRestrictWeps[#self.nutRestrictWeps + 1] = v:GetClass() v:Remove() end hook.Run("OnPlayerRestricted", self) else self:setNetVar("restricted") if (self:getLocalVar("restrictNoMsg")) then self:setLocalVar("restrictNoMsg") end if (self.nutRestrictWeps) then for k, v in ipairs(self.nutRestrictWeps) do self:Give(v) end self.nutRestrictWeps = nil end hook.Run("OnPlayerUnRestricted", self) end end end -- Player ragdoll utility stuff. do function nut.util.findEmptySpace(entity, filter, spacing, size, height, tolerance) spacing = spacing or 32 size = size or 3 height = height or 36 tolerance = tolerance or 5 local position = entity:GetPos() local angles = Angle(0, 0, 0) local mins, maxs = Vector(-spacing * 0.5, -spacing * 0.5, 0), Vector(spacing * 0.5, spacing * 0.5, height) local output = {} for x = -size, size do for y = -size, size do local origin = position + Vector(x * spacing, y * spacing, 0) local color = green local i = 0 local data = {} data.start = origin + mins + Vector(0, 0, tolerance) data.endpos = origin + maxs data.filter = filter or entity local trace = util.TraceLine(data) data.start = origin + Vector(-maxs.x, -maxs.y, tolerance) data.endpos = origin + Vector(mins.x, mins.y, height) local trace2 = util.TraceLine(data) if (trace.StartSolid or trace.Hit or trace2.StartSolid or trace2.Hit or !util.IsInWorld(origin)) then continue end output[#output + 1] = origin end end table.sort(output, function(a, b) return a:Distance(position) < b:Distance(position) end) return output end function playerMeta:isStuck() return util.TraceEntity({ start = self:GetPos(), endpos = self:GetPos(), filter = self }, self).StartSolid end function playerMeta:setRagdolled(state, time, getUpGrace) getUpGrace = getUpGrace or time or 5 if (state) then if (IsValid(self.nutRagdoll)) then self.nutRagdoll:Remove() end local entity = ents.Create("prop_ragdoll") entity:SetPos(self:GetPos()) entity:SetAngles(self:EyeAngles()) entity:SetModel(self:GetModel()) entity:SetSkin(self:GetSkin()) entity:Spawn() entity:setNetVar("player", self) entity:SetCollisionGroup(COLLISION_GROUP_WEAPON) entity:Activate() entity:CallOnRemove("fixer", function() if (IsValid(self)) then self:setLocalVar("blur", nil) self:setLocalVar("ragdoll", nil) if (!entity.nutNoReset) then self:SetPos(entity:GetPos()) end self:SetNoDraw(false) self:SetNotSolid(false) self:Freeze(false) self:SetMoveType(MOVETYPE_WALK) self:SetLocalVelocity(IsValid(entity) and entity.nutLastVelocity or vector_origin) end if (IsValid(self) and !entity.nutIgnoreDelete) then if (entity.nutWeapons) then for k, v in ipairs(entity.nutWeapons) do self:Give(v) end end if (self:isStuck()) then entity:DropToFloor() self:SetPos(entity:GetPos() + Vector(0, 0, 16)) local positions = nut.util.findEmptySpace(self, {entity, self}) for k, v in ipairs(positions) do self:SetPos(v) if (!self:isStuck()) then return end end end end end) local velocity = self:GetVelocity() for i = 0, entity:GetPhysicsObjectCount() - 1 do local physObj = entity:GetPhysicsObjectNum(i) if (IsValid(physObj)) then physObj:SetVelocity(velocity) local index = entity:TranslatePhysBoneToBone(i) if (index) then local position, angles = self:GetBonePosition(index) physObj:SetPos(position) physObj:SetAngles(angles) end end end self:setLocalVar("blur", 25) self.nutRagdoll = entity entity.nutWeapons = {} entity.nutPlayer = self if (getUpGrace) then entity.nutGrace = CurTime() + getUpGrace end if (time and time > 0) then entity.nutStart = CurTime() entity.nutFinish = entity.nutStart + time self:setAction("@wakingUp", nil, nil, entity.nutStart, entity.nutFinish) end for k, v in ipairs(self:GetWeapons()) do entity.nutWeapons[#entity.nutWeapons + 1] = v:GetClass() end self:GodDisable() self:StripWeapons() self:Freeze(true) self:SetNoDraw(true) self:SetNotSolid(true) if (time) then local time2 = time local uniqueID = "nutUnRagdoll"..self:SteamID() timer.Create(uniqueID, 0.33, 0, function() if (IsValid(entity) and IsValid(self)) then local velocity = entity:GetVelocity() entity.nutLastVelocity = velocity self:SetPos(entity:GetPos()) if (velocity:Length2D() >= 8) then if (!entity.nutPausing) then self:setAction() entity.nutPausing = true end return elseif (entity.nutPausing) then self:setAction("@wakingUp", time) entity.nutPausing = false end time = time - 0.33 if (time <= 0) then entity:Remove() end else timer.Remove(uniqueID) end end) end self:setLocalVar("ragdoll", entity:EntIndex()) hook.Run("OnCharFallover", self, entity, true) elseif (IsValid(self.nutRagdoll)) then self.nutRagdoll:Remove() hook.Run("OnCharFallover", self, entity, false) end end end end -- Time related stuff. do -- Gets the current time in the UTC time-zone. function nut.util.getUTCTime() local date = os.date("!*t") local localDate = os.date("*t") localDate.isdst = false return os.difftime(os.time(date), os.time(localDate)) end -- Setup for time strings. local TIME_UNITS = {} TIME_UNITS["s"] = 1 -- Seconds TIME_UNITS["m"] = 60 -- Minutes TIME_UNITS["h"] = 3600 -- Hours TIME_UNITS["d"] = TIME_UNITS["h"] * 24 -- Days TIME_UNITS["w"] = TIME_UNITS["d"] * 7 -- Weeks TIME_UNITS["mo"] = TIME_UNITS["d"] * 30 -- Months TIME_UNITS["y"] = TIME_UNITS["d"] * 365 -- Years -- Gets the amount of seconds from a given formatted string. -- Example: 5y2d7w = 5 years, 2 days, and 7 weeks. -- If just given a minute, it is assumed minutes. function nut.util.getStringTime(text) local minutes = tonumber(text) if (minutes) then return math.abs(minutes * 60) end local time = 0 for amount, unit in text:lower():gmatch("(%d+)(%a+)") do amount = tonumber(amount) if (amount and TIME_UNITS[unit]) then time = time + math.abs(amount * TIME_UNITS[unit]) end end return time end end
mit
nesstea/darkstar
scripts/zones/Davoi/npcs/!.lua
13
2631
----------------------------------- -- Area: Davoi -- NPC: ! -- Involved in Mission: The Davoi Report -- @pos 164 0.1 -21 149 ----------------------------------- package.loaded["scripts/zones/Davoi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/zones/Davoi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local CurrentMission = player:getCurrentMission(SANDORIA) if (CurrentMission == THE_DAVOI_REPORT and player:getVar("MissionStatus") == 1) then player:setVar("MissionStatus",2); player:addKeyItem(LOST_DOCUMENT); player:messageSpecial(KEYITEM_OBTAINED,LOST_DOCUMENT); elseif (CurrentMission == INFILTRATE_DAVOI and player:getVar("MissionStatus") >= 6 and player:getVar("MissionStatus") <= 9) then local X = npc:getXPos(); local Z = npc:getZPos(); if (X >= 292 and X <= 296 and Z >= -30 and Z <= -26 and player:hasKeyItem(EAST_BLOCK_CODE) == false) then player:setVar("MissionStatus",player:getVar("MissionStatus") + 1); player:addKeyItem(EAST_BLOCK_CODE); player:messageSpecial(KEYITEM_OBTAINED,EAST_BLOCK_CODE); elseif (X >= 333 and X <= 337 and Z >= -138 and Z <= -134 and player:hasKeyItem(SOUTH_BLOCK_CODE) == false) then player:setVar("MissionStatus",player:getVar("MissionStatus") + 1); player:addKeyItem(SOUTH_BLOCK_CODE); player:messageSpecial(KEYITEM_OBTAINED,SOUTH_BLOCK_CODE); elseif (X >= 161 and X <= 165 and Z >= -20 and Z <= -16 and player:hasKeyItem(NORTH_BLOCK_CODE) == false) then player:setVar("MissionStatus",player:getVar("MissionStatus") + 1); player:addKeyItem(NORTH_BLOCK_CODE); player:messageSpecial(KEYITEM_OBTAINED,NORTH_BLOCK_CODE); else player:messageSpecial(YOU_SEE_NOTHING); end else player:messageSpecial(YOU_SEE_NOTHING); 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
UnfortunateFruit/darkstar
scripts/globals/effects/accuracy_boost.lua
19
1087
----------------------------------- -- -- EFFECT_ACCURACY_BOOST -- ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) if(effect:getPower()>100) then effect:setPower(50); end target:addMod(MOD_ACCP,effect:getPower()); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) -- the effect loses accuracy of 1 every 3 ticks depending on the source of the acc boost local boostACC_effect_size = effect:getPower(); if(boostACC_effect_size > 0) then effect:setPower(boostACC_effect_size - 1) target:delMod(MOD_ACC,1); end end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) local boostACC_effect_size = effect:getPower(); if(boostACC_effect_size > 0) then target:delMod(MOD_ACCP,effect:getPower()); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Temenos/mobs/Praetorian_Guard_CCCXI.lua
7
1182
----------------------------------- -- Area: Temenos N T -- NPC: Praetorian_Guard ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) if (IsMobDead(16928809)==true and IsMobDead(16928810)==true and IsMobDead(16928811)==true and IsMobDead(16928812)==true ) then GetNPCByID(16928768+28):setPos(-311,80,419); GetNPCByID(16928768+28):setStatus(STATUS_NORMAL); GetNPCByID(16928768+162):setPos(-311,80,417); GetNPCByID(16928768+162):setStatus(STATUS_NORMAL); GetNPCByID(16928768+213):setPos(-311,80,421); GetNPCByID(16928768+213):setStatus(STATUS_NORMAL); GetNPCByID(16928770+454):setStatus(STATUS_NORMAL); end end;
gpl-3.0
nesstea/darkstar
scripts/globals/items/cherry_muffin_+1.lua
18
1296
----------------------------------------- -- ID: 5654 -- Item: Cherry Muffin -- Food Effect: 1Hr, All Races ----------------------------------------- -- Intelligence 2 -- MP % 10 (cap 85) -- Agility -1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD)) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5654); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_INT, 2); target:addMod(MOD_FOOD_MPP, 10); target:addMod(MOD_FOOD_MP_CAP, 85); target:addMod(MOD_AGI, -1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_INT, 2); target:delMod(MOD_FOOD_MPP, 10); target:delMod(MOD_FOOD_MP_CAP, 85); target:delMod(MOD_AGI, -1); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Palborough_Mines/npcs/_3za.lua
13
1505
----------------------------------- -- Area: Palborough Mines -- NPC: Refiner Lid -- Involved In Mission: Journey Abroad -- @zone 143 -- @pos 180 -32 167 ----------------------------------- package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Palborough_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) gravelQty = trade:getItemQty(597); -- Mine Gravel already_in = player:getVar("refiner_input"); if (already_in + gravelQty > 10) then player:startEvent(0x0014); elseif (trade:getItemCount() == gravelQty) then player:tradeComplete(); player:setVar("refiner_input",already_in + gravelQty); player:startEvent(0x0013,597,gravelQty); else player:startEvent(0x0015); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0012); 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
UnfortunateFruit/darkstar
scripts/zones/Temenos/mobs/Kindred_Warrior.lua
17
1111
----------------------------------- -- Area: Temenos N T -- NPC: Kindred_Warrior ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) if(IsMobDead(16928797)==true and IsMobDead(16928798)==true and IsMobDead(16928799)==true )then GetNPCByID(16928768+27):setPos(-120,-80,429); GetNPCByID(16928768+27):setStatus(STATUS_NORMAL); GetNPCByID(16928768+161):setPos(-123,-80,429); GetNPCByID(16928768+161):setStatus(STATUS_NORMAL); GetNPCByID(16928768+212):setPos(-117,-80,429); GetNPCByID(16928768+212):setStatus(STATUS_NORMAL); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/North_Gustaberg_[S]/npcs/Cavernous_Maw.lua
29
1472
----------------------------------- -- Area: North Gustaberg [S] -- NPC: Cavernous Maw -- @pos 466 0 479 88 -- Teleports Players to North Gustaberg ----------------------------------- package.loaded["scripts/zones/North_Gustaberg_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/campaign"); require("scripts/zones/North_Gustaberg_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (hasMawActivated(player,7) == false) then player:startEvent(0x0064); else player:startEvent(0x0065); 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:",csid); -- printf("RESULT:",option); if (option == 1) then if (csid == 0x0064) then player:addNationTeleport(MAW,128); end toMaw(player,12); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Horlais_Peak/bcnms/the_secret_weapon.lua
27
2322
----------------------------------- -- Area: Horlais Peak -- Name: Mission Rank 7 -- @pos -509 158 -211 139 ----------------------------------- package.loaded["scripts/zones/Horlais_Peak/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); 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) 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(SANDORIA,THE_SECRET_WEAPON)) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,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 if (player:getCurrentMission(SANDORIA) == THE_SECRET_WEAPON) then player:addKeyItem(CRYSTAL_DOWSER); player:messageSpecial(KEYITEM_OBTAINED,CRYSTAL_DOWSER); player:setVar("SecretWeaponStatus",3) end end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/berry_snowcone.lua
39
1200
----------------------------------------- -- ID: 5710 -- Item: Berry Snowcone -- Food Effect: 5 Min, All Races ----------------------------------------- -- MP % 30 Cap 30 -- Intelligence 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD)) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5710); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_MPP, 30); target:addMod(MOD_FOOD_MP_CAP, 30); target:addMod(MOD_INT, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_MPP, 30); target:delMod(MOD_FOOD_MP_CAP, 30); target:delMod(MOD_INT, 1); end;
gpl-3.0
nesstea/darkstar
scripts/globals/items/serving_of_flounder_meuniere.lua
18
1572
----------------------------------------- -- ID: 4584 -- Item: serving_of_flounder_meuniere -- Food Effect: 180Min, All Races ----------------------------------------- -- Dexterity 6 -- Mind -1 -- Ranged ACC 15 -- Ranged ATT % 14 -- Ranged ATT Cap 25 -- Enmity -3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4584); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 6); target:addMod(MOD_MND, -1); target:addMod(MOD_RACC, 15); target:addMod(MOD_FOOD_RATTP, 14); target:addMod(MOD_FOOD_RATT_CAP, 25); target:addMod(MOD_ENMITY, -3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 6); target:delMod(MOD_MND, -1); target:delMod(MOD_RACC, 15); target:delMod(MOD_FOOD_RATTP, 14); target:delMod(MOD_FOOD_RATT_CAP, 25); target:delMod(MOD_ENMITY, -3); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Halvung/npcs/qm2.lua
8
1156
----------------------------------- -- Area: Halvung -- NPC: ??? (Spawn Dextrose(ZNM T2)) -- @pos -144 11 464 62 ----------------------------------- package.loaded["scripts/zones/Halvung/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Halvung/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(2589,1) and trade:getItemCount() == 1) then -- Trade Granulated Sugar player:tradeComplete(); SpawnMob(17031598,180):updateClaim(player); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Windurst_Waters/npcs/Prestapiq.lua
36
1606
----------------------------------- -- Area: Windurst Waters -- NPC: Prestapiq -- Only sells when Windurst controls Movalpolos -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(MOVALPOLOS); if (RegionOwner ~= WINDURST) then player:showText(npc,PRESTAPIQ_CLOSED_DIALOG); else player:showText(npc,PRESTAPIQ_OPEN_DIALOG); stock = { 0x0280, 11, --Copper Ore 0x1162, 694, --Coral Fungus 0x1117, 4032, --Danceshroom 0x0672, 6500, --Kopparnickel Ore 0x142D, 736 --Movalpolos Water } showShop(player,WINDURST,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
UnfortunateFruit/darkstar
scripts/zones/Cloister_of_Tides/bcnms/trial_by_water.lua
13
1766
----------------------------------- -- Area: Cloister of Tides -- BCNM: Trial by Water ----------------------------------- package.loaded["scripts/zones/Cloister_of_Tides/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Cloister_of_Tides/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:getQuestStatus(OUTLANDS,TRIAL_BY_WATER) == QUEST_COMPLETED) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,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:delKeyItem(TUNING_FORK_OF_WATER); player:addKeyItem(WHISPER_OF_TIDES); player:messageSpecial(KEYITEM_OBTAINED,WHISPER_OF_TIDES); end end;
gpl-3.0
hongzhen/cbsd
cbsd.lua
3
2614
product="CBSD" myversion="10.2.0" if not workdir then print ( "no workdir" ) os.exit(1) end distdir="/usr/local/cbsd" subr= workdir .. "/nc.lua" nodenamefile= workdir .. "/nodename" settingstui= workdir .. "/settings-tui.subr" dialog= workdir .. "/dialog.subr" tools= workdir .. "/tools.subr" mdtools= workdir .. "/mdtools.subr" zfstool= workdir .. "/zfs.subr" jfs= workdir .. "/jfs.subr" color= workdir .. "/ansiicolor.subr" nodes= workdir .. "/nodes.subr" jrcconf= workdir .. "/rcconf.subr" vimageconf= workdir .. "/vnet.subr" vimagetui= workdir .. "/vnet-tui.subr" inventory= workdir .. "/nc.inventory" nodedescr= workdir .. "/node.desc" initenv= workdir .. "/initenv.subr" system= workdir .. "/system.subr" buildconf= workdir .. "/build.subr" distccacheconf= workdir .. "/distccache.subr" base2pkgconf= workdir .. "/base2pkg.subr" mailconf= workdir .. "/mailtools.subr" strings= workdir .. "/strings.subr" miscdir= workdir .. "/misc" jobdir= workdir .. "/job" srcdir= workdir .. "/src" tmpdir= workdir .. "/tmp" ftmpdir= workdir .. "/ftmp" importdir= workdir .. "/import" exportdir= workdir .. "/export" basejaildir= workdir .. "/basejail" basejailpref="base" jaildatadir= workdir .. "/jails-data" jailfstabdir= workdir .. "/jails-fstab" jailrcconfdir= workdir .. "/jails-rcconf" jailfstabpref="fstab." jaildir= workdir .. "/jails" jaildatapref="data" jailsysdir= workdir .. "/jails-system" bindir= workdir .. "/bin" etcdir= workdir .. "/etc" jailctldir= workdir .. "/jailctl" nodectl= workdir .. "/nodectl" rcddir= workdir .. "/rc.d" sbindir= workdir .. "/sbin" systemdir= workdir .. "/system" moduledir= workdir .. "/modules" toolsdir= workdir .. "/tools" upgradedir= workdir .. "/upgrade" vardir= workdir .. "/var" spooldir= vardir .. "/spool" taskdir= spooldir .. "/task" rundir= vardir .. "/run" maildir= vardir .. "/mail" logdir= vardir .. "/log" sharedir= workdir .. "/share" dbdir= vardir .. "/db" localcbsdconffile= "/cbsd.lua" localcbsdconf= workdir .. localcbsdconffile sudoexecdir= workdir .. "/sudoexec" systemsudoexecdir= distdir .. "/sudoexec" cbsduser="cbsd" production="0" rsshdir= workdir .. "/.rssh" sshdir= workdir .. "/.ssh" templateldir= workdir .. "/template" fwcount_st="99" fwcount_end="2000" rsync_flags="arlHpEAXogt8 --delete" greeting="node" jailmapdb= dbdir .. "/jmap.txt" -- external source for online doc cbsddocsrc="http://www.bsdstore.ru/en" .. myversion .. "/" f=io.open(nodenamefile,"r") if f ~= nil then nodename = f:read("*l") io.close(f) end -- if [ -n "${NOCOLOR}" ]; then -- ECHO="echo" -- else -- ECHO="echo -e" -- [ -f "${color}" ] && . $color -- fi
bsd-2-clause
dpino/snabbswitch
lib/ljsyscall/syscall/netbsd/ffitypes.lua
24
15760
-- This is types for NetBSD and rump kernel, which are the same bar names. local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local abi = require "syscall.abi" local ffi = require "ffi" require "syscall.ffitypes" local helpers = require "syscall.helpers" local version = require "syscall.netbsd.version".version local defs = {} local function append(str) defs[#defs + 1] = str end -- these are the same, could just define as uint if abi.abi64 then append [[ typedef unsigned int _netbsd_clock_t; ]] else append [[ typedef unsigned long _netbsd_clock_t; ]] end -- register_t varies by arch local register_t = { x86 = "int", x64 = "long int", mips = "int32_t", mips64 = "int64_t", sparc = "unsigned long int", sparc64 = "unsigned long int", ia64 = "long int", alpha = "long int", ppc = "long int", ppc64 = "long int", arm = "int", sh3 = "int", m68k = "int", hppa = "int", vax = "int", } append("typedef " .. register_t[abi.arch] .. " _netbsd_register_t;") append [[ typedef uint32_t _netbsd_mode_t; typedef uint8_t _netbsd_sa_family_t; typedef uint64_t _netbsd_dev_t; typedef uint32_t _netbsd_nlink_t; typedef uint64_t _netbsd_ino_t; typedef int64_t _netbsd_time_t; typedef int64_t _netbsd_daddr_t; typedef uint64_t _netbsd_blkcnt_t; typedef uint64_t _netbsd_fsblkcnt_t; typedef uint64_t _netbsd_fsfilcnt_t; typedef uint32_t _netbsd_blksize_t; typedef int _netbsd_clockid_t; typedef int _netbsd_timer_t; typedef int _netbsd_suseconds_t; typedef unsigned int _netbsd_nfds_t; typedef uint32_t _netbsd_id_t; typedef unsigned int _netbsd_tcflag_t; typedef unsigned int _netbsd_speed_t; typedef int32_t _netbsd_lwpid_t; typedef uint32_t _netbsd_fixpt_t; typedef unsigned short u_short; typedef unsigned char u_char; typedef uint64_t u_quad_t; /* these are not used in Linux so not renamed */ typedef unsigned int useconds_t; typedef int32_t lwpid_t; typedef struct { int32_t __fsid_val[2]; } _netbsd_fsid_t; typedef uint32_t _netbsd_fd_mask; typedef struct { _netbsd_fd_mask fds_bits[8]; /* kernel can cope with more */ } _netbsd_fd_set; struct _netbsd_cmsghdr { size_t cmsg_len; int cmsg_level; int cmsg_type; char cmsg_data[?]; }; struct _netbsd_msghdr { void *msg_name; socklen_t msg_namelen; struct iovec *msg_iov; int msg_iovlen; void *msg_control; socklen_t msg_controllen; int msg_flags; }; struct _netbsd_mmsghdr { struct _netbsd_msghdr msg_hdr; unsigned int msg_len; }; struct _netbsd_timespec { _netbsd_time_t tv_sec; long tv_nsec; }; struct _netbsd_timeval { _netbsd_time_t tv_sec; _netbsd_suseconds_t tv_usec; }; struct _netbsd_itimerspec { struct _netbsd_timespec it_interval; struct _netbsd_timespec it_value; }; struct _netbsd_itimerval { struct _netbsd_timeval it_interval; struct _netbsd_timeval it_value; }; typedef struct { uint32_t sig[4]; // note renamed to match Linux } _netbsd_sigset_t; struct _netbsd_sockaddr { uint8_t sa_len; _netbsd_sa_family_t sa_family; char sa_data[14]; }; struct _netbsd_sockaddr_storage { uint8_t ss_len; _netbsd_sa_family_t ss_family; char __ss_pad1[6]; int64_t __ss_align; char __ss_pad2[128 - 2 - 8 - 6]; }; struct _netbsd_sockaddr_in { uint8_t sin_len; _netbsd_sa_family_t sin_family; in_port_t sin_port; struct in_addr sin_addr; int8_t sin_zero[8]; }; struct _netbsd_sockaddr_in6 { uint8_t sin6_len; _netbsd_sa_family_t sin6_family; in_port_t sin6_port; uint32_t sin6_flowinfo; struct in6_addr sin6_addr; uint32_t sin6_scope_id; }; struct _netbsd_sockaddr_un { uint8_t sun_len; _netbsd_sa_family_t sun_family; char sun_path[104]; }; struct _netbsd_stat { _netbsd_dev_t st_dev; _netbsd_mode_t st_mode; _netbsd_ino_t st_ino; _netbsd_nlink_t st_nlink; uid_t st_uid; gid_t st_gid; _netbsd_dev_t st_rdev; struct _netbsd_timespec st_atimespec; struct _netbsd_timespec st_mtimespec; struct _netbsd_timespec st_ctimespec; struct _netbsd_timespec st_birthtimespec; off_t st_size; _netbsd_blkcnt_t st_blocks; _netbsd_blksize_t st_blksize; uint32_t st_flags; uint32_t st_gen; uint32_t st_spare[2]; }; typedef union _netbsd_sigval { int sival_int; void *sival_ptr; } _netbsd_sigval_t; struct _netbsd_sigevent { int sigev_notify; int sigev_signo; union _netbsd_sigval sigev_value; void (*sigev_notify_function)(union _netbsd_sigval); void /* pthread_attr_t */ *sigev_notify_attributes; }; struct _netbsd_kevent { uintptr_t ident; uint32_t filter; uint32_t flags; uint32_t fflags; int64_t data; intptr_t udata; }; struct _netbsd_kfilter_mapping { char *name; size_t len; uint32_t filter; }; ]] if abi.abi64 then append [[ struct _ksiginfo { int _signo; int _code; int _errno; int _pad; /* only on LP64 */ union { struct { pid_t _pid; uid_t _uid; _netbsd_sigval_t _value; } _rt; struct { pid_t _pid; uid_t _uid; int _status; _netbsd_clock_t _utime; _netbsd_clock_t _stime; } _child; struct { void *_addr; int _trap; } _fault; struct { long _band; int _fd; } _poll; } _reason; }; ]] else append [[ struct _ksiginfo { int _signo; int _code; int _errno; union { struct { pid_t _pid; uid_t _uid; _netbsd_sigval_t _value; } _rt; struct { pid_t _pid; uid_t _uid; int _status; _netbsd_clock_t _utime; _netbsd_clock_t _stime; } _child; struct { void *_addr; int _trap; } _fault; struct { long _band; int _fd; } _poll; } _reason; }; ]] end append [[ typedef union _netbsd_siginfo { char si_pad[128]; /* Total size; for future expansion */ struct _ksiginfo _info; } _netbsd_siginfo_t; struct _netbsd_sigaction { union { void (*_sa_handler)(int); void (*_sa_sigaction)(int, _netbsd_siginfo_t *, void *); } _sa_u; _netbsd_sigset_t sa_mask; int sa_flags; }; struct _netbsd_ufs_args { char *fspec; }; struct _netbsd_tmpfs_args { int ta_version; _netbsd_ino_t ta_nodes_max; off_t ta_size_max; uid_t ta_root_uid; gid_t ta_root_gid; _netbsd_mode_t ta_root_mode; }; struct _netbsd_ptyfs_args { int version; gid_t gid; _netbsd_mode_t mode; int flags; }; struct _netbsd_procfs_args { int version; int flags; }; struct _netbsd_dirent { _netbsd_ino_t d_fileno; uint16_t d_reclen; uint16_t d_namlen; uint8_t d_type; char d_name[512]; }; struct _netbsd_ifreq { char ifr_name[16]; union { struct _netbsd_sockaddr ifru_addr; struct _netbsd_sockaddr ifru_dstaddr; struct _netbsd_sockaddr ifru_broadaddr; struct _netbsd_sockaddr_storage ifru_space; short ifru_flags; int ifru_metric; int ifru_mtu; int ifru_dlt; unsigned int ifru_value; void * ifru_data; struct { uint32_t b_buflen; void *b_buf; } ifru_b; } ifr_ifru; }; struct _netbsd_ifaliasreq { char ifra_name[16]; struct _netbsd_sockaddr ifra_addr; struct _netbsd_sockaddr ifra_dstaddr; struct _netbsd_sockaddr ifra_mask; }; struct _netbsd_pollfd { int fd; short int events; short int revents; }; struct _netbsd_flock { off_t l_start; off_t l_len; pid_t l_pid; short l_type; short l_whence; }; struct _netbsd_termios { _netbsd_tcflag_t c_iflag; _netbsd_tcflag_t c_oflag; _netbsd_tcflag_t c_cflag; _netbsd_tcflag_t c_lflag; cc_t c_cc[20]; int c_ispeed; int c_ospeed; }; /* compat issues */ struct _netbsd_compat_60_ptmget { int cfd; int sfd; char cn[16]; char sn[16]; }; struct _netbsd_ptmget { int cfd; int sfd; char cn[1024]; char sn[1024]; }; struct _netbsd_statvfs { unsigned long f_flag; unsigned long f_bsize; unsigned long f_frsize; unsigned long f_iosize; _netbsd_fsblkcnt_t f_blocks; _netbsd_fsblkcnt_t f_bfree; _netbsd_fsblkcnt_t f_bavail; _netbsd_fsblkcnt_t f_bresvd; _netbsd_fsfilcnt_t f_files; _netbsd_fsfilcnt_t f_ffree; _netbsd_fsfilcnt_t f_favail; _netbsd_fsfilcnt_t f_fresvd; uint64_t f_syncreads; uint64_t f_syncwrites; uint64_t f_asyncreads; uint64_t f_asyncwrites; _netbsd_fsid_t f_fsidx; unsigned long f_fsid; unsigned long f_namemax; uid_t f_owner; uint32_t f_spare[4]; char f_fstypename[32]; char f_mntonname[1024]; char f_mntfromname[1024]; }; struct _netbsd_rusage { struct _netbsd_timeval ru_utime; struct _netbsd_timeval ru_stime; long ru_maxrss; long ru_ixrss; long ru_idrss; long ru_isrss; long ru_minflt; long ru_majflt; long ru_nswap; long ru_inblock; long ru_oublock; long ru_msgsnd; long ru_msgrcv; long ru_nsignals; long ru_nvcsw; long ru_nivcsw; }; ]] if abi.le then append [[ struct _netbsd_ktr_header { int ktr_len; short ktr_type; short ktr_version; pid_t ktr_pid; char ktr_comm[17]; union { struct { struct { int32_t tv_sec; long tv_usec; } _tv; const void *_buf; } _v0; struct { struct { int32_t tv_sec; long tv_nsec; } _ts; lwpid_t _lid; } _v1; struct { struct _netbsd_timespec _ts; lwpid_t _lid; } _v2; } _v; }; ]] else append [[ struct _netbsd_ktr_header { int ktr_len; short ktr_version; short ktr_type; pid_t ktr_pid; char ktr_comm[17]; union { struct { struct { int32_t tv_sec; long tv_usec; } _tv; const void *_buf; } _v0; struct { struct { int32_t tv_sec; long tv_nsec; } _ts; lwpid_t _lid; } _v1; struct { struct _netbsd_timespec _ts; lwpid_t _lid; } _v2; } _v; }; ]] end append [[ struct _netbsd_ktr_syscall { int ktr_code; int ktr_argsize; }; struct _netbsd_ktr_sysret { short ktr_code; short ktr_eosys; int ktr_error; _netbsd_register_t ktr_retval; _netbsd_register_t ktr_retval_1; }; struct _netbsd_ktr_genio { int ktr_fd; int ktr_rw; /* enum uoi_rw, changed to constant */ }; struct _netbsd_ktr_psig { int signo; sig_t action; _netbsd_sigset_t mask; int code; }; struct _netbsd_ktr_csw { int out; int user; }; struct _netbsd_ktr_user { char ktr_id[20]; }; struct _netbsd_ktr_saupcall { int ktr_type; int ktr_nevent; int ktr_nint; void *ktr_sas; void *ktr_ap; }; struct _netbsd_ktr_execfd { int ktr_fd; unsigned int ktr_dtype; }; struct _netbsd_ifdrv { char ifd_name[16]; unsigned long ifd_cmd; size_t ifd_len; void *ifd_data; }; struct _netbsd_ifbreq { char ifbr_ifsname[16]; uint32_t ifbr_ifsflags; uint8_t ifbr_state; uint8_t ifbr_priority; uint8_t ifbr_path_cost; uint8_t ifbr_portno; }; struct _netbsd_in6_addrlifetime { _netbsd_time_t ia6t_expire; _netbsd_time_t ia6t_preferred; uint32_t ia6t_vltime; uint32_t ia6t_pltime; }; struct _netbsd_in6_ifstat { u_quad_t ifs6_in_receive; u_quad_t ifs6_in_hdrerr; u_quad_t ifs6_in_toobig; u_quad_t ifs6_in_noroute; u_quad_t ifs6_in_addrerr; u_quad_t ifs6_in_protounknown; u_quad_t ifs6_in_truncated; u_quad_t ifs6_in_discard; u_quad_t ifs6_in_deliver; u_quad_t ifs6_out_forward; u_quad_t ifs6_out_request; u_quad_t ifs6_out_discard; u_quad_t ifs6_out_fragok; u_quad_t ifs6_out_fragfail; u_quad_t ifs6_out_fragcreat; u_quad_t ifs6_reass_reqd; u_quad_t ifs6_reass_ok; u_quad_t ifs6_reass_fail; u_quad_t ifs6_in_mcast; u_quad_t ifs6_out_mcast; }; struct _netbsd_icmp6_ifstat { u_quad_t ifs6_in_msg; u_quad_t ifs6_in_error; u_quad_t ifs6_in_dstunreach; u_quad_t ifs6_in_adminprohib; u_quad_t ifs6_in_timeexceed; u_quad_t ifs6_in_paramprob; u_quad_t ifs6_in_pkttoobig; u_quad_t ifs6_in_echo; u_quad_t ifs6_in_echoreply; u_quad_t ifs6_in_routersolicit; u_quad_t ifs6_in_routeradvert; u_quad_t ifs6_in_neighborsolicit; u_quad_t ifs6_in_neighboradvert; u_quad_t ifs6_in_redirect; u_quad_t ifs6_in_mldquery; u_quad_t ifs6_in_mldreport; u_quad_t ifs6_in_mlddone; u_quad_t ifs6_out_msg; u_quad_t ifs6_out_error; u_quad_t ifs6_out_dstunreach; u_quad_t ifs6_out_adminprohib; u_quad_t ifs6_out_timeexceed; u_quad_t ifs6_out_paramprob; u_quad_t ifs6_out_pkttoobig; u_quad_t ifs6_out_echo; u_quad_t ifs6_out_echoreply; u_quad_t ifs6_out_routersolicit; u_quad_t ifs6_out_routeradvert; u_quad_t ifs6_out_neighborsolicit; u_quad_t ifs6_out_neighboradvert; u_quad_t ifs6_out_redirect; u_quad_t ifs6_out_mldquery; u_quad_t ifs6_out_mldreport; u_quad_t ifs6_out_mlddone; }; struct _netbsd_in6_ifreq { char ifr_name[16]; union { struct _netbsd_sockaddr_in6 ifru_addr; struct _netbsd_sockaddr_in6 ifru_dstaddr; short ifru_flags; int ifru_flags6; int ifru_metric; void * ifru_data; struct _netbsd_in6_addrlifetime ifru_lifetime; struct _netbsd_in6_ifstat ifru_stat; struct _netbsd_icmp6_ifstat ifru_icmp6stat; } ifr_ifru; }; struct _netbsd_in6_aliasreq { char ifra_name[16]; struct _netbsd_sockaddr_in6 ifra_addr; struct _netbsd_sockaddr_in6 ifra_dstaddr; struct _netbsd_sockaddr_in6 ifra_prefixmask; int ifra_flags; struct _netbsd_in6_addrlifetime ifra_lifetime; }; struct _netbsd_rt_metrics { uint64_t rmx_locks; uint64_t rmx_mtu; uint64_t rmx_hopcount; uint64_t rmx_recvpipe; uint64_t rmx_sendpipe; uint64_t rmx_ssthresh; uint64_t rmx_rtt; uint64_t rmx_rttvar; _netbsd_time_t rmx_expire; _netbsd_time_t rmx_pksent; }; struct _netbsd_rt_msghdr { u_short rtm_msglen __attribute__ ((aligned (8))); u_char rtm_version; u_char rtm_type; u_short rtm_index; int rtm_flags; int rtm_addrs; pid_t rtm_pid; int rtm_seq; int rtm_errno; int rtm_use; int rtm_inits; struct _netbsd_rt_metrics rtm_rmx __attribute__ ((aligned (8))); }; struct _netbsd_clockinfo { int hz; int tick; int tickadj; int stathz; int profhz; }; struct _netbsd_loadavg { _netbsd_fixpt_t ldavg[3]; long fscale; }; struct _netbsd_vmtotal { int16_t t_rq; int16_t t_dw; int16_t t_pw; int16_t t_sl; int16_t _reserved1; int32_t t_vm; int32_t t_avm; int32_t t_rm; int32_t t_arm; int32_t t_vmshr; int32_t t_avmshr; int32_t t_rmshr; int32_t t_armshr; int32_t t_free; }; struct _netbsd_ctlname { const char *ctl_name; int ctl_type; }; /* volatile may be an issue... */ struct _netbsd_aiocb { off_t aio_offset; volatile void *aio_buf; size_t aio_nbytes; int aio_fildes; int aio_lio_opcode; int aio_reqprio; struct _netbsd_sigevent aio_sigevent; /* Internal kernel variables */ int _state; int _errno; ssize_t _retval; }; ]] local s = table.concat(defs, "") -- TODO broken, makes this module not a proper function, see #120 -- although this will not ever actually happen... if abi.host == "netbsd" then s = string.gsub(s, "_netbsd_", "") -- remove netbsd types end ffi.cdef(s)
apache-2.0
vonflynee/opencomputersserver
world/opencomputers/4f2775bd-9dcb-42e6-8318-1837ede27e76/lib/keyboard.lua
13
4645
local keyboard = {pressedChars = {}, pressedCodes = {}} keyboard.keys = { ["1"] = 0x02, ["2"] = 0x03, ["3"] = 0x04, ["4"] = 0x05, ["5"] = 0x06, ["6"] = 0x07, ["7"] = 0x08, ["8"] = 0x09, ["9"] = 0x0A, ["0"] = 0x0B, a = 0x1E, b = 0x30, c = 0x2E, d = 0x20, e = 0x12, f = 0x21, g = 0x22, h = 0x23, i = 0x17, j = 0x24, k = 0x25, l = 0x26, m = 0x32, n = 0x31, o = 0x18, p = 0x19, q = 0x10, r = 0x13, s = 0x1F, t = 0x14, u = 0x16, v = 0x2F, w = 0x11, x = 0x2D, y = 0x15, z = 0x2C, apostrophe = 0x28, at = 0x91, back = 0x0E, -- backspace backslash = 0x2B, capital = 0x3A, -- capslock colon = 0x92, comma = 0x33, enter = 0x1C, equals = 0x0D, grave = 0x29, -- accent grave lbracket = 0x1A, lcontrol = 0x1D, lmenu = 0x38, -- left Alt lshift = 0x2A, minus = 0x0C, numlock = 0x45, pause = 0xC5, period = 0x34, rbracket = 0x1B, rcontrol = 0x9D, rmenu = 0xB8, -- right Alt rshift = 0x36, scroll = 0x46, -- Scroll Lock semicolon = 0x27, slash = 0x35, -- / on main keyboard space = 0x39, stop = 0x95, tab = 0x0F, underline = 0x93, -- Keypad (and numpad with numlock off) up = 0xC8, down = 0xD0, left = 0xCB, right = 0xCD, home = 0xC7, ["end"] = 0xCF, pageUp = 0xC9, pageDown = 0xD1, insert = 0xD2, delete = 0xD3, -- Function keys f1 = 0x3B, f2 = 0x3C, f3 = 0x3D, f4 = 0x3E, f5 = 0x3F, f6 = 0x40, f7 = 0x41, f8 = 0x42, f9 = 0x43, f10 = 0x44, f11 = 0x57, f12 = 0x58, f13 = 0x64, f14 = 0x65, f15 = 0x66, f16 = 0x67, f17 = 0x68, f18 = 0x69, f19 = 0x71, -- Japanese keyboards kana = 0x70, kanji = 0x94, convert = 0x79, noconvert = 0x7B, yen = 0x7D, circumflex = 0x90, ax = 0x96, -- Numpad numpad0 = 0x52, numpad1 = 0x4F, numpad2 = 0x50, numpad3 = 0x51, numpad4 = 0x4B, numpad5 = 0x4C, numpad6 = 0x4D, numpad7 = 0x47, numpad8 = 0x48, numpad9 = 0x49, numpadmul = 0x37, numpaddiv = 0xB5, numpadsub = 0x4A, numpadadd = 0x4E, numpaddecimal = 0x53, numpadcomma = 0xB3, numpadenter = 0x9C, numpadequals = 0x8D, } -- Create inverse mapping for name lookup. do local keys = {} for k in pairs(keyboard.keys) do table.insert(keys, k) end for _, k in pairs(keys) do keyboard.keys[keyboard.keys[k]] = k end end ------------------------------------------------------------------------------- function keyboard.isAltDown() return (keyboard.pressedCodes[keyboard.keys.lmenu] or keyboard.pressedCodes[keyboard.keys.rmenu]) ~= nil end function keyboard.isControl(char) return type(char) == "number" and (char < 0x20 or (char >= 0x7F and char <= 0x9F)) end function keyboard.isControlDown() return (keyboard.pressedCodes[keyboard.keys.lcontrol] or keyboard.pressedCodes[keyboard.keys.rcontrol]) ~= nil end function keyboard.isKeyDown(charOrCode) checkArg(1, charOrCode, "string", "number") if type(charOrCode) == "string" then return keyboard.pressedChars[utf8 and utf8.codepoint(charOrCode) or charOrCode:byte()] elseif type(charOrCode) == "number" then return keyboard.pressedCodes[charOrCode] end end function keyboard.isShiftDown() return (keyboard.pressedCodes[keyboard.keys.lshift] or keyboard.pressedCodes[keyboard.keys.rshift]) ~= nil end ------------------------------------------------------------------------------- return keyboard
mit
UnfortunateFruit/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Corbrere.lua
38
1046
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Corbrere -- Type: Standard NPC -- @zone: 94 -- @pos -46.925 -4.5 49.006 -- -- 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(0x019e); 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
nesstea/darkstar
scripts/globals/weaponskills/split_shot.lua
11
1573
----------------------------------- -- Split Shot -- Marksmanship weapon skill -- Skill Level: 40 -- Ignores enemy's defense. Amount ignored varies with TP. -- The amount of defense ignored is 0% @ 100TP, 35% @ 200TP and 50% @ 300TP. -- Aligned with the Aqua Gorget & Light Gorget. -- Aligned with the Aqua Belt & Light Belt. -- Element: None -- Modifiers: AGI:70% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.agi_wsc = 0.7; end -- Defense ignored is 0%, 35%, 50% as per wiki.bluegartr.com params.ignoresDef = true; params.ignored100 = 0; params.ignored200 = 0.35; params.ignored300 = 0.5; local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
ld-test/fun-alloyed
tests/generators.lua
5
3254
-------------------------------------------------------------------------------- -- range -------------------------------------------------------------------------------- dump(range(0)) print('--') for i=1,0 do print(i) end --[[test -- --test]] dump(range(0, 0)) print('--') for i=0,0 do print(i) end --[[test 0 -- 0 --test]] dump(range(5)) print('--') for i=1,5 do print(i) end --[[test 1 2 3 4 5 -- 1 2 3 4 5 --test]] dump(range(0, 5)) print('--') for i=0,5 do print(i) end --[[test 0 1 2 3 4 5 -- 0 1 2 3 4 5 --test]] dump(range(0, 5, 1)) print('--') for i=0,5,1 do print(i) end --[[test 0 1 2 3 4 5 -- 0 1 2 3 4 5 --test]] dump(range(0, 10, 2)) print('--') for i=0,10,2 do print(i) end --[[test 0 2 4 6 8 10 -- 0 2 4 6 8 10 --test]] dump(range(-5)) print('--') for i=-1,-5,-1 do print(i) end --[[test -1 -2 -3 -4 -5 -- -1 -2 -3 -4 -5 --test]] dump(range(0, -5, 1)) print('--') for i=0,-5,1 do print(i) end --[[test -- --test]] dump(range(0, -5, -1)) print('--') for i=0,-5,-1 do print(i) end --[[test 0 -1 -2 -3 -4 -5 -- 0 -1 -2 -3 -4 -5 --test]] dump(range(0, -10, -2)) print('--') for i=0,-10,-2 do print(i) end --[[test 0 -2 -4 -6 -8 -10 -- 0 -2 -4 -6 -8 -10 --test]] dump(range(1.2, 1.6, 0.1)) --[[test 1.2 1.3 1.4 1.5 --test]] -- Invalid step dump(range(0, 5, 0)) --[[test error: step must not be zero --test]] -------------------------------------------------------------------------------- -- duplicate -------------------------------------------------------------------------------- dump(take(5, duplicate(48))) --[[test 48 48 48 48 48 --test]] dump(take(5, duplicate(1,2,3,4,5))) --[[test 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 --test]] print(xrepeat == duplicate) -- an alias --[[test true --test]] print(replicate == duplicate) -- an alias --[[test true --test]] -------------------------------------------------------------------------------- -- tabulate -------------------------------------------------------------------------------- dump(take(5, tabulate(function(x) return 2 * x end))) --[[test 0 2 4 6 8 --test]] -------------------------------------------------------------------------------- -- zeros -------------------------------------------------------------------------------- dump(take(5, zeros())) --[[test 0 0 0 0 0 --test]] -------------------------------------------------------------------------------- -- ones -------------------------------------------------------------------------------- dump(take(5, ones())) --[[test 1 1 1 1 1 --test]] -------------------------------------------------------------------------------- -- rands -------------------------------------------------------------------------------- print(all(function(x) return x >= 0 and x < 1 end, take(5, rands()))) --[[test true --test]] dump(take(5, rands(0))) --[[test error: empty interval --test]] print(all(function(x) return math.floor(x) == x end, take(5, rands(10)))) --[[test true --test]] print(all(function(x) return math.floor(x) == x end, take(5, rands(1024)))) --[[test true --test]] dump(take(5, rands(0, 1))) --[[test 0 0 0 0 0 --test]] dump(take(5, rands(5, 6))) --[[test 5 5 5 5 5 --test]] print(all(function(x) return x >= 10 and x < 20 end, take(20, rands(10, 20)))) --[[test true --test]]
mit
UnfortunateFruit/darkstar
scripts/zones/Windurst_Waters/npcs/Panna-Donna.lua
38
1038
----------------------------------- -- Area: Windurst Waters -- NPC: Panna-Donna -- Type: Mission NPC -- @zone: 238 -- @pos -57.502 -6 229.571 -- -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0069); 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
nesstea/darkstar
scripts/zones/Port_Bastok/npcs/Raifa.lua
12
1041
----------------------------------- -- Area: Port Bastok -- NPC: Raifa -- Type: Quest Giver -- @zone: 236 -- @pos -166.416 -8.48 7.153 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0116); 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
error454/SteamShiva
Resources/Scripts/SteamworksAI_Handler_onAchievementStored.lua
1
1031
-------------------------------------------------------------------------------- -- Handler.......... : onAchievementStored -- Author........... : -- Description...... : -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function SteamworksAI.onAchievementStored ( sAchievementName, nCurProgress, nMaxProgress ) -------------------------------------------------------------------------------- log.message ( "Steamworks: handler onAchievementStored called" ) if ( nMaxProgress == 0 ) then log.warning ( "Steamworks: achievement '"..sAchievementName.."' was stored and achieved." ) else log.warning ( "Steamworks: achievement '"..sAchievementName.."' was stored. Progesss: "..nCurProgress.."/"..nMaxProgress ) end -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
mit
Irubataru/dotfiles
roles/neovim/config/lua/irubataru/plugins.lua
1
18171
local fn = vim.fn -- Automatically install packer local install_path = fn.stdpath("data") .. "/site/pack/packer/start/packer.nvim" if fn.empty(fn.glob(install_path)) > 0 then PACKER_BOOTSTRAP = fn.system({ "git", "clone", "--depth", "1", "https://github.com/wbthomason/packer.nvim", install_path, }) print("Installing packer close and reopen Neovim...") vim.cmd([[packadd packer.nvim]]) end -- Autocommand that reloads neovim whenever you save the plugins.lua file -- vim.cmd([[ -- augroup packer_user_config -- autocmd! -- autocmd BufWritePost plugins.lua source <afile> | PackerSync -- augroup end -- ]]) -- Use a protected call so we don't error out on first use local status_ok, packer = pcall(require, "packer") if not status_ok then return end -- Have packer use a popup window packer.init({ display = { open_fn = function() return require("packer.util").float({ border = "rounded" }) end, }, }) return packer.startup(function(use) use("wbthomason/packer.nvim") -- Have packer manage itself use("lewis6991/impatient.nvim") use("nvim-lua/plenary.nvim") -- plenary: full; complete; entire; absolute; unqualified. All the lua functions I don't want to write twice. use("antoinemadec/FixCursorHold.nvim") -- Keymaps use({ -- folke/which-key.nvim "folke/which-key.nvim", config = function() require("irubataru.plugins.which-key") end, }) -- Colour schemes use("junegunn/seoul256.vim") use("folke/tokyonight.nvim") -- UI and look use({ -- noib3/cokeline.nvim "noib3/cokeline.nvim", -- 👃 A neovim bufferline for people with addictive personalities config = function() require("irubataru.plugins.cokeline") end, requires = "kyazdani42/nvim-web-devicons", }) use({ -- nvim-lualine/lualine.nvim "nvim-lualine/lualine.nvim", -- A blazing fast and easy to configure neovim statusline plugin written in pure lua. config = function() require("irubataru.plugins.lualine") end, requires = "arkav/lualine-lsp-progress", }) use({ -- haya14busa/vim-operator-flashy "haya14busa/vim-operator-flashy", -- Highlight yanked area config = function() require("irubataru.plugins.operator-flashy") end, requires = "kana/vim-operator-user", }) use({ -- Yggdroot/indentLine "Yggdroot/indentLine", -- A vim plugin to display the indention levels with thin vertical lines config = function() require("irubataru.plugins.indentline") end, ft = { "python" }, }) use({ "junegunn/limelight.vim" }) -- Hyperfocus-writing in Vim use({ -- 🦝 Clean and elegant distraction-free writing for NeoVim "Pocco81/true-zen.nvim", config = function() require("irubataru.plugins.true-zen") end }) -- use({ -- junegunn/goyo.vim -- "junegunn/goyo.vim", -- Distraction-free writing in Vim -- config = function() -- require("irubataru.plugins.goyo") -- end, -- }) use({ -- alpha-nvim "goolord/alpha-nvim", config = function() require("irubataru.plugins.alpha") end, }) use({ -- luukvbaal/stabilize.nvim "luukvbaal/stabilize.nvim", -- Neovim plugin to stabilize window open/close events. config = function() require("stabilize").setup() end, }) use({ -- sindrets/winshift.nvim "sindrets/winshift.nvim", -- Rearrange your windows with ease. config = function() require("winshift").setup() end, }) use({ -- nyngwang/NeoZoom.lua "nyngwang/NeoZoom.lua", -- Zoom-in Like a Boss, How? Layout-Preserving Zoomer weighing in 🪶 config = function() require("neo-zoom").setup({ left_ratio = 0.0, top_ratio = 0.0, width_ratio = 1.0, height_ratio = 1.0, border = "none", }) end, }) use({ -- code-biscuits/nvim-biscuits "code-biscuits/nvim-biscuits", config = function() require("nvim-biscuits").setup({ cursor_line_only = false, show_on_start = true, }) end, }) use({ -- rcarriga/nvim-notify "rcarriga/nvim-notify", -- A fancy, configurable, notification manager for NeoVim, config = function() vim.notify = require("notify") end, }) -- Autocomplete use({ -- hrsh7th/nvim-cmp "hrsh7th/nvim-cmp", -- A completion plugin for neovim coded in Lua.tr config = function() require("irubataru.plugins.cmp") end, requires = { "hrsh7th/cmp-nvim-lsp", -- nvim-cmp source for neovim builtin LSP client "hrsh7th/cmp-nvim-lua", -- nvim-cmp source for nvim lua "hrsh7th/cmp-buffer", -- nvim-cmp source for buffer words "hrsh7th/cmp-path", -- nvim-cmp source for path "hrsh7th/cmp-cmdline", -- nvim-cmp source for vim's cmdline "saadparwaiz1/cmp_luasnip", -- luasnip completion source for nvim-cmp { "tzachar/cmp-tabnine", run = "./install.sh" }, -- TabNine plugin for hrsh7th/nvim-cmp { "petertriho/cmp-git", -- Git source for nvim-cmp requires = "nvim-lua/plenary.nvim", config = function() require("cmp_git").setup() end, }, }, }) use("onsails/lspkind-nvim") -- vscode-like pictograms for neovim lsp completion items if require("irubataru.plugins.copilot").options.use then use("hrsh7th/cmp-copilot") -- copilot.vim source for nvim-cmp use({ "github/copilot.vim", -- Neovim plugin for GitHub Copilot config = function() require("irubataru.plugins.copilot") end, }) end -- LSP use({ "neovim/nvim-lspconfig" }) -- Quickstart configurations for the Nvim LSP client use({ -- williamboman/mason.nvim "williamboman/mason.nvim", -- Portable package manager for Neovim that runs everywhere Neovim runs. Easily install and manage LSP servers, DAP servers, linters, and formatters. config = function() require("irubataru.plugins.mason") end, }) use({ "jose-elias-alvarez/null-ls.nvim" }) -- Use Neovim as a language server to inject LSP diagnostics, code actions, and more via Lua. use({ "SmiteshP/nvim-navic" }) -- Simple winbar/statusline plugin that shows your current code context use({ -- utilyre/barbecue.nvim "utilyre/barbecue.nvim", requires = "kyazdani42/nvim-web-devicons", config = function() require("barbecue").setup({ separator = "  ", }) vim.api.nvim_set_hl(0, "NavicSeparator", { default = false, link = "Normal" }) end, }) use({ -- RRethy/vim-illuminate "RRethy/vim-illuminate", -- Vim plugin for automatically highlighting other uses of the word under the cursor. Integrates with Neovim's LSP client for intelligent highlighting. event = "CursorHold", module = "illuminate", config = function() require("irubataru.plugins.illuminate") end, }) use({ -- folke/trouble.nvim "folke/trouble.nvim", -- 🚦 A pretty diagnostics, references, telescope results, quickfix and location list to help you solve all the trouble your code is causing. requires = "kyazdani42/nvim-web-devicons", config = function() require("irubataru.plugins.trouble") end, }) use({ -- rmagatti/goto-preview "rmagatti/goto-preview", -- A small Neovim plugin for previewing definitions using floating windows. config = function() require("irubataru.plugins.goto-preview") end, }) use({ -- ray-x/lsp_signature.nvim "ray-x/lsp_signature.nvim", -- LSP signature hint as you type }) -- Snippets use({ -- L3MON4D3/LuaSnip "L3MON4D3/LuaSnip", -- Snippet Engine for Neovim written in Lua. requires = "rafamadriz/friendly-snippets", config = function() require("irubataru.plugins.luasnip") end, }) -- Tree sitter use({ -- nvim-treesitter/nvim-treesitter "nvim-treesitter/nvim-treesitter", run = ":TSUpdate", config = function() require("irubataru.plugins.treesitter") end, }) -- Fuzzy finding use({ -- nvim-telescope/telescope.nvim "nvim-telescope/telescope.nvim", config = function() require("irubataru.plugins.telescope") end, requires = "nvim-lua/plenary.nvim", }) use("nvim-telescope/telescope-ui-select.nvim") use({ "nvim-telescope/telescope-fzf-native.nvim", run = "make" }) -- Git use({ -- tpope/vim-fugitive "tpope/vim-fugitive", -- The best git plugin config = function() require("irubataru.plugins.fugitive") end, }) use("rhysd/git-messenger.vim") -- Vim and Neovim plugin to reveal the commit messages under the cursor use({ -- sindrets/diffview.nvim "sindrets/diffview.nvim", -- Single tabpage interface for easily cycling through diffs for all modified files for any git rev. requires = "nvim-lua/plenary.nvim", config = function() require("irubataru.plugins.diffview") end, }) use({ -- gitsigns.nvim "lewis6991/gitsigns.nvim", -- Git integration for buffers config = function() require("irubataru.plugins.gitsigns") end, }) -- Unit testing use({ -- nvim-neotest/neotest "nvim-neotest/neotest", -- An extensible framework for interacting with tests within NeoVim. requires = { "nvim-lua/plenary.nvim", "nvim-treesitter/nvim-treesitter", "antoinemadec/FixCursorHold.nvim" }, config = function() require("irubataru.plugins.neotest") end, }) use("nvim-neotest/neotest-python") use({ "nvim-neotest/neotest-vim-test", requires = "vim-test/vim-test" }) -- Other plugins use("tpope/vim-repeat") -- Enable repeating supported plugin maps with . use("tpope/vim-surround") -- quoting/parenthesizing made simple use("tpope/vim-unimpaired") -- Pairs of handy bracket mappings use("tpope/vim-dispatch") -- Asynchronous build and test dispatcher use("wikitopian/hardmode") -- Disable arrow movement, update to takac/vim-hardtime eventually use({ -- numToStr/Comment.nvim "numToStr/Comment.nvim", -- 🧠 💪 // Smart and powerful comment plugin for neovim. Supports commentstring, dot repeat, left-right/up-down motions, hooks, and more config = function() require("irubataru.plugins.commenter") end, }) use({ -- embear/vim-localvimrc "embear/vim-localvimrc", -- Search local vimrc files ('.lvimrc') in the tree (root dir up to current dir) and load them. config = function() require("irubataru.plugins.localvimrc") end, }) use("junegunn/vim-easy-align") -- A Vim alignment plugin use({ -- unblevable/quick-scope "unblevable/quick-scope", -- Highlighting for f,F,t,T config = function() require("irubataru.plugins.quickscope") end, }) use({ -- akinsho/toggleterm.nvim "akinsho/toggleterm.nvim", -- A neovim lua plugin to help easily manage multiple terminal windows config = function() require("irubataru.plugins.toggleterm") end, }) use("AndrewRadev/linediff.vim") -- A vim plugin to perform diffs on blocks of code use("skywind3000/asyncrun.vim") -- Run Async Shell Commands in Vim 8.0 / NeoVim and Output to the Quickfix Window use({ -- kyazdani42/nvim-tree.lua "kyazdani42/nvim-tree.lua", -- A file explorer tree for neovim written in lua requires = "kyazdani42/nvim-web-devicons", config = function() require("irubataru.plugins.nvim_tree") end, }) use({ -- windwp/nvim-autopairs "windwp/nvim-autopairs", -- autopairs for neovim written by lua config = function() require("nvim-autopairs").setup({}) end, }) use({ -- inkarkat/vim-ReplaceWithRegister "inkarkat/vim-ReplaceWithRegister", -- Replace text with the contents of a register. setup = function() require("irubataru.plugins.replace-with-register").setup() end, }) use({ -- ahmedkhalf/project.nvim "ahmedkhalf/project.nvim", -- The superior project management solution for neovim. config = function() require("irubataru.plugins.project") end, }) use({ -- rafcamlet/nvim-luapad "rafcamlet/nvim-luapad", requires = "antoinemadec/FixCursorHold.nvim", cmd = { "Luapad", "LuaRun" }, }) use({ -- ziontee113/icon-picker.nvim "ziontee113/icon-picker.nvim", -- This is a Neovim plugin that helps you pick Nerd Font Icons, Symbols & Emojis requires = "stevearc/dressing.nvim", cmd = { "IconPickerNormal", "IconPickerInsert", "IconPickerYank" }, config = function() require("icon-picker").setup({ disable_legacy_commands = true, }) end, }) use({ -- stevearc/overseer.nvim "stevearc/overseer.nvim", -- A task runner and job management plugin for Neovim config = function() require("overseer").setup({}) end, }) use({ -- max397574/colortils.nvim "max397574/colortils.nvim", -- Some color utils for neovim cmd = "Colortils", config = function() require("colortils").setup({}) end, }) use({ -- aarondiel/spread.nvim "aarondiel/spread.nvim", -- a neovim plugin to spread out inline objects, arrays, parameter lists, etc. after = "nvim-treesitter", }) use({ -- simrat39/symbols-outline.nvim "simrat39/symbols-outline.nvim", -- A tree like view for symbols in Neovim using the Language Server Protocol. Supports all your favourite languages. config = function() require("symbols-outline").setup({}) end, }) -- Language specific plugins -- {{{ -- C/C++ use({ -- octol/vim-cpp-enhanced-highlight "octol/vim-cpp-enhanced-highlight", -- Additional Vim syntax highlighting for C++ (including C++11/14/17) config = function() require("irubataru.plugins.cpp_enhanced_highlight") end, ft = { "cpp" }, }) use({ "preservim/tagbar", ft = { "cpp" } }) -- Vim plugin that displays tags in a window, ordered by scope use({ -- rhysd/vim-clang-format "rhysd/vim-clang-format", -- Vim plugin for clang-format config = function() require("irubataru.plugins.clang-format") end, ft = { "hpp", "cpp", "c" }, requires = "kana/vim-operator-user", }) -- Python use({ -- Chiel92/vim-autoformat "Chiel92/vim-autoformat", -- Provide easy code formatting in Vim by integrating existing code formatters ft = { "python", "tex", "html", "css", "javascript" }, }) use({ "tmhedberg/SimpylFold", ft = { "python" } }) -- No-BS Python code folding for Vim -- Clojure use({ "Olical/conjure", ft = { "clojure" } }) -- Interactive evaluation for Neovim (Clojure, Fennel, Janet, Racket, Hy, MIT Scheme, Guile) use({ -- tpope/vim-sexp-mappings-for-regular-people "tpope/vim-sexp-mappings-for-regular-people", -- vim-sexp mappings for regular people ft = { "clojure" }, requires = { "guns/vim-sexp", ft = { "clojure" } }, -- Precision Editing for S-expressions }) -- LaTeX use({ -- lervag/vimtex "lervag/vimtex", -- A modern Vim and neovim filetype plugin for LaTeX files. ft = { "tex" }, config = function() require("irubataru.plugins.vimtex") end, }) use({ "KeitaNakamura/tex-conceal.vim", ft = { "tex" } }) -- This plugin extends the Conceal feature of Vim for LaTeX. -- Web use({ "pangloss/vim-javascript", ft = { "javascript" } }) -- Vastly improved Javascript indentation and syntax support in Vim. use({ "Olical/vim-syntax-expand", ft = { "javascript" } }) -- Expand characters to code if not in a comment or string use({ "elzr/vim-json", ft = { "json" } }) -- A better JSON for Vim: distinct highlighting of keywords vs values, JSON-specific (non-JS) warnings, quote concealing. use({ "b0o/schemastore.nvim" }) -- A Neovim Lua plugin providing access to the SchemaStore catalog. -- Markdown use({ "SidOfc/mkdx", ft = { "markdown" } }) -- A vim plugin that adds some nice extra's for working with markdown documents use({ "npxbr/glow.nvim", cmd = "Glow" }) -- A markdown preview directly in your neovim. -- Other syntax highlighting use("lazywei/vim-matlab") -- A matlab plugin for vim, includes syntax highlighting, correct indention and so on. use("rsmenon/vim-mathematica") -- Mathematica syntax highlighting (and more) for vim use("vim-scripts/gnuplot.vim") -- Syntax highlighting for Gnuplot use("Glench/Vim-Jinja2-Syntax") -- An up-to-date jinja2 syntax file. use("jalvesaq/Nvim-R") -- Vim plugin to work with R use({ "tmux-plugins/vim-tmux", ft = { "tmux" } }) -- vim plugin for tmux.conf -- }}} -- Plugin graveyard -- {{{ -- Nothing seems to happen when I use it -- use({ -- mvllow/modes.nvim -- "mvllow/modes.nvim", -- config = function() -- require('modes').setup({ -- set_cursor = true, -- set_cursorline = true, -- set_number = true, -- }) -- end -- }) -- Doesn't work as well as I wont, need to revisit -- use({ -- beauwilliams/focus.nvim -- "beauwilliams/focus.nvim", -- config = function() -- require("irubataru.plugins.focus") -- end, -- }) -- Breaks other pop-ups like Mason -- use({ -- sunjon/shade.nvim -- "sunjon/shade.nvim", -- config = function() -- require("shade").setup({ -- overlay_opacity = 70, -- opacity_step = 5, -- }) -- end, -- }) -- use { "glepnir/template.nvim", config = configs.template } -- Quickly insert templates into file -- DAP -- {{{ -- use { "mfussenegger/nvim-dap" } -- use { "theHamsta/nvim-dap-virtual-text" } -- use { "rcarriga/nvim-dap-ui" } -- }}} -- Clojure support -- {{{ -- use { 'tpope/vim-fireplace', ft = { 'clojure' } } -- Clojure REPL support -- use { 'guns/vim-clojure-static', ft = { 'clojure' } } -- Meikel Brandmeyer's excellent Clojure runtime files -- use { 'guns/vim-clojure-highlight', ft = { 'clojure' } } -- Extend builtin syntax highlighting to referred and aliased vars in Clojure buffers -- use { 'vim-scripts/paredit.vim', ft = { 'clojure' } } -- Paredit Mode: Structured Editing of Lisp S-expressions -- use { 'venantius/vim-cljfmt', ft = { 'clojure' } } -- A Vim plugin for cljfmt, the Clojure formatting tool. -- }}} -- }}} -- Automatically set up your configuration after cloning packer.nvim -- Put this at the end after all plugins if PACKER_BOOTSTRAP then require("packer").sync() end end)
mit
dpino/snabbswitch
lib/ljsyscall/syscall/linux/x86/ffi.lua
24
1567
-- x86 specific definitions return { ucontext = [[ typedef int greg_t, gregset_t[19]; typedef struct _fpstate { unsigned long cw, sw, tag, ipoff, cssel, dataoff, datasel; struct { unsigned short significand[4], exponent; } _st[8]; unsigned long status; } *fpregset_t; typedef struct { gregset_t gregs; fpregset_t fpregs; unsigned long oldmask, cr2; } mcontext_t; typedef struct __ucontext { unsigned long uc_flags; struct __ucontext *uc_link; stack_t uc_stack; mcontext_t uc_mcontext; sigset_t uc_sigmask; unsigned long __fpregs_mem[28]; } ucontext_t; ]], stat = [[ struct stat { unsigned long long st_dev; unsigned char __pad0[4]; unsigned long __st_ino; unsigned int st_mode; unsigned int st_nlink; unsigned long st_uid; unsigned long st_gid; unsigned long long st_rdev; unsigned char __pad3[4]; long long st_size; unsigned long st_blksize; unsigned long long st_blocks; unsigned long st_atime; unsigned long st_atime_nsec; unsigned long st_mtime; unsigned int st_mtime_nsec; unsigned long st_ctime; unsigned long st_ctime_nsec; unsigned long long st_ino; }; ]], statfs = [[ typedef long statfs_word; struct statfs64 { statfs_word f_type; statfs_word f_bsize; uint64_t f_blocks; uint64_t f_bfree; uint64_t f_bavail; uint64_t f_files; uint64_t f_ffree; kernel_fsid_t f_fsid; statfs_word f_namelen; statfs_word f_frsize; statfs_word f_flags; statfs_word f_spare[4]; } __attribute__((packed,aligned(4))); ]], }
apache-2.0