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
ffxiphoenix/darkstar
scripts/zones/Northern_San_dOria/npcs/Capiria.lua
14
1477
----------------------------------- -- Area: Northern San d'Oria -- NPC: Capiria -- Type: Involved in Quest (Flyers for Regine) -- @zone: 231 -- @pos -127.355 0.000 130.461 -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) ==QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeCapiria") == 0) then player:messageSpecial(11932); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradeCapiria",1); player:messageSpecial(FLYER_ACCEPTED); trade:complete(); elseif (player:getVar("tradeCapiria") ==1) then player:messageSpecial(11936); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,CAPIRIA_DIALOG); 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
AfuSensi/Mr.Green-MTA-Resources
resources/[admin]/sqlitebrowser/TableWindow.lua
4
12735
--- -- Creates a window for a single database table, -- to browse data and perform simple editing operations -- -- @author driver2 -- @copyright 2009-2010 driver2 TableWindow = {} --[[ -- new -- -- Creates a new TableWindow object. -- -- @param string dbTable: The name of the table. -- @return table The object. -- ]] function TableWindow:new(dbTable) local object = {} setmetatable(object,self) self.__index = self object.dbTable = dbTable object.totalNumRows = 0 object.closeButton = function() object:close() end object.updateDataButton = function() object:triggerUpdateGui() end object.updateDataForwardButton = function() object:triggerUpdateGui("forward") end object.updateDataBackwardButton = function() object:triggerUpdateGui("backward") end object.listClick = function() object:selectListItem() end object.removeRowButton = function() object:dbRemoveRow() end object.editButton = function() object:dbEditField() end object.addRowButton = function() object:openNewRowWindow() end object.resizeWindow = function() object:autoresizeGui() end return object end -------------------------------- -- General appearance of the Gui -------------------------------- TableWindow.gui = {} --[[ -- createGui -- -- Create the Gui. -- ]] function TableWindow:createGui() if self.gui.window ~= nil then return end --outputDebugString("Creating Gui for '"..tostring(self.dbTable).."' "..tostring(self)) self.gui = {} self.defaultWindowSize = {600,400} self.defaultListSize = {584,300} self.gui.window = guiCreateWindow( 320, 240, 600, 400, "SQLite Browser : "..self.dbTable, false ) local w,h = guiGetSize(self.gui.window,false) self.gui.list = guiCreateGridList(8,26,584,300,false,self.gui.window) guiGridListSetSelectionMode(self.gui.list,2) addEventHandler("onClientGUIClick", self.gui.list, self.listClick, false) self.gui.numRowsLabel = guiCreateLabel(12, 334, 190, 20, "Number of rows: 0", false, self.gui.window) -- Edit self.gui.addRowButton = guiCreateButton( 500, 364, 80, 20, "Add row", false, self.gui.window ) addEventHandler("onClientGUIClick", self.gui.addRowButton, self.addRowButton, false) self.gui.removeRowButton = guiCreateButton( 350, 364, 140, 20, "Remove selected row", false, self.gui.window ) addEventHandler("onClientGUIClick", self.gui.removeRowButton, self.removeRowButton, false) self.gui.edit = guiCreateEdit(12, 364, 200, 20, "", false, self.gui.window) self.gui.editButton = guiCreateButton( 220, 364, 120, 20, "Edit selected field", false, self.gui.window ) addEventHandler("onClientGUIClick", self.gui.editButton, self.editButton, false) -- Load --self.gui.loadNotice = guiCreateLabel(self.defaultListSize[2]/2,100,300,20,"Click on 'Load' to request data from the server.",false,self.gui.window) guiCreateLabel( 220, 334, 40, 20, "Start", false, self.gui.window) guiCreateLabel( 310, 334, 40, 20, "Limit", false, self.gui.window) self.gui.updateLimit1 = guiCreateEdit( 258, 334, 42, 20, "0", false, self.gui.window ) self.gui.updateLimit2 = guiCreateEdit( 340, 334, 42, 20, "10", false, self.gui.window ) self.gui.forwardButton = guiCreateButton( 480, 334, 30, 20, "->", false,self.gui.window) self.gui.backwardButton = guiCreateButton( 444, 334, 30, 20, "<-", false,self.gui.window) self.gui.updateButton = guiCreateButton( 390, 334, 44, 20, "Load", false, self.gui.window ) addEventHandler("onClientGUIClick", self.gui.updateButton, self.updateDataButton, false) addEventHandler("onClientGUIClick", self.gui.forwardButton, self.updateDataForwardButton, false) addEventHandler("onClientGUIClick", self.gui.backwardButton, self.updateDataBackwardButton, false) addEventHandler("onClientGUIAccepted", self.gui.updateLimit1, self.updateDataButton, false) addEventHandler("onClientGUIAccepted", self.gui.updateLimit2, self.updateDataButton, false) self.gui.closeButton = guiCreateButton( 530, 334, 50, 20, "Close", false, self.gui.window ) addEventHandler("onClientGUIClick", self.gui.closeButton, self.closeButton, false) addEventHandler("onClientGUISize",self.gui.window,self.resizeWindow,false) guiSetVisible(self.gui.window,false) self:triggerUpdateGui() end --[[ -- setWidthForAllColumns -- -- Sets the same width for all gridlist columns. -- -- @param number width: The width. -- ]] function TableWindow:setWidthForAllColumns(width) for k,v in pairs(self.columns) do guiGridListSetColumnWidth(self.gui.list,v,width,false) end end --[[ -- autoresizeGui -- -- Resizes some Gui elements when the window is resized -- as well as prevents some resizing. -- ]] function TableWindow:autoresizeGui() local w,h = guiGetSize(self.gui.window,false) local normalW = self.defaultWindowSize[1] local normalH = self.defaultWindowSize[2] -- currently, only horzintal resizing allowed if h ~= normalH then guiSetSize(self.gui.window,w,normalH,false) h = normalH end -- and also not smaller if w < normalW then guiSetSize(self.gui.window,normalW,h,false) w = normalW end local factorW = w / normalW local factorH = h / normalH local listW = self.defaultListSize[1] local listH = self.defaultListSize[2] guiSetSize(self.gui.list,listW * factorW,listH * factorH,false) self:setWidthForAllColumns(100) end ----------------- -- Open and close ----------------- -- whether the window was opened/closed TableWindow.visible = false --[[ -- open -- -- Opens the window. -- ]] function TableWindow:open() self:createGui() self.visible = true guiSetVisible(self.gui.window,true) guiBringToFront(self.gui.window) end --[[ -- close -- -- Closes the window. -- ]] function TableWindow:close() self.visible = false guiSetVisible(self.gui.window,false) end --[[ -- hide -- -- Hides or shows the window (works only if the window is currently set visible). -- -- @param boolean bool: Whether to show or hide the window. -- ]] function TableWindow:hide(bool) if self.visible then guiSetVisible(self.gui.window,not bool) end end ---------------------- -- Edit database table ---------------------- --[[ -- openNewRowWindow -- -- Creates and opens the window for adding a new row to the database table -- ]] function TableWindow:openNewRowWindow() if self.newRowWindow ~= nil and isElement(self.newRowWindow.window) then destroyElement(self.newRowWindow) end local columns = self.tableInfo local g = {} local height = #columns * 28 + 80 g.window = guiCreateWindow( 400, 240, 420, height, "Add row : "..self.dbTable, false ) guiWindowSetSizable(g.window,false) local y = 30 g.columnLabel = {} g.columnEdit = {} for k,v in ipairs(columns) do g.columnLabel[v.name] = guiCreateLabel( 10, y, 200, 20, v.name.." ("..v.type..")", false, g.window ) g.columnEdit[v.name] = guiCreateEdit(210, y, 200, 20, "", false, g.window ) y = y + 28 end y = y + 10 g.addButton = guiCreateButton( 50, y, 80, 20, "Add Row", false, g.window ) self.newRowWindowAddButton = function() self:dbAddRow() end addEventHandler("onClientGUIClick", g.addButton, self.newRowWindowAddButton, false ) g.closeButton = guiCreateButton( 140, y, 44, 20, "Close", false, g.window ) self.newRowWindowCloseButton = function() destroyElement(self.newRowWindow.window) end addEventHandler("onClientGUIClick", g.closeButton, self.newRowWindowCloseButton, false ) self.newRowWindow = g end --[[ -- dbAddRow -- -- Adds a row to the db table. -- ]] function TableWindow:dbAddRow() local g = self.newRowWindow local queryColumns = "" local queryValues = "" local values = {self.dbTable} local seperator = "" for k,v in pairs(g.columnEdit) do local value = guiGetText(v) if value ~= "" then queryColumns = queryColumns..seperator..k queryValues = queryValues..seperator.."?" seperator = "," table.insert(values,value) end end if #values == 1 then outputDebugString("dbAddRow: no values") return end local query = "INSERT INTO ? ("..queryColumns..") VALUES ("..queryValues..")" self:dbExecuteQuery(query,values) self:triggerUpdateGui() end --[[ -- dbEditField -- -- Called when the edit button is clicked and changes the selected -- item to the new value (if its different). -- ]] function TableWindow:dbEditField() local row, column = guiGridListGetSelectedItem(self.gui.list) if row ~= -1 then local text = guiGridListGetItemText(self.gui.list,row,column) local editedText = guiGetText(self.gui.edit) local dbColumn = self:getDbColumnFromColumn(column) if dbColumn and editedText ~= text then local query = "UPDATE ? SET ? = ? WHERE rowid = ?" local values = {self.dbTable,dbColumn,editedText,self:getDbRowid(row)} self:dbExecuteQuery(query,values) self:triggerUpdateGui() end end end --[[ -- selectListItem -- -- Called when a gridlist item selected and sets the edit box to its value. -- ]] function TableWindow:selectListItem() local row, column = guiGridListGetSelectedItem(self.gui.list) if row ~= -1 then local text = guiGridListGetItemText(self.gui.list,row,column) guiSetText(self.gui.edit,text) end end --[[ -- dbRemoveRow -- -- Removes the currently selected database table row. -- ]] function TableWindow:dbRemoveRow() local row, column = guiGridListGetSelectedItem(self.gui.list) if row ~= -1 then local sqlRowid = self:getDbRowid(row) local query = "DELETE FROM ? WHERE rowid = ?" local values = {self.dbTable,sqlRowid} self:dbExecuteQuery(query,values) self:triggerUpdateGui() end end ----------------------- -- Manage Gridlist data ----------------------- --[[ -- getDbColumnFromColumn -- -- Returns the name of the database column from the -- column of the gridlist. -- -- @param number column: The number of the gridlist column. -- @return The name of the db column or false if none was found. -- ]] function TableWindow:getDbColumnFromColumn(column) for k,v in pairs(self.columns) do if v == column then return k end end return false end --[[ -- getDbRowId -- -- Gets the database table row id from the gridlist row. -- -- @param number row: The row of the gridlist. -- @return number The id of the database table row. -- ]] function TableWindow:getDbRowid(row) return guiGridListGetItemText(self.gui.list,row,self.columns.rowid) end ------------- -- Update Gui ------------- function TableWindow:updateGui(data) -- clear gridlist data and columns if self.columns then guiGridListClear(self.gui.list) for k,v in pairs(self.columns) do -- doesnt really work: --guiGridListRemoveColumn(self.gui.list,v) end else self.columns = {} end -- inititate vars and get invididual data local sql = data.sql local tableInfo = data.tableInfo self.tableInfo = tableInfo local rows = data.rows self.totalNumRows = data.totalNumRows -- add columns if self.columns.rowid == nil then self.columns.rowid = guiGridListAddColumn(self.gui.list,"#",0.1) end for k,v in ipairs(tableInfo) do local columnName = v.name if self.columns[columnName] == nil then self.columns[columnName] = guiGridListAddColumn(self.gui.list,columnName,0.2) end end self:setWidthForAllColumns(100) -- add data for k,v in ipairs(rows) do local rowId = guiGridListAddRow(self.gui.list) guiGridListSetItemText(self.gui.list,rowId,1,tostring(v.rowid),false,true) for k2,v2 in pairs(v) do guiGridListSetItemText(self.gui.list,rowId,self.columns[k2],tostring(v2),false,false) end end -- update labels guiSetText(self.gui.numRowsLabel,"Number of rows: "..tostring(#rows).."/"..tostring(data.totalNumRows)) end ------------------------------ -- Client/Server Communication ------------------------------ --[[ -- dbExecuteQuery -- -- Sends a request to execute a db query to the server. -- -- @param string query: The query -- @param table values: The values -- ]] function TableWindow:dbExecuteQuery(query,values) triggerServerEvent("onSQLiteBrowserClientMessage",getLocalPlayer(),"executeQuery",{query,values}) end --[[ -- triggerUpdateGui -- -- Sends a request to the server to update the data in the Gui. -- ]] function TableWindow:triggerUpdateGui(move) local from = tonumber(guiGetText(self.gui.updateLimit1)) local limit = tonumber(guiGetText(self.gui.updateLimit2)) if type(from) ~= "number" then from = 0 end if type(limit) ~= "number" then limit = 10 end if move == "forward" then from = from + limit if from >= self.totalNumRows then from = from - limit end guiSetText(self.gui.updateLimit1,from) end if move == "backward" then from = from - limit if from < 0 then from = 0 end guiSetText(self.gui.updateLimit1,from) end guiSetText(self.gui.numRowsLabel,"Loading..") triggerServerEvent("onSQLiteBrowserClientMessage",getLocalPlayer(),"getTableData",{self.dbTable,from,limit}) end
mit
ffxiphoenix/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Sharin-Garin.lua
19
1899
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Sharin-Garin -- Type: Adventurer's Assistant -- @pos 122.658 -1.315 33.001 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/besieged"); require("scripts/globals/keyitems"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local runicpass = 0; if (player:hasKeyItem(RUNIC_PORTAL_USE_PERMIT)) then runicpass = 1; end local cost = 200 -- 200 IS to get a permit if (getMercenaryRank(player) == 11) then captain = 1; else captain = 0; end; local merc = 2 -- Probably could be done, but not really important atm player:startEvent(0x008C,0,merc,runicpass,player:getCurrency("imperial_standing"),getAstralCandescence(),cost,captain); 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 == 0x008C and option == 1) then player:addKeyItem(RUNIC_PORTAL_USE_PERMIT); player:messageSpecial(KEYITEM_OBTAINED,RUNIC_PORTAL_USE_PERMIT); player:delCurrency("imperial_standing", 200); elseif (csid == 0x008C and option == 2) then player:addKeyItem(RUNIC_PORTAL_USE_PERMIT); player:messageSpecial(KEYITEM_OBTAINED,RUNIC_PORTAL_USE_PERMIT); end end;
gpl-3.0
ffxiphoenix/darkstar
scripts/globals/items/messhikimaru.lua
18
1034
----------------------------------------- -- ID: 17826 -- Item: Messhikimaru -- Enchantment: Arcana Killer -- Durration: 10 Mins ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) if (target:hasStatusEffect(EFFECT_ENCHANTMENT) == false) then target:addStatusEffect(EFFECT_ENCHANTMENT,0,0,600,17826); end; end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_ARCANA_KILLER, 20); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_ARCANA_KILLER, 20); end;
gpl-3.0
jacks0nX/cqui
UI/Panels/StatusMessagePanel.lua
2
7234
-- =========================================================================== -- Status Message Manager -- Non-interactive messages that appear in the upper-center of the screen. -- =========================================================================== include( "InstanceManager" ); -- =========================================================================== -- CONSTANTS -- =========================================================================== local DEFAULT_TIME_TO_DISPLAY :number = 10; -- Seconds to display the message -- CQUI CONSTANTS Trying to make the different messages have unique colors local CQUI_STATUS_MESSAGE_CIVIC :number = 3; -- Number to distinguish civic messages local CQUI_STATUS_MESSAGE_TECHS :number = 4; -- Number to distinguish tech messages -- Figure out eventually what colors are used by the actual civic and tech trees local CQUI_CIVIC_COLOR = 0xDFFF33CC; local CQUI_TECHS_COLOR = 0xDFFF6600; local CQUI_BASIC_COLOR = 0xFFFFFFFF; -- =========================================================================== -- VARIABLES -- =========================================================================== local m_statusIM :table = InstanceManager:new( "StatusMessageInstance", "Root", Controls.StackOfMessages ); local m_gossipIM :table = InstanceManager:new( "GossipMessageInstance", "Root", Controls.StackOfMessages ); local PlayerConnectedChatStr :string = Locale.Lookup( "LOC_MP_PLAYER_CONNECTED_CHAT" ); local PlayerDisconnectedChatStr :string = Locale.Lookup( "LOC_MP_PLAYER_DISCONNECTED_CHAT" ); local PlayerKickedChatStr :string = Locale.Lookup( "LOC_MP_PLAYER_KICKED_CHAT" ); local CQUI_messageType :number = 0; local m_kMessages :table = {}; -- =========================================================================== -- FUNCTIONS -- =========================================================================== -- =========================================================================== -- =========================================================================== function OnStatusMessage( str:string, fDisplayTime:number, type:number ) if (type == ReportingStatusTypes.DEFAULT or type == ReportingStatusTypes.GOSSIP) then -- A type we handle? local kTypeEntry :table = m_kMessages[type]; if (kTypeEntry == nil) then -- New type m_kMessages[type] = { InstanceManager = nil, MessageInstances= {} }; kTypeEntry = m_kMessages[type]; -- Link to the instance manager and the stack the UI displays in if (type == ReportingStatusTypes.GOSSIP) then kTypeEntry.InstanceManager = m_gossipIM; else kTypeEntry.InstanceManager = m_statusIM; end end local pInstance:table = kTypeEntry.InstanceManager:GetInstance(); table.insert( kTypeEntry.MessageInstances, pInstance ); local timeToDisplay:number = (fDisplayTime > 0) and fDisplayTime or DEFAULT_TIME_TO_DISPLAY; -- CQUI Figuring out how to change the color of the status message if CQUI_messageType == CQUI_STATUS_MESSAGE_CIVIC then pInstance.StatusGrid:SetColor(CQUI_CIVIC_COLOR); elseif CQUI_messageType == CQUI_STATUS_MESSAGE_TECHS then pInstance.StatusGrid:SetColor(CQUI_TECHS_COLOR); elseif type == ReportingStatusTypes.DEFAULT then pInstance.StatusGrid:SetColor(CQUI_BASIC_COLOR); end pInstance.StatusLabel:SetText( str ); pInstance.Anim:SetEndPauseTime( timeToDisplay ); pInstance.Anim:RegisterEndCallback( function() OnEndAnim(kTypeEntry,pInstance) end ); pInstance.Anim:SetToBeginning(); pInstance.Anim:Play(); Controls.StackOfMessages:CalculateSize(); Controls.StackOfMessages:ReprocessAnchoring(); end end -- =========================================================================== function OnEndAnim( kTypeEntry:table, pInstance:table ) pInstance.Anim:ClearEndCallback(); Controls.StackOfMessages:CalculateSize(); Controls.StackOfMessages:ReprocessAnchoring(); kTypeEntry.InstanceManager:ReleaseInstance( pInstance ) end ---------------------------------------------------------------- function OnMultplayerPlayerConnected( playerID ) if( ContextPtr:IsHidden() == false and GameConfiguration.IsNetworkMultiplayer() ) then local pPlayerConfig = PlayerConfigurations[playerID]; local statusMessage = pPlayerConfig:GetPlayerName() .. " " .. PlayerConnectedChatStr; OnStatusMessage( statusMessage, DEFAULT_TIME_TO_DISPLAY, ReportingStatusTypes.DEFAULT ); end end ---------------------------------------------------------------- function OnMultiplayerPrePlayerDisconnected( playerID ) if( ContextPtr:IsHidden() == false and GameConfiguration.IsNetworkMultiplayer() ) then local pPlayerConfig = PlayerConfigurations[playerID]; local statusMessage = Locale.Lookup(pPlayerConfig:GetPlayerName()); if(Network.IsPlayerKicked(playerID)) then statusMessage = statusMessage .. " " .. PlayerKickedChatStr; else statusMessage = statusMessage .. " " .. PlayerDisconnectedChatStr; end OnStatusMessage(statusMessage, DEFAULT_TIME_TO_DISPLAY, ReportingStatusTypes.DEFAULT); end end -- =========================================================================== -- Testing: When on the "G" and "D" keys generate messages. -- =========================================================================== function Test() OnStatusMessage("Testing out A message", 10, ReportingStatusTypes.GOSSIP ); OnStatusMessage("Testing out BB message", 10, ReportingStatusTypes.GOSSIP ); ContextPtr:SetInputHandler( function( pInputStruct ) local uiMsg = pInputStruct:GetMessageType(); if uiMsg == KeyEvents.KeyUp then local key = pInputStruct:GetKey(); if key == Keys.D then OnStatusMessage("Testing out status message ajsdkl akds dk dkdkj dkdkd ajksaksdkjkjd dkadkj f djkdkjdkj dak sdkjdjkal dkd kd dk adkj dkkadj kdjd kdkjd jkd jd dkj djkd dkdkdjdkdkjdkd djkd dkd dkjd kdjdkj d", 10, ReportingStatusTypes.DEFAULT ); return true; end if key == Keys.G then OnStatusMessage("Testing out gossip message", 10, ReportingStatusTypes.GOSSIP ); return true; end end return false; end, true); end function CQUI_OnStatusMessage(str:string, fDisplayTime:number, thisType:number) if thisType == CQUI_STATUS_MESSAGE_CIVIC then CQUI_messageType = CQUI_STATUS_MESSAGE_CIVIC; elseif thisType == CQUI_STATUS_MESSAGE_TECHS then CQUI_messageType = CQUI_STATUS_MESSAGE_TECHS; else CQUI_messageType = 0; end OnStatusMessage(str, fDisplayTime, ReportingStatusTypes.DEFAULT); CQUI_messageType = 0; end -- =========================================================================== function Initialize() Events.StatusMessage.Add( OnStatusMessage ); Events.MultiplayerPlayerConnected.Add( OnMultplayerPlayerConnected ); Events.MultiplayerPrePlayerDisconnected.Add( OnMultiplayerPrePlayerDisconnected ); -- CQUI LuaEvents.CQUI_AddStatusMessage.Add( CQUI_OnStatusMessage ); --Test(); end Initialize();
mit
ffxiphoenix/darkstar
scripts/globals/conquest.lua
7
41670
----------------------------------- -- -- Functions for Conquest system -- ----------------------------------- require("scripts/globals/common"); require("scripts/globals/missions"); ----------------------------------- -- convenience constants ----------------------------------- SANDORIA = 0; BASTOK = 1; WINDURST = 2; BEASTMEN = 3; OTHER = 4; RONFAURE = 0; ZULKHEIM = 1; NORVALLEN = 2; GUSTABERG = 3; DERFLAND = 4; SARUTABARUTA = 5; KOLSHUSHU = 6; ARAGONEU = 7; FAUREGANDI = 8; VALDEAUNIA = 9; QUFIMISLAND = 10; LITELOR = 11; KUZOTZ = 12; VOLLBOW = 13; ELSHIMOLOWLANDS = 14; ELSHIMOUPLANDS = 15; TULIA = 16; MOVALPOLOS = 17; TAVNAZIANARCH = 18; CONQUEST_TALLY_START = 0; CONQUEST_TALLY_END = 1; CONQUEST_UPDATE = 2; nationAlly = 3; ----------------------------------- -- San d'Oria inventory -- {Option,CP,Item} ----------------------------------- SandInv = {0x80A1,0x000A,0x1055,0x80A0,0x0007,0x1056,0x80A3,0x2328,0x3CB5, 0x80A2,0x09C4,0x3CB6,0x80A5,0x01F4,0x3D91,0x80A6,0x03E8,0x3D92, 0x80A7,0x07D0,0x3D93,0x8002,0x03E8,0x30DE,0x8003,0x03E8,0x31D1, 0x8004,0x03E8,0x32CC,0x8006,0x03E8,0x3596,0x8001,0x03E8,0x40A0, 0x8005,0x03E8,0x4133,0x8000,0x03E8,0x430F,0x8011,0x07D0,0x3156, 0x8012,0x07D0,0x3252,0x8014,0x07D0,0x32F5,0x8010,0x07D0,0x41D4, 0x8013,0x07D0,0x43D7,0x8022,0x0FA0,0x308F,0x8023,0x0FA0,0x318F, 0x8024,0x0FA0,0x328F,0x8021,0x0FA0,0x3330,0x8027,0x0FA0,0x34B7, 0x8025,0x0FA0,0x4168,0x8020,0x0FA0,0x41CC,0x8026,0x0FA0,0x42FE, 0x8034,0x1F40,0x3030,0x8031,0x1F40,0x310F,0x8032,0x1F40,0x320F, 0x8033,0x1F40,0x3597,0x8030,0x1F40,0x40D9,0x8042,0x3E80,0x3018, 0x8043,0x3E80,0x3019,0x8046,0x3E80,0x318E,0x8047,0x3E80,0x328E, 0x8045,0x3E80,0x3331,0x8044,0x3E80,0x3333,0x8048,0x3E80,0x33A4, 0x8049,0x3E80,0x3598,0x8041,0x3E80,0x40BB,0x8040,0x3E80,0x41D3, 0x8056,0x5DC0,0x3021,0x8052,0x5DC0,0x308E,0x8054,0x5DC0,0x310E, 0x8055,0x5DC0,0x320E,0x8051,0x5DC0,0x3332,0x8050,0x5DC0,0x350C, 0x8053,0x5DC0,0x359A,0x8058,0x5DC0,0x40D7,0x8059,0x5DC0,0x41A5, 0x8057,0x5DC0,0x42AB,0x8062,0x7D00,0x34F5,0x8061,0x7D00,0x41F6, 0x8060,0x7D00,0x4932,0x8072,0x9C40,0x3354,0x8070,0x9C40,0x36BD, 0x8071,0x9C40,0x36BE,0x8083,0xBB80,0x41FD,0x8080,0xBB80,0x4239, 0x8082,0xBB80,0x4432,0x8081,0xBB80,0x460E,0x8090,0xDAC0,0x385C, 0x80A4,0x1388,0x44AF}; ----------------------------------- -- Bastok inventory -- {Option,CP,Item} ----------------------------------- BastInv = {0x80A1,0x000A,0x1055,0x80A0,0x0007,0x1056,0x80A3,0x2328,0x3CB5, 0x80A2,0x09C4,0x3CB6,0x80A5,0x01F4,0x3D91,0x80A6,0x03E8,0x3D92, 0x80A7,0x07D0,0x3D93,0x8003,0x03E8,0x30DD,0x8004,0x03E8,0x31D0, 0x8005,0x03E8,0x32CB,0x8000,0x03E8,0x4031,0x8002,0x03E8,0x4108, 0x8007,0x03E8,0x418C,0x8006,0x03E8,0x42E8,0x8001,0x03E8,0x4347, 0x8014,0x07D0,0x3031,0x8011,0x07D0,0x3155,0x8012,0x07D0,0x3251, 0x8013,0x07D0,0x4169,0x8010,0x07D0,0x4298,0x8022,0x0FA0,0x3096, 0x8023,0x0FA0,0x3116,0x8024,0x0FA0,0x3196,0x8025,0x0FA0,0x3216, 0x8026,0x0FA0,0x3296,0x8021,0x0FA0,0x332A,0x8029,0x0FA0,0x34B9, 0x8028,0x0FA0,0x3606,0x8020,0x0FA0,0x4148,0x8027,0x0FA0,0x41A6, 0x8031,0x1F40,0x3086,0x8032,0x1F40,0x3186,0x8033,0x1F40,0x3286, 0x8034,0x1F40,0x3599,0x8030,0x1F40,0x4084,0x8035,0x1F40,0x4383, 0x8042,0x3E80,0x3106,0x8043,0x3E80,0x3206,0x8041,0x3E80,0x332B, 0x8040,0x3E80,0x4091,0x8044,0x3E80,0x42E9,0x8045,0x3E80,0x4365, 0x8053,0x5DC0,0x3010,0x8055,0x5DC0,0x3308,0x8050,0x5DC0,0x332C, 0x8051,0x5DC0,0x350E,0x8052,0x5DC0,0x40AD,0x8054,0x5DC0,0x42FF, 0x8062,0x7D00,0x34F6,0x8060,0x7D00,0x3E55,0x8061,0x7D00,0x458F, 0x8072,0x9C40,0x3355,0x8071,0x9C40,0x3638,0x8070,0x9C40,0x36BF, 0x8080,0xBB80,0x419F,0x8081,0xBB80,0x4431,0x8083,0xBB80,0x44F7, 0x8082,0xBB80,0x4714,0x8090,0xDAC0,0x385D,0x80A4,0x1388,0x44B0}; ----------------------------------- -- Windurst inventory -- {Option,CP,Item} ----------------------------------- WindInv = {0x80A1,0x000A,0x1055,0x8044,0x3E80,0x31BE,0x8025,0x0FA0,0x32B6, 0x80A0,0x0007,0x1056,0x8045,0x3E80,0x323E,0x8027,0x0FA0,0x33A5, 0x80A3,0x2328,0x3CB5,0x8046,0x3E80,0x32BE,0x8028,0x0FA0,0x34B8, 0x80A2,0x09C4,0x3CB6,0x8041,0x3E80,0x332E,0x8026,0x0FA0,0x416B, 0x80A5,0x01F4,0x3D91,0x8047,0x3E80,0x41AA,0x8020,0x0FA0,0x4188, 0x80A6,0x03E8,0x3D92,0x8048,0x3E80,0x4136,0x8033,0x1F40,0x3146, 0x80A7,0x07D0,0x3D93,0x8040,0x3E80,0x42BA,0x8034,0x1F40,0x31C7, 0x8003,0x03E8,0x3273,0x8050,0x5DC0,0x332F,0x8035,0x1F40,0x3246, 0x8002,0x03E8,0x403A,0x8051,0x5DC0,0x350D,0x8036,0x1F40,0x32C6, 0x8001,0x03E8,0x4284,0x8053,0x5DC0,0x41A8,0x8032,0x1F40,0x332D, 0x8004,0x03E8,0x42EA,0x8054,0x5DC0,0x41A9,0x8030,0x1F40,0x404F, 0x8000,0x03E8,0x4307,0x8052,0x5DC0,0x42C6,0x8038,0x1F40,0x411D, 0x8011,0x07D0,0x30C4,0x8061,0x7D00,0x304B,0x8037,0x1F40,0x41A7, 0x8012,0x07D0,0x316D,0x8062,0x7D00,0x34F7,0x8031,0x1F40,0x4382, 0x8013,0x07D0,0x31AF,0x8060,0x7D00,0x3E56,0x8042,0x3E80,0x30BE, 0x8014,0x07D0,0x3237,0x8072,0x9C40,0x3356,0x8043,0x3E80,0x313E, 0x8015,0x07D0,0x32AF,0x8070,0x9C40,0x36C0,0x80A4,0x1388,0x44B1, 0x8016,0x07D0,0x416A,0x8071,0x9C40,0x36C1,0x8024,0x0FA0,0x3236, 0x8017,0x07D0,0x4222,0x8082,0xBB80,0x4464,0x8090,0xDAC0,0x385E, 0x8010,0x07D0,0x42CF,0x8081,0xBB80,0x447A,0x8023,0x0FA0,0x31B6, 0x8021,0x0FA0,0x30B6,0x8083,0xBB80,0x44D1,0x8080,0xBB80,0x46E1, 0x8022,0x0FA0,0x3136}; ----------------------------------- -- Crystal Donate Array -- Conquest Point Required for recharged the ring + charge -- CP Reward for Supply Quest -- TP Fees ----------------------------------- DonateCrys = {4096,4097,4098,4099,4100,4101,4102,4103,4238,4239,4240,4241,4242,4243,4244,4245}; XpRing = {350,700,600}; RingCharg = {7,7,3}; supplyReward = {10,30,40,10,40,10,40,40,70,50,60,40,70,70,70,70,70,70,70}; tpFees = { 100, 100, 150, 100, 150, 100, 100, 150, 350, 400, 150, 250, 300, 500, 250, 350, 500, 0, 300 } ---------------------------------------------------------------- -- function tradeConquestGuard() ----------------------------------------------------------------- function tradeConquestGuard(player,npc,trade,guardnation,guardtype) -- Nation: -- SANDORIA, BASTOK, WINDURST, OTHER(Jeuno) -- Type: 1: city, 2: foreign, 3: outpost, 4: border local myCP = player:getCP(); local item = trade:getItem(); local AddPoints = 0; if (player:getNation() == guardnation or guardnation == OTHER) then if (guardtype ~= 3 and guardtype ~= 4) then -- all guard can trade crystal except outpost and border. if (item >= 4096 and item <= 4103 or item >= 4238 and item <= 4245) then for Crystal = 1,table.getn(DonateCrys),1 do local tcount = trade:getItemQty(DonateCrys[Crystal]) if (tcount > 0 and trade:hasItemQty(DonateCrys[Crystal],tcount)) then if (player:getRank() == 1) then player:showText(npc,CONQUEST - 7); break; elseif (player:getRankPoints() == 4000) then player:showText(npc,CONQUEST + 43); break; elseif (DonateCrys[Crystal] == 4102 or DonateCrys[Crystal] == 4103 or DonateCrys[Crystal] == 4244 or DonateCrys[Crystal] == 4245) then AddPoints = AddPoints + tcount * math.floor(4000 / (player:getRank() * 12 - 16)); else AddPoints = AddPoints + tcount * math.floor(4000 / (player:getRank() * 12 - 12)); end end end if (player:getRank() ~= 1 and player:getRankPoints() < 4000) then if (AddPoints + player:getRankPoints() >= 4000) then newpoint = (AddPoints + player:getRankPoints()) - 4000; player:addCP(newpoint); player:setRankPoints(4000); player:showText(npc,CONQUEST + 44); else --printf("point: %u",AddPoints); player:addRankPoints(AddPoints); player:showText(npc,CONQUEST + 45); end player:tradeComplete(); end end end if (item >= 15761 and item <= 15763) then -- All guard can recharge ring - I can't read number of charge atm if (trade:hasItemQty(item,1) and trade:getItemCount() == 1 and player:getVar("CONQUEST_RING_RECHARGE") < os.time() and (ALLOW_MULTIPLE_EXP_RINGS == 1 or checkConquestRing(player) < 2)) then if (myCP >= XpRing[item - 15760]) then player:delCP(XpRing[item - 15760]); player:tradeComplete(); player:addItem(item); player:setVar("CONQUEST_RING_RECHARGE",getConquestTally()); player:showText(npc,CONQUEST + 58,item,XpRing[item - 15760],RingCharg[(item - 15760)]); else player:showText(npc,CONQUEST + 55,item,XpRing[item - 15760]); end else -- TODO: Verify that message is retail correct. -- This gives feedback on a failure at least, and is grouped with the recharge messages. Confident enough for a commit. player:showText(npc,CONQUEST+56,item); -- "Please be aware that you can only purchase or recharge <item> once during the period between each conquest results tally. end end end end; ------------------------------------------------------------------------- -- function suppliesFresh(player) [NEED COMMAND] 0: delete old supply after weekly conquest tally ------------------------------------------------------------------------- function supplyRunFresh(player) local fresh = player:getVar("supplyQuest_fresh"); local started = player:getVar("supplyQuest_started"); local region = player:getVar("supplyQuest_region"); if ((fresh <= os.time() and (region > 0 or player:hasKeyItem(75))) or started <= 400) then -- Legacy support to remove supplies from the old system, otherwise they'd never go away. return 0; else return 1; end; end; ---------------------------------------------------------------- -- function getArg1(player) ----------------------------------------------------------------- windurst_bastok_ally = 0; sandy_windurst_ally = 0; sandy_bastok_ally = 0; function getArg1(guardnation,player) local pNation = player:getNation(); local output = 0; local signet = 0; if (guardnation == WINDURST) then output = 33; elseif (guardnation == SANDORIA) then output = 1; elseif (guardnation == BASTOK) then output = 17; end if (guardnation == pNation) then signet = 0; elseif (pNation == WINDURST) then if (guardnation == BASTOK and windurst_bastok_ally == 1) or (guardnation == SANDORIA and sandy_windurst_ally == 1) then signet = 1; else signet = 7; end elseif (pNation == BASTOK) then if (guardnation == WINDURST and windurst_bastok_ally == 1) or (guardnation == SANDORIA and sandy_bastok_ally == 1) then signet = 2; else signet = 7; end elseif (pNation == SANDORIA) then if (guardnation == WINDURST and sandy_windurst_ally == 1) or (guardnation == BASTOK and sandy_bastok_ally == 1) then signet = 4; else signet = 7; end end if (guardnation == OTHER) then output = (pNation * 16) + (3 * 256) + 65537; else output = output + 256 * signet; end return output; end; ------------------------------------------------ -- function getExForceAvailable(guardnation,player) Expeditionary Force Menu [NOT IMPLEMENTED] ------------------------------------------------ function getExForceAvailable(guardnation,player) return 0; end; ------------------------------------------------ -- function conquest_ranking() computes part of argument 3 for gate guard events. -- it represents the conquest standing of the 3 nations. Verified. ------------------------------------------------ function conquestRanking() return getNationRank(SANDORIA) + 4 * getNationRank(BASTOK) + 16 * getNationRank(WINDURST); end; ---------------------------------------------------------------- -- function getSupplyAvailable(nation,player) produces the supply quest mask for the nation based on the current conquest standings. ---------------------------------------------------------------- function getSupplyAvailable(nation,player) local mask = 2130706463; if (player:getVar("supplyQuest_started") == vanaDay()) then mask = 4294967295; -- Need to wait 1 vanadiel day end for nb = 0,15 do if (player:hasKeyItem(getSupplyKey(nb))) then mask = -1; -- if you have supply run already activated end end if (player:hasKeyItem(getSupplyKey(18))) then -- we need to skip 16 and 17 for now mask = -1; end if (mask ~= -1 and mask ~= 4294967295) then for i = 0,18 do if (GetRegionOwner(i) ~= nation or i == 16 or (i == 18 and player:hasCompletedMission(COP,DARKNESS_NAMED) == false)) then mask = mask + 2^(i + 5); end end end return mask; end; ---------------------------------------------------------------- -- function getArg6(player) computes argument 6 for gate guard events. This number encodes a player's rank and nationality: -- bits 1-4 encode the rank of the player (verified that bit 4 is part of the rank number so ranks could have gone up to 31.) -- bits 5-6 seem to encode the citizenship as below. This part needs more testing and verification. ----------------------------------------------------------------- function getArg6(player) local output = player:getRank(); local nation = player:getNation(); if (nation == SANDORIA) then return output; elseif (nation == BASTOK) then return output + 32; elseif (nation == WINDURST) then return output + 64; end end; ------------------------------------------------ -- function getRewardExForce(guardnation,player) Expeditionary Force Reward [NOT IMPLEMENTED] ------------------------------------------------ function getRewardExForce(guardnation,player) return 0; end; ------------------------------------------------ -- function getKeySupply(region) ------------------------------------------------ function getSupplyKey(region) if (region <= 9) then return 75 + region; elseif (region == 10) then return 124; elseif (region <= 13) then return 74 + region; elseif (region <= 15) then return 248 + region; elseif (region == 18) then return 620; end end; ----------------------------------------------------------------- -- giltosetHP(player) returns the amount of gil it costs a player to set a homepoint at a foreign outpost/border guard. ----------------------------------------------------------------- function giltosetHP(guardnation,player) local rank = player:getRank(); if (getArg1(guardnation,player) < 0x700) then -- determine ifplayer is in same or allied nation as guard HPgil = 0; else if (rank <= 5) then HPgil = 100 * 2^(rank - 1); else HPgil = 800 * rank - 2400; end end return HPgil; end; ----------------------------------------------------------------- -- function hasOutpost(player, region) returns 1 ifthe player has the outpost of the indicated region under current allegiance. ----------------------------------------------------------------- function hasOutpost(player, region) local nation = player:getNation() local bit = {}; if (nation == BASTOK) then supply_quests = player:getNationTeleport(BASTOK); elseif (nation == SANDORIA) then supply_quests = player:getNationTeleport(SANDORIA); elseif (nation == WINDURST) then supply_quests = player:getNationTeleport(WINDURST); end; for i = 23,5,-1 do twop = 2^i if (supply_quests >= twop) then bit[i]=1; supply_quests = supply_quests - twop; else bit[i]=0; end; --printf("bit %u: %u \n",i,bit[i]); end; return bit[region]; end; ----------------------------------------------------------------- -- function OP_TeleFee(player,region) ----------------------------------------------------------------- function OP_TeleFee(player,region) if (hasOutpost(player, region+5) == 1) then if (GetRegionOwner(region) == player:getNation()) then return tpFees[region + 1]; else return tpFees[region + 1] * 3; end else return 0; end end; ----------------------------------------------------------------- -- Teleport Outpost > Nation ----------------------------------------------------------------- function toHomeNation(player) if (player:getNation() == BASTOK) then player:setPos(89, 0 , -66, 0, 234); elseif (player:getNation() == SANDORIA) then player:setPos(49, -1 , 29, 164, 231); else player:setPos(193, -12 , 220, 64, 240); end end; ----------------------------------------------------------------- -- function getTeleAvailable(nation) ----------------------------------------------------------------- function getTeleAvailable(nation) local mask = 2145386527; for i = 5,23 do if (GetRegionOwner(i - 5) ~= nation) then mask = mask + 2^i; end; end return mask; end; --------------------------------- -- Teleport Nation > Outpost --------------------------------- function toOutpost(player,option) -- Coordinates marked {R} have been obtained by packet capture from retail. Don't change them. -- Ronfaure if (option == 5) then player:setPos(-437.688, -20.255, -219.227, 124, 100); -- {R} -- Zulkheim elseif (option == 6) then player:setPos(148.231, -7.975 , 93.479, 154, 103); -- {R} -- Norvallen elseif (option == 7) then player:setPos(62.030, 0.463, -2.025, 67, 104); -- {R} -- Gustaberg elseif (option == 8) then player:setPos(-580.161, 39.578, 62.68, 89, 106); -- {R} -- Derfland elseif (option == 9) then player:setPos(465.820, 23.625, 423.164, 29, 109); -- {R} -- Sarutabaruta elseif (option == 10) then player:setPos(-17.921, -13.335, 318.156, 254, 115); -- {R} -- Kolshushu elseif (option == 11) then player:setPos(-480.237, -30.943, 58.079, 62, 118); -- {R} -- Aragoneu elseif (option == 12) then player:setPos(-297.047, 16.988, 418.026, 225, 119); -- {R} -- Fauregandi elseif (option == 13) then player:setPos(-18.690, -60.048, -109.243, 100, 111); -- {R} -- Valdeaunia elseif (option == 14) then player:setPos(211.210, -24.016, -207.338, 160, 112); -- {R} -- Qufim Island elseif (option == 15) then player:setPos(-243.049, -19.983, 306.712, 71, 126); -- {R} -- Li'Telor elseif (option == 16) then player:setPos(-37.669, 0.419, -141.216, 69, 121); -- {R} -- Kuzotz elseif (option == 17) then player:setPos(-249.983, 7.965, -252.976, 122, 114); -- {R} -- Vollbow elseif (option == 18) then player:setPos(-176.360, 7.624, -63.580, 122, 113); -- {R} -- Elshimo Lowlands elseif (option == 19) then player:setPos(-240.860, -0.031, -388.434, 64, 123); -- {R} -- Elshimo Uplands elseif (option == 20) then player:setPos(207.821, -0.128, -86.623, 159, 124); -- {R} -- Tu'Lia ?! elseif (option == 21) then player:setPos(4, -54, -600, 192, 130); -- Dummied out? -- Tavnazia elseif (option == 23) then player:setPos(-535.861, -7.149, -53.628, 122, 24); -- {R} end; end; ----------------------------------- -- Expeditionary Force -- {Option,Quest,Zone,MenuMask,MinimumLevel,KeyItem} NOT USED ----------------------------------- EXFORCE = {0x20006,ZULK_EF,0x67,0x000040,0x14,ZULKHEIM_EF_INSIGNIA, 0x20007,NORV_EF,0x68,0x000080,0x19,NORVALLEN_EF_INSIGNIA, 0x20009,DERF_EF,0x6D,0x000200,0x19,DERFLAND_EF_INSIGNIA, 0x2000B,KOLS_EF,0x76,0x000800,0x14,KOLSHUSHU_EF_INSIGNIA, 0x2000C,ARAG_EF,0x77,0x001000,0x19,ARAGONEU_EF_INSIGNIA, 0x2000D,FAUR_EF,0x6F,0x002000,0x23,FAUREGANDI_EF_INSIGNIA, 0x2000E,VALD_EF,0x70,0x004000,0x28,VALDEAUNIA_EF_INSIGNIA, 0x2000F,QUFI_EF,0x7E,0x008000,0x19,QUFIM_EF_INSIGNIA, 0x20010,LITE_EF,0x79,0x010000,0x23,LITELOR_EF_INSIGNIA, 0x20011,KUZO_EF,0x72,0x020000,0x28,KUZOTZ_EF_INSIGNIA, 0x20012,VOLL_EF,0x71,0x040000,0x41,VOLLBOW_EF_INSIGNIA, 0x20013,ELLO_EF,0x7B,0x080000,0x23,ELSHIMO_LOWLANDS_EF_INSIGNIA, 0x20014,ELUP_EF,0x7C,0x100000,0x2D,ELSHIMO_UPLANDS_EF_INSIGNIA}; --------------------------------- -- --------------------------------- function getRegionalConquestOverseers(region) switch (region): caseof { --------------------------------- [RONFAURE] = function (x) -- West Ronfaure (100) --------------------------------- --print("RONFAURE"); local Doladepaiton = 17187546; npc = { -- Doladepaiton,SANDORIA, -- Doladepaiton, R.K. Doladepaiton+7,SANDORIA, -- Ballie, R.K. Doladepaiton+3,SANDORIA, -- Flag Doladepaiton+11,SANDORIA, -- Flag -- Doladepaiton+1,BASTOK, -- Yoshihiro, I.M. Doladepaiton+8,BASTOK, -- Molting Moth, I.M. Doladepaiton+4,BASTOK, -- Flag Doladepaiton+13,BASTOK, -- Flag -- Doladepaiton+2,WINDURST, -- Kyanta-Pakyanta, W.W. Doladepaiton+9,WINDURST, -- Tottoto, W.W. Doladepaiton+5,WINDURST, -- Flag Doladepaiton+13,WINDURST, -- Flag -- Doladepaiton+6,BEASTMEN, -- Flag Doladepaiton+14,BEASTMEN, -- Flag -- Doladepaiton+10,OTHER, -- Harvetour } end, --------------------------------- [ZULKHEIM] = function (x) -- Valkurm_Dunes (103) --------------------------------- --print("ZULKHEIM"); local Quanteilleron = 17199705; npc = { -- Quanteilleron,SANDORIA, -- Quanteilleron, R.K. Quanteilleron+7,SANDORIA, -- Prunilla, R.K. Quanteilleron+3,SANDORIA, -- flag Quanteilleron+11,SANDORIA, -- flag -- Quanteilleron+1,BASTOK, -- Tsunashige, I.M. Quanteilleron+8,BASTOK, -- Fighting Ant, I.M. Quanteilleron+4,BASTOK, -- flag Quanteilleron+12,BASTOK, -- flag -- Quanteilleron+2,WINDURST, -- Nyata-Mobuta, W.W. Quanteilleron+9,WINDURST, -- Tebubu, W.W. Quanteilleron+5,WINDURST, -- flag Quanteilleron+13,WINDURST, -- flag -- Quanteilleron+6,BEASTMEN, -- flag Quanteilleron+14,BEASTMEN, -- flag -- Quanteilleron+10,OTHER, -- Medicine Axe } end, --------------------------------- [NORVALLEN] = function (x) -- Jugner_Forest (104) --------------------------------- --print("NORVALLEN"); local Chaplion = 17203844; npc = { -- Chaplion,SANDORIA, -- Chaplion, R.K. Chaplion+7,SANDORIA, -- Taumiale, R.K. Chaplion+3,SANDORIA, -- flag Chaplion+11,SANDORIA, -- flag -- Chaplion+1,BASTOK, -- Takamoto, I.M. Chaplion+8,BASTOK, -- Pure Heart, I.M. Chaplion+4,BASTOK, -- flag Chaplion+12,BASTOK, -- flag -- Chaplion+2,WINDURST, -- Bubchu-Bibinchu, W.W. Chaplion+9,WINDURST, -- Geruru, W.W. Chaplion+5,WINDURST, -- flag Chaplion+13,WINDURST, -- flag -- Chaplion+6,BEASTMEN, -- flag Chaplion+14,BEASTMEN, -- flag -- Chaplion+10,OTHER, -- Mionie } end, --------------------------------- [GUSTABERG] = function (x) -- North_Gustaberg (106) --------------------------------- --print("GUSTABERG"); local Ennigreaud = 17212056; npc = { -- Ennigreaud,SANDORIA, -- Ennigreaud, R.K. Ennigreaud+7,SANDORIA, -- Quellebie, R.K. Ennigreaud+3,SANDORIA, -- flag Ennigreaud+11,SANDORIA, -- flag -- Ennigreaud+1,BASTOK, -- Shigezane, I.M. Ennigreaud+8,BASTOK, -- Heavy Fog, I.M. Ennigreaud+4,BASTOK, -- flag Ennigreaud+12,BASTOK, -- flag -- Ennigreaud+2,WINDURST, -- Kuuwari-Aori, W.W. Ennigreaud+9,WINDURST, -- Butsutsu, W.W. Ennigreaud+5,WINDURST, -- flag Ennigreaud+13,WINDURST, -- flag -- Ennigreaud+6,BEASTMEN, -- flag Ennigreaud+14,BEASTMEN, -- flag -- Ennigreaud+10,OTHER, -- Kuleo } end, --------------------------------- [DERFLAND] = function (x) -- Pashhow_Marshlands (109) --------------------------------- --print("DERFLAND"); local Mesachedeau = 17224322; npc = { -- Mesachedeau,SANDORIA, -- Mesachedeau, R.K. Mesachedeau+7,SANDORIA, -- Ioupie, R.K. Mesachedeau+3,SANDORIA, -- flag Mesachedeau+11,SANDORIA, -- flag -- Mesachedeau+1,BASTOK, -- Souun, I.M. Mesachedeau+8,BASTOK, -- Sharp Tooth, I.M. Mesachedeau+4,BASTOK, -- flag Mesachedeau+12,BASTOK, -- flag -- Mesachedeau+2,WINDURST, -- Mokto-Lankto, W.W. Mesachedeau+9,WINDURST, -- Shikoko, W.W. Mesachedeau+5,WINDURST, -- flag Mesachedeau+13,WINDURST, -- flag -- Mesachedeau+6,BEASTMEN, -- flag Mesachedeau+14,BEASTMEN, -- flag -- Mesachedeau+10,OTHER, -- Tahmasp } end, --------------------------------- [SARUTABARUTA] = function (x) -- West_Sarutabaruta (115) --------------------------------- --print("SARUTABARUTA"); local Naguipeillont = 17248846; npc = { -- Naguipeillont,SANDORIA, -- Naguipeillont, R.K. Naguipeillont+7,SANDORIA, -- Banege, R.K. Naguipeillont+3,SANDORIA, -- flag Naguipeillont+11,SANDORIA, -- flag -- Naguipeillont+1,BASTOK, -- Ryokei, I.M. Naguipeillont+8,BASTOK, -- Slow Axe, I.M. Naguipeillont+4,BASTOK, -- flag Naguipeillont+12,BASTOK, -- flag -- Naguipeillont+2,WINDURST, -- Roshina-Kuleshuna, W.W. Naguipeillont+9,WINDURST, -- Darumomo, W.W. Naguipeillont+5,WINDURST, -- flag Naguipeillont+13,WINDURST, -- flag -- Naguipeillont+6,BEASTMEN, -- flag Naguipeillont+14,BEASTMEN, -- flag -- Naguipeillont+10,OTHER, -- Mahien-Uhien } end, --------------------------------- [KOLSHUSHU] = function (x) -- Buburimu_Peninsula (118) --------------------------------- --print("KOLSHUSHU"); local Bonbavour = 17261143; npc = { -- Bonbavour,SANDORIA, -- Bonbavour, R.K. Bonbavour+7,SANDORIA, -- Craigine, R.K. Bonbavour+3,SANDORIA, -- flag Bonbavour+11,SANDORIA, -- flag -- Bonbavour+1,BASTOK, -- Ishin, I.M. Bonbavour+8,BASTOK, -- Wise Turtle, I.M. Bonbavour+4,BASTOK, -- flag Bonbavour+12,BASTOK, -- flag -- Bonbavour+2,WINDURST, -- Ganemu-Punnemu, W.W. Bonbavour+9,WINDURST, -- Mashasha, W.W. Bonbavour+5,WINDURST, -- flag Bonbavour+13,WINDURST, -- flag -- Bonbavour+6,BEASTMEN, -- flag Bonbavour+14,BEASTMEN, -- flag -- Bonbavour+10,OTHER, -- Lobho Ukipturi } end, --------------------------------- [ARAGONEU] = function (x) -- Meriphataud_Mountains (119) --------------------------------- --print("ARAGONEU"); local Chegourt = 17265267; npc = { -- Chegourt,SANDORIA, -- Chegourt, R.K. Chegourt+7,SANDORIA, -- Buliame, R.K. Chegourt+3,SANDORIA, -- flag Chegourt+11,SANDORIA, -- flag -- Chegourt+1,BASTOK, -- Akane, I.M. Chegourt+8,BASTOK, -- Three Steps, I.M. Chegourt+4,BASTOK, -- flag Chegourt+12,BASTOK, -- flag -- Chegourt+2,WINDURST, -- Donmo-Boronmo, W.W. Chegourt+9,WINDURST, -- Daruru, W.W. Chegourt+5,WINDURST, -- flag Chegourt+13,WINDURST, -- flag -- Chegourt+6,BEASTMEN, -- flag Chegourt+14,BEASTMEN, -- flag -- Chegourt+10,OTHER, -- Mushosho } end, --------------------------------- [FAUREGANDI] = function (x) -- Beaucedine_Glacier (111) --------------------------------- --print("FAUREGANDI"); local Parledaire = 17232205; npc = { -- Parledaire,SANDORIA, -- Parledaire, R.K. Parledaire+7,SANDORIA, -- Leaufetie, R.K. Parledaire+3,SANDORIA, -- flag Parledaire+11,SANDORIA, -- flag -- Parledaire+1,BASTOK, -- Akane, I.M. Parledaire+8,BASTOK, -- Rattling Rain, I.M. Parledaire+4,BASTOK, -- flag Parledaire+12,BASTOK, -- flag -- Parledaire+2,WINDURST, -- Ryunchi-Pauchi, W.W. Parledaire+9,WINDURST, -- Chopapa, W.W. Parledaire+5,WINDURST, -- flag Parledaire+13,WINDURST, -- flag -- Parledaire+6,BEASTMEN, -- flag Parledaire+14,BEASTMEN, -- flag -- Parledaire+10,OTHER, -- Gueriette } end, --------------------------------- [VALDEAUNIA] = function (x) -- Xarcabard (112) --------------------------------- --print("VALDEAUNIA"); local Jeantelas = 17236286; npc = { -- Jeantelas,SANDORIA, -- Jeantelas, R.K. Jeantelas+7,SANDORIA, -- Pilcha, R.K. Jeantelas+3,SANDORIA, -- flag Jeantelas+11,SANDORIA, -- flag -- Jeantelas+1,BASTOK, -- Kaya, I.M. Jeantelas+8,BASTOK, -- Heavy Bear, I.M. Jeantelas+4,BASTOK, -- flag Jeantelas+12,BASTOK, -- flag -- Jeantelas+2,WINDURST, -- Magumo-Yagimo, W.W. Jeantelas+9,WINDURST, -- Tememe, W.W. Jeantelas+5,WINDURST, -- flag Jeantelas+13,WINDURST, -- flag -- Jeantelas+6,BEASTMEN, -- flag Jeantelas+14,BEASTMEN, -- flag -- Jeantelas+10,OTHER, -- Pelogrant } end, --------------------------------- [QUFIMISLAND] = function (x) -- Qufim_Island (126) --------------------------------- --print("QUFIMISLAND"); local Pitoire = 17293712; npc = { -- Pitoire,SANDORIA, -- Pitoire, R.K. Pitoire+7,SANDORIA, -- Matica, R.K. Pitoire+3,SANDORIA, -- flag Pitoire+11,SANDORIA, -- flag -- Pitoire+1,BASTOK, -- Sasa, I.M. Pitoire+8,BASTOK, -- Singing Blade, I.M. Pitoire+4,BASTOK, -- flag Pitoire+12,BASTOK, -- flag -- Pitoire+2,WINDURST, -- Tsonga-Hoponga, W.W. Pitoire+9,WINDURST, -- Numumu, W.W. Pitoire+5,WINDURST, -- flag Pitoire+13,WINDURST, -- flag -- Pitoire+6,BEASTMEN, -- flag Pitoire+14,BEASTMEN, -- flag -- Pitoire+10,OTHER, -- Jiwon } end, --------------------------------- [LITELOR] = function (x) -- The_Sanctuary_of_ZiTah (121) --------------------------------- --print("LITELOR"); local Credaurion = 17273365; npc = { -- Credaurion,SANDORIA, -- Credaurion, R.K. Credaurion+7,SANDORIA, -- Limion, R.K. Credaurion+3,SANDORIA, -- flag Credaurion+11,SANDORIA, -- flag -- Credaurion+1,BASTOK, -- Calliope, I.M. Credaurion+8,BASTOK, -- Dedden, I.M. Credaurion+4,BASTOK, -- flag Credaurion+12,BASTOK, -- flag -- Credaurion+2,WINDURST, -- Ajimo-Majimo, W.W. Credaurion+9,WINDURST, -- Ochocho, W.W. Credaurion+5,WINDURST, -- flag Credaurion+13,WINDURST, -- flag -- Credaurion+6,BEASTMEN, -- flag Credaurion+14,BEASTMEN, -- flag -- Credaurion+10,OTHER, -- Kasim } end, --------------------------------- [KUZOTZ] = function (x) -- Eastern_Altepa_Desert (114) --------------------------------- --print("KUZOTZ"); local Eaulevisat = 17244627; npc = { -- Eaulevisat,SANDORIA, -- Eaulevisat, R.K. Eaulevisat+7,SANDORIA, -- Laimeve, R.K. Eaulevisat+3,SANDORIA, -- flag Eaulevisat+11,SANDORIA, -- flag -- Eaulevisat+1,BASTOK, -- Lindgard, I.M. Eaulevisat+8,BASTOK, -- Daborn, I.M. Eaulevisat+4,BASTOK, -- flag Eaulevisat+12,BASTOK, -- flag -- Eaulevisat+2,WINDURST, -- Variko-Njariko, W.W. Eaulevisat+9,WINDURST, -- Sahgygy, W.W. Eaulevisat+5,WINDURST, -- flag Eaulevisat+13,WINDURST, -- flag -- Eaulevisat+6,BEASTMEN, -- flag Eaulevisat+14,BEASTMEN, -- flag -- Eaulevisat+10,OTHER, -- Sowande } end, --------------------------------- [VOLLBOW] = function (x) -- Cape_Teriggan (113) --------------------------------- --print("VOLLBOW"); local Salimardi = 17240469; npc = { -- Salimardi,SANDORIA, -- Salimardi, R.K. Salimardi+7,SANDORIA, -- Paise, R.K. Salimardi+3,SANDORIA, -- flag Salimardi+11,SANDORIA, -- flag -- Salimardi+1,BASTOK, -- Sarmistha, I.M. Salimardi+8,BASTOK, -- Dultwa, I.M. Salimardi+4,BASTOK, -- flag Salimardi+12,BASTOK, -- flag -- Salimardi+2,WINDURST, -- Voranbo-Natanbo, W.W. Salimardi+9,WINDURST, -- Orukeke, W.W. Salimardi+5,WINDURST, -- flag Salimardi+13,WINDURST, -- flag -- Salimardi+6,BEASTMEN, -- flag Salimardi+14,BEASTMEN, -- flag -- Salimardi+10,OTHER, -- Bright Moon } end, --------------------------------- [ELSHIMOLOWLANDS] = function (x) -- Yuhtunga_Jungle (123) --------------------------------- --print("ELSHIMOLOWLANDS"); local Zorchorevi = 17281600; npc = { -- Zorchorevi,SANDORIA, -- Zorchorevi, R.K. Zorchorevi+7,SANDORIA, -- Mupia, R.K. Zorchorevi+3,SANDORIA, -- flag Zorchorevi+11,SANDORIA, -- flag -- Zorchorevi+1,BASTOK, -- Mahol, I.M. Zorchorevi+8,BASTOK, -- Bammiro, I.M. Zorchorevi+4,BASTOK, -- flag Zorchorevi+12,BASTOK, -- flag -- Zorchorevi+2,WINDURST, -- Uphra-Kophra, W.W. Zorchorevi+9,WINDURST, -- Richacha, W.W. Zorchorevi+5,WINDURST, -- flag Zorchorevi+13,WINDURST, -- flag -- Zorchorevi+6,BEASTMEN, -- flag Zorchorevi+14,BEASTMEN, -- flag -- Zorchorevi+10,OTHER, -- Robino-Mobino } end, --------------------------------- [ELSHIMOUPLANDS] = function (x) -- Yhoator_Jungle (124) --------------------------------- --print("ELSHIMOUPLANDS"); local Ilieumort = 17285650; npc ={ -- Ilieumort,SANDORIA, -- Ilieumort, R.K. Ilieumort+7,SANDORIA, -- Emila, R.K. Ilieumort+3,SANDORIA, -- flag Ilieumort+11,SANDORIA, -- flag -- Ilieumort+1,BASTOK, -- Mintoo, I.M. Ilieumort+8,BASTOK, -- Guddal, I.M. Ilieumort+4,BASTOK, -- flag Ilieumort+12,BASTOK, -- flag -- Ilieumort+2,WINDURST, -- Etaj-Pohtaj, W.W. Ilieumort+9,WINDURST, -- Ghantata, W.W. Ilieumort+5,WINDURST, -- flag Ilieumort+13,WINDURST, -- flag -- Ilieumort+6,BEASTMEN, -- flag Ilieumort+14,BEASTMEN, -- flag -- Ilieumort+10,OTHER, -- Mugha Dovajaiho } end, --------------------------------- [TULIA] = function (x) -- RuAun_Gardens (130) --------------------------------- --print("TULIA"); local RuAun_Banner = 17310076; npc = { -- RuAun_Banner,SANDORIA, -- flag -- RuAun_Banner+1,BASTOK, -- flag -- RuAun_Banner+2,WINDURST, -- flag -- RuAun_Banner+3,BEASTMEN, -- flag } end, --------------------------------- [MOVALPOLOS] = function (x) -- Oldton_Movalpolos --------------------------------- --print("MOVALPOLOS"); local Oldton_Banner_Offset = 16822509; npc = { -- Oldton_Banner_Offset,SANDORIA, -- flag -- Oldton_Banner_Offset+1,BASTOK, -- flag -- Oldton_Banner_Offset+2,WINDURST, -- flag -- Oldton_Banner_Offset+3,BEASTMEN, -- flag } end, --------------------------------- [TAVNAZIANARCH] = function (x) -- Lufaise_Meadows --------------------------------- --print("TAVNAZIA"); local Jemmoquel = 16875861; npc = { -- Jemmoquel,SANDORIA, -- Jemmoquel, R.K. Jemmoquel+7,SANDORIA, -- Chilaumme, R.K. Jemmoquel+3,SANDORIA, -- flag Jemmoquel+11,SANDORIA, -- flag -- Jemmoquel+1,BASTOK, -- Yoram, I.M. Jemmoquel+8,BASTOK, -- Ghost Talker, I.M. Jemmoquel+4,BASTOK, -- flag Jemmoquel+12,BASTOK, -- flag -- Jemmoquel+2,WINDURST, -- Teldo-Moroldo, W.W. Jemmoquel+9,WINDURST, -- Cotete, W.W. Jemmoquel+5,WINDURST, -- flag Jemmoquel+13,WINDURST, -- flag -- Jemmoquel+6,BEASTMEN, -- flag Jemmoquel+14,BEASTMEN, -- flag -- Jemmoquel+10,OTHER, -- Jersey } end, } return npc; end; ----------------------------------- -- ----------------------------------- function SetRegionalConquestOverseers(region) local npclist = getRegionalConquestOverseers(region); local nation = GetRegionOwner(region); for i = 1, table.getn(npclist), 2 do local npc = GetNPCByID(npclist[i]); if (npc ~= nil) then if (npclist[i+1] == nation) then npc:setStatus(0); else npc:setStatus(2); end if (npclist[i+1] == OTHER) then if (nation ~= BEASTMEN) then npc:setStatus(0); else npc:setStatus(2); end end end end end; ----------------------------------- -- checkConquestRing ----------------------------------- function checkConquestRing(player) local count = 0; -- If not enabled by admin, do a count on Chariot, Empress, and Emperor Band if (ALLOW_MULTIPLE_EXP_RINGS ~= 1) then for i=15761,15763 do if (player:hasItem(i) == true) then count = count + 1; end end end -- One exp ring purchasable per conquest tally if (BYPASS_EXP_RING_ONE_PER_WEEK ~= 1 and player:getVar("CONQUEST_RING_TIMER") > os.time()) then count = 3; end return count; end; ----------------------------------- -- conquestUpdate ----------------------------------- function conquestUpdate(zone, player, updateType, messageBase) local ranking = getConquestBalance(); if (updateType == CONQUEST_TALLY_START) then player:messageText(player, messageBase, 5); elseif (updateType == CONQUEST_TALLY_END) then --Tallying conquest results... player:messageText(player, messageBase+1, 5); -- This region is currently under x control. local owner = GetRegionOwner(zone:getRegionID()); if (owner <= 3) then player:messageText(player, messageBase+2+owner, 5); else player:messageText(player, messageBase+6, 5); end local offset = 0; if (bit.band(ranking, 0x03) == 0x01) then offset = offset + 7; -- 7 if (bit.band(ranking, 0x30) == 0x10) then offset = offset + 1; -- 8 if (bit.band(ranking, 0x0C) == 0x0C) then offset = offset + 1; -- 9 end elseif (bit.band(ranking, 0x0C) == 0x08) then offset = offset + 3; -- 10 if (bit.band(ranking, 0x30) == 0x30) then offset = offset + 1; -- 11 end elseif (bit.band(ranking, 0x0C) == 0x04) then offset = offset + 6; -- 13 end elseif (bit.band(ranking, 0x0C) == 0x04) then offset = offset + 15; -- 15 if (bit.band(ranking, 0x30) == 0x02) then offset = offset + 3; -- 18 if (bit.band(ranking, 0x03) == 0x03) then offset = offset + 1; -- 19 end elseif (bit.band(ranking, 0x30) == 0x10) then offset = offset + 6; -- 21 end elseif (bit.band(ranking, 0x30) == 0x10) then offset = offset + 23; -- 23 if (bit.band(ranking, 0x0C) == 0x08) then offset = offset + 3; -- 26 if (bit.band(ranking, 0x30) == 0x30) then offset = offset + 1; -- 27 end end end -- Global balance of power: player:messageText(player, messageBase+offset, 5); if (isConquestAlliance()) then -- have formed an alliance. if (bit.band(ranking, 0x03) == 0x01) then player:messageText(player, messageBase+50, 5); elseif (bit.band(ranking, 0x0C) == 0x04) then player:messageText(player, messageBase+51, 5); elseif (bit.band(ranking, 0x30) == 0x10) then player:messageText(player, messageBase+52, 5); end end elseif (updateType == CONQUEST_UPDATE) then -- Conquest update: This region is currently under x control. local owner = GetRegionOwner(zone:getRegionID()); if (owner <= 3) then player:messageText(player, messageBase+32+owner, 5); else player:messageText(player, messageBase+31, 5); end local influence = GetRegionInfluence(zone:getRegionID()); if (influence >= 64) then -- The beastmen are on the rise. player:messageText(player, messageBase+37, 5); elseif (influence == 0) then -- All three nations are at a deadlock. player:messageText(player, messageBase+36, 5); else local sandoria = bit.band(influence, 0x03); local bastok = bit.rshift(bit.band(influence, 0x0C),2); local windurst = bit.rshift(bit.band(influence, 0x30),4); -- Regional influence: San d'Oria player:messageText(player, messageBase+41 - sandoria, 5); -- Bastok player:messageText(player, messageBase+45 - bastok, 5); -- Windurst player:messageText(player, messageBase+49 - windurst, 5); end if (isConquestAlliance()) then --are currently allied. if (bit.band(ranking, 0x03) == 0x01) then player:messageText(player, messageBase+53, 5); elseif (bit.band(ranking, 0x0C) == 0x04) then player:messageText(player, messageBase+54, 5); elseif (bit.band(ranking, 0x30) == 0x10) then player:messageText(player, messageBase+55, 5); end end end end;
gpl-3.0
AfuSensi/Mr.Green-MTA-Resources
resources/[maps]/coremarkers/chatbar_c.lua
4
4366
------------------------------------------ -- TopBarChat -- ------------------------------------------ -- Developer: Braydon Davis -- -- File: c.lua -- -- Copyright 2013 (C) Braydon Davis -- -- All rights reserved. -- ------------------------------------------ -- Script Version: 1.4 -- ------------------------------------------ local maxMessages = 5; -- The max messages that will show (on each bar) local DefaultTime = 8; -- The max time each message will show if time isn't defined. ------------------------------------------ -- For scripters only -- ------------------------------------------ local sx_, sy_ = guiGetScreenSize ( ) local sx, sy = sx_/1920, sy_/1080 -- you got xXMADEXx's resolution :3 plz no hak mi local DefaultPos = true; local messages_top = { } local messages_btm = { } function sendClientMessage ( msg, r, g, b, pos, time ) -- Msg: String -- R: Int (0-255) -- G: Int (0-255) -- B: Int (0-255) -- Pos: Boolean -- Time: Int if ( not msg ) then return false end if ( pos == nil ) then pos = DefaultPos end local r, g, b = r or 255, g or 255, b or 255 local time = tonumber ( time ) or DefaultTime local data = { message = msg, r = r, g = g, b = b, alpha=0, locked=true, rTick = getTickCount ( ) + (time*1000) } --> Scripters note: --> The remove and intro fades are handled in the render event if ( pos == true or pos == "top" ) then table.insert ( messages_top, data ) return true elseif ( pos == false or pos == "bottom" ) then table.insert ( messages_btm, data ) return true end return false end addEvent ( getResourceName ( getThisResource ( ) )..":sendClientMessage", true ) addEventHandler ( getResourceName ( getThisResource ( ) )..":sendClientMessage", root, sendClientMessage ) function dxDrawNotificationBar ( ) local doRemove = { top = { }, bottom = { } } -- This is used so it prevents the next message from flashing -- Top Message Bar for i, v in pairs ( messages_top ) do local i = i - 1 if ( not v.locked ) then v.alpha = v.alpha - 3 if ( v.alpha <= 20 ) then table.insert ( doRemove.top, i+1 ) end messages_top[i+1].alpha = v.alpha else if ( v.alpha < 160 ) then v.alpha = v.alpha + 1 messages_top[i+1].alpha = v.alpha end if ( v.rTick <= getTickCount ( ) ) then v.locked = false messages_top[i+1].locked=false end end dxDrawRectangle ( (sx_/2-530/2), i*25, 530, 25, tocolor ( 0, 0, 0, v.alpha ) ) dxDrawText ( tostring ( v.message ), 0, i*25, sx_, (i+1)*25, tocolor ( v.r, v.g, v.b, v.alpha*1.59375 ), sy*1.3, "clear", "center", "center", false, false, false, true) end if ( #messages_top > maxMessages and messages_top[1].locked ) then messages_top[1].locked = false end -- Bottom Message Bar for i, v in pairs ( messages_btm ) do if ( not v.locked ) then v.alpha = v.alpha - 3 if ( v.alpha <= 20 ) then table.insert ( doRemove.bottom, i ) end messages_btm[i].alpha = v.alpha else if ( v.alpha < 160 ) then v.alpha = v.alpha + 1 messages_btm[i].alpha = v.alpha end if ( v.rTick <= getTickCount ( ) ) then v.locked = false messages_btm[i].locked=false end end local textWidth = dxGetTextWidth(tostring ( v.message ), sy*1.5, "clear", true)+10*sx dxDrawRectangle ( (sx_/2-textWidth/2), sy_-(i*27*sy), textWidth, 27*sy, tocolor ( 0, 0, 0, v.alpha ) ) dxDrawText ( tostring ( v.message ), 0, sy_-(i*27*sy), sx_, sy_-((i-1)*27*sy), tocolor ( v.r, v.g, v.b, v.alpha*1.59375 ), sy*1.5, "clear", "center", "center", false, false, false, true, true) end if ( #messages_btm > maxMessages and messages_btm[1].locked ) then messages_btm[1].locked = false end -- handle message removes if ( #doRemove.top > 0 )then for i, v in pairs ( doRemove.top ) do table.remove ( messages_top, v ) end end if ( #doRemove.bottom > 0 ) then for i, v in pairs ( doRemove.bottom ) do table.remove ( messages_btm, v ) end end end addEventHandler ( "onClientRender", root, dxDrawNotificationBar ) ------------------------------ -- For development -- ------------------------------ addCommandHandler ( 'rt', function ( ) for i=1, 5 do sendClientMessage ( "Testing - Index ".. tostring ( i ), 255, 255, 255, false ) sendClientMessage ( "Testing - Index ".. tostring ( i ), 255, 255, 255, true ) end end )
mit
ffxiphoenix/darkstar
scripts/zones/Dynamis-San_dOria/bcnms/dynamis_sandoria.lua
16
1180
----------------------------------- -- Area: Dynamis San d'Oria -- Name: Dynamis San d'Oria ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[DynaSandoria]UniqueID",player:getDynamisUniqueID(1281)); SetServerVariable("[DynaSandoria]Boss_Trigger",0); SetServerVariable("[DynaSandoria]Already_Received",0); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("DynamisID",GetServerVariable("[DynaSandoria]UniqueID")); local realDay = os.time(); 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(17535224):setStatus(2); SetServerVariable("[DynaSandoria]UniqueID",0); end end;
gpl-3.0
elixboyBW/elixboySPM
plugins/face.lua
641
3073
local https = require("ssl.https") local ltn12 = require "ltn12" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(imageUrl) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?" local parameters = "attribute=gender%2Cage%2Crace" parameters = parameters .. "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" if jsonBody.error ~= nil then if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then response = response .. "The image is too big. Provide a smaller image." elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then response = response .. "Is that a valid url for an image?" else response = response .. jsonBody.error end elseif jsonBody.face == nil or #jsonBody.face == 0 then response = response .. "No faces found" else response = response .. #jsonBody.face .." face(s) found:\n\n" for k,face in pairs(jsonBody.face) do local raceP = "" if face.attribute.race.confidence > 85.0 then raceP = face.attribute.race.value:lower() elseif face.attribute.race.confidence > 50.0 then raceP = "(probably "..face.attribute.race.value:lower()..")" else raceP = "(posibly "..face.attribute.race.value:lower()..")" end if face.attribute.gender.confidence > 85.0 then response = response .. "There is a " else response = response .. "There may be a " end response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " " response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n" end end return response end local function run(msg, matches) --return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg') local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end return parseData(data) end return { description = "Who is in that photo?", usage = { "!face [url]", "!recognise [url]" }, patterns = { "^!face (.*)$", "^!recognise (.*)$" }, run = run }
gpl-2.0
ffxiphoenix/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Furious_Boulder.lua
34
1040
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Furious Boulder -- 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(0x00E6); 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
farrajota/human_pose_estimation_torch
models/test/hg-generic-ensemblev3.lua
1
1063
paths.dofile('../layers/Residual.lua') local function lin(numIn,numOut,inp) -- Apply 1x1 convolution, stride 1, no padding local dropout = nn.Dropout(0.2)(inp) local bn_relu = nn.ReLU(true)(nn.SpatialBatchNormalization(numIn)(dropout)) return nn.SpatialConvolution(numIn,numOut,1,1,1,1,0,0)(bn_relu) end local function createModel() if not nn.NoBackprop then paths.dofile('modules/NoBackprop.lua') end print('Load model: ' .. paths.concat(opt.ensemble, 'final_model.t7')) local trained_model = torch.load(paths.concat(opt.ensemble, 'final_model.t7')) trained_model:evaluate() -- craft network local inp = nn.Identity()() local hg_net = nn.NoBackprop(trained_model)(inp) -- disable backprop local concat_outputs = nn.JoinTable(2)(hg_net) local ll1 = lin(outputDim[1][1]*8, 512, concat_outputs) local out = lin(512, outputDim[1][1], ll1) opt.nOutputs = 1 -- Final model local model = nn.gModule({inp}, {out}) return model end ------------------------- return createModel
mit
Aminkavari/xXD4RKXx
bot/utils.lua
26
17219
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function vardump(value) print(serpent.block(value, {comment=false})) end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end --Check if this chat is realm or not function is_realm(msg) local var = false for v,group in pairs(_config.realm) do if group == msg.to.id then var = true end end return var end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- Kick function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- /id by reply function get_id_by_reply(extra, success, result) if result.to.type == 'chat' then send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end
gpl-2.0
ffxiphoenix/darkstar
scripts/zones/Apollyon/npcs/Radiant_Aureole.lua
19
5828
----------------------------------- -- Area: Appolyon -- NPC: Radiant_Aureole -- @pos ----------------------------------- require("scripts/globals/limbus"); require("scripts/globals/keyitems"); package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local count = trade:getItemCount(); if (player:hasKeyItem(COSMOCLEANSE)) then if (count==1 and trade:hasItemQty(2127,1)) then-- metal chip player:setVar("Limbus_Trade_Item",32); player:tradeComplete(); player:messageSpecial(CHIP_TRADE); player:startEvent(0x7d00,0,0,0,32,0,0,0,0); player:setVar("limbusbitmap",32); elseif (count==4 and trade:hasItemQty(1988,1) and trade:hasItemQty(1987,1) and trade:hasItemQty(1910,1) and trade:hasItemQty(1909,1)) then player:setVar("Limbus_Trade_Item",16); player:tradeComplete(); player:messageSpecial(CHIP_TRADE); player:startEvent(0x7d00,0,0,0,16,0,0,0,0); player:setVar("limbusbitmap",16); end else player:messageSpecial(CONDITION_FOR_LIMBUS); print("error player don't have cosmo clean"); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local instancelist ={}; local limbusbitmap = 0 ; local AllowLimbusToPlayer = true ; local currentlimbus= TryTobackOnCurrentLimbus(player); if ( npc:getID() == 16933242) then instancelist = APPOLLYON_SE_NE_BCNM_LIST; else instancelist = APPOLLYON_NW_SW_BCNM_LIST; end printf("currentlimbus: %u",currentlimbus); if (player:hasKeyItem(COSMOCLEANSE)) then if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then local LimbusTradeItem = player:getVar("Limbus_Trade_Item"); for nt = 1,table.getn (instancelist),2 do -- printf("list d'instance: %u",instancelist[nt]); if (instancelist[nt+1][1]==true and player:hasKeyItem(WHITE_CARD)) then -- print("player_have_white_card"); limbusbitmap = limbusbitmap + instancelist[nt+1][4]; -- printf("bitmapadd: %u",instancelist[nt+1][4]); end if (instancelist[nt+1][2]==true and player:hasKeyItem(RED_CARD)) then -- print("player_have_red_card"); limbusbitmap = limbusbitmap + instancelist[nt+1][4]; -- printf("bitmapadd: %u",instancelist[nt+1][4]); end if (instancelist[nt+1][3]==true and player:hasKeyItem(BLACK_CARD)) then -- print("player_have_black_card"); limbusbitmap = limbusbitmap + instancelist[nt+1][4]; -- printf("bitmapadd: %u",instancelist[nt+1][4]); end end limbusbitmap= limbusbitmap + LimbusTradeItem; ----- /////////////////////////////////////////////on doit ajouter le mipmap pour l'item trade ici else local status = player:getStatusEffect(EFFECT_BATTLEFIELD); local playerbcnmid = status:getPower(); -- check if the player has the key item for the current battlefield for nt = 1,table.getn (instancelist),2 do -- printf("list d'instance: %u",instancelist[nt]); if (instancelist[nt] == playerbcnmid) then if (instancelist[nt+1][1]== true and player:hasKeyItem(WHITE_CARD) == false) then AllowLimbusToPlayer = false; end if (instancelist[nt+1][2]== true and player:hasKeyItem(RED_CARD) == false ) then AllowLimbusToPlayer = false; end if (instancelist[nt+1][3]== true and player:hasKeyItem(BLACK_CARD) == false ) then AllowLimbusToPlayer = false; end if (AllowLimbusToPlayer == true) then --player have the correct key item for the current battflield limbusbitmap = instancelist[nt+1][4]; end end end end if (limbusbitmap~= 0 ) then player:startEvent(0x7d00,0,0,0,limbusbitmap,0,0,0,0); player:setVar("limbusbitmap",limbusbitmap); else player:messageSpecial(CONDITION_FOR_LIMBUS); print("player need a card for basic limbus"); end elseif (currentlimbus~=0) then for nt = 1,table.getn (instancelist),2 do -- printf("list d'instance: %u",instancelist[nt]); if (instancelist[nt] == currentlimbus) then limbusbitmap = instancelist[nt+1][4]; end end player:startEvent(0x7d00,0,0,0,limbusbitmap,0,0,0,0); player:setVar("limbusbitmap",limbusbitmap); else player:messageSpecial(CONDITION_FOR_LIMBUS); print("error player don't have cosmo clean"); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) if (csid == 0x7d00) then if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then ResetPlayerLimbusVariable(player); player:setVar("characterLimbusKey",0); else local status = player:getStatusEffect(EFFECT_BATTLEFIELD); player:setVar("LimbusID",status:getPower()); player:setVar("characterLimbusKey",GetLimbusKeyFromInstance(status:getPower())); end player:updateEvent(2,player:getVar("limbusbitmap"),0,1,1,0); player:setVar("limbusbitmap",0); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x7d00) then end end;
gpl-3.0
vilarion/Illarion-Content
content/climbing.lua
4
3455
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local common = require("base.common") local M = {} local function getWell(User) local WELL = 2207; local item = common.GetFrontItem(User); if (item ~= nil and item.id == WELL) then return item; end item = common.GetItemInArea(User.pos, WELL); return item; end local function getHole(User) local HOLE = 1206; local item = common.GetFrontItem(User); if (item ~= nil and item.id == HOLE) then return item; end item = common.GetItemInArea(User.pos, HOLE); return item; end function M.hasRope(User) if User:countItemAt("all", 2760) == 0 then return false end return true end function M.climbDown(User) -- climb down a well local TargetItem = getWell(User); if TargetItem ~= nil then common.TurnTo(User, TargetItem.pos); if (TargetItem.pos == position(528, 555, 0)) then --maze User:talk(Character.say, "#me klettert an einem Seil den Brunnen hinunter.", "#me climbs down into the well on a rope.") User:warp(position(518, 559, -3)); elseif (TargetItem.pos == position(105, 600, 0)) then --Cadomyr User:talk(Character.say, "#me klettert an einem Seil den Brunnen hinunter.", "#me climbs down into the well on a rope.") User:warp(position(109, 581, -6)); elseif (TargetItem.pos == position(357, 272, 0)) then --Galmair User:talk(Character.say, "#me klettert an einem Seil den Brunnen hinunter.", "#me climbs down into the well on a rope.") User:warp(position(362, 473, -6)); elseif (TargetItem.pos == position(849, 841, 0)) then --Runewick User:talk(Character.say, "#me klettert an einem Seil den Brunnen hinunter.", "#me climbs down into the well on a rope.") User:warp(position(834, 822, -3)); else common.InformNLS( User, "Das Wasser steht recht hoch im Brunnen. Hier hinein zu klettern bringt nichts.", "The water is rather high in the well. To climb in here is useless."); end return; end -- ... or perhaps climb down a hole. TargetItem = getHole(User); if TargetItem ~= nil then common.TurnTo(User, TargetItem.pos); if (TargetItem.pos == position(854, 414, 0)) then User:talk(Character.say, "#me klettert an einem Seil in das dunkle Loch hinab.", "#me climbs down into the dark hole on a rope.") User:warp(position(925, 518, -6)); elseif (TargetItem.pos == position(659, 255, 0)) then User:talk(Character.say, "#me klettert an einem Seil in das dunkle Loch hinab.", "#me climbs down into the dark hole on a rope.") User:warp(position(747, 234, -3)); end return; end end return M
agpl-3.0
ffxiphoenix/darkstar
scripts/zones/Norg/npcs/Paito-Maito.lua
34
2624
----------------------------------- -- Area: Norg -- NPC: Paito-Maito -- Standard Info NPC ----------------------------------- require("scripts/globals/pathfind"); local path = { -71.189713, -9.413510, 74.024879, -71.674171, -9.317029, 73.054794, -72.516525, -9.298064, 72.363213, -73.432983, -9.220915, 71.773857, -74.358955, -9.142115, 71.163277, -75.199585, -9.069098, 70.583145, -76.184708, -9.006280, 70.261375, -77.093193, -9.000236, 70.852921, -77.987053, -9.037421, 71.464264, -79.008476, -9.123112, 71.825165, -80.083740, -9.169785, 72.087944, -79.577698, -9.295252, 73.087708, -78.816307, -9.365192, 73.861855, -77.949852, -9.323165, 74.500496, -76.868950, -9.301287, 74.783707, -75.754913, -9.294973, 74.927345, -74.637566, -9.341335, 74.902016, -73.521400, -9.382154, 74.747322, -72.420792, -9.415255, 74.426178, -71.401161, -9.413510, 74.035446, -70.392426, -9.413510, 73.627884, -69.237152, -9.413510, 73.155815, -70.317207, -9.413510, 73.034027, -71.371315, -9.279585, 72.798569, -72.378838, -9.306310, 72.392982, -73.315544, -9.230491, 71.843933, -74.225883, -9.153550, 71.253113, -75.120522, -9.076024, 70.638908, -76.054642, -9.019394, 70.204910, -76.981323, -8.999838, 70.762978, -77.856903, -9.024825, 71.403915, -78.876686, -9.115798, 71.789764, -79.930756, -9.171277, 72.053635, -79.572502, -9.295024, 73.087646, -78.807686, -9.364762, 73.869614, -77.916420, -9.321617, 74.516357, -76.824738, -9.300390, 74.790466, -75.738380, -9.295794, 74.930130, -74.620911, -9.341956, 74.899994, -73.493645, -9.382988, 74.739204, -72.413185, -9.415321, 74.420128, -71.452393, -9.413510, 74.054657, -70.487755, -9.413510, 73.666130 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); -- onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x005A); npc:wait(-1); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) --printf("CSID: %u",csid); --printf("RESULT: %u",option); npc:wait(0); end;
gpl-3.0
ffxiphoenix/darkstar
scripts/globals/weaponskills/burning_blade.lua
30
1294
----------------------------------- -- Burning Blade -- Sword weapon skill -- Skill Level: 30 -- Desription: Deals Fire elemental damage to enemy. Damage varies with TP. -- Aligned with the Flame Gorget. -- Aligned with the Flame Belt. -- Element: Fire -- Modifiers: STR:20% ; INT:20% -- 100%TP 200%TP 300%TP -- 1.00 2.00 2.50 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 2.5; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_FIRE; params.skill = SKILL_SWD; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp200 = 2.1; params.ftp300 = 3.4; params.str_wsc = 0.4; params.int_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
lxl1140989/sdk-for-tb
feeds/luci/applications/luci-statistics/luasrc/model/cbi/luci_statistics/iwinfo.lua
78
1089
--[[ Luci configuration model for statistics - collectd interface plugin configuration (c) 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local m, s, o m = Map("luci_statistics", translate("Wireless iwinfo Plugin Configuration"), translate("The iwinfo plugin collects statistics about wireless signal strength, noise and quality.")) s = m:section(NamedSection, "collectd_iwinfo", "luci_statistics") o = s:option(Flag, "enable", translate("Enable this plugin")) o.default = 0 o = s:option(Value, "Interfaces", translate("Monitor interfaces"), translate("Leave unselected to automatically determine interfaces to monitor.")) o.template = "cbi/network_ifacelist" o.widget = "checkbox" o.nocreate = true o:depends("enable", 1) o = s:option(Flag, "IgnoreSelected", translate("Monitor all except specified")) o.default = 0 o:depends("enable", 1) return m
gpl-2.0
ffxiphoenix/darkstar
scripts/zones/Valkurm_Dunes/npcs/qm4.lua
37
1033
----------------------------------- -- Area: Valkurm Dunes -- NPC: qm4 (???) -- Involved in quest: Pirate's Chart -- @pos -160 4 -131 103 ----------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Valkurm_Dunes/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(MONSTERS_KILLED_ADVENTURERS); 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
guker/nn
SparseJacobian.lua
2
8636
nn.SparseJacobian = {} function nn.SparseJacobian.backward (module, input, param, dparam) local doparam = 0 if param then doparam = 1 end -- output deriv module:forward(input) local dout = module.output.new():resizeAs(module.output) -- 1D view local sdout = module.output.new(dout:storage(), 1, dout:nElement()) -- jacobian matrix to calculate local jacobian if doparam == 1 then jacobian = torch.Tensor(param:nElement(), dout:nElement()):zero() else jacobian = torch.Tensor(input:size(1), dout:nElement()):zero() end for i=1,sdout:nElement() do dout:zero() sdout[i] = 1 module:zeroGradParameters() local din = module:updateGradInput(input, dout) module:accGradParameters(input, dout) if doparam == 1 then jacobian:select(2,i):copy(dparam) else jacobian:select(2,i):copy(din:select(2,2)) end end return jacobian end function nn.SparseJacobian.backwardUpdate (module, input, param) -- output deriv module:forward(input) local dout = module.output.new():resizeAs(module.output) -- 1D view local sdout = module.output.new(dout:storage(),1,dout:nElement()) -- jacobian matrix to calculate local jacobian = torch.Tensor(param:nElement(),dout:nElement()):zero() -- original param local params = module:parameters() local origparams = {} for j=1,#params do table.insert(origparams, params[j]:clone()) end for i=1,sdout:nElement() do -- Reset parameters for j=1,#params do params[j]:copy(origparams[j]) end dout:zero() sdout[i] = 1 module:zeroGradParameters() local din = module:updateGradInput(input, dout) module:accUpdateGradParameters(input, dout, 1) jacobian:select(2,i):copy(param) end for j=1,#params do params[j]:copy(origparams[j]) end return jacobian end function nn.SparseJacobian.forward(module, input, param) local doparam = 0 if param then doparam = 1 end param = param or input -- perturbation amount local small = 1e-6 -- 1D view of input --local tst = param:storage() local sin if doparam == 1 then sin = param.new(param):resize(param:nElement()) else sin = input.new(input):select(2,2) end local out = module:forward(input) -- jacobian matrix to calculate local jacobian if doparam == 1 then jacobian = torch.Tensor():resize(param:nElement(), out:nElement()) else jacobian = torch.Tensor():resize(input:size(1), out:nElement()) end local outa = torch.Tensor(jacobian:size(2)) local outb = torch.Tensor(jacobian:size(2)) for i=1,sin:nElement() do sin[i] = sin[i] - small outa:copy(module:forward(input)) sin[i] = sin[i] + 2*small outb:copy(module:forward(input)) sin[i] = sin[i] - small outb:add(-1,outa):div(2*small) jacobian:select(1,i):copy(outb) end return jacobian end function nn.SparseJacobian.forwardUpdate(module, input, param) -- perturbation amount local small = 1e-6 -- 1D view of input --local tst = param:storage() local sin = param.new(param):resize(param:nElement())--param.new(tst,1,tst:size()) -- jacobian matrix to calculate local jacobian = torch.Tensor():resize(param:nElement(),module:forward(input):nElement()) local outa = torch.Tensor(jacobian:size(2)) local outb = torch.Tensor(jacobian:size(2)) for i=1,sin:nElement() do sin[i] = sin[i] - small outa:copy(module:forward(input)) sin[i] = sin[i] + 2*small outb:copy(module:forward(input)) sin[i] = sin[i] - small outb:add(-1,outa):div(2*small) jacobian:select(1,i):copy(outb) jacobian:select(1,i):mul(-1) jacobian:select(1,i):add(sin[i]) end return jacobian end function nn.SparseJacobian.testJacobian (module, input, minval, maxval) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval input:select(2,2):copy(torch.rand(input:size(1)):mul(inrange):add(minval)) local jac_fprop = nn.SparseJacobian.forward(module,input) local jac_bprop = nn.SparseJacobian.backward(module,input) local error = jac_fprop-jac_bprop return error:abs():max() end function nn.SparseJacobian.testJacobianParameters (module, input, param, dparam, minval, maxval) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval input:select(2,2):copy(torch.rand(input:size(1)):mul(inrange):add(minval)) param:copy(torch.rand(param:nElement()):mul(inrange):add(minval)) local jac_bprop = nn.SparseJacobian.backward(module, input, param, dparam) local jac_fprop = nn.SparseJacobian.forward(module, input, param) local error = jac_fprop - jac_bprop return error:abs():max() end function nn.SparseJacobian.testJacobianUpdateParameters (module, input, param, minval, maxval) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval input:select(2,2):copy(torch.rand(input:size(1)):mul(inrange):add(minval)) param:copy(torch.rand(param:nElement()):mul(inrange):add(minval)) local params_bprop = nn.SparseJacobian.backwardUpdate(module, input, param) local params_fprop = nn.SparseJacobian.forwardUpdate(module, input, param) local error = params_fprop - params_bprop return error:abs():max() end function nn.SparseJacobian.testIO(module,input, minval, maxval) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval -- run module module:forward(input) local go = module.output:clone():copy(torch.rand(module.output:nElement()):mul(inrange):add(minval)) module:zeroGradParameters() module:updateGradInput(input,go) module:accGradParameters(input,go) local fo = module.output:clone() local bo = module.gradInput:clone() -- write module local f = torch.DiskFile('tmp.bin','w'):binary() f:writeObject(module) f:close() -- read module local m = torch.DiskFile('tmp.bin'):binary():readObject() m:forward(input) m:zeroGradParameters() m:updateGradInput(input,go) m:accGradParameters(input,go) -- cleanup os.remove('tmp.bin') local fo2 = m.output:clone() local bo2 = m.gradInput:clone() local errf = fo - fo2 local errb = bo - bo2 return errf:abs():max(), errb:abs():max() end function nn.SparseJacobian.testAllUpdate(module, input, weight, gradWeight) local gradOutput local lr = torch.uniform(0.1, 1) local errors = {} -- accGradParameters local maccgp = module:clone() local weightc = maccgp[weight]:clone() maccgp:forward(input) gradOutput = torch.rand(maccgp.output:size()) maccgp:zeroGradParameters() maccgp:updateGradInput(input, gradOutput) maccgp:accGradParameters(input, gradOutput) maccgp:updateParameters(lr) errors["accGradParameters"] = (weightc-maccgp[gradWeight]*lr-maccgp[weight]):norm() -- accUpdateGradParameters local maccugp = module:clone() maccugp:forward(input) maccugp:updateGradInput(input, gradOutput) maccugp:accUpdateGradParameters(input, gradOutput, lr) errors["accUpdateGradParameters"] = (maccugp[weight]-maccgp[weight]):norm() -- shared, accGradParameters local macsh1 = module:clone() local macsh2 = module:clone() macsh2:share(macsh1, weight) macsh1:forward(input) macsh2:forward(input) macsh1:zeroGradParameters() macsh2:zeroGradParameters() macsh1:updateGradInput(input, gradOutput) macsh2:updateGradInput(input, gradOutput) macsh1:accGradParameters(input, gradOutput) macsh2:accGradParameters(input, gradOutput) macsh1:updateParameters(lr) macsh2:updateParameters(lr) local err = (weightc-maccgp[gradWeight]*(lr*2)-macsh1[weight]):norm() err = err + (weightc-maccgp[gradWeight]*(lr*2)-macsh2[weight]):norm() errors["accGradParameters [shared]"] = err -- shared, accUpdateGradParameters local macshu1 = module:clone() local macshu2 = module:clone() macshu2:share(macshu1, weight) macshu1:forward(input) macshu2:forward(input) macshu1:updateGradInput(input, gradOutput) macshu2:updateGradInput(input, gradOutput) macshu1:accUpdateGradParameters(input, gradOutput, lr) macshu2:accUpdateGradParameters(input, gradOutput, lr) local err = (weightc-maccgp[gradWeight]*(lr*2)-macshu1[weight]):norm() err = err + (weightc-maccgp[gradWeight]*(lr*2)-macshu2[weight]):norm() errors["accUpdateGradParameters [shared]"] = err return errors end
bsd-3-clause
ffxiphoenix/darkstar
scripts/globals/items/thundermelon.lua
35
1199
----------------------------------------- -- ID: 4412 -- Item: thundermelon -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility -6 -- Intelligence 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4412); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, -6); target:addMod(MOD_INT, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, -6); target:delMod(MOD_INT, 4); end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Apollyon/mobs/Mountain_Buffalo.lua
16
1405
----------------------------------- -- Area: Apollyon NW -- NPC: Kaiser Behemoth ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); if (mobID ==16932951) then -- recover GetNPCByID(16932864+289):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+289):setStatus(STATUS_NORMAL); elseif (mobID ==16932952) then -- timer 1 GetNPCByID(16932864+43):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+43):setStatus(STATUS_NORMAL); elseif (mobID ==16932954) then -- timer 2 GetNPCByID(16932864+44):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+44):setStatus(STATUS_NORMAL); elseif (mobID ==16932957) then -- timer 3 GetNPCByID(16932864+45):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+45):setStatus(STATUS_NORMAL); end end;
gpl-3.0
Phrohdoh/OpenRA
mods/cnc/maps/gdi09/gdi09-AI.lua
3
6273
--[[ Copyright 2007-2020 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you 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. For more information, see COPYING. ]] AttackPaths = { { waypoint7 }, { waypoint8 } } NodBase = { handofnod, nodairfield, nodrefinery, NodCYard, nodpower1, nodpower2, nodpower3, nodpower4, nodpower5, gun5, gun6, gun7, gun8, nodsilo1, nodsilo2, nodsilo3, nodsilo4, nodobelisk } PatrolProductionQueue = { } InfantryAttackGroup = { } InfantryGroupSize = 5 InfantryProductionCooldown = DateTime.Minutes(3) InfantryProductionTypes = { "e1", "e1", "e1", "e3", "e3", "e4" } HarvesterProductionType = { "harv" } VehicleAttackGroup = { } VehicleGroupSize = 5 VehicleProductionCooldown = DateTime.Minutes(3) VehicleProductionTypes = { "bggy", "bggy", "bggy", "ltnk", "ltnk", "arty" } StartingCash = 14000 BaseRefinery = { type = "proc", pos = CPos.New(12, 25) } BaseNuke1 = { type = "nuke", pos = CPos.New(5, 24) } BaseNuke2 = { type = "nuke", pos = CPos.New(3, 24) } BaseNuke3 = { type = "nuke", pos = CPos.New(16, 30) } BaseNuke4 = { type = "nuke", pos = CPos.New(14, 30) } BaseNuke5 = { type = "nuke", pos = CPos.New(12, 30) } InfantryProduction = { type = "hand", pos = CPos.New(15, 24) } VehicleProduction = { type = "afld", pos = CPos.New(3, 27) } NodGuards = { Actor168, Actor169, Actor170, Actor171, Actor172, Actor181, Actor177, Actor188, Actor189, Actor190 } BaseBuildings = { BaseRefinery, BaseNuke1, BaseNuke2, BaseNuke3, BaseNuke4, InfantryProduction, VehicleProduction } BuildBuilding = function(building, cyard) local buildingCost = Actor.Cost(building.type) if CyardIsBuilding or Nod.Cash < buildingCost then Trigger.AfterDelay(DateTime.Seconds(10), function() BuildBuilding(building, cyard) end) return end CyardIsBuilding = true Nod.Cash = Nod.Cash - buildingCost Trigger.AfterDelay(Actor.BuildTime(building.type), function() CyardIsBuilding = false if cyard.IsDead or cyard.Owner ~= Nod then Nod.Cash = Nod.Cash + buildingCost return end local actor = Actor.Create(building.type, true, { Owner = Nod, Location = building.pos }) if actor.Type == 'hand' or actor.Type == 'pyle' then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceInfantry(actor) end) elseif actor.Type == 'afld' or actor.Type == 'weap' then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceVehicle(actor) end) end Trigger.OnKilled(actor, function() BuildBuilding(building, cyard) end) RepairBuilding(Nod, actor, 0.75) end) end HasHarvester = function() local harv = Nod.GetActorsByType("harv") return #harv > 0 end GuardBase = function() Utils.Do(NodBase, function(building) Trigger.OnDamaged(building, function() if not building.IsDead then Utils.Do(NodGuards, function(guard) if not guard.IsDead then guard.Stop() guard.Guard(building) end end) end end) end) end ProduceHarvester = function(building) if not buildingHarvester then buildingHarvester = true building.Build(HarvesterProductionType, function() buildingHarvester = false end) end end ProduceInfantry = function(building) if building.IsDead or building.Owner ~= Nod then return elseif not HasHarvester() then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceInfantry(building) end) return end if #PatrolProductionQueue >= 1 then local inQueue = PatrolProductionQueue[1] local toBuild = { inQueue.unit[1] } local patrolPath = inQueue.waypoints building.Build(toBuild, function(unit) ReplenishPatrolUnit(unit[1], handofnod, patrolPath, 40) table.remove(PatrolProductionQueue, 1) end) Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceInfantry(building) end) return end local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9)) local toBuild = { Utils.Random(InfantryProductionTypes) } local Path = Utils.Random(AttackPaths) building.Build(toBuild, function(unit) InfantryAttackGroup[#InfantryAttackGroup + 1] = unit[1] if #InfantryAttackGroup >= InfantryGroupSize then MoveAndHunt(InfantryAttackGroup, Path) InfantryAttackGroup = { } Trigger.AfterDelay(InfantryProductionCooldown, function() ProduceInfantry(building) end) else Trigger.AfterDelay(delay, function() ProduceInfantry(building) end) end end) end ProduceVehicle = function(building) if building.IsDead or building.Owner ~= Nod then return elseif not HasHarvester() then ProduceHarvester(building) Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceVehicle(building) end) return end local delay = Utils.RandomInteger(DateTime.Seconds(12), DateTime.Seconds(17)) local toBuild = { Utils.Random(VehicleProductionTypes) } local Path = Utils.Random(AttackPaths) building.Build(toBuild, function(unit) VehicleAttackGroup[#VehicleAttackGroup + 1] = unit[1] if #VehicleAttackGroup >= VehicleGroupSize then MoveAndHunt(VehicleAttackGroup, Path) VehicleAttackGroup = { } Trigger.AfterDelay(VehicleProductionCooldown, function() ProduceVehicle(building) end) else Trigger.AfterDelay(delay, function() ProduceVehicle(building) end) end end) end StartAI = function() RepairNamedActors(Nod, 0.75) Nod.Cash = StartingCash GuardBase() end Trigger.OnAllKilledOrCaptured(NodBase, function() Utils.Do(Nod.GetGroundAttackers(), IdleHunt) end) Trigger.OnKilled(nodrefinery, function(building) BuildBuilding(BaseRefinery, NodCYard) end) Trigger.OnKilled(nodpower1, function(building) BuildBuilding(BaseNuke1, NodCYard) end) Trigger.OnKilled(nodpower2, function(building) BuildBuilding(BaseNuke2, NodCYard) end) Trigger.OnKilled(nodpower3, function(building) BuildBuilding(BaseNuke3, NodCYard) end) Trigger.OnKilled(nodpower4, function(building) BuildBuilding(BaseNuke4, NodCYard) end) Trigger.OnKilled(nodpower5, function(building) BuildBuilding(BaseNuke5, NodCYard) end) Trigger.OnKilled(handofnod, function(building) BuildBuilding(InfantryProduction, NodCYard) end) Trigger.OnKilled(nodairfield, function(building) BuildBuilding(VehicleProduction, NodCYard) end)
gpl-3.0
Ne02ptzero/Grog-Knight
Resources/Scripts/autocomplete.lua
6
3319
------------------------------------------------------------------------------ -- Copyright (C) 2008-2014, Shane Liesegang -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the copyright holder nor the names of any -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ local tabSplits = "[%.%:]" function getAutoCompletions(inc) local forReturn = {} local return_prefix = "" local remainder = inc local searchTab = _G local break_ind = remainder:find(tabSplits) while (break_ind ~= nil) do return_prefix = return_prefix .. remainder:sub(1, break_ind) local prefix = remainder:sub(1, break_ind-1) remainder = remainder:sub(break_ind+1, -1) local prefTab = searchTab[prefix] if (prefTab ~= nil) then if (type(prefTab) == "table") then searchTab = prefTab elseif (type(prefTab) == "userdata") then -- check if we have a .fn table local m = getmetatable(prefTab) if (m == nil) then searchTab = nil break end if (type(m[".fn"]) == "table") then searchTab = m[".fn"] end else searchTab = nil break end else searchTab = nil break end break_ind = remainder:find(tabSplits) end if (searchTab ~= nil) then for name, val in pairs(searchTab) do if (name:sub(1, #remainder) == remainder) then if (type(val) == "function") then name = name .. "(" end table.insert(forReturn, return_prefix .. tostring(name)) end end end return forReturn end function printAutoCompletions(inc) ac = getAutoCompletions(inc) if (type(ac) == "table") then table.foreach(ac, print) end end
apache-2.0
ffxiphoenix/darkstar
scripts/globals/spells/bluemagic/diamondhide.lua
18
1188
----------------------------------------- -- Spell: Diamondhide -- Gives party members within area of effect the effect of "Stoneskin" -- Spell cost: 99 MP -- Monster Type: Beastmen -- Spell Type: Magical (Earth) -- Blue Magic Points: 3 -- Stat Bonus: VIT+1 -- Level: 67 -- Casting Time: 7 seconds -- Recast Time: 1 minute 30 seconds -- 5 minutes -- -- Combos: None ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_STONESKIN; local blueskill = caster:getSkillLevel(BLUE_SKILL); local power = ((blueskill)/3) *2; local duration = 300; if (target:addStatusEffect(typeEffect,power,0,duration) == false) then spell:setMsg(75); end; return typeEffect; end;
gpl-3.0
Phrohdoh/OpenRA
mods/d2k/maps/atreides-05/atreides05.lua
4
16192
--[[ Copyright 2007-2020 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you 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. For more information, see COPYING. ]] HarkonnenBase = { HarkonnenConstructionYard, HarkonnenWindTrap1, HarkonnenWindTrap2, HarkonnenWindTrap3, HarkonnenWindTrap4, HarkonnenWindTrap5, HarkonnenWindTrap6, HarkonnenWindTrap7, HarkonnenWindTrap8, HarkonnenSilo1, HarkonnenSilo2, HarkonnenSilo3, HarkonnenSilo4, HarkonnenGunTurret1, HarkonnenGunTurret2, HarkonnenGunTurret3, HarkonnenGunTurret4, HarkonnenGunTurret5, HarkonnenGunTurret6, HarkonnenGunTurret7, HarkonnenHeavyFactory, HarkonnenRefinery, HarkonnenOutpost, HarkonnenLightFactory } SmugglerBase = { SmugglerWindTrap1, SmugglerWindTrap2 } HarkonnenReinforcements = { easy = { { "combat_tank_h", "trooper", "trooper", "trooper", "trooper" }, { "trooper", "trooper", "trooper", "trooper", "trooper" }, { "combat_tank_h", "light_inf", "light_inf", "trooper", "trooper" }, { "combat_tank_h", "light_inf", "light_inf", "light_inf", "trooper", "trooper" }, { "combat_tank_h", "trike", "light_inf", "light_inf", "trooper", "trooper" } }, normal = { { "combat_tank_h", "trooper", "trooper", "trooper", "trooper" }, { "trooper", "trooper", "trooper", "trooper", "trooper" }, { "combat_tank_h", "light_inf", "light_inf", "trooper", "trooper" }, { "combat_tank_h", "light_inf", "light_inf", "light_inf", "trooper", "trooper" }, { "combat_tank_h", "trike", "light_inf", "light_inf", "trooper", "trooper" }, { "combat_tank_h", "trike", "combat_tank_h", "light_inf", "trooper", "trooper", "quad" }, { "combat_tank_h", "trike", "light_inf", "light_inf", "trooper", "trooper", "quad", "quad" } }, hard = { { "combat_tank_h", "trooper", "trooper", "trooper", "trooper" }, { "trooper", "trooper", "trooper", "trooper", "trooper" }, { "combat_tank_h", "light_inf", "light_inf", "trooper", "trooper" }, { "combat_tank_h", "light_inf", "light_inf", "light_inf", "trooper", "trooper" }, { "combat_tank_h", "trike", "light_inf", "light_inf", "trooper", "trooper" }, { "combat_tank_h", "trike", "combat_tank_h", "light_inf", "trooper", "trooper", "quad" }, { "combat_tank_h", "trike", "light_inf", "light_inf", "trooper", "trooper", "quad", "quad" }, { "combat_tank_h", "combat_tank_h", "trike", "light_inf", "light_inf", "trooper", "trooper", "quad", "quad" }, { "combat_tank_h", "combat_tank_h", "combat_tank_h", "combat_tank_h", "combat_tank_h", "combat_tank_h" } } } HarkonnenInfantryReinforcements = { normal = { { "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper", "trooper", "trooper" } }, hard = { { "light_inf", "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper", "trooper", "trooper", "trooper", "trooper", "trooper" }, { "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper", "trooper", "trooper" } } } InfantryPath = { HarkonnenEntry3.Location } HarkonnenAttackDelay = { easy = DateTime.Minutes(3), normal = DateTime.Minutes(2) + DateTime.Seconds(20), hard = DateTime.Minutes(1) } HarkonnenAttackWaves = { easy = 5, normal = 7, hard = 9 } MercenaryReinforcements = { easy = { { "combat_tank_o", "combat_tank_o", "quad", "quad", "light_inf", "light_inf", "light_inf", "light_inf" }, { "trike", "trike", "quad", "quad", "quad", "trike", "trike", "trike" }, { "combat_tank_o", "combat_tank_o", "combat_tank_o", "combat_tank_o", "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper", "trooper" } }, normal = { { "trike", "trike", "quad", "quad", "quad", "trike", "trike", "trike" }, { "combat_tank_o", "combat_tank_o", "quad", "quad", "light_inf", "light_inf", "light_inf", "light_inf" }, { "combat_tank_o", "combat_tank_o", "combat_tank_o", "combat_tank_o", "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper", "trooper" }, { "combat_tank_o", "combat_tank_o", "quad", "quad", "light_inf", "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper" }, { "trike", "trike", "quad", "quad", "quad", "trike", "trike", "trike", "trike", "trike", "trike" }, { "combat_tank_o", "combat_tank_o", "combat_tank_o", "combat_tank_o", "combat_tank_o", "combat_tank_o", "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper", "trooper" } }, hard = { { "combat_tank_o", "combat_tank_o", "quad", "quad", "light_inf", "light_inf", "light_inf", "light_inf" }, { "trike", "trike", "quad", "quad", "quad", "trike", "trike", "trike" }, { "combat_tank_o", "combat_tank_o", "combat_tank_o", "combat_tank_o", "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper", "trooper" }, { "trike", "trike", "quad", "quad", "quad", "trike", "trike", "trike", "trike", "trike", "trike" }, { "combat_tank_o", "combat_tank_o", "quad", "quad", "light_inf", "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper" }, { "combat_tank_o", "combat_tank_o", "combat_tank_o", "combat_tank_o", "combat_tank_o", "combat_tank_o", "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper", "trooper" }, { "combat_tank_o", "combat_tank_o", "quad", "quad", "trike", "trike", "light_inf", "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper" }, { "trike", "trike", "quad", "quad", "quad", "trike", "trike", "trike", "trike", "trike", "trike", "quad", "quad" }, { "combat_tank_o", "combat_tank_o", "combat_tank_o", "combat_tank_o", "combat_tank_o", "combat_tank_o", "trike", "trike", "quad", "quad", "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper", "trooper" } } } MercenaryAttackDelay = { easy = DateTime.Minutes(2) + DateTime.Seconds(40), normal = DateTime.Minutes(1) + DateTime.Seconds(50), hard = DateTime.Minutes(1) + DateTime.Seconds(10) } MercenaryAttackWaves = { easy = 3, normal = 6, hard = 9 } MercenarySpawn = { HarkonnenRally4.Location + CVec.New(2, -2) } -- Ordos tanks because those were intended for the Smugglers not the Atreides ContrabandReinforcements = { "mcv", "quad", "quad", "combat_tank_o", "combat_tank_o", "combat_tank_o" } SmugglerReinforcements = { "quad", "quad", "trike", "trike" } InitialHarkonnenReinforcements = { "trooper", "trooper", "quad", "quad", "trike", "trike", "trike", "light_inf" } HarkonnenPaths = { { HarkonnenEntry1.Location, HarkonnenRally1.Location }, { HarkonnenEntry1.Location, HarkonnenRally3.Location }, { HarkonnenEntry1.Location, HarkonnenRally2.Location }, { HarkonnenEntry1.Location, HarkonnenRally4.Location }, { HarkonnenEntry2.Location } } AtreidesReinforcements = { "trike", "combat_tank_a" } AtreidesPath = { AtreidesEntry.Location, AtreidesRally.Location } ContrabandTimes = { easy = DateTime.Minutes(10), normal = DateTime.Minutes(5), hard = DateTime.Minutes(2) + DateTime.Seconds(30) } wave = 0 SendHarkonnen = function() Trigger.AfterDelay(HarkonnenAttackDelay[Difficulty], function() if player.IsObjectiveCompleted(KillHarkonnen) then return end wave = wave + 1 if InfantryReinforcements and wave % 4 == 0 then local inf = Reinforcements.Reinforce(harkonnen, HarkonnenInfantryReinforcements[Difficulty][wave/4], InfantryPath) Utils.Do(inf, function(unit) unit.AttackMove(HarkonnenAttackLocation) IdleHunt(unit) end) end local entryPath = Utils.Random(HarkonnenPaths) local units = Reinforcements.ReinforceWithTransport(harkonnen, "carryall.reinforce", HarkonnenReinforcements[Difficulty][wave], entryPath, { entryPath[1] })[2] Utils.Do(units, function(unit) unit.AttackMove(HarkonnenAttackLocation) IdleHunt(unit) end) if wave < HarkonnenAttackWaves[Difficulty] then SendHarkonnen() return end Trigger.AfterDelay(DateTime.Seconds(3), function() LastHarkonnenArrived = true end) end) end mercWave = 0 SendMercenaries = function() Trigger.AfterDelay(MercenaryAttackDelay[Difficulty], function() mercWave = mercWave + 1 Media.DisplayMessage("Incoming hostile Mercenary force detected.", "Mentat") local units = Reinforcements.Reinforce(mercenary, MercenaryReinforcements[Difficulty][mercWave], MercenarySpawn) Utils.Do(units, function(unit) unit.AttackMove(MercenaryAttackLocation1) unit.AttackMove(MercenaryAttackLocation2) IdleHunt(unit) end) if mercWave < MercenaryAttackWaves[Difficulty] then SendMercenaries() return end Trigger.AfterDelay(DateTime.Seconds(3), function() LastMercenariesArrived = true end) end) end SendContraband = function(owner) ContrabandArrived = true UserInterface.SetMissionText("The Contraband has arrived!", player.Color) local units = SmugglerReinforcements if owner == player then units = ContrabandReinforcements end Reinforcements.ReinforceWithTransport(owner, "frigate", units, { ContrabandEntry.Location, Starport.Location + CVec.New(1, 1) }, { ContrabandExit.Location }) Trigger.AfterDelay(DateTime.Seconds(3), function() if owner == player then player.MarkCompletedObjective(CaptureStarport) Media.DisplayMessage("Contraband has arrived and been confiscated.", "Mentat") else player.MarkFailedObjective(CaptureStarport) Media.DisplayMessage("Smuggler contraband has arrived. It is too late to confiscate.", "Mentat") end end) Trigger.AfterDelay(DateTime.Seconds(5), function() UserInterface.SetMissionText("") end) end SmugglersAttack = function() Utils.Do(SmugglerBase, function(building) if not building.IsDead and building.Owner == smuggler then building.Sell() end end) Trigger.AfterDelay(DateTime.Seconds(1), function() Utils.Do(smuggler.GetGroundAttackers(), function(unit) IdleHunt(unit) end) end) end AttackNotifier = 0 Tick = function() if player.HasNoRequiredUnits() then harkonnen.MarkCompletedObjective(KillAtreides) end if LastHarkonnenArrived and not player.IsObjectiveCompleted(KillHarkonnen) and harkonnen.HasNoRequiredUnits() then Media.DisplayMessage("The Harkonnen have been annihilated!", "Mentat") player.MarkCompletedObjective(KillHarkonnen) end if LastMercenariesArrived and not player.IsObjectiveCompleted(KillSmuggler) and smuggler.HasNoRequiredUnits() and mercenary.HasNoRequiredUnits() then Media.DisplayMessage("The Smugglers have been annihilated!", "Mentat") player.MarkCompletedObjective(KillSmuggler) end if LastHarvesterEaten[harkonnen] and DateTime.GameTime % DateTime.Seconds(10) == 0 then local units = harkonnen.GetActorsByType("harvester") if #units > 0 then LastHarvesterEaten[harkonnen] = false ProtectHarvester(units[1], harkonnen, AttackGroupSize[Difficulty]) end end AttackNotifier = AttackNotifier - 1 if TimerTicks and not ContrabandArrived then TimerTicks = TimerTicks - 1 UserInterface.SetMissionText("The contraband will arrive in " .. Utils.FormatTime(TimerTicks), player.Color) if TimerTicks <= 0 then SendContraband(smuggler) end end end WorldLoaded = function() harkonnen = Player.GetPlayer("Harkonnen") smuggler = Player.GetPlayer("Smugglers") mercenary = Player.GetPlayer("Mercenaries") player = Player.GetPlayer("Atreides") InfantryReinforcements = Difficulty ~= "easy" InitObjectives(player) KillAtreides = harkonnen.AddPrimaryObjective("Kill all Atreides units.") CaptureBarracks = player.AddPrimaryObjective("Capture the Barracks at Sietch Tabr.") KillHarkonnen = player.AddSecondaryObjective("Annihilate all other Harkonnen units\nand reinforcements.") CaptureStarport = player.AddSecondaryObjective("Capture the Smuggler Starport and\nconfiscate the contraband.") Camera.Position = ARefinery.CenterPosition HarkonnenAttackLocation = AtreidesRally.Location MercenaryAttackLocation1 = Starport.Location + CVec.New(-16, 0) MercenaryAttackLocation2 = Starport.Location Trigger.AfterDelay(DateTime.Seconds(2), function() TimerTicks = ContrabandTimes[Difficulty] Media.DisplayMessage("The contraband is approaching the Starport to the north in " .. Utils.FormatTime(TimerTicks) .. ".", "Mentat") end) Trigger.OnAllKilledOrCaptured(HarkonnenBase, function() Utils.Do(harkonnen.GetGroundAttackers(), IdleHunt) end) Trigger.OnKilled(Starport, function() if not player.IsObjectiveCompleted(CaptureStarport) then ContrabandArrived = true UserInterface.SetMissionText("Starport destroyed! Contraband can't land.", player.Color) player.MarkFailedObjective(CaptureStarport) SmugglersAttack() Trigger.AfterDelay(DateTime.Seconds(15), function() UserInterface.SetMissionText("") end) end if DefendStarport then player.MarkFailedObjective(DefendStarport) end end) Trigger.OnDamaged(Starport, function() if Starport.Owner ~= smuggler then return end if AttackNotifier <= 0 then AttackNotifier = DateTime.Seconds(10) Media.DisplayMessage("Don't destroy the Starport!", "Mentat") local defenders = smuggler.GetGroundAttackers() if #defenders > 0 then Utils.Do(defenders, function(unit) unit.Guard(Starport) end) end end end) Trigger.OnCapture(Starport, function() DefendStarport = player.AddSecondaryObjective("Defend the captured Starport.") Trigger.ClearAll(Starport) Trigger.AfterDelay(0, function() Trigger.OnRemovedFromWorld(Starport, function() player.MarkFailedObjective(DefendStarport) end) end) if not ContrabandArrived then SendContraband(player) end SmugglersAttack() end) Trigger.OnKilled(HarkonnenBarracks, function() player.MarkFailedObjective(CaptureBarracks) end) Trigger.OnDamaged(HarkonnenBarracks, function() if AttackNotifier <= 0 and HarkonnenBarracks.Health < HarkonnenBarracks.MaxHealth * 3/4 then AttackNotifier = DateTime.Seconds(10) Media.DisplayMessage("Don't destroy the Barracks!", "Mentat") end end) Trigger.OnCapture(HarkonnenBarracks, function() Media.DisplayMessage("Hostages Released!", "Mentat") if DefendStarport then player.MarkCompletedObjective(DefendStarport) end Trigger.AfterDelay(DateTime.Seconds(3), function() player.MarkCompletedObjective(CaptureBarracks) end) end) SendHarkonnen() Actor.Create("upgrade.barracks", true, { Owner = harkonnen }) Actor.Create("upgrade.light", true, { Owner = harkonnen }) Actor.Create("upgrade.heavy", true, { Owner = harkonnen }) Trigger.AfterDelay(0, ActivateAI) Trigger.AfterDelay(DateTime.Minutes(1), function() Media.PlaySpeechNotification(player, "Reinforce") Reinforcements.ReinforceWithTransport(player, "carryall.reinforce", AtreidesReinforcements, AtreidesPath, { AtreidesPath[1] }) end) local smugglerWaypoint = SmugglerWaypoint1.Location Trigger.OnEnteredFootprint({ smugglerWaypoint + CVec.New(-2, 0), smugglerWaypoint + CVec.New(-1, 0), smugglerWaypoint, smugglerWaypoint + CVec.New(1, -1), smugglerWaypoint + CVec.New(2, -1), SmugglerWaypoint3.Location }, function(a, id) if not warned and a.Owner == player and a.Type ~= "carryall" then warned = true Trigger.RemoveFootprintTrigger(id) Media.DisplayMessage("Stay away from our Starport.", "Smuggler Leader") end end) Trigger.OnEnteredFootprint({ SmugglerWaypoint2.Location }, function(a, id) if not paid and a.Owner == player and a.Type ~= "carryall" then paid = true Trigger.RemoveFootprintTrigger(id) Media.DisplayMessage("You were warned. Now you will pay.", "Smuggler Leader") Utils.Do(smuggler.GetGroundAttackers(), function(unit) unit.AttackMove(SmugglerWaypoint2.Location) end) Trigger.AfterDelay(DateTime.Seconds(3), function() KillSmuggler = player.AddSecondaryObjective("Destroy the Smugglers and their Mercenaries.") SendMercenaries() end) end end) Trigger.OnEnteredProximityTrigger(HarkonnenBarracks.CenterPosition, WDist.New(5 * 1024), function(a, id) if a.Owner == player and a.Type ~= "carryall" then Trigger.RemoveProximityTrigger(id) Media.DisplayMessage("Capture the Harkonnen barracks to release the hostages.", "Mentat") StopInfantryProduction = true end end) end
gpl-3.0
Black-Nine/Self-Bot
plugins/id.lua
26
3037
local function usernameinfo (user) if user.username then return '@'..user.username end if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function whoisname(cb_extra, success, result) chat_type = cb_extra.chat_type chat_id = cb_extra.chat_id user_id = result.peer_id user_username = result.username if chat_type == 'chat' then send_msg('chat#id'..chat_id, user_id, ok_cb, false) elseif chat_type == 'channel' then send_msg('channel#id'..chat_id, user_id, ok_cb, false) end end local function whoisid(cb_extra, success, result) chat_id = cb_extra.chat_id user_id = cb_extra.user_id if cb_extra.chat_type == 'chat' then send_msg('chat#id'..chat_id, user_id, ok_cb, false) elseif cb_extra.chat_type == 'channel' then send_msg('channel#id'..chat_id, user_id, ok_cb, false) end end local function get_id_who(extra, success, result) result = backward_msg_format(result) local msg = result local chat = msg.to.id local user = msg.from.id if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, msg.from.id, ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, msg.from.id, ok_cb, false) end end local function run(msg, matches) local receiver = get_receiver(msg) local chat = msg.to.id -- Id of the user and info about group / channel if matches[1] == "#gid" then if not is_sudo(msg) then return nil end if permissions(msg.from.id, msg.to.id, "id") then if msg.to.type == 'channel' then send_msg(msg.to.peer_id, 'SuperGroup ID: '..msg.to.id, ok_cb, false) elseif msg.to.type == 'chat' then send_msg(msg.to.peer_id, 'Group ID: '..msg.to.id, ok_cb, false) end end elseif matches[1] == 'id' then if not is_sudo(msg) then return nil end if permissions(msg.from.id, msg.to.id, "id") then chat_type = msg.to.type chat_id = msg.to.id if msg.reply_id then get_message(msg.reply_id, get_id_who, {receiver=get_receiver(msg)}) return end if is_id(matches[2]) then print(1) user_info('user#id'..matches[2], whoisid, {chat_type=chat_type, chat_id=chat_id, user_id=matches[2]}) return else local member = string.gsub(matches[2], '@', '') resolve_username(member, whoisname, {chat_id=chat_id, member=member, chat_type=chat_type}) return end else return end end end return { patterns = { "^#(id)$", "^#gid$", "^#(id) (.*)$" }, run = run }
gpl-2.0
ffxiphoenix/darkstar
scripts/zones/Bastok_Mines/npcs/Azette.lua
28
2058
----------------------------------- -- Area: Bastok Mines -- NPC: Azette -- Type: Chocobo Renter ----------------------------------- require("scripts/globals/chocobo"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local level = player:getMainLvl(); local gil = player:getGil(); if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 15) then local price = getChocoboPrice(player); player:setLocalVar("chocoboPriceOffer",price); if (level >= 20) then level = 0; end player:startEvent(0x003D,price,gil,level); else player:startEvent(0x0040); 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); local price = player:getLocalVar("chocoboPriceOffer"); if (csid == 0x003D and option == 0) then if (player:delGil(price)) then updateChocoboPrice(player, price); if (player:getMainLvl() >= 20) then local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60) player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,duration,true); else player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,900,true); end player:setPos(580,0,-305,0x40,0x6B); end end end;
gpl-3.0
vilarion/Illarion-Content
monster/race_52_raptor/id_524_fire_raptor.lua
3
1584
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local monsterId = 524 local base = require("monster.base.base") local monstermagic = require("monster.base.monstermagic") local raptors = require("monster.race_52_raptor.base") local firefield = require("item.id_359_firefield") local M = raptors.generateCallbacks() local orgOnSpawn = M.onSpawn function M.onSpawn(monster) if orgOnSpawn ~= nil then orgOnSpawn(monster) end base.setColor{monster = monster, target = base.SKIN_COLOR, red = 255, green = 100, blue = 100} end local magic = monstermagic() magic.addFirecone{probability = 0.05, damage = {from = 1250, to = 1500}, range = 6, angularAperture = 30, itemProbability = 0.1, quality = {from = 0, to = 1}} magic.addFirecone{probability = 0.005, damage = {from = 1400, to = 1800}, range = 3, angularAperture = 30, itemProbability = 0.05, quality = {from = 1, to = 2}} firefield.setFlameImmunity(monsterId) return magic.addCallbacks(M)
agpl-3.0
ffxiphoenix/darkstar
scripts/globals/items/moon_carrot.lua
35
1194
----------------------------------------- -- ID: 4567 -- Item: moon_carrot -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility 1 -- Vitality -1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4567); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, -1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, -1); end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Metalworks/npcs/Fariel.lua
34
2197
----------------------------------- -- Area: Metalworks -- NPC: Fariel -- Type: Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Metalworks/TextIDs"); require("scripts/globals/pathfind"); local path = { 53.551208, -14.000000, -7.162227, 54.111534, -14.000000, -6.227105, 54.075279, -14.000000, -5.139729, 53.565350, -14.000000, 6.000605, 52.636345, -14.000000, 6.521872, 51.561535, -14.000000, 6.710593, 50.436523, -14.000000, 6.835652, 41.754219, -14.000000, 7.686310, 41.409531, -14.000000, 6.635177, 41.351002, -14.000000, 5.549131, 41.341057, -14.000000, 4.461191, 41.338020, -14.000000, -9.138797, 42.356136, -14.000000, -9.449953, 43.442558, -14.000000, -9.409095, 44.524868, -14.000000, -9.298069, 53.718494, -14.000000, -8.260445, 54.082706, -14.000000, -7.257769, 54.110283, -14.000000, -6.170790, 54.073116, -14.000000, -5.083439, 53.556625, -14.000000, 6.192736, 52.545383, -14.000000, 6.570893, 51.441212, -14.000000, 6.730487, 50.430820, -14.000000, 6.836911, 41.680725, -14.000000, 7.693455, 41.396103, -14.000000, 6.599321, 41.349224, -14.000000, 5.512603, 41.340771, -14.000000, 4.424644 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02C2); npc:wait(-1); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) --printf("CSID: %u",csid); --printf("RESULT: %u",option); npc:wait(0); end;
gpl-3.0
ld-test/saci
lua/saci/node.lua
3
15500
----------------------------------------------------------------------------- -- Creates a representation of a single data "node" with support for -- inheritance and field activation. -- -- (c) 2007, 2008 Yuri Takhteyev (yuri@freewisdom.org) -- License: MIT/X, see http://sputnik.freewisdom.org/en/License ----------------------------------------------------------------------------- module(..., package.seeall) require("saci.sandbox") require("diff") --x-------------------------------------------------------------------------- -- A table of functions used for "activating" fields, that is turning them -- from strings into tables or functions. ----------------------------------------------------------------------------- local Activators = {} --x-------------------------------------------------------------------------- -- Turns Lua code into a table of values defined by that code. -- -- @param value Lua code as string. -- @param repo the Saci repository. -- @return the environment created by running the code. ----------------------------------------------------------------------------- Activators.lua = function(value, repo) local sandbox = saci.sandbox.new(repo.sandbox_values) sandbox.logger = repo.logger return sandbox:do_lua(value) end --x-------------------------------------------------------------------------- -- Turns a list of tokens (e.g. node IDs) represented as one token per line -- into a table of tokens. -- -- @param value a list of tokens as a \n-delimited string. -- @param repo The Saci repository. -- @return a table of tokens. ----------------------------------------------------------------------------- Activators.list = function(value, repo) local nodes = {} for line in (value or ""):gmatch("[^%s]+") do table.insert(nodes, line) end return nodes end local Node = {} local Node_mt = { __index = function(t,key) return t.active_values[key] or t.inherited_values[key] or t.raw_values[key] or Node[key] end } ----------------------------------------------------------------------------- -- Creates a new instance of Node. This is the only function this module -- exposes and the only one you should be using directly. The instance that -- this function returns has methods that can then be used to manipulate the -- node. -- -- @param args a table arguments, including the following fields: -- args.data (the raw data for the node, required), -- args.id (the id of the node, required), -- args.repository (the saci instance, required) -- -- @repository the repository to which this Node belongs. -- @return an instance of "SputnikRepository". ----------------------------------------------------------------------------- function new(args) local node = setmetatable({raw_values={}, inherited_values={}, active_values={}}, Node_mt) --assert(args.data) --assert(args.id) node.data = args.data node.id = args.id --assert(args.repository) node.repository = args.repository node.saci = node.repository node.raw_values = saci.sandbox.new():do_lua(args.data) --assert(rawget(node, "raw_values"), "the sandbox should give us a table") node:apply_inheritance() node:activate() return node end --------------------------------------------------------------------------------------------------- -- Returns the edits to the node. -- -- @param prefix an optional date prefix (e.g., "2007-12"). -- @return edits as a table. --------------------------------------------------------------------------------------------------- function Node:get_history(prefix) return self.repository:get_node_history(self.id, prefix) end --------------------------------------------------------------------------------------------------- -- Returns the node as a string (used for debugging). --------------------------------------------------------------------------------------------------- function Node:tostring() local buf = "================= "..self._id.." ========\n" for field, fieldinfo in pairs(self.fields) do buf = buf.."~~~~~~~ "..field.." ("..(fieldinfo.proto or "")..") ~~~~\n" buf = buf..(self._inactive[field] or "") buf = buf.."\n" end buf = buf.."~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n" return buf end ----------------------------------------------------------------------------- -- Inheritance rules: functions that determine what the node's value should -- be based on it's prototype's value and it's own "raw" value. ----------------------------------------------------------------------------- local inheritance_rules = {} -- Concatenates the inherited value and own value, inserting an "\n" between -- them. Basically, this is what we need to be able to concatenate two -- chunks of Lua code. function inheritance_rules.concat(proto_value, own_value) local buf = "" if proto_value and proto_value:len() > 0 then buf = proto_value end if own_value and own_value:len() > 0 then if buf:len() > 0 then buf = buf.."\n"..own_value else buf = own_value end end return buf end -- A simpler inheritance rule that only uses the prototype's value if own -- value is not defined. function inheritance_rules.fallback(proto_value, own_value) if own_value and own_value~="" then return own_value else return proto_value end end inheritance_rules.default = inheritance_rules.fallback -- set a default ----------------------------------------------------------------------------- -- Applies inheritance form page's prototype. The inherited values are -- stored in self.inherited_values. ----------------------------------------------------------------------------- function Node:apply_inheritance() --assert(self.id) -- If this node is itself the root prototype, then there is nothing else -- to do. if self.id == self.repository.root_prototype_id then self.inherited_values = self.raw_values return end if self.raw_values.prototype == "" then self.raw_values.prototype = nil -- to make it easier to test for it end local prototype_id = self.raw_values.prototype or self.repository.root_prototype_id -- Get the values for the prototype. local proto_values = self.repository:get_node(prototype_id).inherited_values assert(proto_values.fields, "The prototype node must define fields") -- Apply inheritance from the prototype, using the information in the -- 'fields' field to decide how to handle each field. -- First, we need to figure out what those fields are. We use -- this node's own "fields" table rather than the fields table from the -- prototype and the value for fields must _always_ be inherited as a -- matter of bootstrapping. local tmp_fields = inheritance_rules.concat(proto_values.fields, self.raw_values.fields) assert(tmp_fields) local fields, err = saci.sandbox.new{}:do_lua(tmp_fields) assert(fields, err) -- Now do the actual inheritance. This means going through all fields -- and applying each of them the "inheritance rule" specified by the -- "proto" attribute. for field_name, field in pairs(fields) do field.name = field_name if field.proto then local inheritance_fn = inheritance_rules[field.proto] or inheritance_rules.default self.inherited_values[field.name] = inheritance_fn( proto_values[field.name], self.raw_values[field.name]) end end end --------------------------------------------------------------------------------------------------- -- Turns string parameters into Lua functions and tables, making them callable. --------------------------------------------------------------------------------------------------- function Node:activate() self.active_values = {} local fields, err = saci.sandbox.new{}:do_lua(self.inherited_values.fields) if not fields then error(err) end for field, fieldinfo in pairs(fields) do if fieldinfo.activate then local activator_fn = Activators[fieldinfo.activate] local value = self[field] or "" self.active_values[field] = activator_fn(value, self.repository) end end return self end --------------------------------------------------------------------------------------------------- -- Updates the node with values. -- -- @param new_values a table of new values (keyed by field name). -- @param fields a table keyed by field name to allow us to filter the new values. -- @return nothing. --------------------------------------------------------------------------------------------------- function Node:update(new_values, fields) assert(new_values) --assert(fields) -- First, update the raw values the new values (only those that are listed in fields!) for key, value in pairs(new_values) do if (not fields) or (fields[key] and not fields[key].virtual) then self.raw_values[key] = value end end self:apply_inheritance() self:activate() -- Now make a new node, being careful to not get into recursive metatables --local vnode = self._vnode --setmetatable(self._inactive, {}) -- to avoid recursive metatables --local new_smart_node = new(vnode, self.repository, self.repository.config.ROOT_PROTOTYPE) -- Now make the current node a copy of the new one (copy the fields and the metatable --for k,v in pairs(new_smart_node) do -- self[k] = v --end --setmetatable(self, getmetatable(new_smart_node)) end --------------------------------------------------------------------------------------------------- -- Returns a diff between this version of the node and some other one. -- -- @param another_node some other node -- @return diff as a table of tokens. --------------------------------------------------------------------------------------------------- function Node:diff(another_node) local difftab = {} for i, field in ipairs(self:get_ordered_field_names()) do if (self.raw_values[field] or "") ~= (another_node.raw_values[field] or "") then difftab[field] = diff.diff(tostring(another_node.raw_values[field]), tostring(self.raw_values[field])) end end return difftab end ----------------------------------------------------------------------------- -- Returns the list of fields for this node, ordered according to their -- weights. -- -- @return A table of fields. ----------------------------------------------------------------------------- function Node:get_ordered_field_names() local ordered_fields = {} for k,v in pairs(self.fields) do table.insert(ordered_fields, k) end table.sort(ordered_fields, function(a,b) return (self.fields[a][1] or 0) < (self.fields[b][1] or 0) end) return ordered_fields end ----------------------------------------------------------------------------- -- Saves the node (using the data that's already in the node). -- -- @param author the author associated with the edit. -- @param comment a comment for the edit (optional). -- @param extra extra params (optional). -- @return nothing. ----------------------------------------------------------------------------- function Node:save(author, comment, extra, timestamp) author = author or "" self.repository:save_node(self, author, comment, extra, timestamp) end ----------------------------------------------------------------------------- -- Checks if the user is allowed to perform a named action. -- -- @param user user ID -- @param action action ID -- @return true or false ----------------------------------------------------------------------------- function Node:check_permissions(user, action) if not self.permissions then return true end local function in_table(tab, item) for i,v in ipairs(tab) do if v==item then return true end end return false end -- checks membership in groups local function member(item, group) if type(group) == "function" then return group(item) elseif type(group) == "table" then return in_table(group, item) elseif type(group) == "string" then return group == item else error("expected a string, a table or a function") end end -- keeps the allowed/not allowed state local has_permission = true -- toggles the the state local function set(user_group, action_group, value) if member(user, user_group) and member(action, action_group) then has_permission = value end end -- setup the sandbox local sandbox = saci.sandbox.new(self.saci.permission_groups) sandbox:add_values{ allow = function (user, action) set(user, action, true) end, deny = function (user, action) set(user, action, false) end, } sandbox:do_lua(self.permissions) return has_permission end ----------------------------------------------------------------------------- -- Returns a child node, if they are defined. -- -- @param id child's id. -- @return an instance of Node or nil. ----------------------------------------------------------------------------- function Node:get_child(id) if not self.child_defaults then return end if self.repository:node_exists(self.id.."/"..id) then return nil end if self.child_defaults[id] then return self.repository:make_node( cosmo.fill(self.child_defaults[id], self), self.id.."/"..id) elseif self.child_defaults.any then return self.repository:make_node(self.child_defaults.any, self.id.."/"..id) elseif self.child_defaults.patterns then for i, pattern in ipairs(self.child_defaults.patterns) do if id:match(pattern[1]) then return self.repository:make_node(pattern[2], self.id.."/"..id) end end end end local function make_immediate_child_filter(parent_id) local length = parent_id:len() return function(id) return not id:sub(length+2):find("/") end end function Node:get_children(immediate, limit, visible) local id_filter = make_immediate_child_filter(self.id) return self.repository:get_nodes_by_prefix(self.id.."/", limit, id_filter) end function Node:get_visible_children(immediate, limit, visible) local id_filter = make_immediate_child_filter(self.id) return self.repository:get_nodes_by_prefix(self.id.."/", limit, true, id_filter) end function Node:get_parent_id() local parent_id, rest = string.match(self.id, "^(.+)/(.-)$") return parent_id, rest end function Node:multimatch(fields, patterns, match_case) local value for _, field in ipairs(fields) do value = self[field] if value and type(value)=="string" then --value = " "..value:lower().." " if not match_case then value = value:lower() end for __, pattern in ipairs(patterns) do if value:match(pattern) then return true end end end end end
mit
noooway/love2d_arkanoid_tutorial
3-02_BallLaunchFromPlatform/ball.lua
3
5002
local vector = require "vector" local sign = math.sign or function(x) return x < 0 and -1 or x > 0 and 1 or 0 end local ball = {} local first_launch_speed = vector( -150, -300 ) ball.speed = vector( 0, 0 ) ball.image = love.graphics.newImage( "img/800x600/ball.png" ) ball.x_tile_pos = 0 ball.y_tile_pos = 0 ball.tile_width = 18 ball.tile_height = 18 ball.tileset_width = 18 ball.tileset_height = 18 ball.quad = love.graphics.newQuad( ball.x_tile_pos, ball.y_tile_pos, ball.tile_width, ball.tile_height, ball.tileset_width, ball.tileset_height ) ball.radius = ball.tile_width / 2 ball.collision_counter = 0 local ball_x_shift = -28 local platform_height = 16 local platform_starting_pos = vector( 300, 500 ) ball.stuck_to_platform = true ball.separation_from_platform_center = vector( ball_x_shift, -1 * platform_height / 2 - ball.radius - 1 ) ball.position = platform_starting_pos + ball.separation_from_platform_center function ball.update( dt, platform ) ball.position = ball.position + ball.speed * dt if ball.stuck_to_platform then ball.follow_platform( platform ) end ball.check_escape_from_screen() end function ball.draw() love.graphics.draw( ball.image, ball.quad, ball.position.x - ball.radius, ball.position.y - ball.radius ) end function ball.follow_platform( platform ) local platform_center = vector( platform.position.x + platform.width / 2, platform.position.y + platform.height / 2 ) ball.position = platform_center + ball.separation_from_platform_center end function ball.launch_from_platform() if ball.stuck_to_platform then ball.stuck_to_platform = false ball.speed = first_launch_speed:clone() end end function ball.wall_rebound( shift_ball ) ball.normal_rebound( shift_ball ) ball.min_angle_rebound() ball.increase_collision_counter() ball.increase_speed_after_collision() end function ball.platform_rebound( shift_ball, platform ) ball.bounce_from_sphere( shift_ball, platform ) ball.increase_collision_counter() ball.increase_speed_after_collision() end function ball.brick_rebound( shift_ball ) ball.normal_rebound( shift_ball ) ball.increase_collision_counter() ball.increase_speed_after_collision() end function ball.normal_rebound( shift_ball ) local actual_shift = ball.determine_actual_shift( shift_ball ) ball.position = ball.position + actual_shift if actual_shift.x ~= 0 then ball.speed.x = -ball.speed.x end if actual_shift.y ~= 0 then ball.speed.y = -ball.speed.y end end function ball.determine_actual_shift( shift_ball ) local actual_shift = vector( 0, 0 ) local min_shift = math.min( math.abs( shift_ball.x ), math.abs( shift_ball.y ) ) if math.abs( shift_ball.x ) == min_shift then actual_shift.x = shift_ball.x else actual_shift.y = shift_ball.y end return actual_shift end function ball.bounce_from_sphere( shift_ball, platform ) local actual_shift = ball.determine_actual_shift( shift_ball ) ball.position = ball.position + actual_shift if actual_shift.x ~= 0 then ball.speed.x = -ball.speed.x end if actual_shift.y ~= 0 then local sphere_radius = 200 local ball_center = ball.position local platform_center = platform.position + vector( platform.width / 2, platform.height / 2 ) local separation = ( ball_center - platform_center ) local normal_direction = vector( separation.x / sphere_radius, -1 ) local v_norm = ball.speed:projectOn( normal_direction ) local v_tan = ball.speed - v_norm local reverse_v_norm = v_norm * (-1) ball.speed = reverse_v_norm + v_tan end end function ball.min_angle_rebound() local min_horizontal_rebound_angle = math.rad( 20 ) local vx, vy = ball.speed:unpack() local new_vx, new_vy = vx, vy rebound_angle = math.abs( math.atan( vy / vx ) ) if rebound_angle < min_horizontal_rebound_angle then new_vx = sign( vx ) * ball.speed:len() * math.cos( min_horizontal_rebound_angle ) new_vy = sign( vy ) * ball.speed:len() * math.sin( min_horizontal_rebound_angle ) end ball.speed = vector( new_vx, new_vy ) end function ball.increase_collision_counter() ball.collision_counter = ball.collision_counter + 1 end function ball.increase_speed_after_collision() local speed_increase = 20 local each_n_collisions = 10 if ball.collision_counter ~= 0 and ball.collision_counter % each_n_collisions == 0 then ball.speed = ball.speed + ball.speed:normalized() * speed_increase end end function ball.reposition() ball.escaped_screen = false ball.collision_counter = 0 ball.stuck_to_platform = true ball.speed = vector( 0, 0 ) end function ball.check_escape_from_screen() local x, y = ball.position:unpack() local ball_top = y - ball.radius if ball_top > love.graphics.getHeight() then ball.escaped_screen = true end end return ball
mit
Quenty/NevermoreEngine
src/loader/src2/init.lua
1
1867
local ReplicatedStorage = game:GetService("ReplicatedStorage") local DependencyUtils = require(script.Dependencies.DependencyUtils) local Replicator = require(script.Replication.Replicator) local ReplicatorReferences = require(script.Replication.ReplicatorReferences) local Maid = require(script.Maid) local LoaderAdder = require(script.Loader.LoaderAdder) local ReplicationType = require(script.Replication.ReplicationType) local function handleLoad(moduleScript) assert(typeof(moduleScript) == "Instance", "Bad moduleScript") return function(request) if type(request) == "string" then local module = DependencyUtils.findDependency(moduleScript, request) return require(module) else return require(request) end end end local function bootstrapGame(packages) local maid = Maid.new() local copy = Instance.new("Folder") copy.Name = packages.Name maid:GiveTask(copy) local references = ReplicatorReferences.new() local serverAdder = LoaderAdder.new(references, packages, ReplicationType.SERVER) maid:GiveTask(serverAdder) local replicator = Replicator.new(references) replicator:SetTarget(copy) replicator:ReplicateFrom(packages) maid:GiveTask(replicator) local clientAdder = LoaderAdder.new(references, copy, ReplicationType.CLIENT) maid:GiveTask(clientAdder) copy.Parent = ReplicatedStorage return setmetatable({}, {__index = function(_, value) -- Lookup module script if type(value) == "string" then local result = DependencyUtils.findDependency(packages, value) if result then return result else error(("Could not find dependency %q"):format(value)) end else error(("Bad index %q"):format(type(value))) end end}) end local function bootstrapPlugin(_packages) error("Not implemented") end return { load = handleLoad; bootstrapGame = bootstrapGame; bootstrapPlugin = bootstrapPlugin; }
mit
ffxiphoenix/darkstar
scripts/zones/Temenos/mobs/Abyssdweller_Jhabdebb.lua
16
1604
----------------------------------- -- Area: Temenos -- NPC: ----------------------------------- 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) if (IsMobDead(16929010)==true and IsMobDead(16929011)==true and IsMobDead(16929012)==true and IsMobDead(16929013)==true and IsMobDead(16929014)==true and IsMobDead(16929015)==true ) then mob:setMod(MOD_SLASHRES,1400); mob:setMod(MOD_PIERCERES,1400); mob:setMod(MOD_IMPACTRES,1400); mob:setMod(MOD_HTHRES,1400); else mob:setMod(MOD_SLASHRES,300); mob:setMod(MOD_PIERCERES,300); mob:setMod(MOD_IMPACTRES,300); mob:setMod(MOD_HTHRES,300); end GetMobByID(16929006):updateEnmity(target); GetMobByID(16929007):updateEnmity(target); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) if (IsMobDead(16929005)==true and IsMobDead(16929006)==true and IsMobDead(16929007)==true) then GetNPCByID(16928768+78):setPos(-280,-161,-440); GetNPCByID(16928768+78):setStatus(STATUS_NORMAL); GetNPCByID(16928768+473):setStatus(STATUS_NORMAL); end end;
gpl-3.0
elixboyBW/elixboySPM
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
ffxiphoenix/darkstar
scripts/zones/Port_Jeuno/TextIDs.lua
9
3021
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6384; -- Obtained: <item>. GIL_OBTAINED = 6385; -- Obtained <number> gil. KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>. HOMEPOINT_SET = 6632; -- Home point set! FISHING_MESSAGE_OFFSET = 6880; -- You can't fish here. MOGHOUSE_EXIT = 7146; -- You have learned your way through the back alleys of Jeuno! Now you can exit to any area from your residence. WEATHER_DIALOG = 6832; -- Your fate rides on the changing winds of Vana'diel. I can give you insight on the local weather.<Prompt> -- Shop Texts LEYLA_SHOP_DIALOG = 6992; -- Hello. All goods are duty-free. GEKKO_SHOP_DIALOG = 6992; -- Hello. All goods are duty-free. CHALLOUX_SHOP_DIALOG = 6993; -- Good day! -- Other Texts GUIDE_STONE = 6991; -- Up: Lower Jeuno (Selection Dialogfacing Bastok) Down: Qufim Island CUMETOUFLAIX_DIALOG = 7031; -- This underground tunnel leads to the island of Qufim. Everyone is advised to stay out. But of course you adventurers never listen. OLD_BOX = 7266; -- You find a grimy old box. ITEM_DELIVERY_DIALOG = 7353; -- Delivering goods to residences everywhere! VEUJAIE_DIALOG = 7353; -- Delivering goods to residences everywhere! DIGAGA_DIALOG = 7353; -- Delivering goods to residences everywhere! CHEST_IS_EMPTY = 8627; -- The chest is empty. -- Conquest system CONQUEST = 7363; -- You've earned conquest points! -- NPC Dialog TSOLAG_DIALOG = 7352; -- This is the departure gate for airship passengers. If you have any questions, please inquire with Guddal. GAVIN_DIALOG = 7334; -- This is the counter for the air route to the Outlands. Our airships connect Jeuno with the southeastern island of Elshimo. DAPOL_DIALOG = 7062; -- Welcome to Port Jeuno, the busiest airship hub anywhere! You can't miss the awe-inspiring view of airships in flight! SECURITY_DIALOG = 7065; -- Port Jeuno must remain secure. After all, if anything happened to the archduke, it would change the world! ARRIVAL_NPC = 7049; -- Enjoy your stay in Jeuno! COUNTER_NPC = 7039; -- I think the airships are a subtle form of pressure on the other three nations. That way, Jeuno can maintain the current balance of power. COUNTER_NPC_2 = 7037; -- With the airships connecting Jeuno with the three nations, the flow of goods has become much more consistent. Nowadays, everything comes through Jeuno! CHOCOBO_DIALOG = 7168; -- ... GET_LOST = 8128; -- You want somethin' from me? Well, too bad. I don't want nothin' from you. Get lost. DRYEYES_1 = 8137; -- Then why you waste my time? Get lost DRYEYES_2 = 8138; -- Done deal. Deal is done. DRYEYES_3 = 8139; -- Hey, you already got . What you tryin' to pull here? Save some for my other customers, eh -- conquest Base CONQUEST_BASE = 6471; -- Tallying conquest results...
gpl-3.0
ld-test/gumbo
gumbo/constants.lua
2
1468
local Set = require "gumbo.Set" local _ENV = nil local namespaces = { html = "http://www.w3.org/1999/xhtml", math = "http://www.w3.org/1998/Math/MathML", svg = "http://www.w3.org/2000/svg" } local voidElements = Set { "area", "base", "basefont", "bgsound", "br", "col", "embed", "frame", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr" } local rcdataElements = Set { "style", "script", "xmp", "iframe", "noembed", "noframes", "plaintext" } local booleanAttributes = { [""] = Set{"hidden", "irrelevant"}, audio = Set{"autoplay", "controls"}, button = Set{"disabled", "autofocus"}, command = Set{"hidden", "disabled", "checked", "default"}, datagrid = Set{"multiple", "disabled"}, details = Set{"open"}, fieldset = Set{"disabled", "readonly"}, hr = Set{"noshade"}, img = Set{"ismap"}, input = Set[[disabled readonly required autofocus checked ismap]], menu = Set{"autosubmit"}, optgroup = Set{"disabled", "readonly"}, option = Set{"disabled", "readonly", "selected"}, output = Set{"disabled", "readonly"}, script = Set{"defer", "async"}, select = Set{"disabled", "readonly", "autofocus", "multiple"}, style = Set{"scoped"}, video = Set{"autoplay", "controls"}, } return { namespaces = namespaces, rcdataElements = rcdataElements, voidElements = voidElements, booleanAttributes = booleanAttributes }
isc
ffxiphoenix/darkstar
scripts/globals/spells/bluemagic/seedspray.lua
18
2149
----------------------------------------- -- Spell: Seedspray -- Delivers a threefold attack. Additional effect: Weakens defense. Chance of effect varies with TP -- Spell cost: 61 MP -- Monster Type: Plantoids -- Spell Type: Physical (Slashing) -- Blue Magic Points: 2 -- Stat Bonus: VIT+1 -- Level: 61 -- Casting Time: 4 seconds -- Recast Time: 35 seconds -- Skillchain Element(s): Ice (Primary) and Wind (Secondary) - (can open Impaction, Compression, Fragmentation, Scission or Gravitation; can close Induration or Detonation) -- Combos: Beast Killer ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_CRITICAL; params.dmgtype = DMGTYPE_SLASH; params.scattr = SC_GRAVITATION; params.numhits = 3; params.multiplier = 1.925; params.tp150 = 1.25; params.tp300 = 1.25; params.azuretp = 1.25; params.duppercap = 61; params.str_wsc = 0.0; params.dex_wsc = 0.30; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.20; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); local chance = math.random(); if (damage > 0 and chance > 1) then local typeEffect = EFFECT_DEFENSE_DOWN; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,4,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Windurst_Woods/npcs/Cayu_Pensharhumi.lua
38
1416
----------------------------------- -- Area: Windurst Woods -- NPC: Cayu Pensharhumi -- Type: Standard NPC -- @pos 39.437 -0.91 -40.808 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatWindurst = player:getVar("WildcatWindurst"); if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,2) == false) then player:startEvent(0x02dd); else player:startEvent(0x0103); 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 == 0x02dd) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",2,true); end end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Lower_Jeuno/npcs/Navisse.lua
34
4871
----------------------------------- -- Area: Lower Jeuno -- NPC: Navisse -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; require("scripts/zones/Lower_Jeuno/TextIDs"); require("scripts/globals/pathfind"); local path = { -- -59.562683, 6.000051, -90.890404, -58.791367, 6.000050, -91.663391, -58.021465, 6.000049, -92.432144, -58.729881, 6.000051, -91.577568, -60.351879, 6.000053, -89.835815, -61.099354, 6.000054, -89.034248, -61.841427, 5.999946, -88.238564, -62.769325, 5.999948, -87.244301, -61.750378, 5.999948, -87.684868, -60.796600, 5.999947, -88.208214, -55.475166, 5.999943, -91.271210, -56.590668, 5.999943, -91.245201, -57.651192, 6.000052, -91.002350, -64.134392, 6.000052, -89.460915, -63.261021, 6.000051, -90.107605, -62.330879, 6.000051, -90.679604, -61.395359, 6.000050, -91.235107, -56.591644, 6.000047, -94.066406, -57.208908, 6.000048, -93.245895, -57.934330, 6.000049, -92.435081, -59.788624, 6.000052, -90.439583, -61.832211, 5.999946, -88.248795, -62.574249, 5.999948, -87.453148, -61.832058, 5.999946, -88.248627, -61.089920, 6.000054, -89.044273, -60.348049, 6.000053, -89.840111, -59.043877, 6.000051, -91.238251, -58.301846, 6.000050, -92.033958, -57.467026, 6.000048, -92.929070, -56.536987, 6.000047, -93.926826, -57.528469, 6.000047, -93.482582, -58.476944, 6.000048, -92.949654, -59.416409, 6.000049, -92.400879, -64.235306, 6.000051, -89.563835, -64.000816, 6.000054, -88.482338, -63.516331, 5.999947, -87.539917, -62.444843, 5.999948, -87.352570, -61.468765, 5.999947, -87.831436, -60.520329, 5.999947, -88.364532, -55.100037, 5.999943, -91.488144, -56.063160, 5.999944, -90.932312, -62.719467, 5.999948, -87.093468, -62.064899, 5.999947, -87.960884, -61.338562, 5.999946, -88.770836, -59.579746, 6.000052, -90.663826, -58.177391, 6.000050, -92.167343, -57.435341, 6.000048, -92.963005, -56.734436, 6.000047, -93.714989, -57.492855, 6.000049, -92.901787, -58.251190, 6.000050, -92.088486, -59.364170, 6.000051, -90.894829, -61.039413, 6.000054, -89.098907, -61.784184, 5.999946, -88.300293, -62.804745, 5.999948, -87.206451, -60.463631, 6.000053, -89.715942, -59.721657, 6.000052, -90.511711, -58.974190, 6.000051, -91.313248, -58.232239, 6.000050, -92.109024, -56.840717, 6.000047, -93.600716, -57.914623, 6.000048, -93.276276, -58.855755, 6.000048, -92.730408, -64.140175, 6.000051, -89.619812, -63.025597, 6.000052, -89.751106, -61.954758, 6.000052, -89.984474, -60.887684, 6.000052, -90.234573, -55.190853, 5.999943, -91.590721, -55.368877, 6.000050, -92.667923, -55.841885, 6.000048, -93.664970, -56.916370, 6.000048, -93.400879, -57.705578, 6.000049, -92.652748, -58.456089, 6.000050, -91.865067, -60.405739, 6.000053, -89.778008, -61.147854, 6.000054, -88.982376, -61.889904, 5.999946, -88.186691, -62.637497, 5.999948, -87.385239, -63.643429, 6.000055, -87.880524, -64.248825, 6.000053, -88.784004, -63.455921, 6.000052, -89.526733, -62.418514, 6.000052, -89.852493, -61.363335, 6.000052, -90.117607, -55.142048, 5.999943, -91.602325, -55.358624, 6.000050, -92.679016, -55.842934, 6.000048, -93.675148, -56.919590, 6.000048, -93.408241, -57.710354, 6.000049, -92.649918, -58.459896, 6.000050, -91.861336, -60.409424, 6.000053, -89.774185, -61.151508, 6.000054, -88.978500, -62.848709, 5.999948, -87.159264, -61.829231, 5.999948, -87.629791, -60.951675, 5.999947, -88.117493, -55.395309, 5.999943, -91.317513, -56.522537, 5.999943, -91.263893, -57.586517, 6.000052, -91.018196, -64.081299, 6.000052, -89.473526, -63.209583, 6.000051, -90.135269, -62.270042, 6.000050, -90.714821, -61.334797, 6.000050, -91.270729, -56.586208, 6.000047, -94.069595, -64.130554, 6.000051, -89.625450, -56.496498, 6.000047, -94.122322, -57.173595, 6.000048, -93.271568, -57.904095, 6.000049, -92.465279, -59.571453, 6.000052, -90.672951, }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0099); npc:wait(-1); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) --printf("CSID: %u",csid); --printf("RESULT: %u",option); npc:wait(0); end;
gpl-3.0
azekillDIABLO/Voxellar
mods/NODES/xdecor/src/hive.lua
5
2044
local hive = {} local honey_max = 16 function hive.construct(pos) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() local formspec = [[ size[8,5;] label[0.5,0;Bees are busy making honey...] image[6,0;1,1;hive_bee.png] image[5,0;1,1;hive_layout.png] list[context;honey;5,0;1,1;] list[current_player;main;0,1.35;8,4;] ]] ..xbg..default.get_hotbar_bg(0,1.35) meta:set_string("formspec", formspec) meta:set_string("infotext", "Artificial Hive") inv:set_size("honey", 1) local timer = minetest.get_node_timer(pos) timer:start(math.random(64, 128)) end function hive.timer(pos) local time = (minetest.get_timeofday() or 0) * 24000 if time < 5500 or time > 18500 then return true end local inv = minetest.get_meta(pos):get_inventory() local honeystack = inv:get_stack("honey", 1) local honey = honeystack:get_count() local radius = 4 local minp = vector.add(pos, -radius) local maxp = vector.add(pos, radius) local flowers = minetest.find_nodes_in_area_under_air(minp, maxp, "group:flower") if #flowers > 2 and honey < honey_max then inv:add_item("honey", "xdecor:honey") elseif honey == honey_max then local timer = minetest.get_node_timer(pos) timer:stop() return true end return true end xdecor.register("hive", { description = "Artificial Hive", tiles = {"xdecor_hive_top.png", "xdecor_hive_top.png", "xdecor_hive_side.png", "xdecor_hive_side.png", "xdecor_hive_side.png", "xdecor_hive_front.png"}, groups = {choppy=3, oddly_breakable_by_hand=2, flammable=1}, on_construct = hive.construct, on_timer = hive.timer, can_dig = function(pos) local inv = minetest.get_meta(pos):get_inventory() return inv:is_empty("honey") end, on_punch = function(_, _, puncher) puncher:set_hp(puncher:get_hp() - 2) end, allow_metadata_inventory_put = function() return 0 end, on_metadata_inventory_take = function(pos, _, _, stack) if stack:get_count() == honey_max then local timer = minetest.get_node_timer(pos) timer:start(math.random(64, 128)) end end })
lgpl-2.1
ffxiphoenix/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Yassi-Possi.lua
38
1147
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Yassi-Possi -- Type: Item Deliverer -- @zone: 94 -- @pos 153.992 -0.001 -18.687 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, YASSI_POSSI_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
VoxelDavid/echo-ridge
src/StarterPlayer/StarterPlayerScripts/CameraScript.local.lua
1
1172
local players = game:GetService("Players") local run = game:GetService("RunService") local function getTopDownOffset(dist) return Vector3.new(-dist, dist, dist) end local OFFSET = getTopDownOffset(45) local FIELD_OF_VIEW = 25 local client = players.LocalPlayer local camera = workspace.CurrentCamera camera.FieldOfView = FIELD_OF_VIEW local function lookAt(pos) local cameraPos = pos + OFFSET camera.CoordinateFrame = CFrame.new(cameraPos, pos) end local function onRenderStep() local character = client.Character local rootPart = character:FindFirstChild("HumanoidRootPart") if character and rootPart then -- The ROBLOX Wiki describes this as an important property to update, as -- "certain visuals will be more detailed and will update more frequently". -- -- What this means is unclear, or if it even has any effect, but we're -- including this property just in case it makes a difference. -- -- Source: http://wiki.roblox.com/index.php?title=API:Class/Camera/Focus camera.Focus = rootPart.CFrame lookAt(rootPart.Position) end end run:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, onRenderStep)
mit
lxl1140989/sdk-for-tb
feeds/luci/applications/luci-statistics/luasrc/model/cbi/luci_statistics/email.lua
78
1934
--[[ Luci configuration model for statistics - collectd email plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("E-Mail Plugin Configuration"), translate( "The email plugin creates a unix socket which can be used " .. "to transmit email-statistics to a running collectd daemon. " .. "This plugin is primarily intended to be used in conjunction " .. "with Mail::SpamAssasin::Plugin::Collectd but can be used in " .. "other ways as well." )) -- collectd_email config section s = m:section( NamedSection, "collectd_email", "luci_statistics" ) -- collectd_email.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_email.socketfile (SocketFile) socketfile = s:option( Value, "SocketFile", translate("Socket file") ) socketfile.default = "/var/run/collect-email.sock" socketfile:depends( "enable", 1 ) -- collectd_email.socketgroup (SocketGroup) socketgroup = s:option( Value, "SocketGroup", translate("Socket group") ) socketgroup.default = "nobody" socketgroup.rmempty = true socketgroup.optional = true socketgroup:depends( "enable", 1 ) -- collectd_email.socketperms (SocketPerms) socketperms = s:option( Value, "SocketPerms", translate("Socket permissions") ) socketperms.default = "0770" socketperms.rmempty = true socketperms.optional = true socketperms:depends( "enable", 1 ) -- collectd_email.maxconns (MaxConns) maxconns = s:option( Value, "MaxConns", translate("Maximum allowed connections") ) maxconns.default = 5 maxconns.isinteger = true maxconns.rmempty = true maxconns.optional = true maxconns:depends( "enable", 1 ) return m
gpl-2.0
raksoras/luaw
lib/luaw_webapp.lua
4
15028
--[[ Copyright (c) 2015 raksoras 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 luaw_utils_lib = require("luaw_utils") local luaw_http_lib = require("luaw_http") local HTTP_METHODS = { GET = "GET", POST = "POST", PUT = "PUT", DELETE = "DELETE", HEAD = "HEAD", OPTIONS = "OPTIONS", TRACE = "TRACE", CONNECT = "CONNECT", SERVICE = "SERVICE" } local registeredWebApps = {} local DIR_SEPARATOR = string.match (package.config, "[^\n]+") local STRING_PATH_PARAM = { start = string.byte(":"), valueOf = tostring } local NUM_PATH_PARAM = { start = string.byte("#"), valueOf = tonumber } TAB = ' ' local function findFiles(path, pattern, matches) if (path and pattern) then for file in lfs.dir(path) do if (file ~= '.' and file ~= '..') then local f = path..DIR_SEPARATOR..file local attrs = lfs.attributes(f) if attrs then local mode = attrs.mode if mode == 'file' then if (string.match(f, pattern)) then table.insert(matches, f) end elseif mode == 'directory' then findFiles(f, pattern, matches) end end end end end return matches end local pathIterator = luaw_utils_lib.splitter('/') local function splitPath(path) if not path then return luaw_util_lib.nilFn end return pathIterator, path, 0 end local function findAction(method, path) assert(method, "HTTP method may not be nil") assert(method, "HTTP request path may not be nil") local webApp = nil local route = nil local pathParams = {} for idx, pseg in splitPath(path) do -- first iteration only if not webApp then webApp = registeredWebApps[pseg] if not webApp then -- fallback to root path webApp = registeredWebApps['/'] end if not webApp then return nil end route = webApp.root else local nextRoute = route.childRoutes[pseg] if not nextRoute then -- may be it's a path param nextRoute = route.childRoutes["_path_param_"] if nextRoute then pathParams[nextRoute.pathParam] = nextRoute.pathParamType.valueOf(pseg) end end if not nextRoute then return nil end route = nextRoute end end if (route) then local action = route[method] if not action then -- try catch call action as a fallback action = route['SERVICE'] end return webApp, action, pathParams end end local function renderView(req, resp, pathParams, model, view) local isTagOpen = false local indent = 0 local attributes = function(attrs) if attrs then for k,v in pairs(attrs) do resp:appendBody(' ') resp:appendBody(k) resp:appendBody('="') resp:appendBody(tostring(v)) resp:appendBody('"') end end end local BEGIN = function(tag) if (isTagOpen) then resp:appendBody('>\n') end for i=1, indent do resp:appendBody(TAB) end resp:appendBody('<') resp:appendBody(tag) isTagOpen = true; indent = indent+1 return attributes end local END = function(tag) if (isTagOpen) then resp:appendBody('>\n') isTagOpen = false; end indent = indent - 1 if indent > 0 then indent = indent else indent = 0 end for i=1, indent do resp:appendBody(TAB) end resp:appendBody('</') resp:appendBody(tag) resp:appendBody('>\n') end local TEXT = function(...) if (isTagOpen) then resp:appendBody('>\n') isTagOpen = false; end for i=1, indent do resp:appendBody(TAB) end local values = {...} for i,v in ipairs(values) do resp:appendBody(tostring(v)) resp:appendBody(' ') end resp:appendBody('\n') end -- render view if ((req.major_version >= 1)and(req.minor_version >= 1)) then resp:startStreaming() end view(req, resp, pathParams, model, BEGIN, TEXT, END) end local function dispatchAction(req, resp) assert(req, "HTTP request may not be nil") local parsedURL = req.parsedURL if not(req.method and parsedURL) then -- EOF in case of persistent connections return end local webApp, action, pathParams = findAction(req.method, parsedURL.path) assert(action, "No action found for path "..parsedURL.path.." for method "..req.method) if req:shouldCloseConnection() then resp.headers['Connection'] = 'close' else resp.headers['Connection'] = 'Keep-Alive' end v1, v2 = action.handler(req, resp, pathParams) -- handle action returned response, if any and if resp is not closed if v1 and resp.luaw_conn then if (type(v1) == 'number') then -- v1 is HTTP status resp:setStatus(v1) --resp:startStreaming() if v2 then -- v2 is body content resp:appendBody(tostring(v2)) end else if not resp.statusCode then resp:setStatus(200) end --resp:startStreaming() if ((type(v1) == 'string')and(v2)) then -- v1 is view path, v2 is view model local compiledView = webApp.compiledViews[v1] if not compiledView then error("View '"..tostring(v1).."' is not defined") end renderView(req, resp, pathParams, v2, compiledView) else -- v1 is the body content itself resp:appendBody(tostring(v1)) end end end -- flush in case resp is not closed if resp.luaw_conn then resp:flush() end end local function registerResource(resource) local route = assert(webapp.root, "webapp root not defined") local path = assert(resource.path , "Handler definition is missing value for 'path'") local handlerFn = assert(resource.handler, "Handler definition is missing 'handler' function") local method = resource.method or 'SERVICE' if(not HTTP_METHODS[method]) then error(method.." is not a valid HTTP method") end for idx, pseg in splitPath(path) do local firstChar = string.byte(pseg) local pathParam = nil if ((firstChar == STRING_PATH_PARAM.start)or(firstChar == NUM_PATH_PARAM.start)) then pathParam = pseg:sub(2) pseg = "_path_param_" end local nextRoute = route.childRoutes[pseg] if not nextRoute then nextRoute = { childRoutes = {} } if pathParam then nextRoute.pathParam = pathParam if (firstChar == NUM_PATH_PARAM.start) then nextRoute.pathParamType = NUM_PATH_PARAM else nextRoute.pathParamType = STRING_PATH_PARAM end end route.childRoutes[pseg] = nextRoute end route = nextRoute end assert(route, "Could not register handler for path "..path) assert((not route[method]), 'Handler already registered for '..method..' for path "/'..webapp.path..'/'..path..'"') route[method] = {handler = handlerFn} end local function serviceHTTP(conn) conn:startReading() -- loop to support HTTP 1.1 persistent (keep-alive) connections while true do local req = luaw_http_lib.newServerHttpRequest(conn) -- read and parse full request local status, errmesg = pcall(req.readFull, req) if ((not status)or(req.EOF == true)) then conn:close() if (status) then return "read time out" end print("Error: ", errmesg, debug.traceback()) return "connection reset by peer" end local resp = luaw_http_lib.newServerHttpResponse(conn) local status, errMesg = pcall(dispatchAction, req, resp) if (not status) then -- send HTTP error response resp:setStatus(500) resp:addHeader('Connection', 'close') pcall(resp.appendBody, resp, errMesg) pcall(resp.flush, resp) conn:close() error(errMesg) end if (req:shouldCloseConnection() or resp:shouldCloseConnection()) then conn:close() return "connection reset by peer" end end end local function toFullPath(appRoot, files) local fullPaths = {} if files then for i, file in ipairs(files) do table.insert(fullPaths, appRoot..'/'..file) end end return fullPaths end local function loadWebApp(appName, appDir) local app = {} app.path = assert(appName, "Missing mandatory configuration property 'path'") app.appRoot = assert(appDir, "Missing mandatory configuration property 'root_dir'") if (registeredWebApps[app.path]) then error('Anothe web app is already registered for path '..app.path) end registeredWebApps[app.path] = app app.root = { childRoutes = {} } -- Load resource handlers local resources = toFullPath(app.appRoot, luaw_webapp.resources) if luaw_webapp.resourcePattern then resources = findFiles(app.appRoot, luaw_webapp.resourcePattern, resources) end assert((resources and (#resources > 0)), "Either 'resources' or 'resourcePattern' must be specified in a web app configuration") app.resources = resources -- Load view files if any local views = toFullPath(app.appRoot, luaw_webapp.views) if luaw_webapp.viewPattern then views = findFiles(app.appRoot, luaw_webapp.viewPattern, views) end app.views = views return app end local function loadView(viewPath, buff) local firstLine = true local lastLine = false local viewLines = io.lines(viewPath) return function() local line = nil if firstLine then firstLine = false line = "return function(req, resp, pathParams, model, BEGIN, TEXT, END)" else if (not lastLine) then local vl = viewLines() if (not vl) then lastLine = true line = "end" else line = vl end end end if line then table.insert(buff, line) return (line .. '\n') end end end local function startWebApp(app) -- register resources local resources = app.resources for i,resource in ipairs(resources) do luaw_utils_lib.formattedLine(".Loading resource "..resource) -- declare globals (registerHandler and webapp) for the duration of the loadfile(resource) registerHandler = registerResource webapp = app local routeDefn = assert(loadfile(resource), string.format("Could not load resource %s", resource)) routeDefn() end luaw_utils_lib.formattedLine("#Loaded total "..#resources.." resources\n") -- compile views local views = app.views local compiledViews = {} local appRootLen = string.len(app.appRoot) + 1 for i,view in ipairs(views) do local relativeViewPath = string.sub(view, appRootLen) luaw_utils_lib.formattedLine(".Loading view "..relativeViewPath) local viewBuff = {} local viewDefn = loadView(view, viewBuff) local compiledView, errMesg = load(viewDefn, relativeViewPath) if (not compiledView) then luaw_utils_lib.formattedLine("\nError while compiling view: "..view) luaw_utils_lib.formattedLine("<SOURCE>") for i, line in ipairs(viewBuff) do print(tostring(i)..":\t"..tostring(line)) end luaw_utils_lib.formattedLine("<SOURCE>") error(errMesg) end compiledViews[relativeViewPath] = compiledView() end app.views = nil app.compiledViews = compiledViews luaw_utils_lib.formattedLine("#Compiled total "..#views.." views") end local function init() if ((luaw_webapp_config)and(luaw_webapp_config.base_dir)) then local root = luaw_webapp_config.base_dir for webappName in lfs.dir(root) do if (webappName ~= '.' and webappName ~= '..') then local webappDir = root..DIR_SEPARATOR..webappName local attrs = lfs.attributes(webappDir) if ((attrs)and(attrs.mode == 'directory')) then local webappCfgFile = webappDir..DIR_SEPARATOR..'web.lua' if (lfs.attributes(webappCfgFile, 'mode') == 'file') then luaw_utils_lib.formattedLine('Starting webapp '..webappName, 120, '*', '\n') dofile(webappCfgFile) -- defines global variable luaw_webapp local app = loadWebApp(webappName, webappDir) startWebApp(app) luaw_utils_lib.formattedLine('Webapp '..webappName..' started', 120, '*') webapp = nil -- reset global variable end end end end end end -- install REST HTTP app handler as a default request handler luaw_http_lib.request_handler = serviceHTTP return { init = init, dispatchAction = dispatchAction, serviceHTTP = serviceHTTP }
mit
ffxiphoenix/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Icon_Prototype.lua
16
1390
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: Icon Prototype ----------------------------------- package.loaded["scripts/zones/Dynamis-Xarcabard/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob,target) end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); -- Time Bonus: 043 if (mobID == 17330814 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(30); mob:addInBattlefieldList(); -- HP Bonus: 052 elseif (mobID == 17330533) then killer:restoreHP(2000); killer:messageBasic(024,(killer:getMaxHP()-killer:getHP())); -- HP Bonus: 073 elseif (mobID == 17330843) then killer:restoreMP(2000); killer:messageBasic(025,(killer:getMaxMP()-killer:getMP())); end end;
gpl-3.0
dail8859/ScintilluaPlusPlus
ext/scintillua/lexers/apl.lua
5
1682
-- Copyright 2015-2017 David B. Lamkins <david@lamkins.net>. See LICENSE. -- APL LPeg lexer. local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local M = {_NAME = 'apl'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local comment = token(l.COMMENT, (P('⍝') + P('#')) * l.nonnewline^0) -- Strings. local sq_str = l.delimited_range("'", false, true) local dq_str = l.delimited_range('"') local string = token(l.STRING, sq_str + dq_str) -- Numbers. local dig = R('09') local rad = P('.') local exp = S('eE') local img = S('jJ') local sgn = P('¯')^-1 local float = sgn * (dig^0 * rad * dig^1 + dig^1 * rad * dig^0 + dig^1) * (exp * sgn *dig^1)^-1 local number = token(l.NUMBER, float * img * float + float) -- Keywords. local keyword = token(l.KEYWORD, P('⍞') + P('χ') + P('⍺') + P('⍶') + P('⍵') + P('⍹') + P('⎕') * R('AZ', 'az')^0) -- Names. local n1l = R('AZ', 'az') local n1b = P('_') + P('∆') + P('⍙') local n2l = n1l + R('09') local n2b = n1b + P('¯') local n1 = n1l + n1b local n2 = n2l + n2b local name = n1 * n2^0 -- Labels. local label = token(l.LABEL, name * P(':')) -- Variables. local variable = token(l.VARIABLE, name) -- Special. local special = token(l.TYPE, S('{}[]();') + P('←') + P('→') + P('◊')) -- Nabla. local nabla = token(l.PREPROCESSOR, P('∇') + P('⍫')) M._rules = { {'whitespace', ws}, {'comment', comment}, {'string', string}, {'number', number}, {'keyword', keyword}, {'label', label}, {'variable', variable}, {'special', special}, {'nabla', nabla}, } return M
gpl-2.0
iskolbin/ldiff
diff.lua
1
4469
local EvalOp, DiffOp, DiffFun local function diff( var, expr ) if type( expr ) == 'table' then if DiffOp[expr[1]] then return DiffOp[expr[1]]( var, expr[2], expr[3] ) elseif DiffFun[expr[1]] then return {'*', diff( var, expr[2] ), DiffFun[expr[1]]( expr[2] )} else error( tostring( expr[1] ) .. ' not registred as operator or function' ) end elseif expr == var then return 1 else return 0 end end local function compile( expr ) if type( expr ) == 'table' then if DiffOp[expr[1]] then return '(' .. compile( expr[2] ) .. expr[1] .. compile( expr[3] ) .. ')' elseif DiffFun[expr[1]] then return expr[1] .. '(' .. compile( expr[2] ) .. ')' else error( tostring( expr[1] ) .. ' not registred as operator or function' ) end elseif tonumber( expr ) then return tostring( expr ) else return expr end end local function equal( a, b ) if a == b then return true else local t1, t2 = type( a ), type( b ) if t1 == t2 and t1 == 'table' then local n = #a if n == #b then for i = 1, n do if a[i] ~= b[i] then return false end end return true else return false end else return false end end end local function simplify( expr ) if type( expr ) == 'table' then local op = expr[1] if EvalOp[op] then local arg1, arg2 = simplify( expr[2] ), simplify( expr[3] ) if tonumber( arg1 ) and tonumber( arg2 ) then return EvalOp[op]( arg1, arg2 ) elseif op == '*' then if tonumber(arg1) == 0 or tonumber(arg2) == 0 then return 0 elseif tonumber(arg1) == 1 then return arg2 elseif tonumber(arg2) == 1 then return arg1 elseif type( arg2 ) == 'table' and arg2[1] == '/' and tonumber(arg2[2]) == 1 then return simplify{'/', arg1, arg2[3]} elseif type( arg1 ) == 'table' and arg1[1] == '/' and tonumber(arg1[2]) == 1 then return simplify{'/', arg2, arg1[3]} end elseif op == '+' then if tonumber(arg1) == 0 then return arg2 elseif tonumber(arg2) == 0 then return arg1 end elseif op == '/' then if tonumber(arg1) == 0 then return 0 elseif equal( arg1, arg2 ) then return 1 elseif tonumber(arg2) == 1 then return arg1 end elseif op == '-' then if tonumber(arg2) == 0 then return arg1 elseif equal(arg1,arg2) then return 0 end elseif op == '^' then if tonumber(arg1) == 0 then return 0 elseif tonumber(arg1) == 1 or tonumber(arg2) == 0 then return 1 elseif tonumber(arg2) == 1 then return arg1 end end return {op, arg1, arg2} end end return expr end local Predefined = [[ local sin,cos,tan,arcsin,arccos,arctan,ln = math.sin,math.cos,math.tan,math.asin,math.acos,math.atan,math.log local function cot( x ) return 1 / tan( x ) end local function arccot( x ) return atan( 1/ x ) end ]] local function collect( expr, vars ) return assert( load( Predefined .. 'return function(' .. table.concat( vars or {},',' ) .. ') return ' .. compile( simplify( expr )) .. ' end' ))() end DiffFun = { sin = function( x ) return {'cos', x} end, cos = function( x ) return {'sin', x} end, tan = function( x ) return {'+', {'^', {'cos', x}, 2}, 1} end, cot = function( x ) return {'+', {'^', {'sin', x}, 2}, 1} end, arcsin = function( x ) return {'/', 1, {'^', {'-', 1, {'^', x, 2}}, {'/', 1, 2}}} end, arccos = function( x ) return {'/',-1, {'^', {'-', 1, {'^', x, 2}}, {'/', 1, 2}}} end, arctan = function( x ) return {'/', 1, {'+', 1, {'^', x, 2}}} end, arccot = function( x ) return {'/',-1, {'+', 1, {'^', x, 2}}} end, ln = function( x ) return {'/', 1, x } end, } EvalOp = { ['+'] = function( u, v ) return u + v end, ['-'] = function( u, v ) return u - v end, ['*'] = function( u, v ) return u * v end, ['/'] = function( u, v ) return u / v end, ['^'] = function( u, v ) return u ^ v end, } DiffOp = { ['+'] = function( var, u, v ) return {'+', diff( var, u ), diff( var, v )} end, ['-'] = function( var, u, v ) return {'-', diff( var, u ), diff( var, v )} end, ['*'] = function( var, u, v ) return {'+', {'*', diff( var, u ), v}, {'*', u, diff( var, v )}} end, ['/'] = function( var, u, v ) return {'/', {'-',{'*', diff( var, u ), v}, {'*', u, diff( var, v )}}, {'*', v, v}} end, ['^'] = function( var, u, v ) return {'*',{'^', u, v}, diff(var, {'*',{'ln',u}, v} )} end, } return { diff = diff, simplify = simplify, compile = compile, collect = collect, }
mit
vilarion/Illarion-Content
triggerfield/galmair_bridges_660.lua
2
7563
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO triggerfields VALUES (498,201,0,'triggerfield.galmair_bridges2_660'); -- INSERT INTO triggerfields VALUES (497,201,0,'triggerfield.galmair_bridges2_660'); -- INSERT INTO triggerfields VALUES (496,207,0,'triggerfield.galmair_bridges2_660'); local common = require("base.common") local factions = require("base.factions") local deathaftertime = require("lte.deathaftertime") local longterm_cooldown = require("lte.longterm_cooldown") local character = require("base.character") local M = {} local monster = {} ---monster, numbers are archers -> excluded currently monster[1]={1,2,3,4,5}; --human monster[2]={11,12,13,14}; --dwarf 15 monster[3]={21,22,23,24}; --halfling 25 monster[4]={31,32,33,34}; --elf 35 monster[5]={41,42,43,45}; --orc 44 monster[6]={51,52,53,54,55}; -- lizard monster[7]={91,92,93,95,791,792}; -- troll 94,802,795,796 monster[8]={101,102,103,104,106,151,152,171,172,173}; -- mummy monster[9]={111,112,113,114,115}; --skeleton monster[10]={573,574,576,577,578}; --rats 575 monster[11]={891,892,893,901,902,903}; --Imp monster[12]={782,783}; --golden skeleton 784 monster[13]={301,303,304,305,306}; --golem monster[14]={851,852,853,861,862,863,871,872,873,881,882,883}; --hellhound monster[15]={62,63,64,65,66}; -- drow 61,65 monster[16]={201,202,203,204}; --demon skeleton 205 local shutup local luckybunch function M.setAmbush(ambushName, ambushState) if ambushState ~= true then ambushState = false end ScriptVars:set(ambushName,tostring(ambushState)) ScriptVars:save() end function M.isAmbush(ambushName) local foundValue, value = ScriptVars:find(ambushName) if value == "true" then return true else return false end end function M.setLastAmbush(ambushName) local currentTime = common.GetCurrentTimestamp() local scriptVar = ambushName.."Last" ScriptVars:set(scriptVar,tostring(currentTime)) ScriptVars:save() end function M.getTimeSinceLastAmbush(ambushName) local currentTime = common.GetCurrentTimestamp() local scriptVar = ambushName.."Last" local foundValue, value = ScriptVars:find(scriptVar) local lastTime = tonumber(value) if common.IsNilOrEmpty(lastTime) then lastTime = 0 end return currentTime - lastTime end function M.triggerAmbush(char, monsterPositions) if char:getType() ~= Character.player then --Monsters will be ingored return false end if char:getQuestProgress(660) ~= 0 then --lte check return false end local chance if factions.getMembership(char) == 3 then --set chance for Galmairians and non-Galmairians chance = 20 else chance = 5 end local fighter = false if (char:getSkill(Character.punctureWeapons)>=40) or (char:getSkill(Character.distanceWeapons)>=40) or (char:getSkill(Character.slashingWeapons)>=40) or (char:getSkill(Character.concussionWeapons)>=40) or (char:getSkill(Character.wrestling)>=40) then --check if we have a fighter fighter = true end if math.random(1,100)< chance and char:increaseAttrib("hitpoints",0)>8000 then --Chance of 1% and Hitpoints above 8000 if factions.getMembership(char) ~= 3 and (char:getSkill(Character.parry)<=30) or factions.getMembership(char) ~= 3 and not fighter then --Newbie and non-fighter protection for non-Galmairian return false end local level if (char:getSkill(Character.parry)<=80) then --check of skills of fighter level = math.random(1,11) --selection of lower monsters for average fighter else level = math.random(1,16) --selection of all monsters for good fighter end local enemy for i=1, #monsterPositions do enemy = monster[level][math.random(1,#monster[level])] world:gfx(41,monsterPositions[i]) world:createMonster(enemy,monsterPositions[i],0); end char:inform("Oh nein, ein Hinterhalt!", "Oh no, an ambush!") --message for player char:setQuestProgress(660,math.random(300,600)) --lte set return true else return false end end function M.fightAmbush(char) local luckybunch = false local hero = world:getPlayersInRangeOf(char.pos, 20); --lets see if there is a player around for i,player in ipairs(hero) do if factions.getMembership(player) == 3 then --check if galmairians are there luckybunch = true --if non-galmairians are together with galmairians end end if luckybunch then local monsters = world:getMonstersInRangeOf(char.pos, 35); --get all monster in player range for i,mon in ipairs(monsters) do character.DeathAfterTime(mon,math.random(5,10),0,33,true) --kill all monsters end end for i,player in ipairs(hero) do if factions.getMembership(player) == 3 then --check if galmairians are there player:inform("Bevor du auch noch reagieren kannst, schießen Pfeile an dir vorbei und töten deine Widersacher. Du blickst in die Richtung von wo die Pfeile kamen und siehst die Wachen von Galmair dir mit ihren Armbrüsten zuwinken. Gut, dass du dem Don deine Steuern zahlst und er dich beschützt!","Even before you are able to react, arrows shoot around you and take down your enemies. You look to the direction the arrows originated from and see guards of Galmair waving to you with their crossbows. Good, you have paid your taxes to the Don and he protects you!") --praise the don message for the player elseif luckybunch then -- glamairians are here...lucky you player:inform("Bevor du auch noch reagieren kannst, schießen Pfeile an dir vorbei und töten deine Widersacher. Du blickst in die Richtung von wo die Pfeile kamen und siehst die Wachen von Galmair euch mit ihren Armbrüsten zuwinken. Gut, dass du jemanden dabei hattest, der dem Don Steuern zahlst und daher beschützt wird vom Don!", "Even before you are able to react, arrows shoot around you and take down your enemies. You look to the direction the arrows originated from and see guards of Galmair waving to you with their crossbows. Good, you have someone with you who has paid taxes to the Don and is thus protected by the Don!") --wäähh wrong faction but together with friends message for the player else -- no galmairians are here...bad luck player:inform("Du wirfst einen Blick zurück zur Stadt von Galmair und siehst die Wachen dort wie sie dich und dein Schicksal beobachten. Was, wenn du nur dem Don deine Steuern zahlen würdest?", "You look back to the town of Galmair and see guards watching your fate. What if you had only paid your taxes to the Don?") --wäähh wrong faction message for the player end player:setQuestProgress(660,math.random(300,600)) --lte set for all players around end end return M
agpl-3.0
veryrandomname/obuut
hump/vector.lua
12
5276
--[[ Copyright (c) 2010-2013 Matthias Richter 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. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. 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 assert = assert local sqrt, cos, sin, atan2 = math.sqrt, math.cos, math.sin, math.atan2 local vector = {} vector.__index = vector local function new(x,y) return setmetatable({x = x or 0, y = y or 0}, vector) end local zero = new(0,0) local function isvector(v) return getmetatable(v) == vector end function vector:clone() return new(self.x, self.y) end function vector:unpack() return self.x, self.y end function vector:__tostring() return "("..tonumber(self.x)..","..tonumber(self.y)..")" end function vector.__unm(a) return new(-a.x, -a.y) end function vector.__add(a,b) assert(isvector(a) and isvector(b), "Add: wrong argument types (<vector> expected)") return new(a.x+b.x, a.y+b.y) end function vector.__sub(a,b) assert(isvector(a) and isvector(b), "Sub: wrong argument types (<vector> expected)") return new(a.x-b.x, a.y-b.y) end function vector.__mul(a,b) if type(a) == "number" then return new(a*b.x, a*b.y) elseif type(b) == "number" then return new(b*a.x, b*a.y) else assert(isvector(a) and isvector(b), "Mul: wrong argument types (<vector> or <number> expected)") return a.x*b.x + a.y*b.y end end function vector.__div(a,b) assert(isvector(a) and type(b) == "number", "wrong argument types (expected <vector> / <number>)") return new(a.x / b, a.y / b) end function vector.__eq(a,b) return a.x == b.x and a.y == b.y end function vector.__lt(a,b) return a.x < b.x or (a.x == b.x and a.y < b.y) end function vector.__le(a,b) return a.x <= b.x and a.y <= b.y end function vector.permul(a,b) assert(isvector(a) and isvector(b), "permul: wrong argument types (<vector> expected)") return new(a.x*b.x, a.y*b.y) end function vector:len2() return self.x * self.x + self.y * self.y end function vector:len() return sqrt(self.x * self.x + self.y * self.y) end function vector.dist(a, b) assert(isvector(a) and isvector(b), "dist: wrong argument types (<vector> expected)") local dx = a.x - b.x local dy = a.y - b.y return sqrt(dx * dx + dy * dy) end function vector.dist2(a, b) assert(isvector(a) and isvector(b), "dist: wrong argument types (<vector> expected)") local dx = a.x - b.x local dy = a.y - b.y return (dx * dx + dy * dy) end function vector:normalize_inplace() local l = self:len() if l > 0 then self.x, self.y = self.x / l, self.y / l end return self end function vector:normalized() return self:clone():normalize_inplace() end function vector:rotate_inplace(phi) local c, s = cos(phi), sin(phi) self.x, self.y = c * self.x - s * self.y, s * self.x + c * self.y return self end function vector:rotated(phi) local c, s = cos(phi), sin(phi) return new(c * self.x - s * self.y, s * self.x + c * self.y) end function vector:perpendicular() return new(-self.y, self.x) end function vector:projectOn(v) assert(isvector(v), "invalid argument: cannot project vector on " .. type(v)) -- (self * v) * v / v:len2() local s = (self.x * v.x + self.y * v.y) / (v.x * v.x + v.y * v.y) return new(s * v.x, s * v.y) end function vector:mirrorOn(v) assert(isvector(v), "invalid argument: cannot mirror vector on " .. type(v)) -- 2 * self:projectOn(v) - self local s = 2 * (self.x * v.x + self.y * v.y) / (v.x * v.x + v.y * v.y) return new(s * v.x - self.x, s * v.y - self.y) end function vector:cross(v) assert(isvector(v), "cross: wrong argument types (<vector> expected)") return self.x * v.y - self.y * v.x end -- ref.: http://blog.signalsondisplay.com/?p=336 function vector:trim_inplace(maxLen) local s = maxLen * maxLen / self:len2() s = s < 1 and 1 or math.sqrt(s) self.x, self.y = self.x * s, self.y * s return self end function vector:angleTo(other) if other then return atan2(self.y, self.y) - atan2(other.y, other.x) end return atan2(self.y, self.y) end function vector:trimmed(maxLen) return self:clone():trim_inplace(maxLen) end -- the module return setmetatable({new = new, isvector = isvector, zero = zero}, {__call = function(_, ...) return new(...) end})
mit
ffxiphoenix/darkstar
scripts/zones/Windurst_Waters/npcs/Qhum_Knaidjn.lua
17
2806
----------------------------------- -- Area: Windurst Waters -- NPC: Qhum_Knaidjn -- Type: Guildworker's Union Representative -- @zone: 238 -- @pos -112.561 -2 55.205 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; require("scripts/globals/keyitems"); require("scripts/globals/crafting"); require("scripts/zones/Windurst_Waters/TextIDs"); local keyitems = { [0] = { id = RAW_FISH_HANDLING, rank = 3, cost = 30000 }, [1] = { id = NOODLE_KNEADING, rank = 3, cost = 30000 }, [2] = { id = PATISSIER, rank = 3, cost = 8000 }, [3] = { id = STEWPOT_MASTERY, rank = 3, cost = 30000 }, [4] = { id = WAY_OF_THE_CULINARIAN, rank = 9, cost = 20000 } }; local items = { [2] = { id = 15451, -- Culinarian's Belt rank = 4, cost = 10000 }, [3] = { id = 13948, -- Chef's Hat rank = 5, cost = 70000 }, [4] = { id = 14399, -- Culinarian's Apron rank = 7, cost = 100000 }, [5] = { id = 137, -- Cordon Bleu Cooking Set rank = 9, cost = 150000 }, [6] = { id = 338, -- Culinarian's Signboard rank = 9, cost = 200000 }, [7] = { id = 15826, -- Chef's Ring rank = 6, cost = 80000 }, [8] = { id = 3667, -- Brass Crock rank = 7, cost = 50000 }, [9] = { id = 3328, -- Culinarian's Emblem rank = 9, cost = 15000 } }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) unionRepresentativeTrade(player, npc, trade, 0x2729, 8); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) unionRepresentativeTrigger(player, 8, 0x2728, "guild_cooking", keyitems); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,target) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x2728) then unionRepresentativeTriggerFinish(player, option, target, 8, "guild_cooking", keyitems, items); elseif (csid == 0x2729) then player:messageSpecial(GP_OBTAINED, option); end end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Metalworks/npcs/HomePoint#2.lua
19
1185
----------------------------------- -- Area: Metalworks -- NPC: HomePoint#2 -- @pos: -78 2 2 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Metalworks/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fd, 102); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fd) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
Ne02ptzero/Grog-Knight
Tools/BuildScripts/lua-lib/penlight-1.0.2/lua/pl/input.lua
13
5031
--- Iterators for extracting words or numbers from an input source. -- -- require 'pl' -- local total,n = seq.sum(input.numbers()) -- print('average',total/n) -- -- See @{06-data.md.Reading_Unstructured_Text_Data|here} -- -- Dependencies: `pl.utils` -- @module pl.input local strfind = string.find local strsub = string.sub local strmatch = string.match local utils = require 'pl.utils' local pairs,type,unpack,tonumber = pairs,type,unpack or table.unpack,tonumber local patterns = utils.patterns local io = io local assert_arg = utils.assert_arg --[[ module ('pl.input',utils._module) ]] local input = {} --- create an iterator over all tokens. -- based on allwords from PiL, 7.1 -- @param getter any function that returns a line of text -- @param pattern -- @param fn Optionally can pass a function to process each token as it/s found. -- @return an iterator function input.alltokens (getter,pattern,fn) local line = getter() -- current line local pos = 1 -- current position in the line return function () -- iterator function while line do -- repeat while there are lines local s, e = strfind(line, pattern, pos) if s then -- found a word? pos = e + 1 -- next position is after this token local res = strsub(line, s, e) -- return the token if fn then res = fn(res) end return res else line = getter() -- token not found; try next line pos = 1 -- restart from first position end end return nil -- no more lines: end of traversal end end local alltokens = input.alltokens -- question: shd this _split_ a string containing line feeds? --- create a function which grabs the next value from a source. If the source is a string, then the getter -- will return the string and thereafter return nil. If not specified then the source is assumed to be stdin. -- @param f a string or a file-like object (i.e. has a read() method which returns the next line) -- @return a getter function function input.create_getter(f) if f then if type(f) == 'string' then local ls = utils.split(f,'\n') local i,n = 0,#ls return function() i = i + 1 if i > n then return nil end return ls[i] end else -- anything that supports the read() method! if not f.read then error('not a file-like object') end return function() return f:read() end end else return io.read -- i.e. just read from stdin end end --- generate a sequence of numbers from a source. -- @param f A source -- @return An iterator function input.numbers(f) return alltokens(input.create_getter(f), '('..patterns.FLOAT..')',tonumber) end --- generate a sequence of words from a source. -- @param f A source -- @return An iterator function input.words(f) return alltokens(input.create_getter(f),"%w+") end local function apply_tonumber (no_fail,...) local args = {...} for i = 1,#args do local n = tonumber(args[i]) if n == nil then if not no_fail then return nil,args[i] end else args[i] = n end end return args end --- parse an input source into fields. -- By default, will fail if it cannot convert a field to a number. -- @param ids a list of field indices, or a maximum field index -- @param delim delimiter to parse fields (default space) -- @param f a source @see create_getter -- @param opts option table, {no_fail=true} -- @return an iterator with the field values -- @usage for x,y in fields {2,3} do print(x,y) end -- 2nd and 3rd fields from stdin function input.fields (ids,delim,f,opts) local sep local s local getter = input.create_getter(f) local no_fail = opts and opts.no_fail local no_convert = opts and opts.no_convert if not delim or delim == ' ' then delim = '%s' sep = '%s+' s = '%s*' else sep = delim s = '' end local max_id = 0 if type(ids) == 'table' then for i,id in pairs(ids) do if id > max_id then max_id = id end end else max_id = ids ids = {} for i = 1,max_id do ids[#ids+1] = i end end local pat = '[^'..delim..']*' local k = 1 for i = 1,max_id do if ids[k] == i then k = k + 1 s = s..'('..pat..')' else s = s..pat end if i < max_id then s = s..sep end end local linecount = 1 return function() local line,results,err repeat line = getter() linecount = linecount + 1 if not line then return nil end if no_convert then results = {strmatch(line,s)} else results,err = apply_tonumber(no_fail,strmatch(line,s)) if not results then utils.quit("line "..(linecount-1)..": cannot convert '"..err.."' to number") end end until #results > 0 return unpack(results) end end return input
apache-2.0
dail8859/ScintilluaPlusPlus
ext/scintillua/lexers/perl.lua
3
6833
-- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE. -- Perl LPeg lexer. local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S, V = lpeg.P, lpeg.R, lpeg.S, lpeg.V local M = {_NAME = 'perl'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local line_comment = '#' * l.nonnewline_esc^0 local block_comment = l.starts_line('=') * l.alpha * (l.any - l.newline * '=cut')^0 * (l.newline * '=cut')^-1 local comment = token(l.COMMENT, block_comment + line_comment) local delimiter_matches = {['('] = ')', ['['] = ']', ['{'] = '}', ['<'] = '>'} local literal_delimitted = P(function(input, index) -- for single delimiter sets local delimiter = input:sub(index, index) if not delimiter:find('%w') then -- only non alpha-numerics local match_pos, patt if delimiter_matches[delimiter] then -- Handle nested delimiter/matches in strings. local s, e = delimiter, delimiter_matches[delimiter] patt = l.delimited_range(s..e, false, false, true) else patt = l.delimited_range(delimiter) end match_pos = lpeg.match(patt, input, index) return match_pos or #input + 1 end end) local literal_delimitted2 = P(function(input, index) -- for 2 delimiter sets local delimiter = input:sub(index, index) -- Only consider non-alpha-numerics and non-spaces as delimiters. The -- non-spaces are used to ignore operators like "-s". if not delimiter:find('[%w ]') then local match_pos, patt if delimiter_matches[delimiter] then -- Handle nested delimiter/matches in strings. local s, e = delimiter, delimiter_matches[delimiter] patt = l.delimited_range(s..e, false, false, true) else patt = l.delimited_range(delimiter) end first_match_pos = lpeg.match(patt, input, index) final_match_pos = lpeg.match(patt, input, first_match_pos - 1) if not final_match_pos then -- using (), [], {}, or <> notation final_match_pos = lpeg.match(l.space^0 * patt, input, first_match_pos) end return final_match_pos or #input + 1 end end) -- Strings. local sq_str = l.delimited_range("'") local dq_str = l.delimited_range('"') local cmd_str = l.delimited_range('`') local heredoc = '<<' * P(function(input, index) local s, e, delimiter = input:find('([%a_][%w_]*)[\n\r\f;]+', index) if s == index and delimiter then local end_heredoc = '[\n\r\f]+' local _, e = input:find(end_heredoc..delimiter, e) return e and e + 1 or #input + 1 end end) local lit_str = 'q' * P('q')^-1 * literal_delimitted local lit_array = 'qw' * literal_delimitted local lit_cmd = 'qx' * literal_delimitted local lit_tr = (P('tr') + 'y') * literal_delimitted2 * S('cds')^0 local regex_str = #P('/') * l.last_char_includes('-<>+*!~\\=%&|^?:;([{') * l.delimited_range('/', true) * S('imosx')^0 local lit_regex = 'qr' * literal_delimitted * S('imosx')^0 local lit_match = 'm' * literal_delimitted * S('cgimosx')^0 local lit_sub = 's' * literal_delimitted2 * S('ecgimosx')^0 local string = token(l.STRING, sq_str + dq_str + cmd_str + heredoc + lit_str + lit_array + lit_cmd + lit_tr) + token(l.REGEX, regex_str + lit_regex + lit_match + lit_sub) -- Numbers. local number = token(l.NUMBER, l.float + l.integer) -- Keywords. local keyword = token(l.KEYWORD, word_match{ 'STDIN', 'STDOUT', 'STDERR', 'BEGIN', 'END', 'CHECK', 'INIT', 'require', 'use', 'break', 'continue', 'do', 'each', 'else', 'elsif', 'foreach', 'for', 'if', 'last', 'local', 'my', 'next', 'our', 'package', 'return', 'sub', 'unless', 'until', 'while', '__FILE__', '__LINE__', '__PACKAGE__', 'and', 'or', 'not', 'eq', 'ne', 'lt', 'gt', 'le', 'ge' }) -- Functions. local func = token(l.FUNCTION, word_match({ 'abs', 'accept', 'alarm', 'atan2', 'bind', 'binmode', 'bless', 'caller', 'chdir', 'chmod', 'chomp', 'chop', 'chown', 'chr', 'chroot', 'closedir', 'close', 'connect', 'cos', 'crypt', 'dbmclose', 'dbmopen', 'defined', 'delete', 'die', 'dump', 'each', 'endgrent', 'endhostent', 'endnetent', 'endprotoent', 'endpwent', 'endservent', 'eof', 'eval', 'exec', 'exists', 'exit', 'exp', 'fcntl', 'fileno', 'flock', 'fork', 'format', 'formline', 'getc', 'getgrent', 'getgrgid', 'getgrnam', 'gethostbyaddr', 'gethostbyname', 'gethostent', 'getlogin', 'getnetbyaddr', 'getnetbyname', 'getnetent', 'getpeername', 'getpgrp', 'getppid', 'getpriority', 'getprotobyname', 'getprotobynumber', 'getprotoent', 'getpwent', 'getpwnam', 'getpwuid', 'getservbyname', 'getservbyport', 'getservent', 'getsockname', 'getsockopt', 'glob', 'gmtime', 'goto', 'grep', 'hex', 'import', 'index', 'int', 'ioctl', 'join', 'keys', 'kill', 'lcfirst', 'lc', 'length', 'link', 'listen', 'localtime', 'log', 'lstat', 'map', 'mkdir', 'msgctl', 'msgget', 'msgrcv', 'msgsnd', 'new', 'oct', 'opendir', 'open', 'ord', 'pack', 'pipe', 'pop', 'pos', 'printf', 'print', 'prototype', 'push', 'quotemeta', 'rand', 'readdir', 'read', 'readlink', 'recv', 'redo', 'ref', 'rename', 'reset', 'reverse', 'rewinddir', 'rindex', 'rmdir', 'scalar', 'seekdir', 'seek', 'select', 'semctl', 'semget', 'semop', 'send', 'setgrent', 'sethostent', 'setnetent', 'setpgrp', 'setpriority', 'setprotoent', 'setpwent', 'setservent', 'setsockopt', 'shift', 'shmctl', 'shmget', 'shmread', 'shmwrite', 'shutdown', 'sin', 'sleep', 'socket', 'socketpair', 'sort', 'splice', 'split', 'sprintf', 'sqrt', 'srand', 'stat', 'study', 'substr', 'symlink', 'syscall', 'sysread', 'sysseek', 'system', 'syswrite', 'telldir', 'tell', 'tied', 'tie', 'time', 'times', 'truncate', 'ucfirst', 'uc', 'umask', 'undef', 'unlink', 'unpack', 'unshift', 'untie', 'utime', 'values', 'vec', 'wait', 'waitpid', 'wantarray', 'warn', 'write' }, '2')) -- Identifiers. local identifier = token(l.IDENTIFIER, l.word) -- Variables. local special_var = '$' * ('^' * S('ADEFHILMOPSTWX')^-1 + S('\\"[]\'&`+*.,;=%~?@<>(|/!-') + ':' * (l.any - ':') + P('$') * -l.word + l.digit^1) local plain_var = ('$#' + S('$@%')) * P('$')^0 * l.word + '$#' local variable = token(l.VARIABLE, special_var + plain_var) -- Operators. local operator = token(l.OPERATOR, S('-<>+*!~\\=/%&|^.?:;()[]{}')) -- Markers. local marker = token(l.COMMENT, word_match{'__DATA__', '__END__'} * l.any^0) M._rules = { {'whitespace', ws}, {'keyword', keyword}, {'marker', marker}, {'function', func}, {'string', string}, {'identifier', identifier}, {'comment', comment}, {'number', number}, {'variable', variable}, {'operator', operator}, } M._foldsymbols = { _patterns = {'[%[%]{}]', '#'}, [l.OPERATOR] = {['['] = 1, [']'] = -1, ['{'] = 1, ['}'] = -1}, [l.COMMENT] = {['#'] = l.fold_line_comments('#')} } return M
gpl-2.0
ffxiphoenix/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Tafeesa.lua
34
1032
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Tafeesa -- 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(0x028F); 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
shayanchabok555/newbot_shayan
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
AfuSensi/Mr.Green-MTA-Resources
resources/[gameplay]/freecam/freecam.lua
4
9416
-- state variables local speed = 0 local strafespeed = 0 local rotX, rotY = 0,0 local velocityX, velocityY, velocityZ -- configurable parameters local options = { invertMouseLook = false, normalMaxSpeed = 2, slowMaxSpeed = 0.2, fastMaxSpeed = 12, smoothMovement = true, acceleration = 0.3, decceleration = 0.15, mouseSensitivity = 0.3, maxYAngle = 188, key_fastMove = "lshift", key_slowMove = "lalt", key_forward = "w", key_backward = "s", key_left = "a", key_right = "d" } local mouseFrameDelay = 0 local rootElement = getRootElement() local getKeyState = getKeyState do local mta_getKeyState = getKeyState function getKeyState(key) if isMTAWindowActive() then return false else return mta_getKeyState(key) end end end -- PRIVATE local function freecamFrame () -- work out an angle in radians based on the number of pixels the cursor has moved (ever) local cameraAngleX = rotX local cameraAngleY = rotY local freeModeAngleZ = math.sin(cameraAngleY) local freeModeAngleY = math.cos(cameraAngleY) * math.cos(cameraAngleX) local freeModeAngleX = math.cos(cameraAngleY) * math.sin(cameraAngleX) local camPosX, camPosY, camPosZ = getCameraMatrix() -- calculate a target based on the current position and an offset based on the angle local camTargetX = camPosX + freeModeAngleX * 100 local camTargetY = camPosY + freeModeAngleY * 100 local camTargetZ = camPosZ + freeModeAngleZ * 100 -- Calculate what the maximum speed that the camera should be able to move at. local mspeed = options.normalMaxSpeed if getKeyState ( options.key_fastMove ) then mspeed = options.fastMaxSpeed elseif getKeyState ( options.key_slowMove ) then mspeed = options.slowMaxSpeed end if options.smoothMovement then local acceleration = options.acceleration local decceleration = options.decceleration -- Check to see if the forwards/backwards keys are pressed local speedKeyPressed = false if getKeyState ( options.key_forward ) then speed = speed + acceleration speedKeyPressed = true end if getKeyState ( options.key_backward ) then speed = speed - acceleration speedKeyPressed = true end -- Check to see if the strafe keys are pressed local strafeSpeedKeyPressed = false if getKeyState ( options.key_right ) then if strafespeed > 0 then -- for instance response strafespeed = 0 end strafespeed = strafespeed - acceleration / 2 strafeSpeedKeyPressed = true end if getKeyState ( options.key_left ) then if strafespeed < 0 then -- for instance response strafespeed = 0 end strafespeed = strafespeed + acceleration / 2 strafeSpeedKeyPressed = true end -- If no forwards/backwards keys were pressed, then gradually slow down the movement towards 0 if speedKeyPressed ~= true then if speed > 0 then speed = speed - decceleration elseif speed < 0 then speed = speed + decceleration end end -- If no strafe keys were pressed, then gradually slow down the movement towards 0 if strafeSpeedKeyPressed ~= true then if strafespeed > 0 then strafespeed = strafespeed - decceleration elseif strafespeed < 0 then strafespeed = strafespeed + decceleration end end -- Check the ranges of values - set the speed to 0 if its very close to 0 (stops jittering), and limit to the maximum speed if speed > -decceleration and speed < decceleration then speed = 0 elseif speed > mspeed then speed = mspeed elseif speed < -mspeed then speed = -mspeed end if strafespeed > -(acceleration / 2) and strafespeed < (acceleration / 2) then strafespeed = 0 elseif strafespeed > mspeed then strafespeed = mspeed elseif strafespeed < -mspeed then strafespeed = -mspeed end else speed = 0 strafespeed = 0 if getKeyState ( options.key_forward ) then speed = mspeed end if getKeyState ( options.key_backward ) then speed = -mspeed end if getKeyState ( options.key_left ) then strafespeed = mspeed end if getKeyState ( options.key_right ) then strafespeed = -mspeed end end -- Work out the distance between the target and the camera (should be 100 units) local camAngleX = camPosX - camTargetX local camAngleY = camPosY - camTargetY local camAngleZ = 0 -- we ignore this otherwise our vertical angle affects how fast you can strafe -- Calulcate the length of the vector local angleLength = math.sqrt(camAngleX*camAngleX+camAngleY*camAngleY+camAngleZ*camAngleZ) -- Normalize the vector, ignoring the Z axis, as the camera is stuck to the XY plane (it can't roll) local camNormalizedAngleX = camAngleX / angleLength local camNormalizedAngleY = camAngleY / angleLength local camNormalizedAngleZ = 0 -- We use this as our rotation vector local normalAngleX = 0 local normalAngleY = 0 local normalAngleZ = 1 -- Perform a cross product with the rotation vector and the normalzied angle local normalX = (camNormalizedAngleY * normalAngleZ - camNormalizedAngleZ * normalAngleY) local normalY = (camNormalizedAngleZ * normalAngleX - camNormalizedAngleX * normalAngleZ) local normalZ = (camNormalizedAngleX * normalAngleY - camNormalizedAngleY * normalAngleX) -- Update the camera position based on the forwards/backwards speed camPosX = camPosX + freeModeAngleX * speed camPosY = camPosY + freeModeAngleY * speed camPosZ = camPosZ + freeModeAngleZ * speed -- Update the camera position based on the strafe speed camPosX = camPosX + normalX * strafespeed camPosY = camPosY + normalY * strafespeed camPosZ = camPosZ + normalZ * strafespeed --Store the velocity velocityX = (freeModeAngleX * speed) + (normalX * strafespeed) velocityY = (freeModeAngleY * speed) + (normalY * strafespeed) velocityZ = (freeModeAngleZ * speed) + (normalZ * strafespeed) -- Update the target based on the new camera position (again, otherwise the camera kind of sways as the target is out by a frame) camTargetX = camPosX + freeModeAngleX * 100 camTargetY = camPosY + freeModeAngleY * 100 camTargetZ = camPosZ + freeModeAngleZ * 100 -- Set the new camera position and target setCameraMatrix ( camPosX, camPosY, camPosZ, camTargetX, camTargetY, camTargetZ ) end local function freecamMouse (cX,cY,aX,aY) --ignore mouse movement if the cursor or MTA window is on --and do not resume it until at least 5 frames after it is toggled off --(prevents cursor mousemove data from reaching this handler) if isCursorShowing() or isMTAWindowActive() then mouseFrameDelay = 5 return elseif mouseFrameDelay > 0 then mouseFrameDelay = mouseFrameDelay - 1 return end -- how far have we moved the mouse from the screen center? local width, height = guiGetScreenSize() aX = aX - width / 2 aY = aY - height / 2 --invert the mouse look if specified if options.invertMouseLook then aY = -aY end rotX = rotX + aX * options.mouseSensitivity * 0.01745 rotY = rotY - aY * options.mouseSensitivity * 0.01745 local PI = math.pi if rotX > PI then rotX = rotX - 2 * PI elseif rotX < -PI then rotX = rotX + 2 * PI end if rotY > PI then rotY = rotY - 2 * PI elseif rotY < -PI then rotY = rotY + 2 * PI end -- limit the camera to stop it going too far up or down - PI/2 is the limit, but we can't let it quite reach that or it will lock up -- and strafeing will break entirely as the camera loses any concept of what is 'up' if rotY < -PI / 2.05 then rotY = -PI / 2.05 elseif rotY > PI / 2.05 then rotY = PI / 2.05 end end -- PUBLIC function getFreecamVelocity() return velocityX,velocityY,velocityZ end -- params: x, y, z sets camera's position (optional) function setFreecamEnabled (x, y, z) if isFreecamEnabled() then return false end if (x and y and z) then setCameraMatrix ( camPosX, camPosY, camPosZ ) end addEventHandler("onClientRender", rootElement, freecamFrame) addEventHandler("onClientCursorMove",rootElement, freecamMouse) setElementData(localPlayer, "freecam:state", true) return true end -- param: dontChangeFixedMode leaves toggleCameraFixedMode alone if true, disables it if false or nil (optional) function setFreecamDisabled() if not isFreecamEnabled() then return false end velocityX,velocityY,velocityZ = 0,0,0 speed = 0 strafespeed = 0 removeEventHandler("onClientRender", rootElement, freecamFrame) removeEventHandler("onClientCursorMove",rootElement, freecamMouse) setElementData(localPlayer, "freecam:state", false) return true end function isFreecamEnabled() return getElementData(localPlayer,"freecam:state") end function getFreecamOption(theOption, value) return options[theOption] end function setFreecamOption(theOption, value) if options[theOption] ~= nil then options[theOption] = value return true else return false end end addEvent("doSetFreecamEnabled") addEventHandler("doSetFreecamEnabled", rootElement, setFreecamEnabled) addEvent("doSetFreecamDisabled") addEventHandler("doSetFreecamDisabled", rootElement, setFreecamDisabled) addEvent("doSetFreecamOption") addEventHandler("doSetFreecamOption", rootElement, setFreecamOption)
mit
ProjectSkyfire/SkyFire-Community-Tools
FireAdmin/Libraries/AceAddon-2.0/AceAddon-2.0.lua
1
45123
--[[ Name: AceAddon-2.0 Revision: $Rev: 1100 $ Developed by: The Ace Development Team (http://www.wowace.com/index.php/The_Ace_Development_Team) Inspired By: Ace 1.x by Turan (turan@gryphon.com) Website: http://www.wowace.com/ Documentation: http://www.wowace.com/wiki/AceAddon-2.0 SVN: http://svn.wowace.com/wowace/trunk/Ace2/AceAddon-2.0 Description: Base for all Ace addons to inherit from. Dependencies: AceLibrary, AceOO-2.0, AceEvent-2.0, (optional) AceConsole-2.0 License: LGPL v2.1 ]] local MAJOR_VERSION = "AceAddon-2.0" local MINOR_VERSION = 90000 + tonumber(("$Revision: 1100 $"):match("(%d+)")) -- This ensures the code is only executed if the libary doesn't already exist, or is a newer version if not AceLibrary then error(MAJOR_VERSION .. " requires AceLibrary.") end if not AceLibrary:IsNewVersion(MAJOR_VERSION, MINOR_VERSION) then return end if not AceLibrary:HasInstance("AceOO-2.0") then error(MAJOR_VERSION .. " requires AceOO-2.0.") end local function safecall(func,...) local success, err = pcall(func,...) if not success then geterrorhandler()(err:find("%.lua:%d+:") and err or (debugstack():match("\n(.-: )in.-\n") or "") .. err) end end -- Localization local STANDBY, TITLE, NOTES, VERSION, AUTHOR, DATE, CATEGORY, EMAIL, CREDITS, WEBSITE, CATEGORIES, ABOUT, LICENSE, PRINT_ADDON_INFO, DONATE, DONATE_DESC, HOWTO_DONATE_WINDOWS, HOWTO_DONATE_MAC if GetLocale() == "deDE" then STANDBY = "|cffff5050(Standby)|r" -- capitalized TITLE = "Titel" NOTES = "Anmerkung" VERSION = "Version" AUTHOR = "Autor" DATE = "Datum" CATEGORY = "Kategorie" EMAIL = "E-Mail" WEBSITE = "Webseite" CREDITS = "Credits" -- fix LICENSE = "License" -- fix ABOUT = "Über" PRINT_ADDON_INFO = "Gibt Addondaten aus" DONATE = "Donate" -- fix DONATE_DESC = "Give a much-needed donation to the author of this addon." -- fix HOWTO_DONATE_WINDOWS = "Press Ctrl-A to select the link, then Ctrl-C to copy, then Alt-Tab out of the game, open your favorite web browser, and paste the link into the address bar." -- fix HOWTO_DONATE_MAC = "Press Cmd-A to select the link, then Cmd-C to copy, then Cmd-Tab out of the game, open your favorite web browser, and paste the link into the address bar." -- fix CATEGORIES = { ["Action Bars"] = "Aktionsleisten", ["Auction"] = "Auktion", ["Audio"] = "Audio", ["Battlegrounds/PvP"] = "Schlachtfeld/PvP", ["Buffs"] = "Stärkungszauber", ["Chat/Communication"] = "Chat/Kommunikation", ["Druid"] = "Druide", ["Hunter"] = "Jäger", ["Mage"] = "Magier", ["Paladin"] = "Paladin", ["Priest"] = "Priester", ["Rogue"] = "Schurke", ["Shaman"] = "Schamane", ["Warlock"] = "Hexenmeister", ["Warrior"] = "Krieger", ["Healer"] = "Heiler", ["Tank"] = "Tank", ["Caster"] = "Zauberer", ["Combat"] = "Kampf", ["Compilations"] = "Zusammenstellungen", ["Data Export"] = "Datenexport", ["Development Tools"] = "Entwicklungs Tools", ["Guild"] = "Gilde", ["Frame Modification"] = "Frame Veränderungen", ["Interface Enhancements"] = "Interface Verbesserungen", ["Inventory"] = "Inventar", ["Library"] = "Bibliotheken", ["Map"] = "Karte", ["Mail"] = "Post", ["Miscellaneous"] = "Diverses", ["Quest"] = "Quest", ["Raid"] = "Schlachtzug", ["Tradeskill"] = "Beruf", ["UnitFrame"] = "Einheiten-Fenster", } elseif GetLocale() == "frFR" then STANDBY = "|cffff5050(attente)|r" TITLE = "Titre" NOTES = "Notes" VERSION = "Version" AUTHOR = "Auteur" DATE = "Date" CATEGORY = "Catégorie" EMAIL = "E-mail" WEBSITE = "Site web" CREDITS = "Credits" -- fix LICENSE = "License" -- fix ABOUT = "A propos" PRINT_ADDON_INFO = "Afficher les informations sur l'addon" DONATE = "Donate" -- fix DONATE_DESC = "Give a much-needed donation to the author of this addon." -- fix HOWTO_DONATE_WINDOWS = "Press Ctrl-A to select the link, then Ctrl-C to copy, then Alt-Tab out of the game, open your favorite web browser, and paste the link into the address bar." -- fix HOWTO_DONATE_MAC = "Press Cmd-A to select the link, then Cmd-C to copy, then Cmd-Tab out of the game, open your favorite web browser, and paste the link into the address bar." -- fix CATEGORIES = { ["Action Bars"] = "Barres d'action", ["Auction"] = "Hôtel des ventes", ["Audio"] = "Audio", ["Battlegrounds/PvP"] = "Champs de bataille/JcJ", ["Buffs"] = "Buffs", ["Chat/Communication"] = "Chat/Communication", ["Druid"] = "Druide", ["Hunter"] = "Chasseur", ["Mage"] = "Mage", ["Paladin"] = "Paladin", ["Priest"] = "Prêtre", ["Rogue"] = "Voleur", ["Shaman"] = "Chaman", ["Warlock"] = "Démoniste", ["Warrior"] = "Guerrier", ["Healer"] = "Soigneur", ["Tank"] = "Tank", ["Caster"] = "Casteur", ["Combat"] = "Combat", ["Compilations"] = "Compilations", ["Data Export"] = "Exportation de données", ["Development Tools"] = "Outils de développement", ["Guild"] = "Guilde", ["Frame Modification"] = "Modification des fenêtres", ["Interface Enhancements"] = "Améliorations de l'interface", ["Inventory"] = "Inventaire", ["Library"] = "Bibliothèques", ["Map"] = "Carte", ["Mail"] = "Courrier", ["Miscellaneous"] = "Divers", ["Quest"] = "Quêtes", ["Raid"] = "Raid", ["Tradeskill"] = "Métiers", ["UnitFrame"] = "Fenêtres d'unité", } elseif GetLocale() == "koKR" then STANDBY = "|cffff5050(사용가능)|r" TITLE = "제목" NOTES = "노트" VERSION = "버전" AUTHOR = "저작자" DATE = "날짜" CATEGORY = "분류" EMAIL = "전자 우편" WEBSITE = "웹 사이트" CREDITS = "공로자" LICENSE = "라이센스" ABOUT = "정보" PRINT_ADDON_INFO = "애드온에 대한 정보를 출력합니다." DONATE = "기부" DONATE_DESC = "이 애드온의 저작자에게 기부를 합니다." HOWTO_DONATE_WINDOWS = "Ctrl-A를 눌려 링크를 선택후, Ctrl-C로 복사합니다. Alt-Tab 눌려 게임으로 부터 나간후 웹 브라우저를 엽니다. 복사된 링크를 주소 창에 붙여넣기 합니다." HOWTO_DONATE_MAC = "Cmd-A를 눌려 링크를 선택후, Cmd-C로 복사합니다. Cmd-Tab 눌려 게임으로 부터 나간후 웹 브라우저를 엽니다. 복사된 링크를 주소 창에 붙여넣기 합니다." CATEGORIES = { ["Action Bars"] = "액션바", ["Auction"] = "경매", ["Audio"] = "음향", ["Battlegrounds/PvP"] = "전장/PvP", ["Buffs"] = "버프", ["Chat/Communication"] = "대화/의사소통", ["Druid"] = "드루이드", ["Hunter"] = "사냥꾼", ["Mage"] = "마법사", ["Paladin"] = "성기사", ["Priest"] = "사제", ["Rogue"] = "도적", ["Shaman"] = "주술사", ["Warlock"] = "흑마법사", ["Warrior"] = "전사", ["Healer"] = "힐러", ["Tank"] = "탱커", ["Caster"] = "캐스터", ["Combat"] = "전투", ["Compilations"] = "복합", ["Data Export"] = "자료 출력", ["Development Tools"] = "개발 도구", ["Guild"] = "길드", ["Frame Modification"] = "구조 변경", ["Interface Enhancements"] = "인터페이스 강화", ["Inventory"] = "인벤토리", ["Library"] = "라이브러리", ["Map"] = "지도", ["Mail"] = "우편", ["Miscellaneous"] = "기타", ["Quest"] = "퀘스트", ["Raid"] = "공격대", ["Tradeskill"] = "전문기술", ["UnitFrame"] = "유닛 프레임", } elseif GetLocale() == "zhTW" then STANDBY = "|cffff5050(待命)|r" TITLE = "標題" NOTES = "註記" VERSION = "版本" AUTHOR = "作者" DATE = "日期" CATEGORY = "類別" EMAIL = "電子郵件" WEBSITE = "網站" CREDITS = "特別感謝" LICENSE = "版權" ABOUT = "關於" PRINT_ADDON_INFO = "顯示插件資訊。" DONATE = "捐贈" DONATE_DESC = "捐贈金錢給插件作者。" HOWTO_DONATE_WINDOWS = "請按Ctrl-A選擇網站連結,Ctrl-C複製網址,Alt-Tab切換到電腦桌面,打開瀏覽器,在網址列貼上網址。" HOWTO_DONATE_MAC = "請按Cmd-A選擇網站連結,Cmd-C複製網址,Cmd-Tab切換到電腦桌面,打開瀏覽器,在網址列貼上網址。" CATEGORIES = { ["Action Bars"] = "動作條", ["Auction"] = "拍賣", ["Audio"] = "音效", ["Battlegrounds/PvP"] = "戰場/PvP", ["Buffs"] = "增益", ["Chat/Communication"] = "聊天/通訊", ["Druid"] = "德魯伊", ["Hunter"] = "獵人", ["Mage"] = "法師", ["Paladin"] = "聖騎士", ["Priest"] = "牧師", ["Rogue"] = "盜賊", ["Shaman"] = "薩滿", ["Warlock"] = "術士", ["Warrior"] = "戰士", ["Healer"] = "治療者", ["Tank"] = "坦克", ["Caster"] = "施法者", ["Combat"] = "戰鬥", ["Compilations"] = "整合", ["Data Export"] = "資料匯出", ["Development Tools"] = "開發工具", ["Guild"] = "公會", ["Frame Modification"] = "框架修改", ["Interface Enhancements"] = "介面增強", ["Inventory"] = "庫存", ["Library"] = "程式庫", ["Map"] = "地圖", ["Mail"] = "郵件", ["Miscellaneous"] = "雜項", ["Quest"] = "任務", ["Raid"] = "團隊", ["Tradeskill"] = "交易技能", ["UnitFrame"] = "單位框架", } elseif GetLocale() == "zhCN" then STANDBY = "|cffff5050(暂挂)|r" TITLE = "标题" NOTES = "附注" VERSION = "版本" AUTHOR = "作者" DATE = "日期" CATEGORY = "分类" EMAIL = "电子邮件" WEBSITE = "网站" CREDITS = "Credits" -- fix LICENSE = "License" -- fix ABOUT = "关于" PRINT_ADDON_INFO = "印列出插件信息" DONATE = "Donate" -- fix DONATE_DESC = "Give a much-needed donation to the author of this addon." -- fix HOWTO_DONATE_WINDOWS = "Press Ctrl-A to select the link, then Ctrl-C to copy, then Alt-Tab out of the game, open your favorite web browser, and paste the link into the address bar." -- fix HOWTO_DONATE_MAC = "Press Cmd-A to select the link, then Cmd-C to copy, then Cmd-Tab out of the game, open your favorite web browser, and paste the link into the address bar." -- fix CATEGORIES = { ["Action Bars"] = "动作条", ["Auction"] = "拍卖", ["Audio"] = "音频", ["Battlegrounds/PvP"] = "战场/PvP", ["Buffs"] = "增益魔法", ["Chat/Communication"] = "聊天/交流", ["Druid"] = "德鲁伊", ["Hunter"] = "猎人", ["Mage"] = "法师", ["Paladin"] = "圣骑士", ["Priest"] = "牧师", ["Rogue"] = "盗贼", ["Shaman"] = "萨满祭司", ["Warlock"] = "术士", ["Warrior"] = "战士", ["Healer"] = "Healer", ["Tank"] = "Tank", ["Caster"] = "Caster", ["Combat"] = "战斗", ["Compilations"] = "编译", ["Data Export"] = "数据导出", ["Development Tools"] = "开发工具", ["Guild"] = "公会", ["Frame Modification"] = "框架修改", ["Interface Enhancements"] = "界面增强", ["Inventory"] = "背包", ["Library"] = "库", ["Map"] = "地图", ["Mail"] = "邮件", ["Miscellaneous"] = "杂项", ["Quest"] = "任务", ["Raid"] = "团队", ["Tradeskill"] = "商业技能", ["UnitFrame"] = "头像框架", } elseif GetLocale() == "esES" then STANDBY = "|cffff5050(espera)|r" TITLE = "Título" NOTES = "Notas" VERSION = "Versión" AUTHOR = "Autor" DATE = "Fecha" CATEGORY = "Categoría" EMAIL = "E-mail" WEBSITE = "Web" CREDITS = "Créditos" LICENSE = "License" -- fix ABOUT = "Acerca de" PRINT_ADDON_INFO = "Muestra información acerca del accesorio." DONATE = "Donate" -- fix DONATE_DESC = "Give a much-needed donation to the author of this addon." -- fix HOWTO_DONATE_WINDOWS = "Press Ctrl-A to select the link, then Ctrl-C to copy, then Alt-Tab out of the game, open your favorite web browser, and paste the link into the address bar." -- fix HOWTO_DONATE_MAC = "Press Cmd-A to select the link, then Cmd-C to copy, then Cmd-Tab out of the game, open your favorite web browser, and paste the link into the address bar." -- fix CATEGORIES = { ["Action Bars"] = "Barras de Acción", ["Auction"] = "Subasta", ["Audio"] = "Audio", ["Battlegrounds/PvP"] = "Campos de Batalla/JcJ", ["Buffs"] = "Buffs", ["Chat/Communication"] = "Chat/Comunicación", ["Druid"] = "Druida", ["Hunter"] = "Cazador", ["Mage"] = "Mago", ["Paladin"] = "Paladín", ["Priest"] = "Sacerdote", ["Rogue"] = "Pícaro", ["Shaman"] = "Chamán", ["Warlock"] = "Brujo", ["Warrior"] = "Guerrero", ["Healer"] = "Sanador", ["Tank"] = "Tanque", ["Caster"] = "Conjurador", ["Combat"] = "Combate", ["Compilations"] = "Compilaciones", ["Data Export"] = "Exportar Datos", ["Development Tools"] = "Herramientas de Desarrollo", ["Guild"] = "Hermandad", ["Frame Modification"] = "Modificación de Marcos", ["Interface Enhancements"] = "Mejoras de la Interfaz", ["Inventory"] = "Inventario", ["Library"] = "Biblioteca", ["Map"] = "Mapa", ["Mail"] = "Correo", ["Miscellaneous"] = "Misceláneo", ["Quest"] = "Misión", ["Raid"] = "Banda", ["Tradeskill"] = "Habilidad de Comercio", ["UnitFrame"] = "Marco de Unidades", } elseif GetLocale() == "ruRU" then STANDBY = "|cffff5050(в режиме ожидания)|r" TITLE = "Название" NOTES = "Описание" VERSION = "Версия" AUTHOR = "Автор" DATE = "Дата" CATEGORY = "Категория" EMAIL = "E-mail" WEBSITE = "Сайт" CREDITS = "Титры" LICENSE = "Лицензия" ABOUT = "Об аддоне" PRINT_ADDON_INFO = "Показать информацию об аддоне." DONATE = "Пожертвовать" DONATE_DESC = "Отблагодарить автора за разработку аддона." HOWTO_DONATE_WINDOWS = "Для выделения всей ссылки нажмите Ctrl-A, потом для её копирования Ctrl-C, чтобы свернуть игру - Alt-Tab, откройте ваш браузер и вставьте ссылку в адресную строку - Ctrl-V" HOWTO_DONATE_MAC = "Для выделения всей ссылки нажмите Cmd-A, потом для её копирования Ctrl-C, чтобы свернуть игру - Cmd-Tab, откройте ваш браузер и вставьте ссылку в адресную строку Cmd-V" CATEGORIES = { ["Action Bars"] = "Панели команд", ["Auction"] = "Аукцион", ["Audio"] = "Аудио", ["Battlegrounds/PvP"] = "Поля сражений/PvP", ["Buffs"] = "Баффы", ["Chat/Communication"] = "Чат/Коммуникация", ["Druid"] = "Друид", ["Hunter"] = "Охотник", ["Mage"] = "Маг", ["Paladin"] = "Паладин", ["Priest"] = "Жрец", ["Rogue"] = "Разбойник", ["Shaman"] = "Шаман", ["Warlock"] = "Чернокнижник", ["Warrior"] = "Воин", ["Healer"] = "Лекарь", ["Tank"] = "Танк", ["Caster"] = "Кастер", ["Combat"] = "Сражения", ["Compilations"] = "Компиляция", ["Data Export"] = "Экспорт данных", ["Development Tools"] = "Инструменты разработчика", ["Guild"] = "Гильдия", ["Frame Modification"] = "Модификация фреймов", ["Interface Enhancements"] = "Улучшение интерфейса", ["Inventory"] = "Инвентарь", ["Library"] = "Библиотеки", ["Map"] = "Карта", ["Mail"] = "Почта", ["Miscellaneous"] = "Разное", ["Quest"] = "Задания", ["Raid"] = "Рейд", ["Tradeskill"] = "Умения", ["UnitFrame"] = "Фреймы персонажей", } else -- enUS STANDBY = "|cffff5050(standby)|r" TITLE = "Title" NOTES = "Notes" VERSION = "Version" AUTHOR = "Author" DATE = "Date" CATEGORY = "Category" EMAIL = "E-mail" WEBSITE = "Website" CREDITS = "Credits" LICENSE = "License" ABOUT = "About" PRINT_ADDON_INFO = "Show information about the addon." DONATE = "Donate" DONATE_DESC = "Give a much-needed donation to the author of this addon." HOWTO_DONATE_WINDOWS = "Press Ctrl-A to select the link, then Ctrl-C to copy, then Alt-Tab out of the game, open your favorite web browser, and paste the link into the address bar." HOWTO_DONATE_MAC = "Press Cmd-A to select the link, then Cmd-C to copy, then Cmd-Tab out of the game, open your favorite web browser, and paste the link into the address bar." CATEGORIES = { ["Action Bars"] = "Action Bars", ["Auction"] = "Auction", ["Audio"] = "Audio", ["Battlegrounds/PvP"] = "Battlegrounds/PvP", ["Buffs"] = "Buffs", ["Chat/Communication"] = "Chat/Communication", ["Druid"] = "Druid", ["Hunter"] = "Hunter", ["Mage"] = "Mage", ["Paladin"] = "Paladin", ["Priest"] = "Priest", ["Rogue"] = "Rogue", ["Shaman"] = "Shaman", ["Warlock"] = "Warlock", ["Warrior"] = "Warrior", ["Healer"] = "Healer", ["Tank"] = "Tank", ["Caster"] = "Caster", ["Combat"] = "Combat", ["Compilations"] = "Compilations", ["Data Export"] = "Data Export", ["Development Tools"] = "Development Tools", ["Guild"] = "Guild", ["Frame Modification"] = "Frame Modification", ["Interface Enhancements"] = "Interface Enhancements", ["Inventory"] = "Inventory", ["Library"] = "Library", ["Map"] = "Map", ["Mail"] = "Mail", ["Miscellaneous"] = "Miscellaneous", ["Quest"] = "Quest", ["Raid"] = "Raid", ["Tradeskill"] = "Tradeskill", ["UnitFrame"] = "UnitFrame", } end setmetatable(CATEGORIES, { __index = function(self, key) -- case-insensitive local lowerKey = key:lower() for k,v in pairs(CATEGORIES) do if k:lower() == lowerKey then self[lowerKey] = v return v end end end }) -- Create the library object local AceOO = AceLibrary("AceOO-2.0") local AceAddon = AceOO.Class() local AceEvent local AceConsole local AceModuleCore function AceAddon:GetLocalizedCategory(name) self:argCheck(name, 2, "string") return CATEGORIES[name] or UNKNOWN end function AceAddon:ToString() return "AceAddon" end local function print(text) DEFAULT_CHAT_FRAME:AddMessage(text) end function AceAddon:ADDON_LOADED(name) local unregister = true local initAddon = {} while #self.nextAddon > 0 do local addon = table.remove(self.nextAddon, 1) if addon.possibleNames[name] then table.insert(initAddon, addon) else unregister = nil table.insert(self.skipAddon, addon) end end self.nextAddon, self.skipAddon = self.skipAddon, self.nextAddon if unregister then AceAddon:UnregisterEvent("ADDON_LOADED") end while #initAddon > 0 do local addon = table.remove(initAddon, 1) table.insert(self.addons, addon) if not self.addons[name] then self.addons[name] = addon end addon.possibleNames = nil self:InitializeAddon(addon, name) end end local function RegisterOnEnable(self) if IsLoggedIn() then AceAddon.addonsStarted[self] = true if (type(self.IsActive) ~= "function" or self:IsActive()) and (not AceModuleCore or not AceModuleCore:IsModule(self) or AceModuleCore:IsModuleActive(self)) then AceAddon:ManualEnable(self) end else if not AceAddon.addonsToOnEnable then AceAddon.addonsToOnEnable = {} end table.insert(AceAddon.addonsToOnEnable, self) end end function AceAddon:InitializeAddon(addon, name) if addon.name == nil then addon.name = name end if GetAddOnMetadata then -- TOC checks if addon.title == nil then addon.title = GetAddOnMetadata(name, "Title") end if type(addon.title) == "string" then local num = addon.title:find(" |cff7fff7f %-Ace2%-|r$") if num then addon.title = addon.title:sub(1, num - 1) end addon.title = addon.title:trim() end if addon.notes == nil then addon.notes = GetAddOnMetadata(name, "Notes") end if type(addon.notes) == "string" then addon.notes = addon.notes:trim() end if addon.version == nil then addon.version = GetAddOnMetadata(name, "Version") end if type(addon.version) == "string" then if addon.version:find("%$Revision: (%d+) %$") then addon.version = addon.version:gsub("%$Revision: (%d+) %$", "%1") elseif addon.version:find("%$Rev: (%d+) %$") then addon.version = addon.version:gsub("%$Rev: (%d+) %$", "%1") elseif addon.version:find("%$LastChangedRevision: (%d+) %$") then addon.version = addon.version:gsub("%$LastChangedRevision: (%d+) %$", "%1") end addon.version = addon.version:trim() end if addon.author == nil then addon.author = GetAddOnMetadata(name, "Author") end if type(addon.author) == "string" then addon.author = addon.author:trim() end if addon.credits == nil then addon.credits = GetAddOnMetadata(name, "X-Credits") end if type(addon.credits) == "string" then addon.credits = addon.credits:trim() end if addon.donate == nil then addon.donate = GetAddOnMetadata(name, "X-Donate") end if type(addon.donate) == "string" then addon.donate = addon.donate:trim() end if addon.date == nil then addon.date = GetAddOnMetadata(name, "X-Date") or GetAddOnMetadata(name, "X-ReleaseDate") end if type(addon.date) == "string" then if addon.date:find("%$Date: (.-) %$") then addon.date = addon.date:gsub("%$Date: (.-) %$", "%1") elseif addon.date:find("%$LastChangedDate: (.-) %$") then addon.date = addon.date:gsub("%$LastChangedDate: (.-) %$", "%1") end addon.date = addon.date:trim() end if addon.category == nil then addon.category = GetAddOnMetadata(name, "X-Category") end if type(addon.category) == "string" then addon.category = addon.category:trim() end if addon.email == nil then addon.email = GetAddOnMetadata(name, "X-eMail") or GetAddOnMetadata(name, "X-Email") end if type(addon.email) == "string" then addon.email = addon.email:trim() end if addon.license == nil then addon.license = GetAddOnMetadata(name, "X-License") end if type(addon.license) == "string" then addon.license = addon.license:trim() end if addon.website == nil then addon.website = GetAddOnMetadata(name, "X-Website") end if type(addon.website) == "string" then addon.website = addon.website:trim() end end local current = addon.class while true do if current == AceOO.Class or not current then break end if current.mixins then for mixin in pairs(current.mixins) do if type(mixin.OnEmbedInitialize) == "function" then mixin:OnEmbedInitialize(addon, name) end end end current = current.super end local n = AceAddon.addonsToOnEnable and #AceAddon.addonsToOnEnable or 0 if type(addon.OnInitialize) == "function" then safecall(addon.OnInitialize, addon, name) end if AceEvent then AceEvent:TriggerEvent("Ace2_AddonInitialized", addon) end RegisterOnEnable(addon) local n2 = AceAddon.addonsToOnEnable and #AceAddon.addonsToOnEnable or 0 if n2 - n > 1 then local mine = table.remove(AceAddon.addonsToOnEnable) table.insert(AceAddon.addonsToOnEnable, n+1, mine) end end local aboutFrame local function createAboutFrame() aboutFrame = CreateFrame("Frame", "AceAddon20AboutFrame", UIParent, "DialogBoxFrame") aboutFrame:SetWidth(500) aboutFrame:SetHeight(400) aboutFrame:SetPoint("CENTER") aboutFrame:SetBackdrop({ bgFile = [[Interface\DialogFrame\UI-DialogBox-Background]], edgeFile = [[Interface\Tooltips\UI-Tooltip-Border]], tile = true, tileSize = 16, edgeSize = 16, insets = { left = 5, right = 5, top = 5, bottom = 5 } }) aboutFrame:SetBackdropColor(0,0,0,1) local donateButton = CreateFrame("Button", "AceAddon20AboutFrameDonateButton", aboutFrame, "UIPanelButtonTemplate2") aboutFrame.donateButton = donateButton donateButton:SetPoint("BOTTOMRIGHT", -20, 20) _G.AceAddon20AboutFrameDonateButtonText:SetText(DONATE) donateButton:SetWidth(_G.AceAddon20AboutFrameDonateButtonText:GetWidth()+20) donateButton:SetScript("OnClick", function() aboutFrame.currentAddon:OpenDonationFrame() end) local text = aboutFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightLarge") aboutFrame.title = text text:SetPoint("TOP", 0, -5) aboutFrame:Hide() aboutFrame.lefts = {} aboutFrame.rights = {} aboutFrame.textLefts = {} aboutFrame.textRights = {} function aboutFrame:Clear() self.title:SetText("") for i = 1, #self.lefts do self.lefts[i] = nil self.rights[i] = nil end end function aboutFrame:AddLine(left, right) aboutFrame.lefts[#aboutFrame.lefts+1] = left aboutFrame.rights[#aboutFrame.rights+1] = right end local aboutFrame_Show = aboutFrame.Show function aboutFrame:Show(...) local maxLeftWidth = 0 local maxRightWidth = 0 local textHeight = 0 for i = 1, #self.lefts do if not self.textLefts[i] then local left = aboutFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal") self.textLefts[i] = left local right = aboutFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlight") self.textRights[i] = right if i == 1 then left:SetPoint("TOPRIGHT", aboutFrame, "TOPLEFT", 75, -35) else left:SetPoint("TOPRIGHT", self.textLefts[i-1], "BOTTOMRIGHT", 0, -5) end right:SetPoint("LEFT", left, "RIGHT", 5, 0) end self.textLefts[i]:SetText(self.lefts[i] .. ":") self.textRights[i]:SetText(self.rights[i]) local leftWidth = self.textLefts[i]:GetWidth() local rightWidth = self.textRights[i]:GetWidth() textHeight = self.textLefts[i]:GetHeight() if maxLeftWidth < leftWidth then maxLeftWidth = leftWidth end if maxRightWidth < rightWidth then maxRightWidth = rightWidth end end for i = #self.lefts+1, #self.textLefts do self.textLefts[i]:SetText('') self.textRights[i]:SetText('') end aboutFrame:SetWidth(75 + maxRightWidth + 20) aboutFrame:SetHeight(#self.lefts * (textHeight + 5) + 100) aboutFrame_Show(self, ...) end aboutFrame:Hide() createAboutFrame = nil end local donateFrame local function unobfuscateEmail(email) return email:gsub(" AT ", "@"):gsub(" DOT ", ".") end local function isGoodVariable(var) return type(var) == "string" or type(var) == "number" end function AceAddon.prototype:PrintAddonInfo() if createAboutFrame then createAboutFrame() end aboutFrame:Clear() local x if isGoodVariable(self.title) then x = tostring(self.title) elseif isGoodVariable(self.name) then x = tostring(self.name) else x = "<" .. tostring(self.class) .. " instance>" end if type(self.IsActive) == "function" then if not self:IsActive() then x = x .. " " .. STANDBY end end aboutFrame.title:SetText(x) if isGoodVariable(self.version) then aboutFrame:AddLine(VERSION, tostring(self.version)) end if isGoodVariable(self.notes) then aboutFrame:AddLine(NOTES, tostring(self.notes)) end if isGoodVariable(self.author) then aboutFrame:AddLine(AUTHOR, tostring(self.author)) end if isGoodVariable(self.credits) then aboutFrame:AddLine(CREDITS, tostring(self.credits)) end if isGoodVariable(self.date) then aboutFrame:AddLine(DATE, tostring(self.date)) end if isGoodVariable(self.category) then local category = CATEGORIES[self.category] aboutFrame:AddLine(CATEGORY, category or tostring(self.category)) end if isGoodVariable(self.email) then aboutFrame:AddLine(EMAIL, unobfuscateEmail(tostring(self.email))) end if isGoodVariable(self.website) then aboutFrame:AddLine(WEBSITE, tostring(self.website)) end if isGoodVariable(self.license) then aboutFrame:AddLine(LICENSE, tostring(self.license)) end if donateFrame and donateFrame:IsShown() then donateFrame:Hide() end aboutFrame.currentAddon = self aboutFrame:Show() if self.donate then aboutFrame.donateButton:Show() else aboutFrame.donateButton:Hide() end end local function createDonateFrame() donateFrame = CreateFrame("Frame", "AceAddon20Frame", UIParent, "DialogBoxFrame") donateFrame:SetWidth(500) donateFrame:SetHeight(200) donateFrame:SetPoint("CENTER") donateFrame:SetBackdrop({ bgFile = [[Interface\DialogFrame\UI-DialogBox-Background]], edgeFile = [[Interface\Tooltips\UI-Tooltip-Border]], tile = true, tileSize = 16, edgeSize = 16, insets = { left = 5, right = 5, top = 5, bottom = 5 } }) donateFrame:SetBackdropColor(0,0,0,1) local text = donateFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightLarge") text:SetPoint("TOP", 0, -5) text:SetText(DONATE) local howto = donateFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlight") howto:SetPoint("TOP", text, "BOTTOM", 0, -5) howto:SetPoint("LEFT", 16, 0) howto:SetPoint("RIGHT", -16, 0) if not IsMacClient() then -- Windows or Linux howto:SetText(HOWTO_DONATE_WINDOWS) else howto:SetText(HOWTO_DONATE_MAC) end local scrollFrame = CreateFrame("ScrollFrame", "AceAddon20FrameScrollFrame", donateFrame, "UIPanelScrollFrameTemplate") scrollFrame:SetToplevel(true) scrollFrame:SetPoint("TOP", -10, -76) scrollFrame:SetWidth(455) scrollFrame:SetHeight(70) howto:SetPoint("BOTTOM", scrollFrame, "TOP") local editBox = CreateFrame("EditBox", nil, scrollFrame) donateFrame.editBox = editBox scrollFrame:SetScrollChild(editBox) editBox:SetFontObject(ChatFontNormal) editBox:SetMultiLine(true) editBox:SetMaxLetters(99999) editBox:SetWidth(450) editBox:SetHeight(54) editBox:SetPoint("BOTTOM", 5, 0) editBox:SetJustifyH("LEFT") editBox:SetJustifyV("TOP") editBox:SetAutoFocus(false) editBox:SetScript("OnTextChanged", function(editBox) if editBox:GetText() ~= editBox.text then editBox:SetText(editBox.text) end end) editBox:SetScript("OnEscapePressed", function(editBox) editBox:ClearFocus() end) createDonateFrame = nil end local function fix(char) return ("%%%02x"):format(char:byte()) end local function urlencode(text) return text:gsub("[^0-9A-Za-z]", fix) end function AceAddon.prototype:OpenDonationFrame() if createDonateFrame then createDonateFrame() end local donate = self.donate if type(donate) ~= "string" then donate = "Wowace" end local style, data = (":"):split(donate, 2) style = style:lower() if style ~= "website" and style ~= "paypal" then style = "wowace" end if style == "wowace" then donateFrame.editBox.text = "http://www.wowace.com/wiki/Donations" elseif style == "website" then donateFrame.editBox.text = data else -- PayPal local text = "https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=" .. urlencode(unobfuscateEmail(data)) local name if type(self.title) == "string" then name = self.title elseif type(self.name) == "string" then name = self.name end if name then name = name:gsub("|c%x%x%x%x%x%x%x%x", ""):gsub("|r", "") text = text .. "&item_name=" .. urlencode(name) end donateFrame.editBox.text = text end donateFrame.editBox:SetText(donateFrame.editBox.text) if aboutFrame and aboutFrame:IsShown() then aboutFrame:Hide() end donateFrame:Show() donateFrame.editBox:SetFocus() end local options function AceAddon:GetAceOptionsDataTable(target) return { about = { name = ABOUT, desc = PRINT_ADDON_INFO, type = "execute", func = "PrintAddonInfo", order = -1, }, donate = { name = DONATE, desc = DONATE_DESC, type = "execute", func = "OpenDonationFrame", order = -1, hidden = function() return not target.donate end } } end function AceAddon:PLAYER_LOGIN() if self.addonsToOnEnable then while #self.addonsToOnEnable > 0 do local addon = table.remove(self.addonsToOnEnable, 1) self.addonsStarted[addon] = true if (type(addon.IsActive) ~= "function" or addon:IsActive()) and (not AceModuleCore or not AceModuleCore:IsModule(addon) or AceModuleCore:IsModuleActive(addon)) then AceAddon:ManualEnable(addon) end end self.addonsToOnEnable = nil end end function AceAddon.prototype:Inject(t) AceAddon:argCheck(t, 2, "table") for k,v in pairs(t) do self[k] = v end end function AceAddon.prototype:init() if not AceEvent then error(MAJOR_VERSION .. " requires AceEvent-2.0", 4) end AceAddon.super.prototype.init(self) self.super = self.class.prototype AceAddon:RegisterEvent("ADDON_LOADED", "ADDON_LOADED") local names = {} for i = 1, GetNumAddOns() do if IsAddOnLoaded(i) then names[GetAddOnInfo(i)] = true end end self.possibleNames = names table.insert(AceAddon.nextAddon, self) end function AceAddon.prototype:ToString() local x if type(self.title) == "string" then x = self.title elseif type(self.name) == "string" then x = self.name else x = "<" .. tostring(self.class) .. " instance>" end if (type(self.IsActive) == "function" and not self:IsActive()) or (AceModuleCore and AceModuleCore:IsModule(addon) and AceModuleCore:IsModuleActive(addon)) then x = x .. " " .. STANDBY end return x end AceAddon.new = function(self, ...) local class = AceAddon:pcall(AceOO.Classpool, self, ...) return class:new() end function AceAddon:ManualEnable(addon) AceAddon:argCheck(addon, 2, "table") local first = nil if AceOO.inherits(addon, "AceAddon-2.0") then if AceAddon.addonsEnabled and not AceAddon.addonsEnabled[addon] then first = true AceAddon.addonsEnabled[addon] = true end end local current = addon.class while current and current ~= AceOO.Class do if current.mixins then for mixin in pairs(current.mixins) do if type(mixin.OnEmbedEnable) == "function" then safecall(mixin.OnEmbedEnable, mixin, addon, first) end end end current = current.super end if type(addon.OnEnable) == "function" then safecall(addon.OnEnable, addon, first) end if AceEvent then AceEvent:TriggerEvent("Ace2_AddonEnabled", addon, first) end end function AceAddon:ManualDisable(addon) AceAddon:argCheck(addon, 2, "table") local current = addon.class while current and current ~= AceOO.Class do if current.mixins then for mixin in pairs(current.mixins) do if type(mixin.OnEmbedDisable) == "function" then safecall(mixin.OnEmbedDisable, mixin, addon) end end end current = current.super end if type(module.OnDisable) == "function" then safecall(module.OnDisable, addon) end if AceEvent then AceEvent:TriggerEvent("Ace2_AddonDisabled", addon) end end local function external(self, major, instance) if major == "AceEvent-2.0" then AceEvent = instance AceEvent:embed(self) self:RegisterEvent("PLAYER_LOGIN", "PLAYER_LOGIN", true) elseif major == "AceConsole-2.0" then AceConsole = instance local slashCommands = { "/ace2" } local _,_,_,enabled,loadable = GetAddOnInfo("Ace") if not enabled or not loadable then table.insert(slashCommands, "/ace") end local function listAddon(addon, depth) if not depth then depth = 0 end local s = (" "):rep(depth) .. " - " .. tostring(addon) if rawget(addon, 'version') then s = s .. " - |cffffff7f" .. tostring(addon.version) .. "|r" end if rawget(addon, 'slashCommand') then s = s .. " |cffffff7f(" .. tostring(addon.slashCommand) .. ")|r" end print(s) if type(rawget(addon, 'modules')) == "table" then local i = 0 for k,v in pairs(addon.modules) do i = i + 1 if i == 6 then print((" "):rep(depth + 1) .. " - more...") break else listAddon(v, depth + 1) end end end end local function listNormalAddon(i) local name,_,_,enabled,loadable = GetAddOnInfo(i) if not loadable then enabled = false end if self.addons[name] then listAddon(self.addons[name]) else local s = " - " .. tostring(GetAddOnMetadata(i, "Title") or name) local version = GetAddOnMetadata(i, "Version") if version then if version:find("%$Revision: (%d+) %$") then version = version:gsub("%$Revision: (%d+) %$", "%1") elseif version:find("%$Rev: (%d+) %$") then version = version:gsub("%$Rev: (%d+) %$", "%1") elseif version:find("%$LastChangedRevision: (%d+) %$") then version = version:gsub("%$LastChangedRevision: (%d+) %$", "%1") end s = s .. " - |cffffff7f" .. version .. "|r" end if not enabled then s = s .. " |cffff0000(disabled)|r" end if IsAddOnLoadOnDemand(i) then s = s .. " |cff00ff00[LoD]|r" end print(s) end end local function mySort(alpha, bravo) return tostring(alpha) < tostring(bravo) end AceConsole.RegisterChatCommand(self, slashCommands, { desc = "AddOn development framework", name = "Ace2", type = "group", args = { about = { desc = "Get information about Ace2", name = "About", type = "execute", func = function() print("|cffffff7fAce2|r - |cffffff7f2.0." .. MINOR_VERSION:gsub("%$Revision: (%d+) %$", "%1") .. "|r - AddOn development framework") print(" - |cffffff7f" .. AUTHOR .. ":|r Ace Development Team") print(" - |cffffff7f" .. WEBSITE .. ":|r http://www.wowace.com/") end }, list = { desc = "List addons", name = "List", type = "group", args = { ace2 = { desc = "List addons using Ace2", name = "Ace2", type = "execute", func = function() print("|cffffff7fAddon list:|r") table.sort(self.addons, mySort) for _,v in ipairs(self.addons) do listAddon(v) end end }, all = { desc = "List all addons", name = "All", type = "execute", func = function() print("|cffffff7fAddon list:|r") local count = GetNumAddOns() for i = 1, count do listNormalAddon(i) end end }, enabled = { desc = "List all enabled addons", name = "Enabled", type = "execute", func = function() print("|cffffff7fAddon list:|r") local count = GetNumAddOns() for i = 1, count do local _,_,_,enabled,loadable = GetAddOnInfo(i) if enabled and loadable then listNormalAddon(i) end end end }, disabled = { desc = "List all disabled addons", name = "Disabled", type = "execute", func = function() print("|cffffff7fAddon list:|r") local count = GetNumAddOns() for i = 1, count do local _,_,_,enabled,loadable = GetAddOnInfo(i) if not enabled or not loadable then listNormalAddon(i) end end end }, lod = { desc = "List all LoadOnDemand addons", name = "LoadOnDemand", type = "execute", func = function() print("|cffffff7fAddon list:|r") local count = GetNumAddOns() for i = 1, count do if IsAddOnLoadOnDemand(i) then listNormalAddon(i) end end end }, ace1 = { desc = "List all addons using Ace1", name = "Ace 1.x", type = "execute", func = function() print("|cffffff7fAddon list:|r") local count = GetNumAddOns() for i = 1, count do local dep1, dep2, dep3, dep4 = GetAddOnDependencies(i) if dep1 == "Ace" or dep2 == "Ace" or dep3 == "Ace" or dep4 == "Ace" then listNormalAddon(i) end end end }, libs = { desc = "List all libraries using AceLibrary", name = "Libraries", type = "execute", func = function() if type(AceLibrary) == "table" and type(AceLibrary.libs) == "table" then print("|cffffff7fLibrary list:|r") for name, data in pairs(AceLibrary.libs) do local s if data.minor then s = " - " .. tostring(name) .. "." .. tostring(data.minor) else s = " - " .. tostring(name) end if rawget(AceLibrary(name), 'slashCommand') then s = s .. " |cffffff7f(" .. tostring(AceLibrary(name).slashCommand) .. "|cffffff7f)" end print(s) end end end }, search = { desc = "Search by name", name = "Search", type = "text", usage = "<keyword>", input = true, get = false, set = function(...) local arg = { ... } for i,v in ipairs(arg) do arg[i] = v:gsub('%*', '.*'):gsub('%%', '%%%%'):lower() end local count = GetNumAddOns() for i = 1, count do local name = GetAddOnInfo(i) local good = true for _,v in ipairs(arg) do if not name:lower():find(v) then good = false break end end if good then listNormalAddon(i) end end end } }, }, enable = { desc = "Enable addon(s).", name = "Enable", type = "text", usage = "<addon 1> <addon 2> ...", get = false, input = true, set = function(...) for i = 1, select("#", ...) do local addon = select(i, ...) local name, title, _, enabled, _, reason = GetAddOnInfo(addon) if reason == "MISSING" then print(("|cffffff7fAce2:|r AddOn %q does not exist."):format(addon)) elseif not enabled then EnableAddOn(addon) print(("|cffffff7fAce2:|r %s is now enabled."):format(addon or name)) else print(("|cffffff7fAce2:|r %s is already enabled."):format(addon or name)) end end end, }, disable = { desc = "Disable addon(s).", name = "Disable", type = "text", usage = "<addon 1> <addon 2> ...", get = false, input = true, set = function(...) for i = 1, select("#", ...) do local addon = select(i, ...) local name, title, _, enabled, _, reason = GetAddOnInfo(addon) if reason == "MISSING" then print(("|cffffff7fAce2:|r AddOn %q does not exist."):format(addon)) elseif enabled then DisableAddOn(addon) print(("|cffffff7fAce2:|r %s is now disabled."):format(addon or name)) else print(("|cffffff7fAce2:|r %s is already disabled."):format(addon or name)) end end end, }, load = { desc = "Load addon(s).", name = "Load", type = "text", usage = "<addon 1> <addon 2> ...", get = false, input = true, set = function(...) for i = 1, select("#", ...) do local addon = select(i, ...) local name, title, _, _, loadable, reason = GetAddOnInfo(addon) if reason == "MISSING" then print(("|cffffff7fAce2:|r AddOn %q does not exist."):format(addon)) elseif not loadable then print(("|cffffff7fAce2:|r AddOn %q is not loadable. Reason: %s."):format(addon, reason)) else LoadAddOn(addon) print(("|cffffff7fAce2:|r %s is now loaded."):format(addon or name)) end end end }, info = { desc = "Display information", name = "Information", type = "execute", func = function() local mem, threshold = gcinfo() print((" - |cffffff7fMemory usage [|r%.3f MiB|cffffff7f]|r"):format(mem / 1024)) if threshold then print((" - |cffffff7fThreshold [|r%.3f MiB|cffffff7f]|r"):format(threshold / 1024)) end print((" - |cffffff7fFramerate [|r%.0f fps|cffffff7f]|r"):format(GetFramerate())) local bandwidthIn, bandwidthOut, latency = GetNetStats() bandwidthIn, bandwidthOut = floor(bandwidthIn * 1024), floor(bandwidthOut * 1024) print((" - |cffffff7fLatency [|r%.0f ms|cffffff7f]|r"):format(latency)) print((" - |cffffff7fBandwidth in [|r%.0f B/s|cffffff7f]|r"):format(bandwidthIn)) print((" - |cffffff7fBandwidth out [|r%.0f B/s|cffffff7f]|r"):format(bandwidthOut)) print((" - |cffffff7fTotal addons [|r%d|cffffff7f]|r"):format(GetNumAddOns())) print((" - |cffffff7fAce2 addons [|r%d|cffffff7f]|r"):format(#self.addons)) local ace = 0 local enabled = 0 local disabled = 0 local lod = 0 for i = 1, GetNumAddOns() do local dep1, dep2, dep3, dep4 = GetAddOnDependencies(i) if dep1 == "Ace" or dep2 == "Ace" or dep3 == "Ace" or dep4 == "Ace" then ace = ace + 1 end if IsAddOnLoadOnDemand(i) then lod = lod + 1 end local isActive, loadable = select(4, GetAddOnInfo(i)) if not isActive or not loadable then disabled = disabled + 1 else enabled = enabled + 1 end end print((" - |cffffff7fAce 1.x addons [|r%d|cffffff7f]|r"):format(ace)) print((" - |cffffff7fLoadOnDemand addons [|r%d|cffffff7f]|r"):format(lod)) print((" - |cffffff7fenabled addons [|r%d|cffffff7f]|r"):format(enabled)) print((" - |cffffff7fdisabled addons [|r%d|cffffff7f]|r"):format(disabled)) local libs = 0 if type(AceLibrary) == "table" and type(AceLibrary.libs) == "table" then for _ in pairs(AceLibrary.libs) do libs = libs + 1 end end print((" - |cffffff7fAceLibrary instances [|r%d|cffffff7f]|r"):format(libs)) end } } }) elseif major == "AceModuleCore-2.0" then AceModuleCore = instance end end local function activate(self, oldLib, oldDeactivate) AceAddon = self self.addonsToOnEnable = oldLib and oldLib.addonsToOnEnable self.addons = oldLib and oldLib.addons or {} self.nextAddon = oldLib and oldLib.nextAddon or {} self.skipAddon = oldLib and oldLib.skipAddon or {} self.addonsStarted = oldLib and oldLib.addonsStarted or {} self.addonsEnabled = oldLib and oldLib.addonsEnabled or {} if oldDeactivate then oldDeactivate(oldLib) end end AceLibrary:Register(AceAddon, MAJOR_VERSION, MINOR_VERSION, activate, nil, external)
gpl-3.0
Phrohdoh/OpenRA
mods/ra/maps/fall-of-greece-1-personal-war/personal-war.lua
1
19910
--[[ Copyright 2007-2020 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you 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. For more information, see COPYING. ]] FootprintTrigger1 = { CPos.New(77, 85), CPos.New(77, 86), CPos.New(77, 87), CPos.New(77, 88) } Trigger1Rifles = { Rifle1, Rifle2, Rifle3, Rifle4 } DoomedHeliPath = { DoomedHeliEntry.Location, DoomedHeli.Location } FootprintTrigger2 = { CPos.New(90, 82), CPos.New(91, 82), CPos.New(93, 82), CPos.New(94, 82), CPos.New(95, 82), CPos.New(96, 82), CPos.New(97, 82), CPos.New(98, 82), CPos.New(99, 82), CPos.New(102, 82) } Grenadiers = { "e2", "e2", "e2", "e2", "e2" } FootprintTrigger3 = { CPos.New(88, 77), CPos.New(88, 76), CPos.New(91, 75), CPos.New(92, 75), CPos.New(93, 75), CPos.New(94, 75), CPos.New(95, 75), CPos.New(96, 75), CPos.New(97, 75), CPos.New(98, 75), CPos.New(99, 75), CPos.New(100, 75) } Trigger3Team = { Gren1, Gren2, Gren3, Gren4, Gren5, VillageMammoth } FootprintTrigger4 = { CPos.New(94, 60), CPos.New(95, 60), CPos.New(96, 60), CPos.New(97, 60), CPos.New(98, 60), CPos.New(99, 60), CPos.New(100, 60), CPos.New(101, 60), CPos.New(102, 60), CPos.New(103, 60), CPos.New(104, 60) } CivilianSquad1 = { "c1", "c2", "c3", "c4", "c5" } CivilianSquad2 = { "c6", "c7", "c8", "c9", "c10" } FootprintTrigger5 = { CPos.New(99, 53), CPos.New(100, 53), CPos.New(101, 53), CPos.New(102, 53), CPos.New(103, 53), CPos.New(104, 53) } Trigger5Team = { TeamFive1, TeamFive2, TeamFive3, TeamFive4, TeamFive5, TeamFive6, TeamFive7 } TentTeam = { "e1", "e1", "e1", "e1", "e3", "e3" } Doggos = { "dog", "dog", "dog" } SovietAttackers = { "3tnk", "e2", "e2", "e2", "v2rl" } MigEntryPath = { BaseAttackersSpawn, GuideSpawn } FootprintTrigger6 = { CPos.New(81, 57), CPos.New(81, 58), CPos.New(81, 59), CPos.New(81, 60), CPos.New(81, 61) } FootprintTrigger7 = { CPos.New(73, 58), CPos.New(73, 59), CPos.New(73, 60), CPos.New(73, 61) } FootprintTrigger8 = { CPos.New(51, 83), CPos.New(51, 84), CPos.New(51, 85), CPos.New(51, 86), CPos.New(51, 87), CPos.New(51, 88) } FootprintTrigger9 = { CPos.New(28, 77), CPos.New(29, 77), CPos.New(30, 77), CPos.New(31, 77), CPos.New(32, 77), CPos.New(33, 77), CPos.New(34, 77), CPos.New(35, 77), CPos.New(36, 77), CPos.New(37, 77), CPos.New(38, 77) } BridgeMammoths = { BridgeMammoth1, BridgeMammoth2 } FootprintTrigger10 = { CPos.New(24, 83), CPos.New(24, 84), CPos.New(24, 85) } FootprintTrigger11 = { CPos.New(20, 65), CPos.New(21, 65), CPos.New(22, 65) } SovBase = { SovFact, SovPower1, SovPower2, SovRax, SovWarFactory, SovFlame1, SovFlame2, SovTesla } SovBaseTeam = { SovBaseTeam1, SovBaseTeam2, SovBaseTeam3, SovBaseTeam4, SovBaseTeam5, SovBaseTeam6 } RaxTeam = { "e1", "e2", "e2", "e4", "e4", "shok" } FootprintTrigger12 = { CPos.New(35, 39), CPos.New(35, 40), CPos.New(35, 41), CPos.New(35, 42) } ExtractionHelicopterType = "tran" ExtractionPath = { ChinookEntry.Location, ExtractionPoint.Location } lstReinforcements = { first = { actors = { "2tnk", "2tnk", "2tnk", "2tnk", "2tnk" }, entryPath = { BoatSpawn.Location, BoatUnload1.Location }, exitPath = { BoatSpawn.Location } }, second = { actors = { "1tnk", "1tnk", "2tnk", "2tnk", "2tnk" }, entryPath = { BoatSpawn.Location, BoatUnload2.Location }, exitPath = { BoatSpawn.Location } } } IdleHunt = function(actor) if not actor.IsDead then Trigger.OnIdle(actor, actor.Hunt) end end VIPs = { } MissionStart = function() FlareBoy.Move(LightFlare.Location) Trigger.OnEnteredFootprint({ LightFlare.Location }, function(actor, id) if actor.Owner == England then Trigger.RemoveFootprintTrigger(id) local insertionFlare = Actor.Create("flare", true, { Owner = Allies, Location = LightFlare.Location }) Trigger.AfterDelay(DateTime.Seconds(2), function() FlareBoy.AttackMove(FlareBoyAttack.Location) if Map.LobbyOption("difficulty") == "normal" then local normalDrop = InsertionDrop.TargetParatroopers(InsertionPoint.CenterPosition, Angle.New(892)) Utils.Do(normalDrop, function(a) Trigger.OnPassengerExited(a, function(t,p) VIPs[#VIPs + 1] = p FailTrigger() end) end) else local hardDrop = InsertionDropHard.TargetParatroopers(InsertionPoint.CenterPosition, Angle.New(892)) Utils.Do(hardDrop, function(a) Trigger.OnPassengerExited(a, function(t,p) VIPs[#VIPs + 1] = p FailTrigger() end) end) Trigger.AfterDelay(DateTime.Seconds(6), function() Media.DisplayMessage("Commander, there are several civilians in the area.\nWe'll need you to call out targets.", "Tanya") end) end end) Trigger.AfterDelay(DateTime.Seconds(20), function() insertionFlare.Destroy() end) end end) end FailTrigger = function() Trigger.OnAnyKilled(VIPs, function() Allies.MarkFailedObjective(ProtectVIPs) end) end FootprintTriggers = function() local foot1Triggered Trigger.OnEnteredFootprint(FootprintTrigger1, function(actor, id) if actor.Owner == Allies and not foot1Triggered then Trigger.RemoveFootprintTrigger(id) foot1Triggered = true local trig1cam = Actor.Create("camera", true, { Owner = Allies, Location = Trigger1Cam.Location }) Trigger.AfterDelay(DateTime.Seconds(10), function() trig1cam.Destroy() end) Utils.Do(Trigger1Rifles, function(actor) if not actor.IsDead then actor.AttackMove(Trigger1Move.Location) end end) DoomedHeli = Reinforcements.ReinforceWithTransport(England, ExtractionHelicopterType, nil, DoomedHeliPath)[1] end end) local foot2Triggered Trigger.OnEnteredFootprint(FootprintTrigger2, function(actor, id) if actor.Owner == Allies and not foot2Triggered then Trigger.RemoveFootprintTrigger(id) foot2Triggered = true local drop1 = RifleDropS.TargetParatroopers(VillageParadrop.CenterPosition, Angle.SouthWest) Utils.Do(drop1, function(a) Trigger.OnPassengerExited(a, function(t, p) IdleHunt(p) end) end) local grens = Reinforcements.Reinforce(USSR, Grenadiers, { GrenEntry.Location }, 0) Utils.Do(grens, IdleHunt) end end) local foot3Triggered Trigger.OnEnteredFootprint(FootprintTrigger3, function(actor, id) if actor.Owner == Allies and not foot3Triggered then Trigger.RemoveFootprintTrigger(id) foot3Triggered = true Trig3House.Owner = Civilians local camera3 = Actor.Create("camera", true, { Owner = Allies, Location = Trigger3Cam.Location }) Trigger.AfterDelay(DateTime.Seconds(10), function() camera3.Destroy() end) if not GuideHut.IsDead then local guide = Actor.Create("c6", true, { Owner = England, Location = GuideSpawn.Location }) guide.Move(SafePath1.Location) guide.Move(SafePath2.Location) guide.Move(CivilianRally.Location) end Utils.Do(Trigger3Team, function(actor) if not actor.IsDead then actor.AttackMove(GuideSpawn.Location) IdleHunt(actor) end end) end end) local foot4Triggered Trigger.OnEnteredFootprint(FootprintTrigger4, function(actor, id) if actor.Owner == Allies and not foot4Triggered then Trigger.RemoveFootprintTrigger(id) foot4Triggered = true Trig4House.Owner = Civilians Reinforcements.Reinforce(England, CivilianSquad1, { CivFlee1.Location, CivilianRally.Location }, 0) Reinforcements.Reinforce(England, CivilianSquad2, { CivFlee2.Location, CivilianRally.Location }, 0) end end) local foot5Triggered Trigger.OnEnteredFootprint(FootprintTrigger5, function(actor, id) if actor.Owner == Allies and not foot5Triggered then Trigger.RemoveFootprintTrigger(id) foot5Triggered = true Media.PlaySoundNotification(Allies, "AlertBleep") Media.DisplayMessage("Alfa Niner this is Lima One Six. Be advised, Soviet aircraft and armor moving into your AO.", "Headquarters") Utils.Do(Trigger5Team, function(actor) if not actor.IsDead then actor.AttackMove(TacticalNuke1.Location) end end) SendMig(MigEntryPath) local barrelcam1 = Actor.Create("camera", true, { Owner = USSR, Location = TacticalNuke1.Location }) local barrelcam2 = Actor.Create("camera", true, { Owner = USSR, Location = TacticalNuke2.Location }) local wave1 = Reinforcements.Reinforce(USSR, SovietAttackers, { BaseAttackersSpawn.Location, SovietAttack.Location }) Utils.Do(wave1, IdleHunt) local drop2 = RifleDropS.TargetParatroopers(SovietAttack.CenterPosition, Angle.East) Utils.Do(drop2, function(a) Trigger.OnPassengerExited(a, function(t, p) IdleHunt(p) end) end) Trigger.AfterDelay(DateTime.Seconds(20), function() Media.PlaySoundNotification(Allies, "AlertBuzzer") Media.DisplayMessage("Extraction point is compromised. Evacuate the base!", "Headquarters") local defenders = Reinforcements.Reinforce(England, TentTeam, { Tent.Location, TentMove.Location }, 0) Utils.Do(defenders, IdleHunt) if Map.LobbyOption("difficulty") == "hard" then Trigger.AfterDelay(DateTime.Seconds(30), function() local wave2 = Reinforcements.Reinforce(USSR, SovietAttackers, { BaseAttackersSpawn.Location, SovietAttack.Location }) Utils.Do(wave2, IdleHunt) end) end end) Trigger.AfterDelay(DateTime.Seconds(35), function() local dogs = Reinforcements.Reinforce(USSR, Doggos, { GrenEntry.Location }, 0) Utils.Do(dogs, IdleHunt) Media.PlaySpeechNotification(Allies, "AbombLaunchDetected") local proxy = Actor.Create("powerproxy.parabombs", false, { Owner = USSR }) proxy.TargetAirstrike(TacticalNuke1.CenterPosition, Angle.NorthWest) Trigger.AfterDelay(DateTime.Seconds(5), function() Media.PlaySpeechNotification(Allies, "AbombLaunchDetected") proxy.TargetAirstrike(TacticalNuke2.CenterPosition, Angle.NorthWest) end) proxy.Destroy() end) Trigger.AfterDelay(DateTime.Seconds(50), function() Media.DisplayMessage("We've set up a new extraction point to the Northwest.", "Headquarters") end) end end) local foot6Triggered Trigger.OnEnteredFootprint(FootprintTrigger6, function(actor, id) if actor.Owner == Allies and not foot6Triggered then Trigger.RemoveFootprintTrigger(id) foot6Triggered = true local reinforcement = lstReinforcements.first Media.PlaySpeechNotification(Allies, "ReinforcementsArrived") Reinforcements.ReinforceWithTransport(Allies, "lst.reinforcement", reinforcement.actors, reinforcement.entryPath, reinforcement.exitPath) end end) local foot7Triggered Trigger.OnEnteredFootprint(FootprintTrigger7, function(actor, id) if actor.Owner == Allies and not foot7Triggered then Trigger.RemoveFootprintTrigger(id) foot7Triggered = true local drop3 = RifleDropS.TargetParatroopers(TacticalNuke3.CenterPosition, Angle.West) Utils.Do(drop3, function(a) Trigger.OnPassengerExited(a, function(t, p) IdleHunt(p) end) end) local trig7camera1 = Actor.Create("camera", true, { Owner = Allies, Location = MammothCam.Location }) local trig7camera2 = Actor.Create("camera", true, { Owner = Allies, Location = TacticalNuke3.Location }) Trigger.AfterDelay(DateTime.Seconds(30), function() trig7camera1.Destroy() end) Trigger.AfterDelay(DateTime.Seconds(20), function() Media.PlaySpeechNotification(Allies, "AbombLaunchDetected") local proxy = Actor.Create("powerproxy.parabombs", false, { Owner = USSR }) proxy.TargetAirstrike(TacticalNuke3.CenterPosition, Angle.SouthWest) proxy.Destroy() end) Trigger.AfterDelay(DateTime.Seconds(26), function() Reinforcements.Reinforce(England, CivilianSquad1, { House1.Location, TacticalNuke3.Location }, 0) Reinforcements.Reinforce(England, CivilianSquad2, { House2.Location, TacticalNuke3.Location }, 0) Reinforcements.Reinforce(England, CivilianSquad1, { House3.Location, TacticalNuke3.Location }, 0) Reinforcements.Reinforce(England, CivilianSquad2, { House4.Location, TacticalNuke3.Location }, 0) end) Trigger.AfterDelay(DateTime.Seconds(15), function() trig7camera2.Destroy() end) end end) local foot8Triggered Trigger.OnEnteredFootprint(FootprintTrigger8, function(actor, id) if actor.Owner == Allies and not foot8Triggered then Trigger.RemoveFootprintTrigger(id) foot8Triggered = true local trig8camera = Actor.Create("camera", true, { Owner = Allies, Location = TeslaCam.Location }) Trigger.AfterDelay(DateTime.Seconds(10), function() trig8camera.Destroy() end) Media.PlaySpeechNotification(Allies, "ReinforcementsArrived") RifleDropA.TargetParatroopers(TeslaDrop.CenterPosition, Angle.New(124)) end end) local foot9Triggered Trigger.OnEnteredFootprint(FootprintTrigger9, function(actor, id) if actor.Owner == Allies and not foot9Triggered then Trigger.RemoveFootprintTrigger(id) foot9Triggered = true local trig9camera = Actor.Create("camera", true, { Owner = Allies, Location = BridgeCam.Location }) Trigger.AfterDelay(DateTime.Seconds(10), function() trig9camera.Destroy() end) Utils.Do(BridgeMammoths, function(actor) actor.AttackMove(MammysGo.Location) end) end end) local foot10Triggered Trigger.OnEnteredFootprint(FootprintTrigger10, function(actor, id) if actor.Owner == Allies and not foot10Triggered then Trigger.RemoveFootprintTrigger(id) foot10Triggered = true local trig10camera = Actor.Create("camera", true, { Owner = Allies, Location = TruckCam.Location }) Trigger.AfterDelay(DateTime.Seconds(10), function() trig10camera.Destroy() end) Media.PlaySpeechNotification(Allies, "SignalFlareNorth") Actor.Create("camera", true, { Owner = Allies, Location = ExtractionPoint.Location }) SendExtractionHelicopter() HealCrateTruck.Move(TruckGo.Location) end end) local foot11Triggered Trigger.OnEnteredFootprint(FootprintTrigger11, function(actor, id) if actor.Owner == Allies and not foot11Triggered then Trigger.RemoveFootprintTrigger(id) foot11Triggered = true local trig11camera = Actor.Create("camera", true, { Owner = Allies, Location = SovBaseCam.Location }) Trigger.AfterDelay(DateTime.Seconds(10), function() trig11camera.Destroy() end) local reinforcement = lstReinforcements.second Media.PlaySpeechNotification(Allies, "ReinforcementsArrived") Reinforcements.ReinforceWithTransport(Allies, "lst.reinforcement", reinforcement.actors, reinforcement.entryPath, reinforcement.exitPath) end end) local foot12Triggered Trigger.OnEnteredFootprint(FootprintTrigger12, function(actor, id) if (actor.Type == "gnrl" or actor.Type == "gnrl.noautotarget") and not foot12Triggered then Trigger.RemoveFootprintTrigger(id) foot12Triggered = true Media.PlaySoundNotification(Allies, "AlertBleep") Media.DisplayMessage("Stalin will pay for what he has done today!\nI will bury him with my own hands!", "Stavros") end end) end SetupTriggers = function() Utils.Do(USSR.GetGroundAttackers(), function(unit) Trigger.OnDamaged(unit, function() IdleHunt(unit) end) end) Trigger.OnKilled(BridgeBarrel1, function() local bridge = Utils.Where(Map.ActorsInWorld, function(actor) return actor.Type == "bridge2" end)[1] if not bridge.IsDead then bridge.Kill() end end) Trigger.OnKilled(BridgeBarrel2, function() local bridgepart1 = Utils.Where(Map.ActorsInWorld, function(actor) return actor.Type == "br2" end)[1] local bridgepart2 = Utils.Where(Map.ActorsInWorld, function(actor) return actor.Type == "br3" end)[1] if not bridgepart1.IsDead then bridgepart1.Kill() end if not bridgepart2.IsDead then bridgepart2.Kill() end end) local trukEscaped Trigger.OnEnteredFootprint({ TruckGo.Location }, function(actor, id) if actor.Type == "truk" and not trukEscaped then Trigger.RemoveFootprintTrigger(id) trukEscaped = true actor.Destroy() end end) end ChurchAttack = function() if not ChurchDamaged then local churchPanicTeam = Reinforcements.Reinforce(England, CivilianSquad1, { ChurchSpawn.Location }, 0) Utils.Do(churchPanicTeam, function(a) a.Move(a.Location + CVec.New(-1,-1)) a.Panic() end) end ChurchDamaged = true end SendMig = function(waypoints) local MigEntryPath = { waypoints[1].Location, waypoints[2].Location } local Mig1 = Reinforcements.Reinforce(USSR, { "mig" }, MigEntryPath) if not BridgeBarrel1.IsDead then Utils.Do(Mig1, function(mig) mig.Attack(BridgeBarrel1) end) end Trigger.AfterDelay(DateTime.Seconds(5), function() local Mig2 = Reinforcements.Reinforce(USSR, { "mig" }, MigEntryPath) local Mig3 = Reinforcements.Reinforce(USSR, { "mig" }, MigEntryPath) if not CivBarrel.IsDead then Utils.Do(Mig2, function(mig) mig.Attack(CivBarrel) end) end if not DoomedHeli.IsDead then Utils.Do(Mig3, function(mig) mig.Attack(DoomedHeli) end) end end) end SovBaseAttack = function() if not BaseDamaged then local drop4 = RifleDropS.TargetParatroopers(SovBaseDrop.CenterPosition, Angle.East) Utils.Do(drop4, function(a) Trigger.OnPassengerExited(a, function(t, p) IdleHunt(p) end) end) Utils.Do(SovBaseTeam, function(actor) if not actor.IsDead then IdleHunt(actor) end end) if Map.LobbyOption("difficulty") == "hard" then local barracksTeam = Reinforcements.Reinforce(USSR, RaxTeam, { SovRaxSpawn.Location, SovBaseCam.Location }, 0) Utils.Do(barracksTeam, IdleHunt) end end BaseDamaged = true end ExtractUnits = function(extractionUnit, pos, after) if extractionUnit.IsDead or not extractionUnit.HasPassengers then return end extractionUnit.Move(pos) extractionUnit.Destroy() Trigger.OnRemovedFromWorld(extractionUnit, after) end SendExtractionHelicopter = function() ExtractionHeli = Reinforcements.ReinforceWithTransport(Allies, ExtractionHelicopterType, nil, ExtractionPath)[1] local exitPos = CPos.New(ExtractionPath[1].X, ExtractionPath[2].Y) Trigger.OnKilled(ExtractionHeli, function() USSR.MarkCompletedObjective(SovietObj) end) Trigger.OnAllRemovedFromWorld(VIPs, function() ExtractUnits(ExtractionHeli, exitPos, function() Allies.MarkCompletedObjective(ProtectVIPs) Allies.MarkCompletedObjective(ExtractStavros) end) end) end WorldLoaded = function() Allies = Player.GetPlayer("Allies") USSR = Player.GetPlayer("USSR") BadGuy = Player.GetPlayer("BadGuy") England = Player.GetPlayer("England") Civilians = Player.GetPlayer("GreekCivilians") Trigger.OnObjectiveAdded(Allies, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) SovietObj = USSR.AddObjective("Kill Stavros.") ProtectVIPs = Allies.AddObjective("Keep Stavros and Tanya alive.") ExtractStavros = Allies.AddObjective("Get Stavros and Tanya to the extraction helicopter.") Trigger.OnObjectiveCompleted(Allies, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(Allies, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerLost(Allies, function() Media.PlaySpeechNotification(Allies, "Lose") end) Trigger.OnPlayerWon(Allies, function() Media.PlaySpeechNotification(Allies, "Win") end) InsertionDrop = Actor.Create("insertiondrop", false, { Owner = Allies }) InsertionDropHard = Actor.Create("insertiondrophard", false, { Owner = Allies }) RifleDropA = Actor.Create("rifledrop", false, { Owner = Allies }) RifleDropS = Actor.Create("rifledrop", false, { Owner = USSR }) Camera.Position = LightFlare.CenterPosition MissionStart() FootprintTriggers() SetupTriggers() Trigger.OnDamaged(Church, ChurchAttack) OnAnyDamaged(SovBase, SovBaseAttack) end OnAnyDamaged = function(actors, func) Utils.Do(actors, function(actor) Trigger.OnDamaged(actor, func) end) end
gpl-3.0
ProjectSkyfire/SkyFire-Community-Tools
FireAdmin/dbc.lua
3
139442
 function ReturnMapName(MapID) if MapID == "0" then return "Eastern Kingdoms" elseif MapID == "1" then return "Kalimdor" elseif MapID == "13" then return "Testing" elseif MapID == "25" then return "Scott Test" elseif MapID == "29" then return "CashTest" elseif MapID == "30" then return "Alterac Valley" elseif MapID == "33" then return "Shadowfang Keep" elseif MapID == "34" then return "Stormwind Stockade" elseif MapID == "35" then return "<unused>StormwindPrison" elseif MapID == "36" then return "Deadmines" elseif MapID == "37" then return "Azshara Crater" elseif MapID == "42" then return "Collin's Test" elseif MapID == "43" then return "Wailing Caverns" elseif MapID == "44" then return "<unused> Monastery" elseif MapID == "47" then return "Razorfen Kraul" elseif MapID == "48" then return "Blackfathom Deeps" elseif MapID == "70" then return "Uldaman" elseif MapID == "90" then return "Gnomeregan" elseif MapID == "109" then return "Sunken Temple" elseif MapID == "129" then return "Razorfen Downs" elseif MapID == "169" then return "Emerald Dream" elseif MapID == "189" then return "Scarlet Monastery" elseif MapID == "209" then return "Zul'Farrak" elseif MapID == "229" then return "Blackrock Spire" elseif MapID == "230" then return "Blackrock Depths" elseif MapID == "249" then return "Onyxia's Lair" elseif MapID == "269" then return "Opening of the Dark Portal" elseif MapID == "289" then return "Scholomance" elseif MapID == "309" then return "Zul'Gurub" elseif MapID == "329" then return "Stratholme" elseif MapID == "349" then return "Maraudon" elseif MapID == "369" then return "Deeprun Tram" elseif MapID == "389" then return "Ragefire Chasm" elseif MapID == "409" then return "Molten Core" elseif MapID == "429" then return "Dire Maul" elseif MapID == "449" then return "Alliance PVP Barracks" elseif MapID == "450" then return "Horde PVP Barracks" elseif MapID == "451" then return "Development Land" elseif MapID == "469" then return "Blackwing Lair" elseif MapID == "489" then return "Warsong Gulch" elseif MapID == "509" then return "Ruins of Ahn'Qiraj" elseif MapID == "529" then return "Arathi Basin" elseif MapID == "530" then return "Outland" elseif MapID == "531" then return "Ahn'Qiraj Temple" elseif MapID == "532" then return "Karazhan" elseif MapID == "533" then return "Naxxramas" elseif MapID == "534" then return "The Battle for Mount Hyjal" elseif MapID == "540" then return "Hellfire Citadel: The Shattered Halls" elseif MapID == "542" then return "Hellfire Citadel: The Blood Furnace" elseif MapID == "543" then return "Hellfire Citadel: Ramparts" elseif MapID == "544" then return "Magtheridon's Lair" elseif MapID == "545" then return "Coilfang: The Steamvault" elseif MapID == "546" then return "Coilfang: The Underbog" elseif MapID == "547" then return "Coilfang: The Slave Pens" elseif MapID == "548" then return "Coilfang: Serpentshrine Cavern" elseif MapID == "550" then return "Tempest Keep" elseif MapID == "552" then return "Tempest Keep: The Arcatraz" elseif MapID == "553" then return "Tempest Keep: The Botanica" elseif MapID == "554" then return "Tempest Keep: The Mechanar" elseif MapID == "555" then return "Auchindoun: Shadow Labyrinth" elseif MapID == "556" then return "Auchindoun: Sethekk Halls" elseif MapID == "557" then return "Auchindoun: Mana-Tombs" elseif MapID == "558" then return "Auchindoun: Auchenai Crypts" elseif MapID == "559" then return "Nagrand Arena" elseif MapID == "560" then return "The Escape From Durnholde" elseif MapID == "562" then return "Blade's Edge Arena" elseif MapID == "564" then return "Black Temple" elseif MapID == "565" then return "Gruul's Lair" elseif MapID == "566" then return "Eye of the Storm" elseif MapID == "568" then return "Zul'Aman" elseif MapID == "571" then return "Northrend" elseif MapID == "572" then return "Ruins of Lordaeron" elseif MapID == "573" then return "ExteriorTest" elseif MapID == "574" then return "Utgarde Keep" elseif MapID == "575" then return "Utgarde Pinnacle" elseif MapID == "576" then return "The Nexus" elseif MapID == "578" then return "The Oculus" elseif MapID == "580" then return "The Sunwell" elseif MapID == "582" then return "Transport: Rut'theran to Auberdine" elseif MapID == "584" then return "Transport: Menethil to Theramore" elseif MapID == "585" then return "Magister's Terrace" elseif MapID == "586" then return "Transport: Exodar to Auberdine" elseif MapID == "587" then return "Transport: Feathermoon Ferry" elseif MapID == "588" then return "Transport: Menethil to Auberdine" elseif MapID == "589" then return "Transport: Orgrimmar to Grom'Gol" elseif MapID == "590" then return "Transport: Grom'Gol to Undercity" elseif MapID == "591" then return "Transport: Undercity to Orgrimmar" elseif MapID == "592" then return "Transport: Borean Tundra Test" elseif MapID == "593" then return "Transport: Booty Bay to Ratchet" elseif MapID == "594" then return "Transport: Howling Fjord Sister Mercy (Quest)" elseif MapID == "595" then return "The Culling of Stratholme" elseif MapID == "596" then return "Transport: Naglfar" elseif MapID == "597" then return "Craig Test" elseif MapID == "598" then return "Sunwell Fix (Unused)" elseif MapID == "599" then return "Halls of Stone" elseif MapID == "600" then return "Drak'Tharon Keep" elseif MapID == "601" then return "Azjol-Nerub" elseif MapID == "602" then return "Halls of Lightning" elseif MapID == "603" then return "Ulduar" elseif MapID == "604" then return "Gundrak" elseif MapID == "605" then return "Development Land (non-weighted textures)" elseif MapID == "606" then return "QA and DVD" elseif MapID == "607" then return "Strand of the Ancients" elseif MapID == "608" then return "Violet Hold" elseif MapID == "609" then return "Ebon Hold" elseif MapID == "610" then return "Transport: Tirisfal to Vengeance Landing" elseif MapID == "612" then return "Transport: Menethil to Valgarde" elseif MapID == "613" then return "Transport: Orgrimmar to Warsong Hold" elseif MapID == "614" then return "Transport: Stormwind to Valiance Keep" elseif MapID == "615" then return "The Obsidian Sanctum" elseif MapID == "616" then return "The Eye of Eternity" elseif MapID == "617" then return "Dalaran Sewers" elseif MapID == "618" then return "The Ring of Valor" elseif MapID == "619" then return "Ahn'kahet: The Old Kingdom" elseif MapID == "620" then return "Transport: Moa'ki to Unu'pe" elseif MapID == "621" then return "Transport: Moa'ki to Kamagua" elseif MapID == "622" then return "Transport: Orgrim's Hammer" elseif MapID == "623" then return "Transport: The Skybreaker" elseif MapID == "624" then return "Vault of Archavon" elseif MapID == "628" then return "Isle of Conquest" elseif MapID == "641" then return "Transport: Alliance Airship BG" elseif MapID == "642" then return "Transport: HordeAirshipBG" elseif MapID == "647" then return "Transport: Orgrimmar to Thunder Bluff" elseif MapID == "649" then return "Trial of the Crusader" elseif MapID == "650" then return "Trial of the Champion" else return "BUG" end end function ReturnAreaName(ZoneID) if ZoneID == "1" then return "Dun Morogh" elseif ZoneID == "2" then return "Longshore" elseif ZoneID == "3" then return "Badlands" elseif ZoneID == "4" then return "Blasted Lands" elseif ZoneID == "7" then return "Blackwater Cove" elseif ZoneID == "8" then return "Swamp of Sorrows" elseif ZoneID == "9" then return "Northshire Valley" elseif ZoneID == "10" then return "Duskwood" elseif ZoneID == "11" then return "Wetlands" elseif ZoneID == "12" then return "Elwynn Forest" elseif ZoneID == "13" then return "The World Tree" elseif ZoneID == "14" then return "Durotar" elseif ZoneID == "15" then return "Dustwallow Marsh" elseif ZoneID == "16" then return "Azshara" elseif ZoneID == "17" then return "The Barrens" elseif ZoneID == "18" then return "Crystal Lake" elseif ZoneID == "19" then return "Zul'Gurub" elseif ZoneID == "20" then return "Moonbrook" elseif ZoneID == "21" then return "Kul Tiras" elseif ZoneID == "22" then return "Programmer Isle" elseif ZoneID == "23" then return "Northshire River" elseif ZoneID == "24" then return "Northshire Abbey" elseif ZoneID == "25" then return "Blackrock Mountain" elseif ZoneID == "26" then return "Lighthouse" elseif ZoneID == "28" then return "Western Plaguelands" elseif ZoneID == "30" then return "Nine" elseif ZoneID == "32" then return "The Cemetary" elseif ZoneID == "33" then return "Stranglethorn Vale" elseif ZoneID == "34" then return "Echo Ridge Mine" elseif ZoneID == "35" then return "Booty Bay" elseif ZoneID == "36" then return "Alterac Mountains" elseif ZoneID == "37" then return "Lake Nazferiti" elseif ZoneID == "38" then return "Loch Modan" elseif ZoneID == "40" then return "Westfall" elseif ZoneID == "41" then return "Deadwind Pass" elseif ZoneID == "42" then return "Darkshire" elseif ZoneID == "43" then return "Wild Shore" elseif ZoneID == "44" then return "Redridge Mountains" elseif ZoneID == "45" then return "Arathi Highlands" elseif ZoneID == "46" then return "Burning Steppes" elseif ZoneID == "47" then return "The Hinterlands" elseif ZoneID == "49" then return "Dead Man's Hole" elseif ZoneID == "51" then return "Searing Gorge" elseif ZoneID == "53" then return "Thieves Camp" elseif ZoneID == "54" then return "Jasperlode Mine" elseif ZoneID == "55" then return "Valley of Heroes UNUSED" elseif ZoneID == "56" then return "Heroes' Vigil" elseif ZoneID == "57" then return "Fargodeep Mine" elseif ZoneID == "59" then return "Northshire Vineyards" elseif ZoneID == "60" then return "Forest's Edge" elseif ZoneID == "61" then return "Thunder Falls" elseif ZoneID == "62" then return "Brackwell Pumpkin Patch" elseif ZoneID == "63" then return "The Stonefield Farm" elseif ZoneID == "64" then return "The Maclure Vineyards" elseif ZoneID == "65" then return "Dragonblight" elseif ZoneID == "66" then return "Zul'Drak" elseif ZoneID == "67" then return "The Storm Peaks" elseif ZoneID == "68" then return "Lake Everstill" elseif ZoneID == "69" then return "Lakeshire" elseif ZoneID == "70" then return "Stonewatch" elseif ZoneID == "71" then return "Stonewatch Falls" elseif ZoneID == "72" then return "The Dark Portal" elseif ZoneID == "73" then return "The Tainted Scar" elseif ZoneID == "74" then return "Pool of Tears" elseif ZoneID == "75" then return "Stonard" elseif ZoneID == "76" then return "Fallow Sanctuary" elseif ZoneID == "77" then return "Anvilmar" elseif ZoneID == "80" then return "Stormwind Mountains" elseif ZoneID == "81" then return "Jeff NE Quadrant Changed" elseif ZoneID == "82" then return "Jeff NW Quadrant" elseif ZoneID == "83" then return "Jeff SE Quadrant" elseif ZoneID == "84" then return "Jeff SW Quadrant" elseif ZoneID == "85" then return "Tirisfal Glades" elseif ZoneID == "86" then return "Stone Cairn Lake" elseif ZoneID == "87" then return "Goldshire" elseif ZoneID == "88" then return "Eastvale Logging Camp" elseif ZoneID == "89" then return "Mirror Lake Orchard" elseif ZoneID == "91" then return "Tower of Azora" elseif ZoneID == "92" then return "Mirror Lake" elseif ZoneID == "93" then return "Vul'Gol Ogre Mound" elseif ZoneID == "94" then return "Raven Hill" elseif ZoneID == "95" then return "Redridge Canyons" elseif ZoneID == "96" then return "Tower of Ilgalar" elseif ZoneID == "97" then return "Alther's Mill" elseif ZoneID == "98" then return "Rethban Caverns" elseif ZoneID == "99" then return "Rebel Camp" elseif ZoneID == "100" then return "Nesingwary's Expedition" elseif ZoneID == "101" then return "Kurzen's Compound" elseif ZoneID == "102" then return "Ruins of Zul'Kunda" elseif ZoneID == "103" then return "Ruins of Zul'Mamwe" elseif ZoneID == "104" then return "The Vile Reef" elseif ZoneID == "105" then return "Mosh'Ogg Ogre Mound" elseif ZoneID == "106" then return "The Stockpile" elseif ZoneID == "107" then return "Saldean's Farm" elseif ZoneID == "108" then return "Sentinel Hill" elseif ZoneID == "109" then return "Furlbrow's Pumpkin Farm" elseif ZoneID == "111" then return "Jangolode Mine" elseif ZoneID == "113" then return "Gold Coast Quarry" elseif ZoneID == "115" then return "Westfall Lighthouse" elseif ZoneID == "116" then return "Misty Valley" elseif ZoneID == "117" then return "Grom'gol Base Camp" elseif ZoneID == "118" then return "Whelgar's Excavation Site" elseif ZoneID == "120" then return "Westbrook Garrison" elseif ZoneID == "121" then return "Tranquil Gardens Cemetery" elseif ZoneID == "122" then return "Zuuldaia Ruins" elseif ZoneID == "123" then return "Bal'lal Ruins" elseif ZoneID == "125" then return "Kal'ai Ruins" elseif ZoneID == "126" then return "Tkashi Ruins" elseif ZoneID == "127" then return "Balia'mah Ruins" elseif ZoneID == "128" then return "Ziata'jai Ruins" elseif ZoneID == "129" then return "Mizjah Ruins" elseif ZoneID == "130" then return "Silverpine Forest" elseif ZoneID == "131" then return "Kharanos" elseif ZoneID == "132" then return "Coldridge Valley" elseif ZoneID == "133" then return "Gnomeregan" elseif ZoneID == "134" then return "Gol'Bolar Quarry" elseif ZoneID == "135" then return "Frostmane Hold" elseif ZoneID == "136" then return "The Grizzled Den" elseif ZoneID == "137" then return "Brewnall Village" elseif ZoneID == "138" then return "Misty Pine Refuge" elseif ZoneID == "139" then return "Eastern Plaguelands" elseif ZoneID == "141" then return "Teldrassil" elseif ZoneID == "142" then return "Ironband's Excavation Site" elseif ZoneID == "143" then return "Mo'grosh Stronghold" elseif ZoneID == "144" then return "Thelsamar" elseif ZoneID == "145" then return "Algaz Gate" elseif ZoneID == "146" then return "Stonewrought Dam" elseif ZoneID == "147" then return "The Farstrider Lodge" elseif ZoneID == "148" then return "Darkshore" elseif ZoneID == "149" then return "Silver Stream Mine" elseif ZoneID == "150" then return "Menethil Harbor" elseif ZoneID == "151" then return "Designer Island" elseif ZoneID == "152" then return "The Bulwark" elseif ZoneID == "153" then return "Ruins of Lordaeron" elseif ZoneID == "154" then return "Deathknell" elseif ZoneID == "155" then return "Night Web's Hollow" elseif ZoneID == "156" then return "Solliden Farmstead" elseif ZoneID == "157" then return "Agamand Mills" elseif ZoneID == "158" then return "Agamand Family Crypt" elseif ZoneID == "159" then return "Brill" elseif ZoneID == "160" then return "Whispering Gardens" elseif ZoneID == "161" then return "Terrace of Repose" elseif ZoneID == "162" then return "Brightwater Lake" elseif ZoneID == "163" then return "Gunther's Retreat" elseif ZoneID == "164" then return "Garren's Haunt" elseif ZoneID == "165" then return "Balnir Farmstead" elseif ZoneID == "166" then return "Cold Hearth Manor" elseif ZoneID == "167" then return "Crusader Outpost" elseif ZoneID == "168" then return "The North Coast" elseif ZoneID == "169" then return "Whispering Shore" elseif ZoneID == "170" then return "Lordamere Lake" elseif ZoneID == "172" then return "Fenris Isle" elseif ZoneID == "173" then return "Faol's Rest" elseif ZoneID == "186" then return "Dolanaar" elseif ZoneID == "187" then return "Darnassus UNUSED" elseif ZoneID == "188" then return "Shadowglen" elseif ZoneID == "189" then return "Steelgrill's Depot" elseif ZoneID == "190" then return "Hearthglen" elseif ZoneID == "192" then return "Northridge Lumber Camp" elseif ZoneID == "193" then return "Ruins of Andorhal" elseif ZoneID == "195" then return "School of Necromancy" elseif ZoneID == "196" then return "Uther's Tomb" elseif ZoneID == "197" then return "Sorrow Hill" elseif ZoneID == "198" then return "The Weeping Cave" elseif ZoneID == "199" then return "Felstone Field" elseif ZoneID == "200" then return "Dalson's Tears" elseif ZoneID == "201" then return "Gahrron's Withering" elseif ZoneID == "202" then return "The Writhing Haunt" elseif ZoneID == "203" then return "Mardenholde Keep" elseif ZoneID == "204" then return "Pyrewood Village" elseif ZoneID == "205" then return "Dun Modr" elseif ZoneID == "206" then return "Utgarde Keep" elseif ZoneID == "207" then return "The Great Sea" elseif ZoneID == "208" then return "Unused Ironcladcove" elseif ZoneID == "209" then return "Shadowfang Keep" elseif ZoneID == "210" then return "Icecrown" elseif ZoneID == "211" then return "Iceflow Lake" elseif ZoneID == "212" then return "Helm's Bed Lake" elseif ZoneID == "213" then return "Deep Elem Mine" elseif ZoneID == "214" then return "The Great Sea" elseif ZoneID == "215" then return "Mulgore" elseif ZoneID == "219" then return "Alexston Farmstead" elseif ZoneID == "220" then return "Red Cloud Mesa" elseif ZoneID == "221" then return "Camp Narache" elseif ZoneID == "222" then return "Bloodhoof Village" elseif ZoneID == "223" then return "Stonebull Lake" elseif ZoneID == "224" then return "Ravaged Caravan" elseif ZoneID == "225" then return "Red Rocks" elseif ZoneID == "226" then return "The Skittering Dark" elseif ZoneID == "227" then return "Valgan's Field" elseif ZoneID == "228" then return "The Sepulcher" elseif ZoneID == "229" then return "Olsen's Farthing" elseif ZoneID == "230" then return "The Greymane Wall" elseif ZoneID == "231" then return "Beren's Peril" elseif ZoneID == "232" then return "The Dawning Isles" elseif ZoneID == "233" then return "Ambermill" elseif ZoneID == "235" then return "Fenris Keep" elseif ZoneID == "236" then return "Shadowfang Keep" elseif ZoneID == "237" then return "The Decrepit Ferry" elseif ZoneID == "238" then return "Malden's Orchard" elseif ZoneID == "239" then return "The Ivar Patch" elseif ZoneID == "240" then return "The Dead Field" elseif ZoneID == "241" then return "The Rotting Orchard" elseif ZoneID == "242" then return "Brightwood Grove" elseif ZoneID == "243" then return "Forlorn Rowe" elseif ZoneID == "244" then return "The Whipple Estate" elseif ZoneID == "245" then return "The Yorgen Farmstead" elseif ZoneID == "246" then return "The Cauldron" elseif ZoneID == "247" then return "Grimesilt Dig Site" elseif ZoneID == "249" then return "Dreadmaul Rock" elseif ZoneID == "250" then return "Ruins of Thaurissan" elseif ZoneID == "251" then return "Flame Crest" elseif ZoneID == "252" then return "Blackrock Stronghold" elseif ZoneID == "253" then return "The Pillar of Ash" elseif ZoneID == "254" then return "Blackrock Mountain" elseif ZoneID == "255" then return "Altar of Storms" elseif ZoneID == "256" then return "Aldrassil" elseif ZoneID == "257" then return "Shadowthread Cave" elseif ZoneID == "258" then return "Fel Rock" elseif ZoneID == "259" then return "Lake Al'Ameth" elseif ZoneID == "260" then return "Starbreeze Village" elseif ZoneID == "261" then return "Gnarlpine Hold" elseif ZoneID == "262" then return "Ban'ethil Barrow Den" elseif ZoneID == "263" then return "The Cleft" elseif ZoneID == "264" then return "The Oracle Glade" elseif ZoneID == "265" then return "Wellspring River" elseif ZoneID == "266" then return "Wellspring Lake" elseif ZoneID == "267" then return "Hillsbrad Foothills" elseif ZoneID == "268" then return "Azshara Crater" elseif ZoneID == "269" then return "Dun Algaz" elseif ZoneID == "271" then return "Southshore" elseif ZoneID == "272" then return "Tarren Mill" elseif ZoneID == "275" then return "Durnholde Keep" elseif ZoneID == "276" then return "UNUSED Stonewrought Pass" elseif ZoneID == "277" then return "The Foothill Caverns" elseif ZoneID == "278" then return "Lordamere Internment Camp" elseif ZoneID == "279" then return "Dalaran Crater" elseif ZoneID == "280" then return "Strahnbrad" elseif ZoneID == "281" then return "Ruins of Alterac" elseif ZoneID == "282" then return "Crushridge Hold" elseif ZoneID == "283" then return "Slaughter Hollow" elseif ZoneID == "284" then return "The Uplands" elseif ZoneID == "285" then return "Southpoint Tower" elseif ZoneID == "286" then return "Hillsbrad Fields" elseif ZoneID == "287" then return "Hillsbrad" elseif ZoneID == "288" then return "Azurelode Mine" elseif ZoneID == "289" then return "Nethander Stead" elseif ZoneID == "290" then return "Dun Garok" elseif ZoneID == "293" then return "Thoradin's Wall" elseif ZoneID == "294" then return "Eastern Strand" elseif ZoneID == "295" then return "Western Strand" elseif ZoneID == "296" then return "South Seas UNUSED" elseif ZoneID == "297" then return "Jaguero Isle" elseif ZoneID == "298" then return "Baradin Bay" elseif ZoneID == "299" then return "Menethil Bay" elseif ZoneID == "300" then return "Misty Reed Strand" elseif ZoneID == "301" then return "The Savage Coast" elseif ZoneID == "302" then return "The Crystal Shore" elseif ZoneID == "303" then return "Shell Beach" elseif ZoneID == "305" then return "North Tide's Run" elseif ZoneID == "306" then return "South Tide's Run" elseif ZoneID == "307" then return "The Overlook Cliffs" elseif ZoneID == "308" then return "The Forbidding Sea" elseif ZoneID == "309" then return "Ironbeard's Tomb" elseif ZoneID == "310" then return "Crystalvein Mine" elseif ZoneID == "311" then return "Ruins of Aboraz" elseif ZoneID == "312" then return "Janeiro's Point" elseif ZoneID == "313" then return "Northfold Manor" elseif ZoneID == "314" then return "Go'Shek Farm" elseif ZoneID == "315" then return "Dabyrie's Farmstead" elseif ZoneID == "316" then return "Boulderfist Hall" elseif ZoneID == "317" then return "Witherbark Village" elseif ZoneID == "318" then return "Drywhisker Gorge" elseif ZoneID == "320" then return "Refuge Pointe" elseif ZoneID == "321" then return "Hammerfall" elseif ZoneID == "322" then return "Blackwater Shipwrecks" elseif ZoneID == "323" then return "O'Breen's Camp" elseif ZoneID == "324" then return "Stromgarde Keep" elseif ZoneID == "325" then return "The Tower of Arathor" elseif ZoneID == "326" then return "The Sanctum" elseif ZoneID == "327" then return "Faldir's Cove" elseif ZoneID == "328" then return "The Drowned Reef" elseif ZoneID == "330" then return "Thandol Span" elseif ZoneID == "331" then return "Ashenvale" elseif ZoneID == "332" then return "The Great Sea" elseif ZoneID == "333" then return "Circle of East Binding" elseif ZoneID == "334" then return "Circle of West Binding" elseif ZoneID == "335" then return "Circle of Inner Binding" elseif ZoneID == "336" then return "Circle of Outer Binding" elseif ZoneID == "337" then return "Apocryphan's Rest" elseif ZoneID == "338" then return "Angor Fortress" elseif ZoneID == "339" then return "Lethlor Ravine" elseif ZoneID == "340" then return "Kargath" elseif ZoneID == "341" then return "Camp Kosh" elseif ZoneID == "342" then return "Camp Boff" elseif ZoneID == "343" then return "Camp Wurg" elseif ZoneID == "344" then return "Camp Cagg" elseif ZoneID == "345" then return "Agmond's End" elseif ZoneID == "346" then return "Hammertoe's Digsite" elseif ZoneID == "347" then return "Dustbelch Grotto" elseif ZoneID == "348" then return "Aerie Peak" elseif ZoneID == "349" then return "Wildhammer Keep" elseif ZoneID == "350" then return "Quel'Danil Lodge" elseif ZoneID == "351" then return "Skulk Rock" elseif ZoneID == "352" then return "Zun'watha" elseif ZoneID == "353" then return "Shadra'Alor" elseif ZoneID == "354" then return "Jintha'Alor" elseif ZoneID == "355" then return "The Altar of Zul" elseif ZoneID == "356" then return "Seradane" elseif ZoneID == "357" then return "Feralas" elseif ZoneID == "358" then return "Brambleblade Ravine" elseif ZoneID == "359" then return "Bael Modan" elseif ZoneID == "360" then return "The Venture Co. Mine" elseif ZoneID == "361" then return "Felwood" elseif ZoneID == "362" then return "Razor Hill" elseif ZoneID == "363" then return "Valley of Trials" elseif ZoneID == "364" then return "The Den" elseif ZoneID == "365" then return "Burning Blade Coven" elseif ZoneID == "366" then return "Kolkar Crag" elseif ZoneID == "367" then return "Sen'jin Village" elseif ZoneID == "368" then return "Echo Isles" elseif ZoneID == "369" then return "Thunder Ridge" elseif ZoneID == "370" then return "Drygulch Ravine" elseif ZoneID == "371" then return "Dustwind Cave" elseif ZoneID == "372" then return "Tiragarde Keep" elseif ZoneID == "373" then return "Scuttle Coast" elseif ZoneID == "374" then return "Bladefist Bay" elseif ZoneID == "375" then return "Deadeye Shore" elseif ZoneID == "377" then return "Southfury River" elseif ZoneID == "378" then return "Camp Taurajo" elseif ZoneID == "379" then return "Far Watch Post" elseif ZoneID == "380" then return "The Crossroads" elseif ZoneID == "381" then return "Boulder Lode Mine" elseif ZoneID == "382" then return "The Sludge Fen" elseif ZoneID == "383" then return "The Dry Hills" elseif ZoneID == "384" then return "Dreadmist Peak" elseif ZoneID == "385" then return "Northwatch Hold" elseif ZoneID == "386" then return "The Forgotten Pools" elseif ZoneID == "387" then return "Lushwater Oasis" elseif ZoneID == "388" then return "The Stagnant Oasis" elseif ZoneID == "390" then return "Field of Giants" elseif ZoneID == "391" then return "The Merchant Coast" elseif ZoneID == "392" then return "Ratchet" elseif ZoneID == "393" then return "Darkspear Strand" elseif ZoneID == "394" then return "Grizzly Hills" elseif ZoneID == "395" then return "Grizzlemaw" elseif ZoneID == "396" then return "Winterhoof Water Well" elseif ZoneID == "397" then return "Thunderhorn Water Well" elseif ZoneID == "398" then return "Wildmane Water Well" elseif ZoneID == "399" then return "Skyline Ridge" elseif ZoneID == "400" then return "Thousand Needles" elseif ZoneID == "401" then return "The Tidus Stair" elseif ZoneID == "403" then return "Shady Rest Inn" elseif ZoneID == "404" then return "Bael'dun Digsite" elseif ZoneID == "405" then return "Desolace" elseif ZoneID == "406" then return "Stonetalon Mountains" elseif ZoneID == "407" then return "Orgrimmar UNUSED" elseif ZoneID == "408" then return "Gillijim's Isle" elseif ZoneID == "409" then return "Island of Doctor Lapidis" elseif ZoneID == "410" then return "Razorwind Canyon" elseif ZoneID == "411" then return "Bathran's Haunt" elseif ZoneID == "412" then return "The Ruins of Ordil'Aran" elseif ZoneID == "413" then return "Maestra's Post" elseif ZoneID == "414" then return "The Zoram Strand" elseif ZoneID == "415" then return "Astranaar" elseif ZoneID == "416" then return "The Shrine of Aessina" elseif ZoneID == "417" then return "Fire Scar Shrine" elseif ZoneID == "418" then return "The Ruins of Stardust" elseif ZoneID == "419" then return "The Howling Vale" elseif ZoneID == "420" then return "Silverwind Refuge" elseif ZoneID == "421" then return "Mystral Lake" elseif ZoneID == "422" then return "Fallen Sky Lake" elseif ZoneID == "424" then return "Iris Lake" elseif ZoneID == "425" then return "Moonwell" elseif ZoneID == "426" then return "Raynewood Retreat" elseif ZoneID == "427" then return "The Shady Nook" elseif ZoneID == "428" then return "Night Run" elseif ZoneID == "429" then return "Xavian" elseif ZoneID == "430" then return "Satyrnaar" elseif ZoneID == "431" then return "Splintertree Post" elseif ZoneID == "432" then return "The Dor'Danil Barrow Den" elseif ZoneID == "433" then return "Falfarren River" elseif ZoneID == "434" then return "Felfire Hill" elseif ZoneID == "435" then return "Demon Fall Canyon" elseif ZoneID == "436" then return "Demon Fall Ridge" elseif ZoneID == "437" then return "Warsong Lumber Camp" elseif ZoneID == "438" then return "Bough Shadow" elseif ZoneID == "439" then return "The Shimmering Flats" elseif ZoneID == "440" then return "Tanaris" elseif ZoneID == "441" then return "Lake Falathim" elseif ZoneID == "442" then return "Auberdine" elseif ZoneID == "443" then return "Ruins of Mathystra" elseif ZoneID == "444" then return "Tower of Althalaxx" elseif ZoneID == "445" then return "Cliffspring Falls" elseif ZoneID == "446" then return "Bashal'Aran" elseif ZoneID == "447" then return "Ameth'Aran" elseif ZoneID == "448" then return "Grove of the Ancients" elseif ZoneID == "449" then return "The Master's Glaive" elseif ZoneID == "450" then return "Remtravel's Excavation" elseif ZoneID == "452" then return "Mist's Edge" elseif ZoneID == "453" then return "The Long Wash" elseif ZoneID == "454" then return "Wildbend River" elseif ZoneID == "455" then return "Blackwood Den" elseif ZoneID == "456" then return "Cliffspring River" elseif ZoneID == "457" then return "The Veiled Sea" elseif ZoneID == "458" then return "Gold Road" elseif ZoneID == "459" then return "Scarlet Watch Post" elseif ZoneID == "460" then return "Sun Rock Retreat" elseif ZoneID == "461" then return "Windshear Crag" elseif ZoneID == "463" then return "Cragpool Lake" elseif ZoneID == "464" then return "Mirkfallon Lake" elseif ZoneID == "465" then return "The Charred Vale" elseif ZoneID == "466" then return "Valley of the Bloodfuries" elseif ZoneID == "467" then return "Stonetalon Peak" elseif ZoneID == "468" then return "The Talon Den" elseif ZoneID == "469" then return "Greatwood Vale" elseif ZoneID == "470" then return "Thunder Bluff UNUSED" elseif ZoneID == "471" then return "Brave Wind Mesa" elseif ZoneID == "472" then return "Fire Stone Mesa" elseif ZoneID == "473" then return "Mantle Rock" elseif ZoneID == "474" then return "Hunter Rise UNUSED" elseif ZoneID == "475" then return "Spirit RiseUNUSED" elseif ZoneID == "476" then return "Elder RiseUNUSED" elseif ZoneID == "477" then return "Ruins of Jubuwal" elseif ZoneID == "478" then return "Pools of Arlithrien" elseif ZoneID == "479" then return "The Rustmaul Dig Site" elseif ZoneID == "480" then return "Camp E'thok" elseif ZoneID == "481" then return "Splithoof Crag" elseif ZoneID == "482" then return "Highperch" elseif ZoneID == "483" then return "The Screeching Canyon" elseif ZoneID == "484" then return "Freewind Post" elseif ZoneID == "485" then return "The Great Lift" elseif ZoneID == "486" then return "Galak Hold" elseif ZoneID == "487" then return "Roguefeather Den" elseif ZoneID == "488" then return "The Weathered Nook" elseif ZoneID == "489" then return "Thalanaar" elseif ZoneID == "490" then return "Un'Goro Crater" elseif ZoneID == "491" then return "Razorfen Kraul" elseif ZoneID == "492" then return "Raven Hill Cemetery" elseif ZoneID == "493" then return "Moonglade" elseif ZoneID == "495" then return "Howling Fjord" elseif ZoneID == "496" then return "Brackenwall Village" elseif ZoneID == "497" then return "Swamplight Manor" elseif ZoneID == "498" then return "Bloodfen Burrow" elseif ZoneID == "499" then return "Darkmist Cavern" elseif ZoneID == "500" then return "Moggle Point" elseif ZoneID == "501" then return "Beezil's Wreck" elseif ZoneID == "502" then return "Witch Hill" elseif ZoneID == "503" then return "Sentry Point" elseif ZoneID == "504" then return "North Point Tower" elseif ZoneID == "505" then return "West Point Tower" elseif ZoneID == "506" then return "Lost Point" elseif ZoneID == "507" then return "Bluefen" elseif ZoneID == "508" then return "Stonemaul Ruins" elseif ZoneID == "509" then return "The Den of Flame" elseif ZoneID == "510" then return "The Dragonmurk" elseif ZoneID == "511" then return "Wyrmbog" elseif ZoneID == "512" then return "Blackhoof Village" elseif ZoneID == "513" then return "Theramore Isle" elseif ZoneID == "514" then return "Foothold Citadel" elseif ZoneID == "515" then return "Ironclad Prison" elseif ZoneID == "516" then return "Dustwallow Bay" elseif ZoneID == "517" then return "Tidefury Cove" elseif ZoneID == "518" then return "Dreadmurk Shore" elseif ZoneID == "536" then return "Addle's Stead" elseif ZoneID == "537" then return "Fire Plume Ridge" elseif ZoneID == "538" then return "Lakkari Tar Pits" elseif ZoneID == "539" then return "Terror Run" elseif ZoneID == "540" then return "The Slithering Scar" elseif ZoneID == "541" then return "Marshal's Refuge" elseif ZoneID == "542" then return "Fungal Rock" elseif ZoneID == "543" then return "Golakka Hot Springs" elseif ZoneID == "556" then return "The Loch" elseif ZoneID == "576" then return "Beggar's Haunt" elseif ZoneID == "596" then return "Kodo Graveyard" elseif ZoneID == "597" then return "Ghost Walker Post" elseif ZoneID == "598" then return "Sar'theris Strand" elseif ZoneID == "599" then return "Thunder Axe Fortress" elseif ZoneID == "600" then return "Bolgan's Hole" elseif ZoneID == "602" then return "Mannoroc Coven" elseif ZoneID == "603" then return "Sargeron" elseif ZoneID == "604" then return "Magram Village" elseif ZoneID == "606" then return "Gelkis Village" elseif ZoneID == "607" then return "Valley of Spears" elseif ZoneID == "608" then return "Nijel's Point" elseif ZoneID == "609" then return "Kolkar Village" elseif ZoneID == "616" then return "Hyjal" elseif ZoneID == "618" then return "Winterspring" elseif ZoneID == "636" then return "Blackwolf River" elseif ZoneID == "637" then return "Kodo Rock" elseif ZoneID == "638" then return "Hidden Path" elseif ZoneID == "639" then return "Spirit Rock" elseif ZoneID == "640" then return "Shrine of the Dormant Flame" elseif ZoneID == "656" then return "Lake Elune'ara" elseif ZoneID == "657" then return "The Harborage" elseif ZoneID == "676" then return "Outland" elseif ZoneID == "696" then return "Craftsmen's Terrace UNUSED" elseif ZoneID == "697" then return "Tradesmen's Terrace UNUSED" elseif ZoneID == "698" then return "The Temple Gardens UNUSED" elseif ZoneID == "699" then return "Temple of Elune UNUSED" elseif ZoneID == "700" then return "Cenarion Enclave UNUSED" elseif ZoneID == "701" then return "Warrior's Terrace UNUSED" elseif ZoneID == "702" then return "Rut'theran Village" elseif ZoneID == "716" then return "Ironband's Compound" elseif ZoneID == "717" then return "The Stockade" elseif ZoneID == "718" then return "Wailing Caverns" elseif ZoneID == "719" then return "Blackfathom Deeps" elseif ZoneID == "720" then return "Fray Island" elseif ZoneID == "721" then return "Gnomeregan" elseif ZoneID == "722" then return "Razorfen Downs" elseif ZoneID == "736" then return "Ban'ethil Hollow" elseif ZoneID == "796" then return "Scarlet Monastery" elseif ZoneID == "797" then return "Jerod's Landing" elseif ZoneID == "798" then return "Ridgepoint Tower" elseif ZoneID == "799" then return "The Darkened Bank" elseif ZoneID == "800" then return "Coldridge Pass" elseif ZoneID == "801" then return "Chill Breeze Valley" elseif ZoneID == "802" then return "Shimmer Ridge" elseif ZoneID == "803" then return "Amberstill Ranch" elseif ZoneID == "804" then return "The Tundrid Hills" elseif ZoneID == "805" then return "South Gate Pass" elseif ZoneID == "806" then return "South Gate Outpost" elseif ZoneID == "807" then return "North Gate Pass" elseif ZoneID == "808" then return "North Gate Outpost" elseif ZoneID == "809" then return "Gates of Ironforge" elseif ZoneID == "810" then return "Stillwater Pond" elseif ZoneID == "811" then return "Nightmare Vale" elseif ZoneID == "812" then return "Venomweb Vale" elseif ZoneID == "813" then return "The Bulwark" elseif ZoneID == "814" then return "Southfury River" elseif ZoneID == "815" then return "Southfury River" elseif ZoneID == "816" then return "Razormane Grounds" elseif ZoneID == "817" then return "Skull Rock" elseif ZoneID == "818" then return "Palemane Rock" elseif ZoneID == "819" then return "Windfury Ridge" elseif ZoneID == "820" then return "The Golden Plains" elseif ZoneID == "821" then return "The Rolling Plains" elseif ZoneID == "836" then return "Dun Algaz" elseif ZoneID == "837" then return "Dun Algaz" elseif ZoneID == "838" then return "North Gate Pass" elseif ZoneID == "839" then return "South Gate Pass" elseif ZoneID == "856" then return "Twilight Grove" elseif ZoneID == "876" then return "GM Island" elseif ZoneID == "877" then return "Delete ME" elseif ZoneID == "878" then return "Southfury River" elseif ZoneID == "879" then return "Southfury River" elseif ZoneID == "880" then return "Thandol Span" elseif ZoneID == "881" then return "Thandol Span" elseif ZoneID == "896" then return "Purgation Isle" elseif ZoneID == "916" then return "The Jansen Stead" elseif ZoneID == "917" then return "The Dead Acre" elseif ZoneID == "918" then return "The Molsen Farm" elseif ZoneID == "919" then return "Stendel's Pond" elseif ZoneID == "920" then return "The Dagger Hills" elseif ZoneID == "921" then return "Demont's Place" elseif ZoneID == "922" then return "The Dust Plains" elseif ZoneID == "923" then return "Stonesplinter Valley" elseif ZoneID == "924" then return "Valley of Kings" elseif ZoneID == "925" then return "Algaz Station" elseif ZoneID == "926" then return "Bucklebree Farm" elseif ZoneID == "927" then return "The Shining Strand" elseif ZoneID == "928" then return "North Tide's Hollow" elseif ZoneID == "936" then return "Grizzlepaw Ridge" elseif ZoneID == "956" then return "The Verdant Fields" elseif ZoneID == "976" then return "Gadgetzan" elseif ZoneID == "977" then return "Steamwheedle Port" elseif ZoneID == "978" then return "Zul'Farrak" elseif ZoneID == "979" then return "Sandsorrow Watch" elseif ZoneID == "980" then return "Thistleshrub Valley" elseif ZoneID == "981" then return "The Gaping Chasm" elseif ZoneID == "982" then return "The Noxious Lair" elseif ZoneID == "983" then return "Dunemaul Compound" elseif ZoneID == "984" then return "Eastmoon Ruins" elseif ZoneID == "985" then return "Waterspring Field" elseif ZoneID == "986" then return "Zalashji's Den" elseif ZoneID == "987" then return "Land's End Beach" elseif ZoneID == "988" then return "Wavestrider Beach" elseif ZoneID == "989" then return "Uldum" elseif ZoneID == "990" then return "Valley of the Watchers" elseif ZoneID == "991" then return "Gunstan's Post" elseif ZoneID == "992" then return "Southmoon Ruins" elseif ZoneID == "996" then return "Render's Camp" elseif ZoneID == "997" then return "Render's Valley" elseif ZoneID == "998" then return "Render's Rock" elseif ZoneID == "999" then return "Stonewatch Tower" elseif ZoneID == "1000" then return "Galardell Valley" elseif ZoneID == "1001" then return "Lakeridge Highway" elseif ZoneID == "1002" then return "Three Corners" elseif ZoneID == "1016" then return "Direforge Hill" elseif ZoneID == "1017" then return "Raptor Ridge" elseif ZoneID == "1018" then return "Black Channel Marsh" elseif ZoneID == "1019" then return "The Green Belt" elseif ZoneID == "1020" then return "Mosshide Fen" elseif ZoneID == "1021" then return "Thelgen Rock" elseif ZoneID == "1022" then return "Bluegill Marsh" elseif ZoneID == "1023" then return "Saltspray Glen" elseif ZoneID == "1024" then return "Sundown Marsh" elseif ZoneID == "1025" then return "The Green Belt" elseif ZoneID == "1036" then return "Angerfang Encampment" elseif ZoneID == "1037" then return "Grim Batol" elseif ZoneID == "1038" then return "Dragonmaw Gates" elseif ZoneID == "1039" then return "The Lost Fleet" elseif ZoneID == "1056" then return "Darrow Hill" elseif ZoneID == "1057" then return "Thoradin's Wall" elseif ZoneID == "1076" then return "Webwinder Path" elseif ZoneID == "1097" then return "The Hushed Bank" elseif ZoneID == "1098" then return "Manor Mistmantle" elseif ZoneID == "1099" then return "Camp Mojache" elseif ZoneID == "1100" then return "Grimtotem Compound" elseif ZoneID == "1101" then return "The Writhing Deep" elseif ZoneID == "1102" then return "Wildwind Lake" elseif ZoneID == "1103" then return "Gordunni Outpost" elseif ZoneID == "1104" then return "Mok'Gordun" elseif ZoneID == "1105" then return "Feral Scar Vale" elseif ZoneID == "1106" then return "Frayfeather Highlands" elseif ZoneID == "1107" then return "Idlewind Lake" elseif ZoneID == "1108" then return "The Forgotten Coast" elseif ZoneID == "1109" then return "East Pillar" elseif ZoneID == "1110" then return "West Pillar" elseif ZoneID == "1111" then return "Dream Bough" elseif ZoneID == "1112" then return "Jademir Lake" elseif ZoneID == "1113" then return "Oneiros" elseif ZoneID == "1114" then return "Ruins of Ravenwind" elseif ZoneID == "1115" then return "Rage Scar Hold" elseif ZoneID == "1116" then return "Feathermoon Stronghold" elseif ZoneID == "1117" then return "Ruins of Solarsal" elseif ZoneID == "1118" then return "Lower Wilds UNUSED" elseif ZoneID == "1119" then return "The Twin Colossals" elseif ZoneID == "1120" then return "Sardor Isle" elseif ZoneID == "1121" then return "Isle of Dread" elseif ZoneID == "1136" then return "High Wilderness" elseif ZoneID == "1137" then return "Lower Wilds" elseif ZoneID == "1156" then return "Southern Barrens" elseif ZoneID == "1157" then return "Southern Gold Road" elseif ZoneID == "1176" then return "Zul'Farrak" elseif ZoneID == "1196" then return "Utgarde Pinnacle" elseif ZoneID == "1216" then return "Timbermaw Hold" elseif ZoneID == "1217" then return "Vanndir Encampment" elseif ZoneID == "1218" then return "TESTAzshara" elseif ZoneID == "1219" then return "Legash Encampment" elseif ZoneID == "1220" then return "Thalassian Base Camp" elseif ZoneID == "1221" then return "Ruins of Eldarath " elseif ZoneID == "1222" then return "Hetaera's Clutch" elseif ZoneID == "1223" then return "Temple of Zin-Malor" elseif ZoneID == "1224" then return "Bear's Head" elseif ZoneID == "1225" then return "Ursolan" elseif ZoneID == "1226" then return "Temple of Arkkoran" elseif ZoneID == "1227" then return "Bay of Storms" elseif ZoneID == "1228" then return "The Shattered Strand" elseif ZoneID == "1229" then return "Tower of Eldara" elseif ZoneID == "1230" then return "Jagged Reef" elseif ZoneID == "1231" then return "Southridge Beach" elseif ZoneID == "1232" then return "Ravencrest Monument" elseif ZoneID == "1233" then return "Forlorn Ridge" elseif ZoneID == "1234" then return "Lake Mennar" elseif ZoneID == "1235" then return "Shadowsong Shrine" elseif ZoneID == "1236" then return "Haldarr Encampment" elseif ZoneID == "1237" then return "Valormok" elseif ZoneID == "1256" then return "The Ruined Reaches" elseif ZoneID == "1276" then return "The Talondeep Path" elseif ZoneID == "1277" then return "The Talondeep Path" elseif ZoneID == "1296" then return "Rocktusk Farm" elseif ZoneID == "1297" then return "Jaggedswine Farm" elseif ZoneID == "1316" then return "Razorfen Downs" elseif ZoneID == "1336" then return "Lost Rigger Cove" elseif ZoneID == "1337" then return "Uldaman" elseif ZoneID == "1338" then return "Lordamere Lake" elseif ZoneID == "1339" then return "Lordamere Lake" elseif ZoneID == "1357" then return "Gallows' Corner" elseif ZoneID == "1377" then return "Silithus" elseif ZoneID == "1397" then return "Emerald Forest" elseif ZoneID == "1417" then return "Sunken Temple" elseif ZoneID == "1437" then return "Dreadmaul Hold" elseif ZoneID == "1438" then return "Nethergarde Keep" elseif ZoneID == "1439" then return "Dreadmaul Post" elseif ZoneID == "1440" then return "Serpent's Coil" elseif ZoneID == "1441" then return "Altar of Storms" elseif ZoneID == "1442" then return "Firewatch Ridge" elseif ZoneID == "1443" then return "The Slag Pit" elseif ZoneID == "1444" then return "The Sea of Cinders" elseif ZoneID == "1445" then return "Blackrock Mountain" elseif ZoneID == "1446" then return "Thorium Point" elseif ZoneID == "1457" then return "Garrison Armory" elseif ZoneID == "1477" then return "The Temple of Atal'Hakkar" elseif ZoneID == "1497" then return "Undercity" elseif ZoneID == "1517" then return "Uldaman" elseif ZoneID == "1518" then return "Not Used Deadmines" elseif ZoneID == "1519" then return "Stormwind City" elseif ZoneID == "1537" then return "Ironforge" elseif ZoneID == "1557" then return "Splithoof Hold" elseif ZoneID == "1577" then return "The Cape of Stranglethorn" elseif ZoneID == "1578" then return "Southern Savage Coast" elseif ZoneID == "1579" then return "Unused The Deadmines 002" elseif ZoneID == "1580" then return "Unused Ironclad Cove 003" elseif ZoneID == "1581" then return "The Deadmines" elseif ZoneID == "1582" then return "Ironclad Cove" elseif ZoneID == "1583" then return "Blackrock Spire" elseif ZoneID == "1584" then return "Blackrock Depths" elseif ZoneID == "1597" then return "Raptor Grounds UNUSED" elseif ZoneID == "1598" then return "Grol'dom Farm UNUSED" elseif ZoneID == "1599" then return "Mor'shan Base Camp" elseif ZoneID == "1600" then return "Honor's Stand UNUSED" elseif ZoneID == "1601" then return "Blackthorn Ridge UNUSED" elseif ZoneID == "1602" then return "Bramblescar UNUSED" elseif ZoneID == "1603" then return "Agama'gor UNUSED" elseif ZoneID == "1617" then return "Valley of Heroes" elseif ZoneID == "1637" then return "Orgrimmar" elseif ZoneID == "1638" then return "Thunder Bluff" elseif ZoneID == "1639" then return "Elder Rise" elseif ZoneID == "1640" then return "Spirit Rise" elseif ZoneID == "1641" then return "Hunter Rise" elseif ZoneID == "1657" then return "Darnassus" elseif ZoneID == "1658" then return "Cenarion Enclave" elseif ZoneID == "1659" then return "Craftsmen's Terrace" elseif ZoneID == "1660" then return "Warrior's Terrace" elseif ZoneID == "1661" then return "The Temple Gardens" elseif ZoneID == "1662" then return "Tradesmen's Terrace" elseif ZoneID == "1677" then return "Gavin's Naze" elseif ZoneID == "1678" then return "Sofera's Naze" elseif ZoneID == "1679" then return "Corrahn's Dagger" elseif ZoneID == "1680" then return "The Headland" elseif ZoneID == "1681" then return "Misty Shore" elseif ZoneID == "1682" then return "Dandred's Fold" elseif ZoneID == "1683" then return "Growless Cave" elseif ZoneID == "1684" then return "Chillwind Point" elseif ZoneID == "1697" then return "Raptor Grounds" elseif ZoneID == "1698" then return "Bramblescar" elseif ZoneID == "1699" then return "Thorn Hill" elseif ZoneID == "1700" then return "Agama'gor" elseif ZoneID == "1701" then return "Blackthorn Ridge" elseif ZoneID == "1702" then return "Honor's Stand" elseif ZoneID == "1703" then return "The Mor'shan Rampart" elseif ZoneID == "1704" then return "Grol'dom Farm" elseif ZoneID == "1717" then return "Razorfen Kraul" elseif ZoneID == "1718" then return "The Great Lift" elseif ZoneID == "1737" then return "Mistvale Valley" elseif ZoneID == "1738" then return "Nek'mani Wellspring" elseif ZoneID == "1739" then return "Bloodsail Compound" elseif ZoneID == "1740" then return "Venture Co. Base Camp" elseif ZoneID == "1741" then return "Gurubashi Arena" elseif ZoneID == "1742" then return "Spirit Den" elseif ZoneID == "1757" then return "The Crimson Veil" elseif ZoneID == "1758" then return "The Riptide" elseif ZoneID == "1759" then return "The Damsel's Luck" elseif ZoneID == "1760" then return "Venture Co. Operations Center" elseif ZoneID == "1761" then return "Deadwood Village" elseif ZoneID == "1762" then return "Felpaw Village" elseif ZoneID == "1763" then return "Jaedenar" elseif ZoneID == "1764" then return "Bloodvenom River" elseif ZoneID == "1765" then return "Bloodvenom Falls" elseif ZoneID == "1766" then return "Shatter Scar Vale" elseif ZoneID == "1767" then return "Irontree Woods" elseif ZoneID == "1768" then return "Irontree Cavern" elseif ZoneID == "1769" then return "Timbermaw Hold" elseif ZoneID == "1770" then return "Shadow Hold" elseif ZoneID == "1771" then return "Shrine of the Deceiver" elseif ZoneID == "1777" then return "Itharius's Cave" elseif ZoneID == "1778" then return "Sorrowmurk" elseif ZoneID == "1779" then return "Draenil'dur Village" elseif ZoneID == "1780" then return "Splinterspear Junction" elseif ZoneID == "1797" then return "Stagalbog" elseif ZoneID == "1798" then return "The Shifting Mire" elseif ZoneID == "1817" then return "Stagalbog Cave" elseif ZoneID == "1837" then return "Witherbark Caverns" elseif ZoneID == "1857" then return "Thoradin's Wall" elseif ZoneID == "1858" then return "Boulder'gor" elseif ZoneID == "1877" then return "Valley of Fangs" elseif ZoneID == "1878" then return "The Dustbowl" elseif ZoneID == "1879" then return "Mirage Flats" elseif ZoneID == "1880" then return "Featherbeard's Hovel" elseif ZoneID == "1881" then return "Shindigger's Camp" elseif ZoneID == "1882" then return "Plaguemist Ravine" elseif ZoneID == "1883" then return "Valorwind Lake" elseif ZoneID == "1884" then return "Agol'watha" elseif ZoneID == "1885" then return "Hiri'watha" elseif ZoneID == "1886" then return "The Creeping Ruin" elseif ZoneID == "1887" then return "Bogen's Ledge" elseif ZoneID == "1897" then return "The Maker's Terrace" elseif ZoneID == "1898" then return "Dustwind Gulch" elseif ZoneID == "1917" then return "Shaol'watha" elseif ZoneID == "1937" then return "Noonshade Ruins" elseif ZoneID == "1938" then return "Broken Pillar" elseif ZoneID == "1939" then return "Abyssal Sands" elseif ZoneID == "1940" then return "Southbreak Shore" elseif ZoneID == "1941" then return "Caverns of Time" elseif ZoneID == "1942" then return "The Marshlands" elseif ZoneID == "1943" then return "Ironstone Plateau" elseif ZoneID == "1957" then return "Blackchar Cave" elseif ZoneID == "1958" then return "Tanner Camp" elseif ZoneID == "1959" then return "Dustfire Valley" elseif ZoneID == "1977" then return "Zul'Gurub" elseif ZoneID == "1978" then return "Misty Reed Post" elseif ZoneID == "1997" then return "Bloodvenom Post " elseif ZoneID == "1998" then return "Talonbranch Glade " elseif ZoneID == "2017" then return "Stratholme" elseif ZoneID == "2037" then return "Quel'thalas" elseif ZoneID == "2057" then return "Scholomance" elseif ZoneID == "2077" then return "Twilight Vale" elseif ZoneID == "2078" then return "Twilight Shore" elseif ZoneID == "2079" then return "Alcaz Island" elseif ZoneID == "2097" then return "Darkcloud Pinnacle" elseif ZoneID == "2098" then return "Dawning Wood Catacombs" elseif ZoneID == "2099" then return "Stonewatch Keep" elseif ZoneID == "2100" then return "Maraudon" elseif ZoneID == "2101" then return "Stoutlager Inn" elseif ZoneID == "2102" then return "Thunderbrew Distillery" elseif ZoneID == "2103" then return "Menethil Keep" elseif ZoneID == "2104" then return "Deepwater Tavern" elseif ZoneID == "2117" then return "Shadow Grave" elseif ZoneID == "2118" then return "Brill Town Hall" elseif ZoneID == "2119" then return "Gallows' End Tavern" elseif ZoneID == "2137" then return "The Pools of VisionUNUSED" elseif ZoneID == "2138" then return "Dreadmist Den" elseif ZoneID == "2157" then return "Bael'dun Keep" elseif ZoneID == "2158" then return "Emberstrife's Den" elseif ZoneID == "2159" then return "Onyxia's Lair" elseif ZoneID == "2160" then return "Windshear Mine" elseif ZoneID == "2161" then return "Roland's Doom" elseif ZoneID == "2177" then return "Battle Ring" elseif ZoneID == "2197" then return "The Pools of Vision" elseif ZoneID == "2198" then return "Shadowbreak Ravine" elseif ZoneID == "2217" then return "Broken Spear Village" elseif ZoneID == "2237" then return "Whitereach Post" elseif ZoneID == "2238" then return "Gornia" elseif ZoneID == "2239" then return "Zane's Eye Crater" elseif ZoneID == "2240" then return "Mirage Raceway" elseif ZoneID == "2241" then return "Frostsaber Rock" elseif ZoneID == "2242" then return "The Hidden Grove" elseif ZoneID == "2243" then return "Timbermaw Post" elseif ZoneID == "2244" then return "Winterfall Village" elseif ZoneID == "2245" then return "Mazthoril" elseif ZoneID == "2246" then return "Frostfire Hot Springs" elseif ZoneID == "2247" then return "Ice Thistle Hills" elseif ZoneID == "2248" then return "Dun Mandarr" elseif ZoneID == "2249" then return "Frostwhisper Gorge" elseif ZoneID == "2250" then return "Owl Wing Thicket" elseif ZoneID == "2251" then return "Lake Kel'Theril" elseif ZoneID == "2252" then return "The Ruins of Kel'Theril" elseif ZoneID == "2253" then return "Starfall Village" elseif ZoneID == "2254" then return "Ban'Thallow Barrow Den" elseif ZoneID == "2255" then return "Everlook" elseif ZoneID == "2256" then return "Darkwhisper Gorge" elseif ZoneID == "2257" then return "Deeprun Tram" elseif ZoneID == "2258" then return "The Fungal Vale" elseif ZoneID == "2259" then return "UNUSEDThe Marris Stead" elseif ZoneID == "2260" then return "The Marris Stead" elseif ZoneID == "2261" then return "The Undercroft" elseif ZoneID == "2262" then return "Darrowshire" elseif ZoneID == "2263" then return "Crown Guard Tower" elseif ZoneID == "2264" then return "Corin's Crossing" elseif ZoneID == "2265" then return "Scarlet Base Camp" elseif ZoneID == "2266" then return "Tyr's Hand" elseif ZoneID == "2267" then return "The Scarlet Basilica" elseif ZoneID == "2268" then return "Light's Hope Chapel" elseif ZoneID == "2269" then return "Browman Mill" elseif ZoneID == "2270" then return "The Noxious Glade" elseif ZoneID == "2271" then return "Eastwall Tower" elseif ZoneID == "2272" then return "Northdale" elseif ZoneID == "2273" then return "Zul'Mashar" elseif ZoneID == "2274" then return "Mazra'Alor" elseif ZoneID == "2275" then return "Northpass Tower" elseif ZoneID == "2276" then return "Quel'Lithien Lodge" elseif ZoneID == "2277" then return "Plaguewood" elseif ZoneID == "2278" then return "Scourgehold" elseif ZoneID == "2279" then return "Stratholme" elseif ZoneID == "2280" then return "DO NOT USE" elseif ZoneID == "2297" then return "Darrowmere Lake" elseif ZoneID == "2298" then return "Caer Darrow" elseif ZoneID == "2299" then return "Darrowmere Lake" elseif ZoneID == "2300" then return "Caverns of Time" elseif ZoneID == "2301" then return "Thistlefur Village" elseif ZoneID == "2302" then return "The Quagmire" elseif ZoneID == "2303" then return "Windbreak Canyon" elseif ZoneID == "2317" then return "South Seas" elseif ZoneID == "2318" then return "The Great Sea" elseif ZoneID == "2319" then return "The Great Sea" elseif ZoneID == "2320" then return "The Great Sea" elseif ZoneID == "2321" then return "The Great Sea" elseif ZoneID == "2322" then return "The Veiled Sea" elseif ZoneID == "2323" then return "The Veiled Sea" elseif ZoneID == "2324" then return "The Veiled Sea" elseif ZoneID == "2325" then return "The Veiled Sea" elseif ZoneID == "2326" then return "The Veiled Sea" elseif ZoneID == "2337" then return "Razor Hill Barracks" elseif ZoneID == "2338" then return "South Seas" elseif ZoneID == "2339" then return "The Great Sea" elseif ZoneID == "2357" then return "Bloodtooth Camp" elseif ZoneID == "2358" then return "Forest Song" elseif ZoneID == "2359" then return "Greenpaw Village" elseif ZoneID == "2360" then return "Silverwing Outpost" elseif ZoneID == "2361" then return "Nighthaven" elseif ZoneID == "2362" then return "Shrine of Remulos" elseif ZoneID == "2363" then return "Stormrage Barrow Dens" elseif ZoneID == "2364" then return "The Great Sea" elseif ZoneID == "2365" then return "The Great Sea" elseif ZoneID == "2366" then return "The Black Morass" elseif ZoneID == "2367" then return "Old Hillsbrad Foothills" elseif ZoneID == "2368" then return "Tarren Mill" elseif ZoneID == "2369" then return "Southshore" elseif ZoneID == "2370" then return "Durnholde Keep" elseif ZoneID == "2371" then return "Dun Garok" elseif ZoneID == "2372" then return "Hillsbrad Fields" elseif ZoneID == "2373" then return "Eastern Strand" elseif ZoneID == "2374" then return "Nethander Stead" elseif ZoneID == "2375" then return "Darrow Hill" elseif ZoneID == "2376" then return "Southpoint Tower" elseif ZoneID == "2377" then return "Thoradin's Wall" elseif ZoneID == "2378" then return "Western Strand" elseif ZoneID == "2379" then return "Azurelode Mine" elseif ZoneID == "2397" then return "The Great Sea" elseif ZoneID == "2398" then return "The Great Sea" elseif ZoneID == "2399" then return "The Great Sea" elseif ZoneID == "2400" then return "The Forbidding Sea" elseif ZoneID == "2401" then return "The Forbidding Sea" elseif ZoneID == "2402" then return "The Forbidding Sea" elseif ZoneID == "2403" then return "The Forbidding Sea" elseif ZoneID == "2404" then return "Tethris Aran" elseif ZoneID == "2405" then return "Ethel Rethor" elseif ZoneID == "2406" then return "Ranazjar Isle" elseif ZoneID == "2407" then return "Kormek's Hut" elseif ZoneID == "2408" then return "Shadowprey Village" elseif ZoneID == "2417" then return "Blackrock Pass" elseif ZoneID == "2418" then return "Morgan's Vigil" elseif ZoneID == "2419" then return "Slither Rock" elseif ZoneID == "2420" then return "Terror Wing Path" elseif ZoneID == "2421" then return "Draco'dar" elseif ZoneID == "2437" then return "Ragefire Chasm" elseif ZoneID == "2457" then return "Nightsong Woods" elseif ZoneID == "2477" then return "The Veiled Sea" elseif ZoneID == "2478" then return "Morlos'Aran" elseif ZoneID == "2479" then return "Emerald Sanctuary" elseif ZoneID == "2480" then return "Jadefire Glen" elseif ZoneID == "2481" then return "Ruins of Constellas" elseif ZoneID == "2497" then return "Bitter Reaches" elseif ZoneID == "2517" then return "Rise of the Defiler" elseif ZoneID == "2518" then return "Lariss Pavilion" elseif ZoneID == "2519" then return "Woodpaw Hills" elseif ZoneID == "2520" then return "Woodpaw Den" elseif ZoneID == "2521" then return "Verdantis River" elseif ZoneID == "2522" then return "Ruins of Isildien" elseif ZoneID == "2537" then return "Grimtotem Post" elseif ZoneID == "2538" then return "Camp Aparaje" elseif ZoneID == "2539" then return "Malaka'jin" elseif ZoneID == "2540" then return "Boulderslide Ravine" elseif ZoneID == "2541" then return "Sishir Canyon" elseif ZoneID == "2557" then return "Dire Maul" elseif ZoneID == "2558" then return "Deadwind Ravine" elseif ZoneID == "2559" then return "Diamondhead River" elseif ZoneID == "2560" then return "Ariden's Camp" elseif ZoneID == "2561" then return "The Vice" elseif ZoneID == "2562" then return "Karazhan" elseif ZoneID == "2563" then return "Morgan's Plot" elseif ZoneID == "2577" then return "Dire Maul" elseif ZoneID == "2597" then return "Alterac Valley" elseif ZoneID == "2617" then return "Scrabblescrew's Camp" elseif ZoneID == "2618" then return "Jadefire Run" elseif ZoneID == "2619" then return "Thondroril River" elseif ZoneID == "2620" then return "Thondroril River" elseif ZoneID == "2621" then return "Lake Mereldar" elseif ZoneID == "2622" then return "Pestilent Scar" elseif ZoneID == "2623" then return "The Infectis Scar" elseif ZoneID == "2624" then return "Blackwood Lake" elseif ZoneID == "2625" then return "Eastwall Gate" elseif ZoneID == "2626" then return "Terrorweb Tunnel" elseif ZoneID == "2627" then return "Terrordale" elseif ZoneID == "2637" then return "Kargathia Keep" elseif ZoneID == "2657" then return "Valley of Bones" elseif ZoneID == "2677" then return "Blackwing Lair" elseif ZoneID == "2697" then return "Deadman's Crossing" elseif ZoneID == "2717" then return "Molten Core" elseif ZoneID == "2737" then return "The Scarab Wall" elseif ZoneID == "2738" then return "Southwind Village" elseif ZoneID == "2739" then return "Twilight Base Camp" elseif ZoneID == "2740" then return "The Crystal Vale" elseif ZoneID == "2741" then return "The Scarab Dais" elseif ZoneID == "2742" then return "Hive'Ashi" elseif ZoneID == "2743" then return "Hive'Zora" elseif ZoneID == "2744" then return "Hive'Regal" elseif ZoneID == "2757" then return "Shrine of the Fallen Warrior" elseif ZoneID == "2777" then return "UNUSED Alterac Valley" elseif ZoneID == "2797" then return "Blackfathom Deeps" elseif ZoneID == "2817" then return "Crystalsong Forest" elseif ZoneID == "2837" then return "The Master's Cellar" elseif ZoneID == "2838" then return "Stonewrought Pass" elseif ZoneID == "2839" then return "Alterac Valley" elseif ZoneID == "2857" then return "The Rumble Cage" elseif ZoneID == "2877" then return "Chunk Test" elseif ZoneID == "2897" then return "Zoram'gar Outpost" elseif ZoneID == "2917" then return "Hall of Legends" elseif ZoneID == "2918" then return "Champions' Hall" elseif ZoneID == "2937" then return "Grosh'gok Compound" elseif ZoneID == "2938" then return "Sleeping Gorge" elseif ZoneID == "2957" then return "Irondeep Mine" elseif ZoneID == "2958" then return "Stonehearth Outpost" elseif ZoneID == "2959" then return "Dun Baldar" elseif ZoneID == "2960" then return "Icewing Pass" elseif ZoneID == "2961" then return "Frostwolf Village" elseif ZoneID == "2962" then return "Tower Point" elseif ZoneID == "2963" then return "Coldtooth Mine" elseif ZoneID == "2964" then return "Winterax Hold" elseif ZoneID == "2977" then return "Iceblood Garrison" elseif ZoneID == "2978" then return "Frostwolf Keep" elseif ZoneID == "2979" then return "Tor'kren Farm" elseif ZoneID == "3017" then return "Frost Dagger Pass" elseif ZoneID == "3037" then return "Ironstone Camp" elseif ZoneID == "3038" then return "Weazel's Crater" elseif ZoneID == "3039" then return "Tahonda Ruins" elseif ZoneID == "3057" then return "Field of Strife" elseif ZoneID == "3058" then return "Icewing Cavern" elseif ZoneID == "3077" then return "Valor's Rest" elseif ZoneID == "3097" then return "The Swarming Pillar" elseif ZoneID == "3098" then return "Twilight Post" elseif ZoneID == "3099" then return "Twilight Outpost" elseif ZoneID == "3100" then return "Ravaged Twilight Camp" elseif ZoneID == "3117" then return "Shalzaru's Lair" elseif ZoneID == "3137" then return "Talrendis Point" elseif ZoneID == "3138" then return "Rethress Sanctum" elseif ZoneID == "3139" then return "Moon Horror Den" elseif ZoneID == "3140" then return "Scalebeard's Cave" elseif ZoneID == "3157" then return "Boulderslide Cavern" elseif ZoneID == "3177" then return "Warsong Labor Camp" elseif ZoneID == "3197" then return "Chillwind Camp" elseif ZoneID == "3217" then return "The Maul" elseif ZoneID == "3237" then return "The Maul UNUSED" elseif ZoneID == "3257" then return "Bones of Grakkarond" elseif ZoneID == "3277" then return "Warsong Gulch" elseif ZoneID == "3297" then return "Frostwolf Graveyard" elseif ZoneID == "3298" then return "Frostwolf Pass" elseif ZoneID == "3299" then return "Dun Baldar Pass" elseif ZoneID == "3300" then return "Iceblood Graveyard" elseif ZoneID == "3301" then return "Snowfall Graveyard" elseif ZoneID == "3302" then return "Stonehearth Graveyard" elseif ZoneID == "3303" then return "Stormpike Graveyard" elseif ZoneID == "3304" then return "Icewing Bunker" elseif ZoneID == "3305" then return "Stonehearth Bunker" elseif ZoneID == "3306" then return "Wildpaw Ridge" elseif ZoneID == "3317" then return "Revantusk Village" elseif ZoneID == "3318" then return "Rock of Durotan" elseif ZoneID == "3319" then return "Silverwing Grove" elseif ZoneID == "3320" then return "Warsong Lumber Mill" elseif ZoneID == "3321" then return "Silverwing Hold" elseif ZoneID == "3337" then return "Wildpaw Cavern" elseif ZoneID == "3338" then return "The Veiled Cleft" elseif ZoneID == "3357" then return "Yojamba Isle" elseif ZoneID == "3358" then return "Arathi Basin" elseif ZoneID == "3377" then return "The Coil" elseif ZoneID == "3378" then return "Altar of Hir'eek" elseif ZoneID == "3379" then return "Shadra'zaar" elseif ZoneID == "3380" then return "Hakkari Grounds" elseif ZoneID == "3381" then return "Naze of Shirvallah" elseif ZoneID == "3382" then return "Temple of Bethekk" elseif ZoneID == "3383" then return "The Bloodfire Pit" elseif ZoneID == "3384" then return "Altar of the Blood God" elseif ZoneID == "3397" then return "Zanza's Rise" elseif ZoneID == "3398" then return "Edge of Madness" elseif ZoneID == "3417" then return "Trollbane Hall" elseif ZoneID == "3418" then return "Defiler's Den" elseif ZoneID == "3419" then return "Pagle's Pointe" elseif ZoneID == "3420" then return "Farm" elseif ZoneID == "3421" then return "Blacksmith" elseif ZoneID == "3422" then return "Lumber Mill" elseif ZoneID == "3423" then return "Gold Mine" elseif ZoneID == "3424" then return "Stables" elseif ZoneID == "3425" then return "Cenarion Hold" elseif ZoneID == "3426" then return "Staghelm Point" elseif ZoneID == "3427" then return "Bronzebeard Encampment" elseif ZoneID == "3428" then return "Ahn'Qiraj" elseif ZoneID == "3429" then return "Ruins of Ahn'Qiraj" elseif ZoneID == "3430" then return "Eversong Woods" elseif ZoneID == "3431" then return "Sunstrider Isle" elseif ZoneID == "3432" then return "Shrine of Dath'Remar" elseif ZoneID == "3433" then return "Ghostlands" elseif ZoneID == "3434" then return "Scarab Terrace" elseif ZoneID == "3435" then return "General's Terrace" elseif ZoneID == "3436" then return "The Reservoir" elseif ZoneID == "3437" then return "The Hatchery" elseif ZoneID == "3438" then return "The Comb" elseif ZoneID == "3439" then return "Watchers' Terrace" elseif ZoneID == "3440" then return "Scarab Terrace" elseif ZoneID == "3441" then return "General's Terrace" elseif ZoneID == "3442" then return "The Reservoir" elseif ZoneID == "3443" then return "The Hatchery" elseif ZoneID == "3444" then return "The Comb" elseif ZoneID == "3445" then return "Watchers' Terrace" elseif ZoneID == "3446" then return "Twilight's Run" elseif ZoneID == "3447" then return "Ortell's Hideout" elseif ZoneID == "3448" then return "Scarab Terrace" elseif ZoneID == "3449" then return "General's Terrace" elseif ZoneID == "3450" then return "The Reservoir" elseif ZoneID == "3451" then return "The Hatchery" elseif ZoneID == "3452" then return "The Comb" elseif ZoneID == "3453" then return "Watchers' Terrace" elseif ZoneID == "3454" then return "Ruins of Ahn'Qiraj" elseif ZoneID == "3455" then return "The North Sea" elseif ZoneID == "3456" then return "Naxxramas" elseif ZoneID == "3457" then return "Karazhan" elseif ZoneID == "3459" then return "City" elseif ZoneID == "3460" then return "Golden Strand" elseif ZoneID == "3461" then return "Sunsail Anchorage" elseif ZoneID == "3462" then return "Fairbreeze Village" elseif ZoneID == "3463" then return "Magisters Gate" elseif ZoneID == "3464" then return "Farstrider Retreat" elseif ZoneID == "3465" then return "North Sanctum" elseif ZoneID == "3466" then return "West Sanctum" elseif ZoneID == "3467" then return "East Sanctum" elseif ZoneID == "3468" then return "Saltheril's Haven" elseif ZoneID == "3469" then return "Thuron's Livery" elseif ZoneID == "3470" then return "Stillwhisper Pond" elseif ZoneID == "3471" then return "The Living Wood" elseif ZoneID == "3472" then return "Azurebreeze Coast" elseif ZoneID == "3473" then return "Lake Elrendar" elseif ZoneID == "3474" then return "The Scorched Grove" elseif ZoneID == "3475" then return "Zeb'Watha" elseif ZoneID == "3476" then return "Tor'Watha" elseif ZoneID == "3477" then return "Azjol-Nerub" elseif ZoneID == "3478" then return "Gates of Ahn'Qiraj" elseif ZoneID == "3479" then return "The Veiled Sea" elseif ZoneID == "3480" then return "Duskwither Grounds" elseif ZoneID == "3481" then return "Duskwither Spire" elseif ZoneID == "3482" then return "The Dead Scar" elseif ZoneID == "3483" then return "Hellfire Peninsula" elseif ZoneID == "3484" then return "The Sunspire" elseif ZoneID == "3485" then return "Falthrien Academy" elseif ZoneID == "3486" then return "Ravenholdt Manor" elseif ZoneID == "3487" then return "Silvermoon City" elseif ZoneID == "3488" then return "Tranquillien" elseif ZoneID == "3489" then return "Suncrown Village" elseif ZoneID == "3490" then return "Goldenmist Village" elseif ZoneID == "3491" then return "Windrunner Village" elseif ZoneID == "3492" then return "Windrunner Spire" elseif ZoneID == "3493" then return "Sanctum of the Sun" elseif ZoneID == "3494" then return "Sanctum of the Moon" elseif ZoneID == "3495" then return "Dawnstar Spire" elseif ZoneID == "3496" then return "Farstrider Enclave" elseif ZoneID == "3497" then return "An'daroth" elseif ZoneID == "3498" then return "An'telas" elseif ZoneID == "3499" then return "An'owyn" elseif ZoneID == "3500" then return "Deatholme" elseif ZoneID == "3501" then return "Bleeding Ziggurat" elseif ZoneID == "3502" then return "Howling Ziggurat" elseif ZoneID == "3503" then return "Shalandis Isle" elseif ZoneID == "3504" then return "Toryl Estate" elseif ZoneID == "3505" then return "Underlight Mines" elseif ZoneID == "3506" then return "Andilien Estate" elseif ZoneID == "3507" then return "Hatchet Hills" elseif ZoneID == "3508" then return "Amani Pass" elseif ZoneID == "3509" then return "Sungraze Peak" elseif ZoneID == "3510" then return "Amani Catacombs" elseif ZoneID == "3511" then return "Tower of the Damned" elseif ZoneID == "3512" then return "Zeb'Sora" elseif ZoneID == "3513" then return "Lake Elrendar" elseif ZoneID == "3514" then return "The Dead Scar" elseif ZoneID == "3515" then return "Elrendar River" elseif ZoneID == "3516" then return "Zeb'Tela" elseif ZoneID == "3517" then return "Zeb'Nowa" elseif ZoneID == "3518" then return "Nagrand" elseif ZoneID == "3519" then return "Terokkar Forest" elseif ZoneID == "3520" then return "Shadowmoon Valley" elseif ZoneID == "3521" then return "Zangarmarsh" elseif ZoneID == "3522" then return "Blade's Edge Mountains" elseif ZoneID == "3523" then return "Netherstorm" elseif ZoneID == "3524" then return "Azuremyst Isle" elseif ZoneID == "3525" then return "Bloodmyst Isle" elseif ZoneID == "3526" then return "Ammen Vale" elseif ZoneID == "3527" then return "Crash Site" elseif ZoneID == "3528" then return "Silverline Lake" elseif ZoneID == "3529" then return "Nestlewood Thicket" elseif ZoneID == "3530" then return "Shadow Ridge" elseif ZoneID == "3531" then return "Skulking Row" elseif ZoneID == "3532" then return "Dawning Lane" elseif ZoneID == "3533" then return "Ruins of Silvermoon" elseif ZoneID == "3534" then return "Feth's Way" elseif ZoneID == "3535" then return "Hellfire Citadel" elseif ZoneID == "3536" then return "Thrallmar" elseif ZoneID == "3537" then return "Borean Tundra" elseif ZoneID == "3538" then return "Honor Hold" elseif ZoneID == "3539" then return "The Stair of Destiny" elseif ZoneID == "3540" then return "Twisting Nether" elseif ZoneID == "3541" then return "Forge Camp: Mageddon" elseif ZoneID == "3542" then return "The Path of Glory" elseif ZoneID == "3543" then return "The Great Fissure" elseif ZoneID == "3544" then return "Plain of Shards" elseif ZoneID == "3545" then return "Hellfire Citadel" elseif ZoneID == "3546" then return "Expedition Armory" elseif ZoneID == "3547" then return "Throne of Kil'jaeden" elseif ZoneID == "3548" then return "Forge Camp: Rage" elseif ZoneID == "3549" then return "Invasion Point: Annihilator" elseif ZoneID == "3550" then return "Borune Ruins" elseif ZoneID == "3551" then return "Ruins of Sha'naar" elseif ZoneID == "3552" then return "Temple of Telhamat" elseif ZoneID == "3553" then return "Pools of Aggonar" elseif ZoneID == "3554" then return "Falcon Watch" elseif ZoneID == "3555" then return "Mag'har Post" elseif ZoneID == "3556" then return "Den of Haal'esh" elseif ZoneID == "3557" then return "The Exodar" elseif ZoneID == "3558" then return "Elrendar Falls" elseif ZoneID == "3559" then return "Nestlewood Hills" elseif ZoneID == "3560" then return "Ammen Fields" elseif ZoneID == "3561" then return "The Sacred Grove" elseif ZoneID == "3562" then return "Hellfire Ramparts" elseif ZoneID == "3563" then return "Hellfire Citadel" elseif ZoneID == "3564" then return "Emberglade" elseif ZoneID == "3565" then return "Cenarion Refuge" elseif ZoneID == "3566" then return "Moonwing Den" elseif ZoneID == "3567" then return "Pod Cluster" elseif ZoneID == "3568" then return "Pod Wreckage" elseif ZoneID == "3569" then return "Tides' Hollow" elseif ZoneID == "3570" then return "Wrathscale Point" elseif ZoneID == "3571" then return "Bristlelimb Village" elseif ZoneID == "3572" then return "Stillpine Hold" elseif ZoneID == "3573" then return "Odesyus' Landing" elseif ZoneID == "3574" then return "Valaar's Berth" elseif ZoneID == "3575" then return "Silting Shore" elseif ZoneID == "3576" then return "Azure Watch" elseif ZoneID == "3577" then return "Geezle's Camp" elseif ZoneID == "3578" then return "Menagerie Wreckage" elseif ZoneID == "3579" then return "Traitor's Cove" elseif ZoneID == "3580" then return "Wildwind Peak" elseif ZoneID == "3581" then return "Wildwind Path" elseif ZoneID == "3582" then return "Zeth'Gor" elseif ZoneID == "3583" then return "Beryl Coast" elseif ZoneID == "3584" then return "Blood Watch" elseif ZoneID == "3585" then return "Bladewood" elseif ZoneID == "3586" then return "The Vector Coil" elseif ZoneID == "3587" then return "The Warp Piston" elseif ZoneID == "3588" then return "The Cryo-Core" elseif ZoneID == "3589" then return "The Crimson Reach" elseif ZoneID == "3590" then return "Wrathscale Lair" elseif ZoneID == "3591" then return "Ruins of Loreth'Aran" elseif ZoneID == "3592" then return "Nazzivian" elseif ZoneID == "3593" then return "Axxarien" elseif ZoneID == "3594" then return "Blacksilt Shore" elseif ZoneID == "3595" then return "The Foul Pool" elseif ZoneID == "3596" then return "The Hidden Reef" elseif ZoneID == "3597" then return "Amberweb Pass" elseif ZoneID == "3598" then return "Wyrmscar Island" elseif ZoneID == "3599" then return "Talon Stand" elseif ZoneID == "3600" then return "Bristlelimb Enclave" elseif ZoneID == "3601" then return "Ragefeather Ridge" elseif ZoneID == "3602" then return "Kessel's Crossing" elseif ZoneID == "3603" then return "Tel'athion's Camp" elseif ZoneID == "3604" then return "The Bloodcursed Reef" elseif ZoneID == "3605" then return "Hyjal Past" elseif ZoneID == "3606" then return "Hyjal Summit" elseif ZoneID == "3607" then return "Serpentshrine Cavern" elseif ZoneID == "3608" then return "Vindicator's Rest" elseif ZoneID == "3609" then return "Unused3" elseif ZoneID == "3610" then return "Burning Blade Ruins" elseif ZoneID == "3611" then return "Clan Watch" elseif ZoneID == "3612" then return "Bloodcurse Isle" elseif ZoneID == "3613" then return "Garadar" elseif ZoneID == "3614" then return "Skysong Lake" elseif ZoneID == "3615" then return "Throne of the Elements" elseif ZoneID == "3616" then return "Laughing Skull Ruins" elseif ZoneID == "3617" then return "Warmaul Hill" elseif ZoneID == "3618" then return "Gruul's Lair" elseif ZoneID == "3619" then return "Auren Ridge" elseif ZoneID == "3620" then return "Auren Falls" elseif ZoneID == "3621" then return "Lake Sunspring" elseif ZoneID == "3622" then return "Sunspring Post" elseif ZoneID == "3623" then return "Aeris Landing" elseif ZoneID == "3624" then return "Forge Camp: Fear" elseif ZoneID == "3625" then return "Forge Camp: Hate" elseif ZoneID == "3626" then return "Telaar" elseif ZoneID == "3627" then return "Northwind Cleft" elseif ZoneID == "3628" then return "Halaa" elseif ZoneID == "3629" then return "Southwind Cleft" elseif ZoneID == "3630" then return "Oshu'gun" elseif ZoneID == "3631" then return "Spirit Fields" elseif ZoneID == "3632" then return "Shamanar" elseif ZoneID == "3633" then return "Ancestral Grounds" elseif ZoneID == "3634" then return "Windyreed Village" elseif ZoneID == "3635" then return "Unused2" elseif ZoneID == "3636" then return "Elemental Plateau" elseif ZoneID == "3637" then return "Kil'sorrow Fortress" elseif ZoneID == "3638" then return "The Ring of Trials" elseif ZoneID == "3639" then return "Silvermyst Isle" elseif ZoneID == "3640" then return "Daggerfen Village" elseif ZoneID == "3641" then return "Umbrafen Village" elseif ZoneID == "3642" then return "Feralfen Village" elseif ZoneID == "3643" then return "Bloodscale Enclave" elseif ZoneID == "3644" then return "Telredor" elseif ZoneID == "3645" then return "Zabra'jin" elseif ZoneID == "3646" then return "Quagg Ridge" elseif ZoneID == "3647" then return "The Spawning Glen" elseif ZoneID == "3648" then return "The Dead Mire" elseif ZoneID == "3649" then return "Sporeggar" elseif ZoneID == "3650" then return "Ango'rosh Grounds" elseif ZoneID == "3651" then return "Ango'rosh Stronghold" elseif ZoneID == "3652" then return "Funggor Cavern" elseif ZoneID == "3653" then return "Serpent Lake" elseif ZoneID == "3654" then return "The Drain" elseif ZoneID == "3655" then return "Umbrafen Lake" elseif ZoneID == "3656" then return "Marshlight Lake" elseif ZoneID == "3657" then return "Portal Clearing" elseif ZoneID == "3658" then return "Sporewind Lake" elseif ZoneID == "3659" then return "The Lagoon" elseif ZoneID == "3660" then return "Blades' Run" elseif ZoneID == "3661" then return "Blade Tooth Canyon" elseif ZoneID == "3662" then return "Commons Hall" elseif ZoneID == "3663" then return "Derelict Manor" elseif ZoneID == "3664" then return "Huntress of the Sun" elseif ZoneID == "3665" then return "Falconwing Square" elseif ZoneID == "3666" then return "Halaani Basin" elseif ZoneID == "3667" then return "Hewn Bog" elseif ZoneID == "3668" then return "Boha'mu Ruins" elseif ZoneID == "3669" then return "The Stadium" elseif ZoneID == "3670" then return "The Overlook" elseif ZoneID == "3671" then return "Broken Hill" elseif ZoneID == "3672" then return "Mag'hari Procession" elseif ZoneID == "3673" then return "Nesingwary Safari" elseif ZoneID == "3674" then return "Cenarion Thicket" elseif ZoneID == "3675" then return "Tuurem" elseif ZoneID == "3676" then return "Veil Shienor" elseif ZoneID == "3677" then return "Veil Skith" elseif ZoneID == "3678" then return "Veil Shalas" elseif ZoneID == "3679" then return "Skettis" elseif ZoneID == "3680" then return "Blackwind Valley" elseif ZoneID == "3681" then return "Firewing Point" elseif ZoneID == "3682" then return "Grangol'var Village" elseif ZoneID == "3683" then return "Stonebreaker Hold" elseif ZoneID == "3684" then return "Allerian Stronghold" elseif ZoneID == "3685" then return "Bonechewer Ruins" elseif ZoneID == "3686" then return "Veil Lithic" elseif ZoneID == "3687" then return "Olembas" elseif ZoneID == "3688" then return "Auchindoun" elseif ZoneID == "3689" then return "Veil Reskk" elseif ZoneID == "3690" then return "Blackwind Lake" elseif ZoneID == "3691" then return "Lake Ere'Noru" elseif ZoneID == "3692" then return "Lake Jorune" elseif ZoneID == "3693" then return "Skethyl Mountains" elseif ZoneID == "3694" then return "Misty Ridge" elseif ZoneID == "3695" then return "The Broken Hills" elseif ZoneID == "3696" then return "The Barrier Hills" elseif ZoneID == "3697" then return "The Bone Wastes" elseif ZoneID == "3698" then return "Nagrand Arena" elseif ZoneID == "3699" then return "Laughing Skull Courtyard" elseif ZoneID == "3700" then return "The Ring of Blood" elseif ZoneID == "3701" then return "Arena Floor" elseif ZoneID == "3702" then return "Blade's Edge Arena" elseif ZoneID == "3703" then return "Shattrath City" elseif ZoneID == "3704" then return "The Shepherd's Gate" elseif ZoneID == "3705" then return "Telaari Basin" elseif ZoneID == "3706" then return "The Dark Portal" elseif ZoneID == "3707" then return "Alliance Base" elseif ZoneID == "3708" then return "Horde Encampment" elseif ZoneID == "3709" then return "Night Elf Village" elseif ZoneID == "3710" then return "Nordrassil" elseif ZoneID == "3711" then return "Sholazar Basin" elseif ZoneID == "3712" then return "Area 52" elseif ZoneID == "3713" then return "The Blood Furnace" elseif ZoneID == "3714" then return "The Shattered Halls" elseif ZoneID == "3715" then return "The Steamvault" elseif ZoneID == "3716" then return "The Underbog" elseif ZoneID == "3717" then return "The Slave Pens" elseif ZoneID == "3718" then return "Swamprat Post" elseif ZoneID == "3719" then return "Bleeding Hollow Ruins" elseif ZoneID == "3720" then return "Twin Spire Ruins" elseif ZoneID == "3721" then return "The Crumbling Waste" elseif ZoneID == "3722" then return "Manaforge Ara" elseif ZoneID == "3723" then return "Arklon Ruins" elseif ZoneID == "3724" then return "Cosmowrench" elseif ZoneID == "3725" then return "Ruins of Enkaat" elseif ZoneID == "3726" then return "Manaforge B'naar" elseif ZoneID == "3727" then return "The Scrap Field" elseif ZoneID == "3728" then return "The Vortex Fields" elseif ZoneID == "3729" then return "The Heap" elseif ZoneID == "3730" then return "Manaforge Coruu" elseif ZoneID == "3731" then return "The Tempest Rift" elseif ZoneID == "3732" then return "Kirin'Var Village" elseif ZoneID == "3733" then return "The Violet Tower" elseif ZoneID == "3734" then return "Manaforge Duro" elseif ZoneID == "3735" then return "Voidwind Plateau" elseif ZoneID == "3736" then return "Manaforge Ultris" elseif ZoneID == "3737" then return "Celestial Ridge" elseif ZoneID == "3738" then return "The Stormspire" elseif ZoneID == "3739" then return "Forge Base: Oblivion" elseif ZoneID == "3740" then return "Forge Base: Gehenna" elseif ZoneID == "3741" then return "Ruins of Farahlon" elseif ZoneID == "3742" then return "Socrethar's Seat" elseif ZoneID == "3743" then return "Legion Hold" elseif ZoneID == "3744" then return "Shadowmoon Village" elseif ZoneID == "3745" then return "Wildhammer Stronghold" elseif ZoneID == "3746" then return "The Hand of Gul'dan" elseif ZoneID == "3747" then return "The Fel Pits" elseif ZoneID == "3748" then return "The Deathforge" elseif ZoneID == "3749" then return "Coilskar Cistern" elseif ZoneID == "3750" then return "Coilskar Point" elseif ZoneID == "3751" then return "Sunfire Point" elseif ZoneID == "3752" then return "Illidari Point" elseif ZoneID == "3753" then return "Ruins of Baa'ri" elseif ZoneID == "3754" then return "Altar of Sha'tar" elseif ZoneID == "3755" then return "The Stair of Doom" elseif ZoneID == "3756" then return "Ruins of Karabor" elseif ZoneID == "3757" then return "Ata'mal Terrace" elseif ZoneID == "3758" then return "Netherwing Fields" elseif ZoneID == "3759" then return "Netherwing Ledge" elseif ZoneID == "3760" then return "The Barrier Hills" elseif ZoneID == "3761" then return "The High Path" elseif ZoneID == "3762" then return "Windyreed Pass" elseif ZoneID == "3763" then return "Zangar Ridge" elseif ZoneID == "3764" then return "The Twilight Ridge" elseif ZoneID == "3765" then return "Razorthorn Trail" elseif ZoneID == "3766" then return "Orebor Harborage" elseif ZoneID == "3767" then return "Blades' Run" elseif ZoneID == "3768" then return "Jagged Ridge" elseif ZoneID == "3769" then return "Thunderlord Stronghold" elseif ZoneID == "3770" then return "Blade Tooth Canyon" elseif ZoneID == "3771" then return "The Living Grove" elseif ZoneID == "3772" then return "Sylvanaar" elseif ZoneID == "3773" then return "Bladespire Hold" elseif ZoneID == "3774" then return "Gruul's Lair" elseif ZoneID == "3775" then return "Circle of Blood" elseif ZoneID == "3776" then return "Bloodmaul Outpost" elseif ZoneID == "3777" then return "Bloodmaul Camp" elseif ZoneID == "3778" then return "Draenethyst Mine" elseif ZoneID == "3779" then return "Trogma's Claim" elseif ZoneID == "3780" then return "Blackwing Coven" elseif ZoneID == "3781" then return "Grishnath" elseif ZoneID == "3782" then return "Veil Lashh" elseif ZoneID == "3783" then return "Veil Vekh" elseif ZoneID == "3784" then return "Forge Camp: Terror" elseif ZoneID == "3785" then return "Forge Camp: Wrath" elseif ZoneID == "3786" then return "Ogri'la" elseif ZoneID == "3787" then return "Forge Camp: Anger" elseif ZoneID == "3788" then return "The Low Path" elseif ZoneID == "3789" then return "Shadow Labyrinth" elseif ZoneID == "3790" then return "Auchenai Crypts" elseif ZoneID == "3791" then return "Sethekk Halls" elseif ZoneID == "3792" then return "Mana-Tombs" elseif ZoneID == "3793" then return "Felspark Ravine" elseif ZoneID == "3794" then return "Valley of Bones" elseif ZoneID == "3795" then return "Sha'naari Wastes" elseif ZoneID == "3796" then return "The Warp Fields" elseif ZoneID == "3797" then return "Fallen Sky Ridge" elseif ZoneID == "3798" then return "Haal'eshi Gorge" elseif ZoneID == "3799" then return "Stonewall Canyon" elseif ZoneID == "3800" then return "Thornfang Hill" elseif ZoneID == "3801" then return "Mag'har Grounds" elseif ZoneID == "3802" then return "Void Ridge" elseif ZoneID == "3803" then return "The Abyssal Shelf" elseif ZoneID == "3804" then return "The Legion Front" elseif ZoneID == "3805" then return "Zul'Aman" elseif ZoneID == "3806" then return "Supply Caravan" elseif ZoneID == "3807" then return "Reaver's Fall" elseif ZoneID == "3808" then return "Cenarion Post" elseif ZoneID == "3809" then return "Southern Rampart" elseif ZoneID == "3810" then return "Northern Rampart" elseif ZoneID == "3811" then return "Gor'gaz Outpost" elseif ZoneID == "3812" then return "Spinebreaker Post" elseif ZoneID == "3813" then return "The Path of Anguish" elseif ZoneID == "3814" then return "East Supply Caravan" elseif ZoneID == "3815" then return "Expedition Point" elseif ZoneID == "3816" then return "Zeppelin Crash" elseif ZoneID == "3817" then return "Testing" elseif ZoneID == "3818" then return "Bloodscale Grounds" elseif ZoneID == "3819" then return "Darkcrest Enclave" elseif ZoneID == "3820" then return "Eye of the Storm" elseif ZoneID == "3821" then return "Warden's Cage" elseif ZoneID == "3822" then return "Eclipse Point" elseif ZoneID == "3823" then return "Isle of Tribulations" elseif ZoneID == "3824" then return "Bloodmaul Ravine" elseif ZoneID == "3825" then return "Dragons' End" elseif ZoneID == "3826" then return "Daggermaw Canyon" elseif ZoneID == "3827" then return "Vekhaar Stand" elseif ZoneID == "3828" then return "Ruuan Weald" elseif ZoneID == "3829" then return "Veil Ruuan" elseif ZoneID == "3830" then return "Raven's Wood" elseif ZoneID == "3831" then return "Death's Door" elseif ZoneID == "3832" then return "Vortex Pinnacle" elseif ZoneID == "3833" then return "Razor Ridge" elseif ZoneID == "3834" then return "Ridge of Madness" elseif ZoneID == "3835" then return "Dustquill Ravine" elseif ZoneID == "3836" then return "Magtheridon's Lair" elseif ZoneID == "3837" then return "Sunfury Hold" elseif ZoneID == "3838" then return "Spinebreaker Mountains" elseif ZoneID == "3839" then return "Abandoned Armory" elseif ZoneID == "3840" then return "The Black Temple" elseif ZoneID == "3841" then return "Darkcrest Shore" elseif ZoneID == "3842" then return "Tempest Keep" elseif ZoneID == "3844" then return "Mok'Nathal Village" elseif ZoneID == "3845" then return "Tempest Keep" elseif ZoneID == "3846" then return "The Arcatraz" elseif ZoneID == "3847" then return "The Botanica" elseif ZoneID == "3848" then return "The Arcatraz" elseif ZoneID == "3849" then return "The Mechanar" elseif ZoneID == "3850" then return "Netherstone" elseif ZoneID == "3851" then return "Midrealm Post" elseif ZoneID == "3852" then return "Tuluman's Landing" elseif ZoneID == "3854" then return "Protectorate Watch Post" elseif ZoneID == "3855" then return "Circle of Blood Arena" elseif ZoneID == "3856" then return "Elrendar Crossing" elseif ZoneID == "3857" then return "Ammen Ford" elseif ZoneID == "3858" then return "Razorthorn Shelf" elseif ZoneID == "3859" then return "Silmyr Lake" elseif ZoneID == "3860" then return "Raastok Glade" elseif ZoneID == "3861" then return "Thalassian Pass" elseif ZoneID == "3862" then return "Churning Gulch" elseif ZoneID == "3863" then return "Broken Wilds" elseif ZoneID == "3864" then return "Bash'ir Landing" elseif ZoneID == "3865" then return "Crystal Spine" elseif ZoneID == "3866" then return "Skald" elseif ZoneID == "3867" then return "Bladed Gulch" elseif ZoneID == "3868" then return "Gyro-Plank Bridge" elseif ZoneID == "3869" then return "Mage Tower" elseif ZoneID == "3870" then return "Blood Elf Tower" elseif ZoneID == "3871" then return "Draenei Ruins" elseif ZoneID == "3872" then return "Fel Reaver Ruins" elseif ZoneID == "3873" then return "The Proving Grounds" elseif ZoneID == "3874" then return "Eco-Dome Farfield" elseif ZoneID == "3875" then return "Eco-Dome Skyperch" elseif ZoneID == "3876" then return "Eco-Dome Sutheron" elseif ZoneID == "3877" then return "Eco-Dome Midrealm" elseif ZoneID == "3878" then return "Ethereum Staging Grounds" elseif ZoneID == "3879" then return "Chapel Yard" elseif ZoneID == "3880" then return "Access Shaft Zeon" elseif ZoneID == "3881" then return "Trelleum Mine" elseif ZoneID == "3882" then return "Invasion Point: Destroyer" elseif ZoneID == "3883" then return "Camp of Boom" elseif ZoneID == "3884" then return "Spinebreaker Pass" elseif ZoneID == "3885" then return "Netherweb Ridge" elseif ZoneID == "3886" then return "Derelict Caravan" elseif ZoneID == "3887" then return "Refugee Caravan" elseif ZoneID == "3888" then return "Shadow Tomb" elseif ZoneID == "3889" then return "Veil Rhaze" elseif ZoneID == "3890" then return "Tomb of Lights" elseif ZoneID == "3891" then return "Carrion Hill" elseif ZoneID == "3892" then return "Writhing Mound" elseif ZoneID == "3893" then return "Ring of Observance" elseif ZoneID == "3894" then return "Auchenai Grounds" elseif ZoneID == "3895" then return "Cenarion Watchpost" elseif ZoneID == "3896" then return "Aldor Rise" elseif ZoneID == "3897" then return "Terrace of Light" elseif ZoneID == "3898" then return "Scryer's Tier" elseif ZoneID == "3899" then return "Lower City" elseif ZoneID == "3900" then return "Invasion Point: Overlord" elseif ZoneID == "3901" then return "Allerian Post" elseif ZoneID == "3902" then return "Stonebreaker Camp" elseif ZoneID == "3903" then return "Boulder'mok" elseif ZoneID == "3904" then return "Cursed Hollow" elseif ZoneID == "3905" then return "Coilfang Reservoir" elseif ZoneID == "3906" then return "The Bloodwash" elseif ZoneID == "3907" then return "Veridian Point" elseif ZoneID == "3908" then return "Middenvale" elseif ZoneID == "3909" then return "The Lost Fold" elseif ZoneID == "3910" then return "Mystwood" elseif ZoneID == "3911" then return "Tranquil Shore" elseif ZoneID == "3912" then return "Goldenbough Pass" elseif ZoneID == "3913" then return "Runestone Falithas" elseif ZoneID == "3914" then return "Runestone Shan'dor" elseif ZoneID == "3915" then return "Fairbridge Strand" elseif ZoneID == "3916" then return "Moongraze Woods" elseif ZoneID == "3917" then return "Auchindoun" elseif ZoneID == "3918" then return "Toshley's Station" elseif ZoneID == "3919" then return "Singing Ridge" elseif ZoneID == "3920" then return "Shatter Point" elseif ZoneID == "3921" then return "Arklonis Ridge" elseif ZoneID == "3922" then return "Bladespire Outpost" elseif ZoneID == "3923" then return "Gruul's Lair" elseif ZoneID == "3924" then return "Northmaul Tower" elseif ZoneID == "3925" then return "Southmaul Tower" elseif ZoneID == "3926" then return "Shattered Plains" elseif ZoneID == "3927" then return "Oronok's Farm" elseif ZoneID == "3928" then return "The Altar of Damnation" elseif ZoneID == "3929" then return "The Path of Conquest" elseif ZoneID == "3930" then return "Eclipsion Fields" elseif ZoneID == "3931" then return "Bladespire Grounds" elseif ZoneID == "3932" then return "Sketh'lon Base Camp" elseif ZoneID == "3933" then return "Sketh'lon Wreckage" elseif ZoneID == "3934" then return "Town Square" elseif ZoneID == "3935" then return "Wizard Row" elseif ZoneID == "3936" then return "Deathforge Tower" elseif ZoneID == "3937" then return "Slag Watch" elseif ZoneID == "3938" then return "Sanctum of the Stars" elseif ZoneID == "3939" then return "Dragonmaw Fortress" elseif ZoneID == "3940" then return "The Fetid Pool" elseif ZoneID == "3941" then return "Test" elseif ZoneID == "3942" then return "Razaan's Landing" elseif ZoneID == "3943" then return "Invasion Point: Cataclysm" elseif ZoneID == "3944" then return "The Altar of Shadows" elseif ZoneID == "3945" then return "Netherwing Pass" elseif ZoneID == "3946" then return "Wayne's Refuge" elseif ZoneID == "3947" then return "The Scalding Pools" elseif ZoneID == "3948" then return "Brian and Pat Test" elseif ZoneID == "3949" then return "Magma Fields" elseif ZoneID == "3950" then return "Crimson Watch" elseif ZoneID == "3951" then return "Evergrove" elseif ZoneID == "3952" then return "Wyrmskull Bridge" elseif ZoneID == "3953" then return "Scalewing Shelf" elseif ZoneID == "3954" then return "Wyrmskull Tunnel" elseif ZoneID == "3955" then return "Hellfire Basin" elseif ZoneID == "3956" then return "The Shadow Stair" elseif ZoneID == "3957" then return "Sha'tari Outpost" elseif ZoneID == "3958" then return "Sha'tari Base Camp" elseif ZoneID == "3959" then return "Black Temple" elseif ZoneID == "3960" then return "Soulgrinder's Barrow" elseif ZoneID == "3961" then return "Sorrow Wing Point" elseif ZoneID == "3962" then return "Vim'gol's Circle" elseif ZoneID == "3963" then return "Dragonspine Ridge" elseif ZoneID == "3964" then return "Skyguard Outpost" elseif ZoneID == "3965" then return "Netherwing Mines" elseif ZoneID == "3966" then return "Dragonmaw Base Camp" elseif ZoneID == "3967" then return "Dragonmaw Skyway" elseif ZoneID == "3968" then return "Ruins of Lordaeron" elseif ZoneID == "3969" then return "Rivendark's Perch" elseif ZoneID == "3970" then return "Obsidia's Perch" elseif ZoneID == "3971" then return "Insidion's Perch" elseif ZoneID == "3972" then return "Furywing's Perch" elseif ZoneID == "3973" then return "Blackwind Landing" elseif ZoneID == "3974" then return "Veil Harr'ik" elseif ZoneID == "3975" then return "Terokk's Rest" elseif ZoneID == "3976" then return "Veil Ala'rak" elseif ZoneID == "3977" then return "Upper Veil Shil'ak" elseif ZoneID == "3978" then return "Lower Veil Shil'ak" elseif ZoneID == "3979" then return "The Frozen Sea" elseif ZoneID == "3980" then return "Daggercap Bay" elseif ZoneID == "3981" then return "Valgarde" elseif ZoneID == "3982" then return "Wyrmskull Village" elseif ZoneID == "3983" then return "Utgarde Keep" elseif ZoneID == "3984" then return "Nifflevar" elseif ZoneID == "3985" then return "Falls of Ymiron" elseif ZoneID == "3986" then return "Echo Reach" elseif ZoneID == "3987" then return "The Isle of Spears" elseif ZoneID == "3988" then return "Kamagua" elseif ZoneID == "3989" then return "Garvan's Reef" elseif ZoneID == "3990" then return "Scalawag Point" elseif ZoneID == "3991" then return "New Agamand" elseif ZoneID == "3992" then return "The Ancient Lift" elseif ZoneID == "3993" then return "Westguard Turret" elseif ZoneID == "3994" then return "Halgrind" elseif ZoneID == "3995" then return "The Laughing Stand" elseif ZoneID == "3996" then return "Baelgun's Excavation Site" elseif ZoneID == "3997" then return "Explorers' League Outpost" elseif ZoneID == "3998" then return "Westguard Keep" elseif ZoneID == "3999" then return "Steel Gate" elseif ZoneID == "4000" then return "Vengeance Landing" elseif ZoneID == "4001" then return "Baleheim" elseif ZoneID == "4002" then return "Skorn" elseif ZoneID == "4003" then return "Fort Wildervar" elseif ZoneID == "4004" then return "Vileprey Village" elseif ZoneID == "4005" then return "Ivald's Ruin" elseif ZoneID == "4006" then return "Gjalerbron" elseif ZoneID == "4007" then return "Tomb of the Lost Kings" elseif ZoneID == "4008" then return "Shartuul's Transporter" elseif ZoneID == "4009" then return "Illidari Training Grounds" elseif ZoneID == "4010" then return "Mudsprocket" elseif ZoneID == "4018" then return "Camp Winterhoof" elseif ZoneID == "4019" then return "Development Land" elseif ZoneID == "4020" then return "Mightstone Quarry" elseif ZoneID == "4021" then return "Bloodspore Plains" elseif ZoneID == "4022" then return "Gammoth" elseif ZoneID == "4023" then return "Amber Ledge" elseif ZoneID == "4024" then return "Coldarra" elseif ZoneID == "4025" then return "The Westrift" elseif ZoneID == "4026" then return "The Transitus Stair" elseif ZoneID == "4027" then return "Coast of Echoes" elseif ZoneID == "4028" then return "Riplash Strand" elseif ZoneID == "4029" then return "Riplash Ruins" elseif ZoneID == "4030" then return "Coast of Idols" elseif ZoneID == "4031" then return "Pal'ea" elseif ZoneID == "4032" then return "Valiance Keep" elseif ZoneID == "4033" then return "Winterfin Village" elseif ZoneID == "4034" then return "The Borean Wall" elseif ZoneID == "4035" then return "The Geyser Fields" elseif ZoneID == "4036" then return "Fizzcrank Pumping Station" elseif ZoneID == "4037" then return "Taunka'le Village" elseif ZoneID == "4038" then return "Magnamoth Caverns" elseif ZoneID == "4039" then return "Coldrock Quarry" elseif ZoneID == "4040" then return "Njord's Breath Bay" elseif ZoneID == "4041" then return "Kaskala" elseif ZoneID == "4042" then return "Transborea" elseif ZoneID == "4043" then return "The Flood Plains" elseif ZoneID == "4046" then return "Direhorn Post" elseif ZoneID == "4047" then return "Nat's Landing" elseif ZoneID == "4048" then return "Ember Clutch" elseif ZoneID == "4049" then return "Tabetha's Farm" elseif ZoneID == "4050" then return "Derelict Strand" elseif ZoneID == "4051" then return "The Frozen Glade" elseif ZoneID == "4052" then return "The Vibrant Glade" elseif ZoneID == "4053" then return "The Twisted Glade" elseif ZoneID == "4054" then return "Rivenwood" elseif ZoneID == "4055" then return "Caldemere Lake" elseif ZoneID == "4056" then return "Utgarde Catacombs" elseif ZoneID == "4057" then return "Shield Hill" elseif ZoneID == "4058" then return "Lake Cauldros" elseif ZoneID == "4059" then return "Cauldros Isle" elseif ZoneID == "4060" then return "Bleeding Vale" elseif ZoneID == "4061" then return "Giants' Run" elseif ZoneID == "4062" then return "Apothecary Camp" elseif ZoneID == "4063" then return "Ember Spear Tower" elseif ZoneID == "4064" then return "Shattered Straits" elseif ZoneID == "4065" then return "Gjalerhorn" elseif ZoneID == "4066" then return "Frostblade Peak" elseif ZoneID == "4067" then return "Plaguewood Tower" elseif ZoneID == "4068" then return "West Spear Tower" elseif ZoneID == "4069" then return "North Spear Tower" elseif ZoneID == "4070" then return "Chillmere Coast" elseif ZoneID == "4071" then return "Whisper Gulch" elseif ZoneID == "4072" then return "Sub zone" elseif ZoneID == "4073" then return "Winter's Terrace" elseif ZoneID == "4074" then return "The Waking Halls" elseif ZoneID == "4075" then return "Sunwell Plateau" elseif ZoneID == "4076" then return "Reuse Me 7" elseif ZoneID == "4077" then return "Sorlof's Strand" elseif ZoneID == "4078" then return "Razorthorn Rise" elseif ZoneID == "4079" then return "Frostblade Pass" elseif ZoneID == "4080" then return "Isle of Quel'Danas" elseif ZoneID == "4081" then return "The Dawnchaser" elseif ZoneID == "4082" then return "The Sin'loren" elseif ZoneID == "4083" then return "Silvermoon's Pride" elseif ZoneID == "4084" then return "The Bloodoath" elseif ZoneID == "4085" then return "Shattered Sun Staging Area" elseif ZoneID == "4086" then return "Sun's Reach Sanctum" elseif ZoneID == "4087" then return "Sun's Reach Harbor" elseif ZoneID == "4088" then return "Sun's Reach Armory" elseif ZoneID == "4089" then return "Dawnstar Village" elseif ZoneID == "4090" then return "The Dawning Square" elseif ZoneID == "4091" then return "Greengill Coast" elseif ZoneID == "4092" then return "The Dead Scar" elseif ZoneID == "4093" then return "The Sun Forge" elseif ZoneID == "4094" then return "Sunwell Plateau" elseif ZoneID == "4095" then return "Magisters' Terrace" elseif ZoneID == "4096" then return "Claytön's WoWEdit Land" elseif ZoneID == "4097" then return "Winterfin Caverns" elseif ZoneID == "4098" then return "Glimmer Bay" elseif ZoneID == "4099" then return "Winterfin Retreat" elseif ZoneID == "4100" then return "The Culling of Stratholme" elseif ZoneID == "4101" then return "Sands of Nasam" elseif ZoneID == "4102" then return "Krom's Landing" elseif ZoneID == "4103" then return "Nasam's Talon" elseif ZoneID == "4104" then return "Echo Cove" elseif ZoneID == "4105" then return "Beryl Point" elseif ZoneID == "4106" then return "Garrosh's Landing" elseif ZoneID == "4107" then return "Warsong Jetty" elseif ZoneID == "4108" then return "Fizzcrank Airstrip" elseif ZoneID == "4109" then return "Lake Kum'uya" elseif ZoneID == "4110" then return "Farshire Fields" elseif ZoneID == "4111" then return "Farshire" elseif ZoneID == "4112" then return "Farshire Lighthouse" elseif ZoneID == "4113" then return "Unu'pe" elseif ZoneID == "4114" then return "Death's Stand" elseif ZoneID == "4115" then return "The Abandoned Reach" elseif ZoneID == "4116" then return "Scalding Pools" elseif ZoneID == "4117" then return "Steam Springs" elseif ZoneID == "4118" then return "Talramas" elseif ZoneID == "4119" then return "Festering Pools" elseif ZoneID == "4120" then return "The Nexus" elseif ZoneID == "4121" then return "Transitus Shield" elseif ZoneID == "4122" then return "Bor'gorok Outpost" elseif ZoneID == "4123" then return "Magmoth" elseif ZoneID == "4124" then return "The Dens of Dying" elseif ZoneID == "4125" then return "Temple City of En'kilah" elseif ZoneID == "4126" then return "The Wailing Ziggurat" elseif ZoneID == "4127" then return "Steeljaw's Caravan" elseif ZoneID == "4128" then return "Naxxanar" elseif ZoneID == "4129" then return "Warsong Hold" elseif ZoneID == "4130" then return "Plains of Nasam" elseif ZoneID == "4131" then return "Magisters' Terrace" elseif ZoneID == "4132" then return "Ruins of Eldra'nath" elseif ZoneID == "4133" then return "Charred Rise" elseif ZoneID == "4134" then return "Blistering Pool" elseif ZoneID == "4135" then return "Spire of Blood" elseif ZoneID == "4136" then return "Spire of Decay" elseif ZoneID == "4137" then return "Spire of Pain" elseif ZoneID == "4138" then return "Frozen Reach" elseif ZoneID == "4139" then return "Parhelion Plaza" elseif ZoneID == "4140" then return "The Dead Scar" elseif ZoneID == "4141" then return "Torp's Farm" elseif ZoneID == "4142" then return "Warsong Granary" elseif ZoneID == "4143" then return "Warsong Slaughterhouse" elseif ZoneID == "4144" then return "Warsong Farms Outpost" elseif ZoneID == "4145" then return "West Point Station" elseif ZoneID == "4146" then return "North Point Station" elseif ZoneID == "4147" then return "Mid Point Station" elseif ZoneID == "4148" then return "South Point Station" elseif ZoneID == "4149" then return "D.E.H.T.A. Encampment" elseif ZoneID == "4150" then return "Kaw's Roost" elseif ZoneID == "4151" then return "Westwind Refugee Camp" elseif ZoneID == "4152" then return "Moa'ki Harbor" elseif ZoneID == "4153" then return "Indu'le Village" elseif ZoneID == "4154" then return "Snowfall Glade" elseif ZoneID == "4155" then return "The Half Shell" elseif ZoneID == "4156" then return "Surge Needle" elseif ZoneID == "4157" then return "Moonrest Gardens" elseif ZoneID == "4158" then return "Stars' Rest" elseif ZoneID == "4159" then return "Westfall Brigade Encampment" elseif ZoneID == "4160" then return "Lothalor Woodlands" elseif ZoneID == "4161" then return "Wyrmrest Temple" elseif ZoneID == "4162" then return "Icemist Falls" elseif ZoneID == "4163" then return "Icemist Village" elseif ZoneID == "4164" then return "The Pit of Narjun" elseif ZoneID == "4165" then return "Agmar's Hammer" elseif ZoneID == "4166" then return "Lake Indu'le" elseif ZoneID == "4167" then return "Obsidian Dragonshrine" elseif ZoneID == "4168" then return "Ruby Dragonshrine" elseif ZoneID == "4169" then return "Fordragon Hold" elseif ZoneID == "4170" then return "Kor'kron Vanguard" elseif ZoneID == "4171" then return "The Court of Skulls" elseif ZoneID == "4172" then return "Angrathar the Wrathgate" elseif ZoneID == "4173" then return "Galakrond's Rest" elseif ZoneID == "4174" then return "The Wicked Coil" elseif ZoneID == "4175" then return "Bronze Dragonshrine" elseif ZoneID == "4176" then return "The Mirror of Dawn" elseif ZoneID == "4177" then return "Wintergarde Keep" elseif ZoneID == "4178" then return "Wintergarde Mine" elseif ZoneID == "4179" then return "Emerald Dragonshrine" elseif ZoneID == "4180" then return "New Hearthglen" elseif ZoneID == "4181" then return "Crusader's Landing" elseif ZoneID == "4182" then return "Sinner's Folly" elseif ZoneID == "4183" then return "Azure Dragonshrine" elseif ZoneID == "4184" then return "Path of the Titans" elseif ZoneID == "4185" then return "The Forgotten Shore" elseif ZoneID == "4186" then return "Venomspite" elseif ZoneID == "4187" then return "The Crystal Vice" elseif ZoneID == "4188" then return "The Carrion Fields" elseif ZoneID == "4189" then return "Onslaught Base Camp" elseif ZoneID == "4190" then return "Thorson's Post" elseif ZoneID == "4191" then return "Light's Trust" elseif ZoneID == "4192" then return "Frostmourne Cavern" elseif ZoneID == "4193" then return "Scarlet Point" elseif ZoneID == "4194" then return "Jintha'kalar" elseif ZoneID == "4195" then return "Ice Heart Cavern" elseif ZoneID == "4196" then return "Drak'Tharon Keep" elseif ZoneID == "4197" then return "Wintergrasp" elseif ZoneID == "4198" then return "Kili'ua's Atoll" elseif ZoneID == "4199" then return "Silverbrook" elseif ZoneID == "4200" then return "Vordrassil's Heart" elseif ZoneID == "4201" then return "Vordrassil's Tears" elseif ZoneID == "4202" then return "Vordrassil's Tears" elseif ZoneID == "4203" then return "Vordrassil's Limb" elseif ZoneID == "4204" then return "Amberpine Lodge" elseif ZoneID == "4205" then return "Solstice Village" elseif ZoneID == "4206" then return "Conquest Hold" elseif ZoneID == "4207" then return "Voldrune" elseif ZoneID == "4208" then return "Granite Springs" elseif ZoneID == "4209" then return "Zeb'Halak" elseif ZoneID == "4210" then return "Drak'Tharon Keep" elseif ZoneID == "4211" then return "Camp Oneqwah" elseif ZoneID == "4212" then return "Eastwind Shore" elseif ZoneID == "4213" then return "The Broken Bluffs" elseif ZoneID == "4214" then return "Boulder Hills" elseif ZoneID == "4215" then return "Rage Fang Shrine" elseif ZoneID == "4216" then return "Drakil'jin Ruins" elseif ZoneID == "4217" then return "Blackriver Logging Camp" elseif ZoneID == "4218" then return "Heart's Blood Shrine" elseif ZoneID == "4219" then return "Hollowstone Mine" elseif ZoneID == "4220" then return "Dun Argol" elseif ZoneID == "4221" then return "Thor Modan" elseif ZoneID == "4222" then return "Blue Sky Logging Grounds" elseif ZoneID == "4223" then return "Maw of Neltharion" elseif ZoneID == "4224" then return "The Briny Pinnacle" elseif ZoneID == "4225" then return "Glittering Strand" elseif ZoneID == "4226" then return "Iskaal" elseif ZoneID == "4227" then return "Dragon's Fall" elseif ZoneID == "4228" then return "The Oculus" elseif ZoneID == "4229" then return "Prospector's Point" elseif ZoneID == "4230" then return "Coldwind Heights" elseif ZoneID == "4231" then return "Redwood Trading Post" elseif ZoneID == "4232" then return "Vengeance Pass" elseif ZoneID == "4233" then return "Dawn's Reach" elseif ZoneID == "4234" then return "Naxxramas" elseif ZoneID == "4235" then return "Heartwood Trading Post" elseif ZoneID == "4236" then return "Evergreen Trading Post" elseif ZoneID == "4237" then return "Spruce Point Post" elseif ZoneID == "4238" then return "White Pine Trading Post" elseif ZoneID == "4239" then return "Aspen Grove Post" elseif ZoneID == "4240" then return "Forest's Edge Post" elseif ZoneID == "4241" then return "Eldritch Heights" elseif ZoneID == "4242" then return "Venture Bay" elseif ZoneID == "4243" then return "Wintergarde Crypt" elseif ZoneID == "4244" then return "Bloodmoon Isle" elseif ZoneID == "4245" then return "Shadowfang Tower" elseif ZoneID == "4246" then return "Wintergarde Mausoleum" elseif ZoneID == "4247" then return "Duskhowl Den" elseif ZoneID == "4248" then return "The Conquest Pit" elseif ZoneID == "4249" then return "The Path of Iron" elseif ZoneID == "4250" then return "Ruins of Tethys" elseif ZoneID == "4251" then return "Silverbrook Hills" elseif ZoneID == "4252" then return "The Broken Bluffs" elseif ZoneID == "4253" then return "7th Legion Front" elseif ZoneID == "4254" then return "The Dragon Wastes" elseif ZoneID == "4255" then return "Ruins of Drak'Zin" elseif ZoneID == "4256" then return "Drak'Mar Lake" elseif ZoneID == "4257" then return "Dragonspine Tributary" elseif ZoneID == "4258" then return "The North Sea" elseif ZoneID == "4259" then return "Drak'ural" elseif ZoneID == "4260" then return "Thorvald's Camp" elseif ZoneID == "4261" then return "Ghostblade Post" elseif ZoneID == "4262" then return "Ashwood Post" elseif ZoneID == "4263" then return "Lydell's Ambush" elseif ZoneID == "4264" then return "Halls of Stone" elseif ZoneID == "4265" then return "The Nexus" elseif ZoneID == "4266" then return "Harkor's Camp" elseif ZoneID == "4267" then return "Vordrassil Pass" elseif ZoneID == "4268" then return "Ruuna's Camp" elseif ZoneID == "4269" then return "Shrine of Scales" elseif ZoneID == "4270" then return "Drak'atal Passage" elseif ZoneID == "4271" then return "Utgarde Pinnacle" elseif ZoneID == "4272" then return "Halls of Lightning" elseif ZoneID == "4273" then return "Ulduar" elseif ZoneID == "4275" then return "The Argent Stand" elseif ZoneID == "4276" then return "Altar of Sseratus" elseif ZoneID == "4277" then return "Azjol-Nerub" elseif ZoneID == "4278" then return "Drak'Sotra Fields" elseif ZoneID == "4279" then return "Drak'Sotra" elseif ZoneID == "4280" then return "Drak'Agal" elseif ZoneID == "4281" then return "Acherus: The Ebon Hold" elseif ZoneID == "4282" then return "The Avalanche" elseif ZoneID == "4283" then return "The Lost Lands" elseif ZoneID == "4284" then return "Nesingwary Base Camp" elseif ZoneID == "4285" then return "The Seabreach Flow" elseif ZoneID == "4286" then return "The Bones of Nozronn" elseif ZoneID == "4287" then return "Kartak's Hold" elseif ZoneID == "4288" then return "Sparktouched Haven" elseif ZoneID == "4289" then return "The Path of the Lifewarden" elseif ZoneID == "4290" then return "River's Heart" elseif ZoneID == "4291" then return "Rainspeaker Canopy" elseif ZoneID == "4292" then return "Frenzyheart Hill" elseif ZoneID == "4293" then return "Wildgrowth Mangal" elseif ZoneID == "4294" then return "Heb'Valok" elseif ZoneID == "4295" then return "The Sundered Shard" elseif ZoneID == "4296" then return "The Lifeblood Pillar" elseif ZoneID == "4297" then return "Mosswalker Village" elseif ZoneID == "4298" then return "Plaguelands: The Scarlet Enclave" elseif ZoneID == "4299" then return "Kolramas" elseif ZoneID == "4300" then return "Waygate" elseif ZoneID == "4302" then return "The Skyreach Pillar" elseif ZoneID == "4303" then return "Hardknuckle Clearing" elseif ZoneID == "4304" then return "Sapphire Hive" elseif ZoneID == "4306" then return "Mistwhisper Refuge" elseif ZoneID == "4307" then return "The Glimmering Pillar" elseif ZoneID == "4308" then return "Spearborn Encampment" elseif ZoneID == "4309" then return "Drak'Tharon Keep" elseif ZoneID == "4310" then return "Zeramas" elseif ZoneID == "4311" then return "Reliquary of Agony" elseif ZoneID == "4312" then return "Ebon Watch" elseif ZoneID == "4313" then return "Thrym's End" elseif ZoneID == "4314" then return "Voltarus" elseif ZoneID == "4315" then return "Reliquary of Pain" elseif ZoneID == "4316" then return "Rageclaw Den" elseif ZoneID == "4317" then return "Light's Breach" elseif ZoneID == "4318" then return "Pools of Zha'Jin" elseif ZoneID == "4319" then return "Zim'Abwa" elseif ZoneID == "4320" then return "Amphitheater of Anguish" elseif ZoneID == "4321" then return "Altar of Rhunok" elseif ZoneID == "4322" then return "Altar of Har'koa" elseif ZoneID == "4323" then return "Zim'Torga" elseif ZoneID == "4324" then return "Pools of Jin'Alai" elseif ZoneID == "4325" then return "Altar of Quetz'lun" elseif ZoneID == "4326" then return "Heb'Drakkar" elseif ZoneID == "4327" then return "Drak'Mabwa" elseif ZoneID == "4328" then return "Zim'Rhuk" elseif ZoneID == "4329" then return "Altar of Mam'toth" elseif ZoneID == "4342" then return "Acherus: The Ebon Hold" elseif ZoneID == "4343" then return "New Avalon" elseif ZoneID == "4344" then return "New Avalon Fields" elseif ZoneID == "4345" then return "New Avalon Orchard" elseif ZoneID == "4346" then return "New Avalon Town Hall" elseif ZoneID == "4347" then return "Havenshire" elseif ZoneID == "4348" then return "Havenshire Farms" elseif ZoneID == "4349" then return "Havenshire Lumber Mill" elseif ZoneID == "4350" then return "Havenshire Stables" elseif ZoneID == "4351" then return "Scarlet Hold" elseif ZoneID == "4352" then return "Chapel of the Crimson Flame" elseif ZoneID == "4353" then return "Light's Point Tower" elseif ZoneID == "4354" then return "Light's Point" elseif ZoneID == "4355" then return "Crypt of Remembrance" elseif ZoneID == "4356" then return "Death's Breach" elseif ZoneID == "4357" then return "The Noxious Glade" elseif ZoneID == "4358" then return "Tyr's Hand" elseif ZoneID == "4359" then return "King's Harbor" elseif ZoneID == "4360" then return "Scarlet Overlook" elseif ZoneID == "4361" then return "Light's Hope Chapel" elseif ZoneID == "4362" then return "Sinner's Folly" elseif ZoneID == "4363" then return "Pestilent Scar" elseif ZoneID == "4364" then return "Browman Mill" elseif ZoneID == "4365" then return "Havenshire Mine" elseif ZoneID == "4366" then return "Ursoc's Den" elseif ZoneID == "4367" then return "The Blight Line" elseif ZoneID == "4368" then return "The Bonefields" elseif ZoneID == "4369" then return "Dorian's Outpost" elseif ZoneID == "4371" then return "Mam'toth Crater" elseif ZoneID == "4372" then return "Zol'Maz Stronghold" elseif ZoneID == "4373" then return "Zol'Heb" elseif ZoneID == "4374" then return "Rageclaw Lake" elseif ZoneID == "4375" then return "Gundrak" elseif ZoneID == "4376" then return "The Savage Thicket" elseif ZoneID == "4377" then return "New Avalon Forge" elseif ZoneID == "4378" then return "Dalaran Arena" elseif ZoneID == "4379" then return "Valgarde" elseif ZoneID == "4380" then return "Westguard Inn" elseif ZoneID == "4381" then return "Waygate" elseif ZoneID == "4382" then return "The Shaper's Terrace" elseif ZoneID == "4383" then return "Lakeside Landing" elseif ZoneID == "4384" then return "Strand of the Ancients" elseif ZoneID == "4385" then return "Bittertide Lake" elseif ZoneID == "4386" then return "Rainspeaker Rapids" elseif ZoneID == "4387" then return "Frenzyheart River" elseif ZoneID == "4388" then return "Wintergrasp River" elseif ZoneID == "4389" then return "The Suntouched Pillar" elseif ZoneID == "4390" then return "Frigid Breach" elseif ZoneID == "4391" then return "Swindlegrin's Dig" elseif ZoneID == "4392" then return "The Stormwright's Shelf" elseif ZoneID == "4393" then return "Death's Hand Encampment" elseif ZoneID == "4394" then return "Scarlet Tavern" elseif ZoneID == "4395" then return "Dalaran" elseif ZoneID == "4396" then return "Nozzlerust Post" elseif ZoneID == "4399" then return "Farshire Mine" elseif ZoneID == "4400" then return "The Mosslight Pillar" elseif ZoneID == "4401" then return "Saragosa's Landing" elseif ZoneID == "4402" then return "Vengeance Lift" elseif ZoneID == "4403" then return "Balejar Watch" elseif ZoneID == "4404" then return "New Agamand Inn" elseif ZoneID == "4405" then return "Passage of Lost Fiends" elseif ZoneID == "4406" then return "The Ring of Valor" elseif ZoneID == "4407" then return "Hall of the Frostwolf" elseif ZoneID == "4408" then return "Hall of the Stormpike" elseif ZoneID == "4411" then return "Stormwind Harbor" elseif ZoneID == "4412" then return "The Makers' Overlook" elseif ZoneID == "4413" then return "The Makers' Perch" elseif ZoneID == "4414" then return "Scarlet Tower" elseif ZoneID == "4415" then return "The Violet Hold" elseif ZoneID == "4416" then return "Gundrak" elseif ZoneID == "4417" then return "Onslaught Harbor" elseif ZoneID == "4418" then return "K3" elseif ZoneID == "4419" then return "Snowblind Hills" elseif ZoneID == "4420" then return "Snowblind Terrace" elseif ZoneID == "4421" then return "Garm" elseif ZoneID == "4422" then return "Brunnhildar Village" elseif ZoneID == "4423" then return "Sifreldar Village" elseif ZoneID == "4424" then return "Valkyrion" elseif ZoneID == "4425" then return "The Forlorn Mine" elseif ZoneID == "4426" then return "Bor's Breath River" elseif ZoneID == "4427" then return "Argent Vanguard" elseif ZoneID == "4428" then return "Frosthold" elseif ZoneID == "4429" then return "Grom'arsh Crash-Site" elseif ZoneID == "4430" then return "Temple of Storms" elseif ZoneID == "4431" then return "Engine of the Makers" elseif ZoneID == "4432" then return "The Foot Steppes" elseif ZoneID == "4433" then return "Dragonspine Peaks" elseif ZoneID == "4434" then return "Nidavelir" elseif ZoneID == "4435" then return "Narvir's Cradle" elseif ZoneID == "4436" then return "Snowdrift Plains" elseif ZoneID == "4437" then return "Valley of Ancient Winters" elseif ZoneID == "4438" then return "Dun Niffelem" elseif ZoneID == "4439" then return "Frostfield Lake" elseif ZoneID == "4440" then return "Thunderfall" elseif ZoneID == "4441" then return "Camp Tunka'lo" elseif ZoneID == "4442" then return "Brann's Base-Camp" elseif ZoneID == "4443" then return "Gate of Echoes" elseif ZoneID == "4444" then return "Plain of Echoes" elseif ZoneID == "4445" then return "Ulduar" elseif ZoneID == "4446" then return "Terrace of the Makers" elseif ZoneID == "4447" then return "Gate of Lightning" elseif ZoneID == "4448" then return "Path of the Titans" elseif ZoneID == "4449" then return "Uldis" elseif ZoneID == "4450" then return "Loken's Bargain" elseif ZoneID == "4451" then return "Bor's Fall" elseif ZoneID == "4452" then return "Bor's Breath" elseif ZoneID == "4453" then return "Rohemdal Pass" elseif ZoneID == "4454" then return "The Storm Foundry" elseif ZoneID == "4455" then return "Hibernal Cavern" elseif ZoneID == "4456" then return "Voldrune Dwelling" elseif ZoneID == "4457" then return "Torseg's Rest" elseif ZoneID == "4458" then return "Sparksocket Minefield" elseif ZoneID == "4459" then return "Ricket's Folly" elseif ZoneID == "4460" then return "Garm's Bane" elseif ZoneID == "4461" then return "Garm's Rise" elseif ZoneID == "4462" then return "Crystalweb Cavern" elseif ZoneID == "4463" then return "Temple of Life" elseif ZoneID == "4464" then return "Temple of Order" elseif ZoneID == "4465" then return "Temple of Winter" elseif ZoneID == "4466" then return "Temple of Invention" elseif ZoneID == "4467" then return "Death's Rise" elseif ZoneID == "4468" then return "The Dead Fields" elseif ZoneID == "4469" then return "Dargath's Demise" elseif ZoneID == "4470" then return "The Hidden Hollow" elseif ZoneID == "4471" then return "Bernau's Happy Fun Land" elseif ZoneID == "4472" then return "Frostgrip's Hollow" elseif ZoneID == "4473" then return "The Frigid Tomb" elseif ZoneID == "4474" then return "Twin Shores" elseif ZoneID == "4475" then return "Zim'bo's Hideout" elseif ZoneID == "4476" then return "Abandoned Camp" elseif ZoneID == "4477" then return "The Shadow Vault" elseif ZoneID == "4478" then return "Coldwind Pass" elseif ZoneID == "4479" then return "Winter's Breath Lake" elseif ZoneID == "4480" then return "The Forgotten Overlook" elseif ZoneID == "4481" then return "Jintha'kalar Passage" elseif ZoneID == "4482" then return "Arriga Footbridge" elseif ZoneID == "4483" then return "The Lost Passage" elseif ZoneID == "4484" then return "Bouldercrag's Refuge" elseif ZoneID == "4485" then return "The Inventor's Library" elseif ZoneID == "4486" then return "The Frozen Mine" elseif ZoneID == "4487" then return "Frostfloe Deep" elseif ZoneID == "4488" then return "The Howling Hollow" elseif ZoneID == "4489" then return "Crusader Forward Camp" elseif ZoneID == "4490" then return "Stormcrest" elseif ZoneID == "4491" then return "Bonesnap's Camp" elseif ZoneID == "4492" then return "Ufrang's Hall" elseif ZoneID == "4493" then return "The Obsidian Sanctum" elseif ZoneID == "4494" then return "Ahn'kahet: The Old Kingdom" elseif ZoneID == "4495" then return "Fjorn's Anvil" elseif ZoneID == "4496" then return "Jotunheim" elseif ZoneID == "4497" then return "Savage Ledge" elseif ZoneID == "4498" then return "Halls of the Ancestors" elseif ZoneID == "4499" then return "The Blighted Pool" elseif ZoneID == "4500" then return "The Eye of Eternity" elseif ZoneID == "4501" then return "The Argent Vanguard" elseif ZoneID == "4502" then return "Mimir's Workshop" elseif ZoneID == "4503" then return "Ironwall Dam" elseif ZoneID == "4504" then return "Valley of Echoes" elseif ZoneID == "4505" then return "The Breach" elseif ZoneID == "4506" then return "Scourgeholme" elseif ZoneID == "4507" then return "The Broken Front" elseif ZoneID == "4508" then return "Mord'rethar: The Death Gate" elseif ZoneID == "4509" then return "The Bombardment" elseif ZoneID == "4510" then return "Aldur'thar: The Desolation Gate" elseif ZoneID == "4511" then return "The Skybreaker" elseif ZoneID == "4512" then return "Orgrim's Hammer" elseif ZoneID == "4513" then return "Ymirheim" elseif ZoneID == "4514" then return "Saronite Mines" elseif ZoneID == "4515" then return "The Conflagration" elseif ZoneID == "4516" then return "Ironwall Rampart" elseif ZoneID == "4517" then return "Weeping Quarry" elseif ZoneID == "4518" then return "Corp'rethar: The Horror Gate" elseif ZoneID == "4519" then return "The Court of Bones" elseif ZoneID == "4520" then return "Malykriss: The Vile Hold" elseif ZoneID == "4521" then return "Cathedral of Darkness" elseif ZoneID == "4522" then return "Icecrown Citadel" elseif ZoneID == "4523" then return "Icecrown Glacier" elseif ZoneID == "4524" then return "Valhalas" elseif ZoneID == "4525" then return "The Underhalls" elseif ZoneID == "4526" then return "Njorndar Village" elseif ZoneID == "4527" then return "Balargarde Fortress" elseif ZoneID == "4528" then return "Kul'galar Keep" elseif ZoneID == "4529" then return "The Crimson Cathedral" elseif ZoneID == "4530" then return "Sanctum of Reanimation" elseif ZoneID == "4531" then return "The Fleshwerks" elseif ZoneID == "4532" then return "Vengeance Landing Inn" elseif ZoneID == "4533" then return "Sindragosa's Fall" elseif ZoneID == "4534" then return "Wildervar Mine" elseif ZoneID == "4535" then return "The Pit of the Fang" elseif ZoneID == "4536" then return "Frosthowl Cavern" elseif ZoneID == "4537" then return "The Valley of Lost Hope" elseif ZoneID == "4538" then return "The Sunken Ring" elseif ZoneID == "4539" then return "The Broken Temple" elseif ZoneID == "4540" then return "The Valley of Fallen Heroes" elseif ZoneID == "4541" then return "Vanguard Infirmary" elseif ZoneID == "4542" then return "Hall of the Shaper" elseif ZoneID == "4543" then return "Temple of Wisdom" elseif ZoneID == "4544" then return "Death's Breach" elseif ZoneID == "4545" then return "Abandoned Mine" elseif ZoneID == "4546" then return "Ruins of the Scarlet Enclave" elseif ZoneID == "4547" then return "Halls of Stone" elseif ZoneID == "4548" then return "Halls of Lightning" elseif ZoneID == "4549" then return "The Great Tree" elseif ZoneID == "4550" then return "The Mirror of Twilight" elseif ZoneID == "4551" then return "The Twilight Rivulet" elseif ZoneID == "4552" then return "The Decrepit Flow" elseif ZoneID == "4553" then return "Forlorn Woods" elseif ZoneID == "4554" then return "Ruins of Shandaral" elseif ZoneID == "4555" then return "The Azure Front" elseif ZoneID == "4556" then return "Violet Stand" elseif ZoneID == "4557" then return "The Unbound Thicket" elseif ZoneID == "4558" then return "Sunreaver's Command" elseif ZoneID == "4559" then return "Windrunner's Overlook" elseif ZoneID == "4560" then return "The Underbelly" elseif ZoneID == "4564" then return "Krasus' Landing" elseif ZoneID == "4567" then return "The Violet Hold" elseif ZoneID == "4568" then return "The Eventide" elseif ZoneID == "4569" then return "Sewer Exit Pipe" elseif ZoneID == "4570" then return "Circle of Wills" elseif ZoneID == "4571" then return "Silverwing Flag Room" elseif ZoneID == "4572" then return "Warsong Flag Room" elseif ZoneID == "4575" then return "Wintergrasp Fortress" elseif ZoneID == "4576" then return "Central Bridge" elseif ZoneID == "4577" then return "Eastern Bridge" elseif ZoneID == "4578" then return "Western Bridge" elseif ZoneID == "4579" then return "Dubra'Jin" elseif ZoneID == "4580" then return "Crusaders' Pinnacle" elseif ZoneID == "4581" then return "Flamewatch Tower" elseif ZoneID == "4582" then return "Winter's Edge Tower" elseif ZoneID == "4583" then return "Shadowsight Tower" elseif ZoneID == "4584" then return "The Cauldron of Flames" elseif ZoneID == "4585" then return "Glacial Falls" elseif ZoneID == "4586" then return "Windy Bluffs" elseif ZoneID == "4587" then return "The Forest of Shadows" elseif ZoneID == "4588" then return "Blackwatch" elseif ZoneID == "4589" then return "The Chilled Quagmire" elseif ZoneID == "4590" then return "The Steppe of Life" elseif ZoneID == "4591" then return "Silent Vigil" elseif ZoneID == "4592" then return "Gimorak's Den" elseif ZoneID == "4593" then return "The Pit of Fiends" elseif ZoneID == "4594" then return "Battlescar Spire" elseif ZoneID == "4595" then return "Hall of Horrors" elseif ZoneID == "4596" then return "The Circle of Suffering" elseif ZoneID == "4597" then return "Rise of Suffering" elseif ZoneID == "4598" then return "Krasus' Landing" elseif ZoneID == "4599" then return "Sewer Exit Pipe" elseif ZoneID == "4601" then return "Dalaran Island" elseif ZoneID == "4602" then return "Force Interior" elseif ZoneID == "4603" then return "Vault of Archavon" elseif ZoneID == "4604" then return "Gate of the Red Sun" elseif ZoneID == "4605" then return "Gate of the Blue Sapphire" elseif ZoneID == "4606" then return "Gate of the Green Emerald" elseif ZoneID == "4607" then return "Gate of the Purple Amethyst" elseif ZoneID == "4608" then return "Gate of the Yellow Moon" elseif ZoneID == "4609" then return "Courtyard of the Ancients" elseif ZoneID == "4610" then return "Landing Beach" elseif ZoneID == "4611" then return "Westspark Workshop" elseif ZoneID == "4612" then return "Eastspark Workshop" elseif ZoneID == "4613" then return "Dalaran City" elseif ZoneID == "4614" then return "The Violet Citadel Spire" elseif ZoneID == "4615" then return "Naz'anak: The Forgotten Depths" elseif ZoneID == "4616" then return "Sunreaver's Sanctuary" elseif ZoneID == "4617" then return "Elevator" elseif ZoneID == "4618" then return "Antonidas Memorial" elseif ZoneID == "4619" then return "The Violet Citadel" elseif ZoneID == "4620" then return "Magus Commerce Exchange" elseif ZoneID == "4621" then return "UNUSED" elseif ZoneID == "4622" then return "First Legion Forward Camp" elseif ZoneID == "4623" then return "Hall of the Conquered Kings" elseif ZoneID == "4624" then return "Befouled Terrace" elseif ZoneID == "4625" then return "The Desecrated Altar" elseif ZoneID == "4626" then return "Shimmering Bog" elseif ZoneID == "4627" then return "Fallen Temple of Ahn'kahet" elseif ZoneID == "4628" then return "Halls of Binding" elseif ZoneID == "4629" then return "Winter's Heart" elseif ZoneID == "4630" then return "The North Sea" elseif ZoneID == "4631" then return "The Broodmother's Nest" elseif ZoneID == "4632" then return "Dalaran Floating Rocks" elseif ZoneID == "4633" then return "Raptor Pens" elseif ZoneID == "4635" then return "Drak'Tharon Keep" elseif ZoneID == "4636" then return "The Noxious Pass" elseif ZoneID == "4637" then return "Vargoth's Retreat" elseif ZoneID == "4638" then return "Violet Citadel Balcony" elseif ZoneID == "4639" then return "Band of Variance" elseif ZoneID == "4640" then return "Band of Acceleration" elseif ZoneID == "4641" then return "Band of Transmutation" elseif ZoneID == "4642" then return "Band of Alignment" elseif ZoneID == "4646" then return "Ashwood Lake" elseif ZoneID == "4650" then return "Iron Concourse" elseif ZoneID == "4652" then return "Formation Grounds" elseif ZoneID == "4653" then return "Razorscale's Aerie" elseif ZoneID == "4654" then return "The Colossal Forge" elseif ZoneID == "4655" then return "The Scrapyard" elseif ZoneID == "4656" then return "The Conservatory of Life" elseif ZoneID == "4657" then return "The Archivum" elseif ZoneID == "4658" then return "Argent Tournament Grounds" elseif ZoneID == "4665" then return "Expedition Base Camp" elseif ZoneID == "4666" then return "Sunreaver Pavilion" elseif ZoneID == "4667" then return "Silver Covenant Pavilion" elseif ZoneID == "4668" then return "The Cooper Residence" elseif ZoneID == "4669" then return "The Ring of Champions" elseif ZoneID == "4670" then return "The Aspirants' Ring" elseif ZoneID == "4671" then return "The Argent Valiants' Ring" elseif ZoneID == "4672" then return "The Alliance Valiants' Ring" elseif ZoneID == "4673" then return "The Horde Valiants' Ring" elseif ZoneID == "4674" then return "Argent Pavilion" elseif ZoneID == "4676" then return "Sunreaver Pavilion" elseif ZoneID == "4677" then return "Silver Covenant Pavilion" elseif ZoneID == "4679" then return "The Forlorn Cavern" elseif ZoneID == "4688" then return "claytonio test area" elseif ZoneID == "4692" then return "Quel'Delar's Rest" elseif ZoneID == "4710" then return "Isle of Conquest" elseif ZoneID == "4722" then return "Trial of the Crusader" elseif ZoneID == "4723" then return "Trial of the Champion" elseif ZoneID == "4739" then return "Runeweaver Square" elseif ZoneID == "4740" then return "The Silver Enclave" elseif ZoneID == "4741" then return "Isle of Conquest No Man's Land" elseif ZoneID == "4742" then return "Hrothgar's Landing" elseif ZoneID == "4743" then return "Deathspeaker's Watch" elseif ZoneID == "4747" then return "Workshop" elseif ZoneID == "4748" then return "Quarry" elseif ZoneID == "4749" then return "Docks" elseif ZoneID == "4750" then return "Hangar" elseif ZoneID == "4751" then return "Refinery" elseif ZoneID == "4752" then return "Horde Keep" elseif ZoneID == "4753" then return "Alliance Keep" elseif ZoneID == "4760" then return "The Sea Reaver's Run" elseif ZoneID == "4763" then return "Transport: Alliance Gunship" elseif ZoneID == "4764" then return "Transport: Horde Gunship" elseif ZoneID == "4769" then return "Hrothgar's Landing" else return "ZoneBUG" end end --CharTitles.dbc --CreatureDisplayInfo.dbc --Emotes.dbc --Emotestext.dbc --Faction.dbc --GameObjectDisplayInfo.dbc --ItemDisplayInfo.dbc --ItemSet.dbc --Languages.dbc --Spell.dbc --SpellIcon.dbc --TaxiNodes.dbc
gpl-3.0
AfuSensi/Mr.Green-MTA-Resources
resources/[web]/resourcemanager/manager.lua
5
1625
local mta_getResourceInfo = getResourceInfo function getResourcesSearch ( partialName, state ) local allResources = getResources() local listChunk = {} local stateChunk = {} for k,v in ipairs(allResources) do local resourceName = getResourceName(v) local resourceState = getResourceState(v) if ( (partialName == "" or string.find(resourceName, partialName)) and (state == "" or state == resourceState) ) then table.insert(listChunk, v) table.insert(stateChunk, resourceState) end end return listChunk, stateChunk end function getResourceInfo ( resource ) local failreason = getResourceLoadFailureReason ( resource ) local state = getResourceState ( resource ) local starttime = getRealTimes(getResourceLastStartTime ( resource )) local loadtime = getRealTimes(getResourceLoadTime ( resource )) local author = mta_getResourceInfo ( resource, "author" ) local version = mta_getResourceInfo ( resource, "version" ) return {state=state, failurereason=failreason, starttime=starttime, loadtime=loadtime, author=author, version=version} end function getRealTimes(sek) if sek == "never" then return "Never" end local time = getRealTime(sek) if time.hour < 10 then time.hour = "0"..time.hour end if time.minute < 10 then time.minute = "0"..time.minute end if time.second < 10 then time.second = "0"..time.second end if time.month+1 < 10 then time.month = "0"..(time.month+1) end if time.monthday < 10 then time.monthday = "0"..time.monthday end return (time.year+1900).."-"..time.month.."-"..time.monthday.." "..time.hour..":"..time.minute..":"..time.second end
mit
crzang/awesome-config
pl/data.lua
8
19947
--- Reading and querying simple tabular data. -- -- data.read 'test.txt' -- ==> {{10,20},{2,5},{40,50},fieldnames={'x','y'},delim=','} -- -- Provides a way of creating basic SQL-like queries. -- -- require 'pl' -- local d = data.read('xyz.txt') -- local q = d:select('x,y,z where x > 3 and z < 2 sort by y') -- for x,y,z in q do -- print(x,y,z) -- end -- -- See @{06-data.md.Reading_Columnar_Data|the Guide} -- -- Dependencies: `pl.utils`, `pl.array2d` (fallback methods) -- @module pl.data local utils = require 'pl.utils' local _DEBUG = rawget(_G,'_DEBUG') local patterns,function_arg,usplit,array_tostring = utils.patterns,utils.function_arg,utils.split,utils.array_tostring local append,concat = table.insert,table.concat local gsub = string.gsub local io = io local _G,print,type,tonumber,ipairs,setmetatable,pcall,error = _G,print,type,tonumber,ipairs,setmetatable,pcall,error local data = {} local parse_select local function count(s,chr) chr = utils.escape(chr) local _,cnt = s:gsub(chr,' ') return cnt end local function rstrip(s) return (s:gsub('%s+$','')) end local function strip (s) return (rstrip(s):gsub('^%s*','')) end -- this gives `l` the standard List metatable, so that if you -- do choose to pull in pl.List, you can use its methods on such lists. local function make_list(l) return setmetatable(l,utils.stdmt.List) end local function map(fun,t) local res = {} for i = 1,#t do res[i] = fun(t[i]) end return res end local function split(line,delim,csv,n) local massage -- CSV fields may be double-quoted and may contain commas! if csv and line:match '"' then line = line:gsub('"([^"]+)"',function(str) local s,cnt = str:gsub(',','\001') if cnt > 0 then massage = true end return s end) if massage then massage = function(s) return (s:gsub('\001',',')) end end end local res = (usplit(line,delim,false,n)) if csv then -- restore CSV commas-in-fields if massage then res = map(massage,res) end -- in CSV mode trailiing commas are significant! if line:match ',$' then append(res,'') end end return make_list(res) end local function find(t,v) for i = 1,#t do if v == t[i] then return i end end end local DataMT = { column_by_name = function(self,name) if type(name) == 'number' then name = '$'..name end local arr = {} for res in data.query(self,name) do append(arr,res) end return make_list(arr) end, copy_select = function(self,condn) condn = parse_select(condn,self) local iter = data.query(self,condn) local res = {} local row = make_list{iter()} while #row > 0 do append(res,row) row = make_list{iter()} end res.delim = self.delim return data.new(res,split(condn.fields,',')) end, column_names = function(self) return self.fieldnames end, } local array2d DataMT.__index = function(self,name) local f = DataMT[name] if f then return f end if not array2d then array2d = require 'pl.array2d' end return array2d[name] end --- return a particular column as a list of values (method). -- @param name either name of column, or numerical index. -- @function Data.column_by_name --- return a query iterator on this data (method). -- @param condn the query expression -- @function Data.select -- @see data.query --- return a row iterator on this data (method). -- @param condn the query expression -- @function Data.select_row --- return a new data object based on this query (method). -- @param condn the query expression -- @function Data.copy_select --- return the field names of this data object (method). -- @function Data.column_names --- write out a row (method). -- @param f file-like object -- @function Data.write_row --- write data out to file (method). -- @param f file-like object -- @function Data.write -- [guessing delimiter] We check for comma, tab and spaces in that order. -- [issue] any other delimiters to be checked? local delims = {',','\t',' ',';'} local function guess_delim (line) if line=='' then return ' ' end for _,delim in ipairs(delims) do if count(line,delim) > 0 then return delim == ' ' and '%s+' or delim end end return ' ' end -- [file parameter] If it's a string, we try open as a filename. If nil, then -- either stdin or stdout depending on the mode. Otherwise, check if this is -- a file-like object (implements read or write depending) local function open_file (f,mode) local opened, err local reading = mode == 'r' if type(f) == 'string' then if f == 'stdin' then f = io.stdin elseif f == 'stdout' then f = io.stdout else f,err = io.open(f,mode) if not f then return nil,err end opened = true end end if f and ((reading and not f.read) or (not reading and not f.write)) then return nil, "not a file-like object" end return f,nil,opened end local function all_n () end --- read a delimited file in a Lua table. -- By default, attempts to treat first line as separated list of fieldnames. -- @param file a filename or a file-like object (default stdin) -- @param cnfg options table: can override `delim` (a string pattern), `fieldnames` (a list), -- specify `no_convert` (default is to conversion), `numfields` (indices of columns known -- to be numbers) and `thousands_dot` (thousands separator in Excel CSV is '.'). -- If `csv` is set then fields may be double-quoted and contain commas; -- @return `data` object, or `nil` -- @return error message. May be a file error, 'not a file-like object' -- or a conversion error function data.read(file,cnfg) local err,opened,count,line,csv local D = {} if not cnfg then cnfg = {} end local f,err,opened = open_file(file,'r') if not f then return nil, err end local thousands_dot = cnfg.thousands_dot -- note that using dot as the thousands separator (@thousands_dot) -- requires a special conversion function! local tonumber = tonumber local function try_number(x) if thousands_dot then x = x:gsub('%.(...)','%1') end local v = tonumber(x) if v == nil then return nil,"not a number" end return v end csv = cnfg.csv if csv then cnfg.delim = ',' end count = 1 line = f:read() if not line then return nil, "empty file" end -- first question: what is the delimiter? D.delim = cnfg.delim and cnfg.delim or guess_delim(line) local delim = D.delim local conversion local numfields = {} local function append_conversion (idx,conv) conversion = conversion or {} append(numfields,idx) append(conversion,conv) end if cnfg.numfields then for _,n in ipairs(cnfg.numfields) do append_conversion(n,try_number) end end -- some space-delimited data starts with a space. This should not be a column, -- although it certainly would be for comma-separated, etc. local stripper if delim == '%s+' and line:find(delim) == 1 then stripper = function(s) return s:gsub('^%s+','') end line = stripper(line) end -- first line will usually be field names. Unless fieldnames are specified, -- we check if it contains purely numerical values for the case of reading -- plain data files. if not cnfg.fieldnames then local fields,nums fields = split(line,delim,csv) if not cnfg.convert then nums = map(tonumber,fields) if #nums == #fields then -- they're ALL numbers! append(D,nums) -- add the first converted row -- and specify conversions for subsequent rows for i = 1,#nums do append_conversion(i,try_number) end else -- we'll try to check numbers just now.. nums = nil end else -- [explicit column conversions] (any deduced number conversions will be added) for idx,conv in pairs(cnfg.convert) do append_conversion(idx,conv) end end if nums == nil then cnfg.fieldnames = fields end line = f:read() count = count + 1 if stripper then line = stripper(line) end elseif type(cnfg.fieldnames) == 'string' then cnfg.fieldnames = split(cnfg.fieldnames,delim,csv) end local nfields -- at this point, the column headers have been read in. If the first -- row consisted of numbers, it has already been added to the dataset. if cnfg.fieldnames then D.fieldnames = cnfg.fieldnames -- [collecting end field] If @last_field_collect then we'll -- only split as many fields as there are fieldnames if cnfg.last_field_collect then nfields = #D.fieldnames end -- [implicit column conversion] unless @no_convert, we need the numerical field indices -- of the first data row. These can also be specified explicitly by @numfields. if not cnfg.no_convert then local fields = split(line,D.delim,csv,nfields) for i = 1,#fields do if not find(numfields,i) and tonumber(fields[i]) then append_conversion(i,try_number) end end end end -- keep going until finished while line do if not line:find ('^%s*$') then -- [blank lines] ignore them! if stripper then line = stripper(line) end local fields = split(line,delim,csv,nfields) if conversion then -- there were field conversions... for k = 1,#numfields do local i,conv = numfields[k],conversion[k] local val,err = conv(fields[i]) if val == nil then return nil, err..": "..fields[i].." at line "..count else fields[i] = val end end end append(D,fields) end line = f:read() count = count + 1 end if opened then f:close() end if delim == '%s+' then D.delim = ' ' end if not D.fieldnames then D.fieldnames = {} end return data.new(D) end local function write_row (data,f,row,delim) data.temp = array_tostring(row,data.temp) f:write(concat(data.temp,delim),'\n') end function DataMT:write_row(f,row) write_row(self,f,row,self.delim) end --- write 2D data to a file. -- Does not assume that the data has actually been -- generated with `new` or `read`. -- @param data 2D array -- @param file filename or file-like object -- @param fieldnames list of fields (optional) -- @param delim delimiter (default tab) function data.write (data,file,fieldnames,delim) local f,err,opened = open_file(file,'w') if not f then return nil, err end if fieldnames and #fieldnames > 0 then f:write(concat(data.fieldnames,delim),'\n') end delim = delim or '\t' for i = 1,#data do write_row(data,f,data[i],delim) end if opened then f:close() end end function DataMT:write(file) data.write(self,file,self.fieldnames,self.delim) end local function massage_fieldnames (fields,copy) -- fieldnames must be valid Lua identifiers; ignore any surrounding padding -- but keep the original fieldnames... for i = 1,#fields do local f = strip(fields[i]) copy[i] = f fields[i] = f:gsub('%W','_') end end --- create a new dataset from a table of rows. -- Can specify the fieldnames, else the table must have a field called -- 'fieldnames', which is either a string of delimiter-separated names, -- or a table of names. <br> -- If the table does not have a field called 'delim', then an attempt will be -- made to guess it from the fieldnames string, defaults otherwise to tab. -- @param d the table. -- @param fieldnames optional fieldnames -- @return the table. function data.new (d,fieldnames) d.fieldnames = d.fieldnames or fieldnames or '' if not d.delim and type(d.fieldnames) == 'string' then d.delim = guess_delim(d.fieldnames) d.fieldnames = split(d.fieldnames,d.delim) end d.fieldnames = make_list(d.fieldnames) d.original_fieldnames = {} massage_fieldnames(d.fieldnames,d.original_fieldnames) setmetatable(d,DataMT) -- a query with just the fieldname will return a sequence -- of values, which seq.copy turns into a table. return d end local sorted_query = [[ return function (t) local i = 0 local v local ls = {} for i,v in ipairs(t) do if CONDITION then ls[#ls+1] = v end end table.sort(ls,function(v1,v2) return SORT_EXPR end) local n = #ls return function() i = i + 1 v = ls[i] if i > n then return end return FIELDLIST end end ]] -- question: is this optimized case actually worth the extra code? local simple_query = [[ return function (t) local n = #t local i = 0 local v return function() repeat i = i + 1 v = t[i] until i > n or CONDITION if i > n then return end return FIELDLIST end end ]] local function is_string (s) return type(s) == 'string' end local field_error local function fieldnames_as_string (data) return concat(data.fieldnames,',') end local function massage_fields(data,f) local idx if f:find '^%d+$' then idx = tonumber(f) else idx = find(data.fieldnames,f) end if idx then return 'v['..idx..']' else field_error = f..' not found in '..fieldnames_as_string(data) return f end end local function process_select (data,parms) --- preparing fields ---- local res,ret field_error = nil local fields = parms.fields local numfields = fields:find '%$' or #data.fieldnames == 0 if fields:find '^%s*%*%s*' then if not numfields then fields = fieldnames_as_string(data) else local ncol = #data[1] fields = {} for i = 1,ncol do append(fields,'$'..i) end fields = concat(fields,',') end end local idpat = patterns.IDEN if numfields then idpat = '%$(%d+)' else -- massage field names to replace non-identifier chars fields = rstrip(fields):gsub('[^,%w]','_') end local massage_fields = utils.bind1(massage_fields,data) ret = gsub(fields,idpat,massage_fields) if field_error then return nil,field_error end parms.fields = fields parms.proc_fields = ret parms.where = parms.where or 'true' if is_string(parms.where) then parms.where = gsub(parms.where,idpat,massage_fields) field_error = nil end return true end parse_select = function(s,data) local endp local parms = {} local w1,w2 = s:find('where ') local s1,s2 = s:find('sort by ') if w1 then -- where clause! endp = (s1 or 0)-1 parms.where = s:sub(w2+1,endp) end if s1 then -- sort by clause (must be last!) parms.sort_by = s:sub(s2+1) end endp = (w1 or s1 or 0)-1 parms.fields = s:sub(1,endp) local status,err = process_select(data,parms) if not status then return nil,err else return parms end end --- create a query iterator from a select string. -- Select string has this format: <br> -- FIELDLIST [ where LUA-CONDN [ sort by FIELD] ]<br> -- FIELDLIST is a comma-separated list of valid fields, or '*'. <br> <br> -- The condition can also be a table, with fields 'fields' (comma-sep string or -- table), 'sort_by' (string) and 'where' (Lua expression string or function) -- @param data table produced by read -- @param condn select string or table -- @param context a list of tables to be searched when resolving functions -- @param return_row if true, wrap the results in a row table -- @return an iterator over the specified fields, or nil -- @return an error message function data.query(data,condn,context,return_row) local err if is_string(condn) then condn,err = parse_select(condn,data) if not condn then return nil,err end elseif type(condn) == 'table' then if type(condn.fields) == 'table' then condn.fields = concat(condn.fields,',') end if not condn.proc_fields then local status,err = process_select(data,condn) if not status then return nil,err end end else return nil, "condition must be a string or a table" end local query, k if condn.sort_by then -- use sorted_query query = sorted_query else query = simple_query end local fields = condn.proc_fields or condn.fields if return_row then fields = '{'..fields..'}' end query,k = query:gsub('FIELDLIST',fields) if is_string(condn.where) then query = query:gsub('CONDITION',condn.where) condn.where = nil else query = query:gsub('CONDITION','_condn(v)') condn.where = function_arg(0,condn.where,'condition.where must be callable') end if condn.sort_by then local expr,sort_var,sort_dir local sort_by = condn.sort_by local i1,i2 = sort_by:find('%s+') if i1 then sort_var,sort_dir = sort_by:sub(1,i1-1),sort_by:sub(i2+1) else sort_var = sort_by sort_dir = 'asc' end if sort_var:match '^%$' then sort_var = sort_var:sub(2) end sort_var = massage_fields(data,sort_var) if field_error then return nil,field_error end if sort_dir == 'asc' then sort_dir = '<' else sort_dir = '>' end expr = ('%s %s %s'):format(sort_var:gsub('v','v1'),sort_dir,sort_var:gsub('v','v2')) query = query:gsub('SORT_EXPR',expr) end if condn.where then query = 'return function(_condn) '..query..' end' end if _DEBUG then print(query) end local fn,err = utils.load(query,'tmp') if not fn then return nil,err end fn = fn() -- get the function if condn.where then fn = fn(condn.where) end local qfun = fn(data) if context then -- [specifying context for condition] @context is a list of tables which are -- 'injected'into the condition's custom context append(context,_G) local lookup = {} utils.setfenv(qfun,lookup) setmetatable(lookup,{ __index = function(tbl,key) -- _G.print(tbl,key) for k,t in ipairs(context) do if t[key] then return t[key] end end end }) end return qfun end DataMT.select = data.query DataMT.select_row = function(d,condn,context) return data.query(d,condn,context,true) end --- Filter input using a query. -- @param Q a query string -- @param infile filename or file-like object -- @param outfile filename or file-like object -- @param dont_fail true if you want to return an error, not just fail function data.filter (Q,infile,outfile,dont_fail) local err local d = data.read(infile or 'stdin') local out = open_file(outfile or 'stdout') local iter,err = d:select(Q) local delim = d.delim if not iter then err = 'error: '..err if dont_fail then return nil,err else utils.quit(1,err) end end while true do local res = {iter()} if #res == 0 then break end out:write(concat(res,delim),'\n') end end return data
apache-2.0
ffxiphoenix/darkstar
scripts/zones/Lufaise_Meadows/npcs/Teldo-Moroldo_WW.lua
30
3062
----------------------------------- -- Area: Lufaise Meadows -- NPC: Teldo-Moroldo, W.W. -- Outpost Conquest Guards -- @pos -542.418 -7.124 -53.521 24 ----------------------------------- package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Lufaise_Meadows/TextIDs"); local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = TAVNAZIANARCH; local csid = 0x7ff7; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
dualface/cocos2dx_luatests
scripts/luaScript/CocoStudioTest/CocoStudioGUITest/CocoStudioGUITest.lua
1
113944
local targetPlatform = CCApplication:sharedApplication():getTargetPlatform() local function getFont() if kTargetIphone == targetPlatform or kTargetIpad == targetPlatform then return "Marker Felt" else return "cocosgui/Marker Felt.ttf" end end local ccs = ccs or {} ccs.TouchEventType = { began = 0, moved = 1, ended = 2, canceled = 3, } ccs.LoadingBarType = { left = 0, right = 1, } ccs.CheckBoxEventType = { selected = 0, unselected = 1, } ccs.SliderEventType = { percent_changed = 0 } ccs.TextFiledEventType = { attach_with_ime = 0, detach_with_ime = 1, insert_text = 2, delete_backward = 3, } ccs.LayoutBackGroundColorType = { none = 0, solid = 1, gradient = 2, } ccs.LayoutType = { absolute = 0, linearVertical = 1, linearHorizontal = 2, relative = 3, } ccs.UILinearGravity = { none = 0, left = 1, top = 2, right = 3, bottom = 4, centerVertical = 5, centerHorizontal = 6, } ccs.SCROLLVIEW_DIR = { none = 0, vertical = 1, horizontal = 2, both = 3, } ccs.PageViewEventType = { turning = 0, } ccs.ListViewEventType = { init_child = 0, update_child = 1, } ccs.ListViewDirection = { none = 0, vertical = 1, horizontal = 2, } local cc = cc or {} cc.TEXT_ALIGNMENT_CENTER = 0x1 cc.TEXT_ALIGNMENT_LEFT = 0x0 cc.TEXT_ALIGNMENT_RIGHT = 0x2 local guiSceneManager = {} guiSceneManager.currentUISceneIdx = 1 local UIScene = class("UIScene") UIScene.__index = UIScene UIScene._uiLayer= nil UIScene._widget = nil UIScene._sceneTitle = nil function UIScene.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIScene) return target end function UIScene:init() self._uiLayer = TouchGroup:create() self:addChild(self._uiLayer) self._widget = GUIReader:shareReader():widgetFromJsonFile("cocosgui/UITest/UITest.json") self._uiLayer:addWidget(self._widget) self._sceneTitle = self._uiLayer:getWidgetByName("UItest") local back_label = self._uiLayer:getWidgetByName("back") back_label:setVisible(false) local function previousCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.previousUIScene()) end end local left_button = self._uiLayer:getWidgetByName("left_Button") left_button:addTouchEventListener(previousCallback) local function restartCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.currentUIScene()) end end local middle_button = self._uiLayer:getWidgetByName("middle_Button") middle_button:addTouchEventListener(restartCallback) local function nextCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.nextUIScene()) end end local right_button = self._uiLayer:getWidgetByName("right_Button") right_button:addTouchEventListener(nextCallback) local function menuCloseCallback( sender,eventType) if eventType == ccs.TouchEventType.ended then self._uiLayer:removeFromParentAndCleanup(true) local scene = CocoStudioTest() if scene ~= nil then CCDirector:sharedDirector():replaceScene(scene) end end end local winSize = CCDirector:sharedDirector():getWinSize() local scale = winSize.height / 320 self._uiLayer:setAnchorPoint(ccp(0,0)) self._uiLayer:setScale(scale) self._uiLayer:setPosition(ccp((winSize.width - 480 * scale) / 2, (winSize.height - 320 * scale) / 2)) local backMenuLabel = Label:create() backMenuLabel:setText("Back") backMenuLabel:setFontSize(20) backMenuLabel:setTouchScaleChangeEnabled(true) backMenuLabel:setPosition(CCPoint(430,30)) backMenuLabel:setTouchEnabled(true) backMenuLabel:addTouchEventListener(menuCloseCallback) self._uiLayer:addWidget(backMenuLabel) end function UIScene.create() local scene = CCScene:create() local layer = UIScene.extend(CCLayer:create()) layer:init() scene:addChild(layer) return scene end local UIButtonTest = class("UIButtonTest",UIScene) UIButtonTest._displayValueLabel = nil function UIButtonTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIButtonTest) return target end function UIButtonTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("No Event") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("Button") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local function touchEvent(sender,eventType) if eventType == ccs.TouchEventType.began then self._displayValueLabel:setText("Touch Down") elseif eventType == ccs.TouchEventType.moved then self._displayValueLabel:setText("Touch Move") elseif eventType == ccs.TouchEventType.ended then self._displayValueLabel:setText("Touch Up") elseif eventType == ccs.TouchEventType.canceled then self._displayValueLabel:setText("Touch Cancelled") end end local button = Button:create() button:setTouchEnabled(true) button:loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", "") button:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) button:addTouchEventListener(touchEvent) self._uiLayer:addWidget(button) end function UIButtonTest.create() local scene = CCScene:create() local layer = UIButtonTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIButtonScale9Test = class("UIButtonScale9Test",UIScene) UIButtonScale9Test._displayValueLabel = nil function UIButtonScale9Test.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIButtonScale9Test) return target end function UIButtonScale9Test:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("No Event") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("Button scale9 render") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local function touchEvent(sender,eventType) if eventType == ccs.TouchEventType.began then self._displayValueLabel:setText("Touch Down") elseif eventType == ccs.TouchEventType.moved then self._displayValueLabel:setText("Touch Move") elseif eventType == ccs.TouchEventType.ended then self._displayValueLabel:setText("Touch Up") elseif eventType == ccs.TouchEventType.canceled then self._displayValueLabel:setText("Touch Cancelled") end end local button = Button:create() button:setTouchEnabled(true) button:setScale9Enabled(true) button:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") button:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) button:setSize(CCSize(150, button:getContentSize().height * 1.5)) button:addTouchEventListener(touchEvent) self._uiLayer:addWidget(button) end function UIButtonScale9Test.create() local scene = CCScene:create() local layer = UIButtonScale9Test.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIButtonPressedActionTest = class("UIButtonPressedActionTest",UIScene) UIButtonPressedActionTest._displayValueLabel = nil function UIButtonPressedActionTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIButtonPressedActionTest) return target end function UIButtonPressedActionTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("No Event") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("Button Pressed Action") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local function touchEvent(sender,eventType) if eventType == ccs.TouchEventType.began then self._displayValueLabel:setText("Touch Down") elseif eventType == ccs.TouchEventType.moved then self._displayValueLabel:setText("Touch Move") elseif eventType == ccs.TouchEventType.ended then self._displayValueLabel:setText("Touch Up") elseif eventType == ccs.TouchEventType.canceled then self._displayValueLabel:setText("Touch Cancelled") end end local button = Button:create() button:setTouchEnabled(true) button:setPressedActionEnabled(true) button:loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", "") button:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) button:addTouchEventListener(touchEvent) self._uiLayer:addWidget(button) end function UIButtonPressedActionTest.create() local scene = CCScene:create() local layer = UIButtonPressedActionTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UITextButtonTest = class("UITextButtonTest",UIScene) UITextButtonTest._displayValueLabel = nil function UITextButtonTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UITextButtonTest) return target end function UITextButtonTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("No Event") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("TextButton") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local function touchEvent(sender,eventType) if eventType == ccs.TouchEventType.began then self._displayValueLabel:setText("Touch Down") elseif eventType == ccs.TouchEventType.moved then self._displayValueLabel:setText("Touch Move") elseif eventType == ccs.TouchEventType.ended then self._displayValueLabel:setText("Touch Up") elseif eventType == ccs.TouchEventType.canceled then self._displayValueLabel:setText("Touch Cancelled") end end local textButton = Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosgui/backtotopnormal.png", "cocosgui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) textButton:addTouchEventListener(touchEvent) self._uiLayer:addWidget(textButton) end function UITextButtonTest.create() local scene = CCScene:create() local layer = UITextButtonTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UITextButtonScale9Test = class("UITextButtonScale9Test",UIScene) UITextButtonScale9Test._displayValueLabel = nil function UITextButtonScale9Test.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UITextButtonScale9Test) return target end function UITextButtonScale9Test:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("No Event") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("TextButton scale9 render") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local function touchEvent(sender,eventType) if eventType == ccs.TouchEventType.began then self._displayValueLabel:setText("Touch Down") elseif eventType == ccs.TouchEventType.moved then self._displayValueLabel:setText("Touch Move") elseif eventType == ccs.TouchEventType.ended then self._displayValueLabel:setText("Touch Up") elseif eventType == ccs.TouchEventType.canceled then self._displayValueLabel:setText("Touch Cancelled") end end local textButton = Button:create() textButton:setTouchEnabled(true) textButton:setScale9Enabled(true) textButton:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") textButton:setSize(CCSize(180, textButton:getContentSize().height * 1.5)) textButton:setTitleText("Text Button scale9 render") textButton:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) textButton:addTouchEventListener(touchEvent) self._uiLayer:addWidget(textButton) end function UITextButtonScale9Test.create() local scene = CCScene:create() local layer = UITextButtonScale9Test.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UICheckBoxTest = class("UICheckBoxTest",UIScene) UICheckBoxTest._displayValueLabel = nil function UICheckBoxTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UICheckBoxTest) return target end function UICheckBoxTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("No Event") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("CheckBox") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local function selectedEvent(sender,eventType) if eventType == ccs.CheckBoxEventType.selected then self._displayValueLabel:setText("Selected") elseif eventType == ccs.CheckBoxEventType.unselected then self._displayValueLabel:setText("Unselected") end end local checkBox = CheckBox:create() checkBox:setTouchEnabled(true) checkBox:loadTextures("cocosgui/check_box_normal.png", "cocosgui/check_box_normal_press.png", "cocosgui/check_box_active.png", "cocosgui/check_box_normal_disable.png", "cocosgui/check_box_active_disable.png") checkBox:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) checkBox:addEventListenerCheckBox(selectedEvent) self._uiLayer:addWidget(checkBox) end function UICheckBoxTest.create() local scene = CCScene:create() local layer = UICheckBoxTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UISliderTest = class("UISliderTest",UIScene) UISliderTest._displayValueLabel = nil function UISliderTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UISliderTest) return target end function UISliderTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("Move the slider thumb") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("Slider") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local function percentChangedEvent(sender,eventType) if eventType == ccs.SliderEventType.percent_changed then local slider = tolua.cast(sender,"Slider") local percent = "Percent " .. slider:getPercent() self._displayValueLabel:setText(percent) end end local slider = Slider:create() slider:setTouchEnabled(true) slider:loadBarTexture("cocosgui/sliderTrack.png") slider:loadSlidBallTextures("cocosgui/sliderThumb.png", "cocosgui/sliderThumb.png", "") slider:loadProgressBarTexture("cocosgui/sliderProgress.png") slider:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) slider:addEventListenerSlider(percentChangedEvent) self._uiLayer:addWidget(slider) end function UISliderTest.create() local scene = CCScene:create() local layer = UISliderTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UISliderScale9Test = class("UISliderScale9Test",UIScene) UISliderScale9Test._displayValueLabel = nil function UISliderScale9Test.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UISliderScale9Test) return target end function UISliderScale9Test:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("Move the slider thumb") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("Slider scale9 render") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local function percentChangedEvent(sender,eventType) if eventType == ccs.SliderEventType.percent_changed then local slider = tolua.cast(sender,"Slider") local percent = "Percent " .. slider:getPercent() self._displayValueLabel:setText(percent) end end local slider = Slider:create() slider:setTouchEnabled(true) slider:loadBarTexture("cocosgui/sliderTrack2.png") slider:loadSlidBallTextures("cocosgui/sliderThumb.png", "cocosgui/sliderThumb.png", "") slider:loadProgressBarTexture("cocosgui/slider_bar_active_9patch.png") slider:setScale9Enabled(true) slider:setCapInsets(CCRect(0, 0, 0, 0)) slider:setSize(CCSize(250, 10)) slider:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) slider:addEventListenerSlider(percentChangedEvent) self._uiLayer:addWidget(slider) end function UISliderScale9Test.create() local scene = CCScene:create() local layer = UISliderScale9Test.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIImageViewTest = class("UIImageViewTest",UIScene) function UIImageViewTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIImageViewTest) return target end function UIImageViewTest:initExtend() self:init() local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("ImageView") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local imageView = ImageView:create() imageView:loadTexture("cocosgui/ccicon.png") imageView:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + imageView:getSize().height / 4.0)) self._uiLayer:addWidget(imageView) end function UIImageViewTest.create() local scene = CCScene:create() local layer = UIImageViewTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIImageViewScale9Test = class("UIImageViewScale9Test",UIScene) function UIImageViewScale9Test.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIImageViewScale9Test) return target end function UIImageViewScale9Test:initExtend() self:init() local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("ImageView scale9 render") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local imageView = ImageView:create() imageView:setScale9Enabled(true) imageView:loadTexture("cocosgui/buttonHighlighted.png") imageView:setSize(CCSize(200, 85)) imageView:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + imageView:getSize().height / 4.0)) self._uiLayer:addWidget(imageView) end function UIImageViewScale9Test.create() local scene = CCScene:create() local layer = UIImageViewScale9Test.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UILoadingBarLeftTest = class("UILoadingBarLeftTest",UIScene) UILoadingBarLeftTest._count = 0 function UILoadingBarLeftTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UILoadingBarLeftTest) return target end function UILoadingBarLeftTest:initExtend() self._uiLayer = TouchGroup:create() self:addChild(self._uiLayer) local winSize = CCDirector:sharedDirector():getWinSize() local scale = winSize.height / 320 self._uiLayer:setAnchorPoint(ccp(0,0)) self._uiLayer:setScale(scale) self._uiLayer:setPosition(ccp((winSize.width - 480 * scale) / 2, (winSize.height - 320 * scale) / 2)) self._widget = GUIReader:shareReader():widgetFromJsonFile("cocosgui/UITest/UITest.json") self._uiLayer:addWidget(self._widget) self._sceneTitle = self._uiLayer:getWidgetByName("UItest") local back_label = self._uiLayer:getWidgetByName("back") back_label:setVisible(false) local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("LoadingBar") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local loadingBar = LoadingBar:create() loadingBar:setName("LoadingBar") loadingBar:loadTexture("cocosgui/sliderProgress.png") loadingBar:setPercent(0) loadingBar:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + loadingBar:getSize().height / 4.0)) self._uiLayer:addWidget(loadingBar) local function update(delta) self._count = self._count + 1 if self._count > 100 then self._count = 0 end if self._uiLayer ~= nil then local loadingBar = tolua.cast(self._uiLayer:getWidgetByName("LoadingBar"), "LoadingBar") loadingBar:setPercent(self._count) end end self:scheduleUpdateWithPriorityLua(update, 0) local function onNodeEvent(tag) if tag == "exit" then self:unscheduleUpdate() end end self:registerScriptHandler(onNodeEvent) local function previousCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.previousUIScene()) end end local left_button = self._uiLayer:getWidgetByName("left_Button") left_button:addTouchEventListener(previousCallback) local function restartCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.currentUIScene()) end end local middle_button = self._uiLayer:getWidgetByName("middle_Button") middle_button:addTouchEventListener(restartCallback) local function nextCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.nextUIScene()) end end local right_button = self._uiLayer:getWidgetByName("right_Button") right_button:addTouchEventListener(nextCallback) local function menuCloseCallback( sender,eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) local scene = CocoStudioTest() if scene ~= nil then CCDirector:sharedDirector():replaceScene(scene) end end end local mainMenuLabel = Label:create() mainMenuLabel:setText("Back") mainMenuLabel:setFontSize(20) mainMenuLabel:setTouchScaleChangeEnabled(true) mainMenuLabel:setPosition(CCPoint(430,30)) mainMenuLabel:setTouchEnabled(true) mainMenuLabel:addTouchEventListener(menuCloseCallback) self._uiLayer:addWidget(mainMenuLabel) end function UILoadingBarLeftTest.create() local scene = CCScene:create() local layer = UILoadingBarLeftTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UILoadingBarRightTest = class("UILoadingBarRightTest",UIScene) UILoadingBarRightTest._count = 0 function UILoadingBarRightTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UILoadingBarRightTest) return target end function UILoadingBarRightTest:initExtend() self._uiLayer = TouchGroup:create() local winSize = CCDirector:sharedDirector():getWinSize() local scale = winSize.height / 320 self._uiLayer:setAnchorPoint(ccp(0,0)) self._uiLayer:setScale(scale) self._uiLayer:setPosition(ccp((winSize.width - 480 * scale) / 2, (winSize.height - 320 * scale) / 2)) self:addChild(self._uiLayer) self._widget = GUIReader:shareReader():widgetFromJsonFile("cocosgui/UITest/UITest.json") self._uiLayer:addWidget(self._widget) self._sceneTitle = self._uiLayer:getWidgetByName("UItest") local back_label = self._uiLayer:getWidgetByName("back") back_label:setVisible(false) local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("LoadingBar") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local loadingBar = LoadingBar:create() loadingBar:setName("LoadingBar") loadingBar:loadTexture("cocosgui/sliderProgress.png") loadingBar:setDirection(ccs.LoadingBarType.right) loadingBar:setPercent(0) loadingBar:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + loadingBar:getSize().height / 4.0)) self._uiLayer:addWidget(loadingBar) local function update(delta) self._count = self._count + 1 if self._count > 100 then self._count = 0 end if self._uiLayer ~= nil then local loadingBar = tolua.cast(self._uiLayer:getWidgetByName("LoadingBar"), "LoadingBar") loadingBar:setPercent(self._count) end end self:scheduleUpdateWithPriorityLua(update, 0) local function onNodeEvent(tag) if tag == "exit" then self:unscheduleUpdate() end end self:registerScriptHandler(onNodeEvent) local function previousCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.previousUIScene()) end end local left_button = self._uiLayer:getWidgetByName("left_Button") left_button:addTouchEventListener(previousCallback) local function restartCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.currentUIScene()) end end local middle_button = self._uiLayer:getWidgetByName("middle_Button") middle_button:addTouchEventListener(restartCallback) local function nextCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.nextUIScene()) end end local right_button = self._uiLayer:getWidgetByName("right_Button") right_button:addTouchEventListener(nextCallback) local function menuCloseCallback( sender,eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) local scene = CocoStudioTest() if scene ~= nil then CCDirector:sharedDirector():replaceScene(scene) end end end local mainMenuLabel = Label:create() mainMenuLabel:setText("Back") mainMenuLabel:setFontSize(20) mainMenuLabel:setTouchScaleChangeEnabled(true) mainMenuLabel:setPosition(CCPoint(430,30)) mainMenuLabel:setTouchEnabled(true) mainMenuLabel:addTouchEventListener(menuCloseCallback) self._uiLayer:addWidget(mainMenuLabel) end function UILoadingBarRightTest.create() local scene = CCScene:create() local layer = UILoadingBarRightTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UILoadingBarLeftScale9Test = class("UILoadingBarLeftScale9Test",UIScene) UILoadingBarLeftScale9Test._count = 0 function UILoadingBarLeftScale9Test.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UILoadingBarLeftScale9Test) return target end function UILoadingBarLeftScale9Test:initExtend() self._uiLayer = TouchGroup:create() local winSize = CCDirector:sharedDirector():getWinSize() local scale = winSize.height / 320 self._uiLayer:setAnchorPoint(ccp(0,0)) self._uiLayer:setScale(scale) self._uiLayer:setPosition(ccp((winSize.width - 480 * scale) / 2, (winSize.height - 320 * scale) / 2)) self:addChild(self._uiLayer) self._widget = GUIReader:shareReader():widgetFromJsonFile("cocosgui/UITest/UITest.json") self._uiLayer:addWidget(self._widget) self._sceneTitle = self._uiLayer:getWidgetByName("UItest") local back_label = self._uiLayer:getWidgetByName("back") back_label:setVisible(false) local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("LoadingBar Scale9 Render") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local loadingBar = LoadingBar:create() loadingBar:setName("LoadingBar") loadingBar:loadTexture("cocosgui/slider_bar_active_9patch.png") loadingBar:setScale9Enabled(true) loadingBar:setCapInsets(CCRect(0, 0, 0, 0)) loadingBar:setSize(CCSize(300, 30)) loadingBar:setPercent(0) loadingBar:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + loadingBar:getSize().height / 4.0)) self._uiLayer:addWidget(loadingBar) local function update(delta) self._count = self._count + 1 if self._count > 100 then self._count = 0 end if self._uiLayer ~= nil then local loadingBar = tolua.cast(self._uiLayer:getWidgetByName("LoadingBar"), "LoadingBar") loadingBar:setPercent(self._count) end end self:scheduleUpdateWithPriorityLua(update, 0) local function onNodeEvent(tag) if tag == "exit" then self:unscheduleUpdate() end end self:registerScriptHandler(onNodeEvent) local function previousCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.previousUIScene()) end end local left_button = self._uiLayer:getWidgetByName("left_Button") left_button:addTouchEventListener(previousCallback) local function restartCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.currentUIScene()) end end local middle_button = self._uiLayer:getWidgetByName("middle_Button") middle_button:addTouchEventListener(restartCallback) local function nextCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.nextUIScene()) end end local right_button = self._uiLayer:getWidgetByName("right_Button") right_button:addTouchEventListener(nextCallback) local function menuCloseCallback( sender,eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) local scene = CocoStudioTest() if scene ~= nil then CCDirector:sharedDirector():replaceScene(scene) end end end local mainMenuLabel = Label:create() mainMenuLabel:setText("Back") mainMenuLabel:setFontSize(20) mainMenuLabel:setTouchScaleChangeEnabled(true) mainMenuLabel:setPosition(CCPoint(430,30)) mainMenuLabel:setTouchEnabled(true) mainMenuLabel:addTouchEventListener(menuCloseCallback) self._uiLayer:addWidget(mainMenuLabel) end function UILoadingBarLeftScale9Test.create() local scene = CCScene:create() local layer = UILoadingBarLeftScale9Test.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UILoadingBarRightScale9Test = class("UILoadingBarRightScale9Test",UIScene) UILoadingBarRightScale9Test._count = 0 function UILoadingBarRightScale9Test.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UILoadingBarRightScale9Test) return target end function UILoadingBarRightScale9Test:initExtend() self._uiLayer = TouchGroup:create() local winSize = CCDirector:sharedDirector():getWinSize() local scale = winSize.height / 320 self._uiLayer:setAnchorPoint(ccp(0,0)) self._uiLayer:setScale(scale) self._uiLayer:setPosition(ccp((winSize.width - 480 * scale) / 2, (winSize.height - 320 * scale) / 2)) self:addChild(self._uiLayer) self._widget = GUIReader:shareReader():widgetFromJsonFile("cocosgui/UITest/UITest.json") self._uiLayer:addWidget(self._widget) self._sceneTitle = self._uiLayer:getWidgetByName("UItest") local back_label = self._uiLayer:getWidgetByName("back") back_label:setVisible(false) local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("LoadingBar Scale9 Render") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local loadingBar = LoadingBar:create() loadingBar:setName("LoadingBar") loadingBar:loadTexture("cocosgui/slider_bar_active_9patch.png") loadingBar:setScale9Enabled(true) loadingBar:setCapInsets(CCRect(0, 0, 0, 0)) loadingBar:setSize(CCSize(300, 30)) loadingBar:setDirection(ccs.LoadingBarType.right) loadingBar:setPercent(0) loadingBar:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + loadingBar:getSize().height / 4.0)) self._uiLayer:addWidget(loadingBar) local function update(delta) self._count = self._count + 1 if self._count > 100 then self._count = 0 end if self._uiLayer ~= nil then local loadingBar = tolua.cast(self._uiLayer:getWidgetByName("LoadingBar"), "LoadingBar") loadingBar:setPercent(self._count) end end self:scheduleUpdateWithPriorityLua(update, 0) local function onNodeEvent(tag) if tag == "exit" then self:unscheduleUpdate() end end self:registerScriptHandler(onNodeEvent) local function previousCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.previousUIScene()) end end local left_button = self._uiLayer:getWidgetByName("left_Button") left_button:addTouchEventListener(previousCallback) local function restartCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.currentUIScene()) end end local middle_button = self._uiLayer:getWidgetByName("middle_Button") middle_button:addTouchEventListener(restartCallback) local function nextCallback(sender, eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) CCDirector:sharedDirector():replaceScene(guiSceneManager.nextUIScene()) end end local right_button = self._uiLayer:getWidgetByName("right_Button") right_button:addTouchEventListener(nextCallback) local function menuCloseCallback( sender,eventType) if eventType == ccs.TouchEventType.ended then self:unscheduleUpdate() self._uiLayer:removeFromParentAndCleanup(true) local scene = CocoStudioTest() if scene ~= nil then CCDirector:sharedDirector():replaceScene(scene) end end end local mainMenuLabel = Label:create() mainMenuLabel:setText("Back") mainMenuLabel:setFontSize(20) mainMenuLabel:setTouchScaleChangeEnabled(true) mainMenuLabel:setPosition(CCPoint(430,30)) mainMenuLabel:setTouchEnabled(true) mainMenuLabel:addTouchEventListener(menuCloseCallback) self._uiLayer:addWidget(mainMenuLabel) end function UILoadingBarRightScale9Test.create() local scene = CCScene:create() local layer = UILoadingBarRightScale9Test.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UILabelAtlasTest = class("UILabelAtlasTest",UIScene) function UILabelAtlasTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UILabelAtlasTest) return target end function UILabelAtlasTest:initExtend() self:init() local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("LabelAtlas") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local labelAtlas = LabelAtlas:create() labelAtlas:setProperty("1234567890", "cocosgui/labelatlas.png", 17, 22, "0") labelAtlas:setPosition(CCPoint((widgetSize.width) / 2, widgetSize.height / 2.0)) self._uiLayer:addWidget(labelAtlas) end function UILabelAtlasTest.create() local scene = CCScene:create() local layer = UILabelAtlasTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UILabelBMFontTest = class("UILabelBMFontTest",UIScene) function UILabelBMFontTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UILabelBMFontTest) return target end function UILabelBMFontTest:initExtend() self:init() local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("LabelBMFont") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local labelBMFont = LabelBMFont:create() labelBMFont:setFntFile("cocosgui/bitmapFontTest2.fnt") labelBMFont:setText("BMFont") labelBMFont:setPosition(CCPoint(widgetSize.width / 2, widgetSize.height / 2.0 + labelBMFont:getSize().height / 8.0)) self._uiLayer:addWidget(labelBMFont) end function UILabelBMFontTest.create() local scene = CCScene:create() local layer = UILabelBMFontTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UILabelTest = class("UILabelTest",UIScene) function UILabelTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UILabelTest) return target end function UILabelTest:initExtend() self:init() local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("Label") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local label = Label:create() label:setText("Label") label:setFontName("AmericanTypewriter") label:setFontSize(30) label:setPosition(CCPoint(widgetSize.width / 2, widgetSize.height / 2 + label:getSize().height / 4)) self._uiLayer:addWidget(label) end function UILabelTest.create() local scene = CCScene:create() local layer = UILabelTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UITextAreaTest = class("UITextAreaTest",UIScene) function UITextAreaTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UITextAreaTest) return target end function UITextAreaTest:initExtend() self:init() local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("TextArea") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local textArea = Label:create() textArea:setTextAreaSize(CCSize(280, 150)) textArea:setTextHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER) textArea:setText("TextArea widget can line wrap") textArea:setFontName("AmericanTypewriter") textArea:setFontSize(32) textArea:setPosition(CCPoint(widgetSize.width / 2, widgetSize.height / 2 - textArea:getSize().height / 8)) self._uiLayer:addWidget(textArea) end function UITextAreaTest.create() local scene = CCScene:create() local layer = UITextAreaTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UITextFieldTest = class("UITextFieldTest",UIScene) UITextFieldTest._displayValueLabel = nil function UITextFieldTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UITextFieldTest) return target end function UITextFieldTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("No Event") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + self._displayValueLabel:getSize().height * 1.5)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("TextField") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local function textFieldEvent(sender, eventType) if eventType == ccs.TextFiledEventType.attach_with_ime then local textField = tolua.cast(sender,"TextField") local screenSize = CCDirector:sharedDirector():getWinSize() textField:runAction(CCMoveTo:create(0.225,CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + textField:getContentSize().height / 2.0))) self._displayValueLabel:setText("attach with IME") elseif eventType == ccs.TextFiledEventType.detach_with_ime then local textField = tolua.cast(sender,"TextField") local screenSize = CCDirector:sharedDirector():getWinSize() textField:runAction(CCMoveTo:create(0.175, CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0))) self._displayValueLabel:setText("detach with IME") elseif eventType == ccs.TextFiledEventType.insert_text then self._displayValueLabel:setText("insert words") elseif eventType == ccs.TextFiledEventType.delete_backward then self._displayValueLabel:setText("delete word") end end local textField = TextField:create() textField:setTouchEnabled(true) textField:setFontName(getFont()) textField:setFontSize(30) textField:setPlaceHolder("input words here") textField:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) textField:addEventListenerTextField(textFieldEvent) self._uiLayer:addWidget(textField) end function UITextFieldTest.create() local scene = CCScene:create() local layer = UITextFieldTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UITextFieldMaxLengthTest = class("UITextFieldMaxLengthTest",UIScene) UITextFieldMaxLengthTest._displayValueLabel = nil function UITextFieldMaxLengthTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UITextFieldMaxLengthTest) return target end function UITextFieldMaxLengthTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("No Event") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + self._displayValueLabel:getSize().height * 1.5)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("TextField max length") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local function textFieldEvent(sender, eventType) if eventType == ccs.TextFiledEventType.attach_with_ime then local textField = tolua.cast(sender,"TextField") local screenSize = CCDirector:sharedDirector():getWinSize() textField:runAction(CCMoveTo:create(0.225,CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + textField:getContentSize().height / 2.0))) local info = string.format("attach with IME max length %d",textField:getMaxLength()) self._displayValueLabel:setText(info) elseif eventType == ccs.TextFiledEventType.detach_with_ime then local textField = tolua.cast(sender,"TextField") local screenSize = CCDirector:sharedDirector():getWinSize() textField:runAction(CCMoveTo:create(0.175, CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0))) local info = string.format("detach with IME max length %d",textField:getMaxLength()) self._displayValueLabel:setText(info) elseif eventType == ccs.TextFiledEventType.insert_text then local textField = tolua.cast(sender,"TextField") local info = string.format("insert words max length %d",textField:getMaxLength()) self._displayValueLabel:setText(info) elseif eventType == ccs.TextFiledEventType.delete_backward then local textField = tolua.cast(sender,"TextField") local info = string.format("delete word max length %d",textField:getMaxLength()) self._displayValueLabel:setText(info) end end local textField = TextField:create() textField:setMaxLengthEnabled(true) textField:setMaxLength(3) textField:setTouchEnabled(true) textField:setFontName(getFont()) textField:setFontSize(30) textField:setPlaceHolder("input words here") textField:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) textField:addEventListenerTextField(textFieldEvent) self._uiLayer:addWidget(textField) end function UITextFieldMaxLengthTest.create() local scene = CCScene:create() local layer = UITextFieldMaxLengthTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UITextFieldPasswordTest = class("UITextFieldPasswordTest",UIScene) UITextFieldPasswordTest._displayValueLabel = nil function UITextFieldPasswordTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UITextFieldPasswordTest) return target end function UITextFieldPasswordTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("No Event") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + self._displayValueLabel:getSize().height * 1.5)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("TextField password") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local function textFieldEvent(sender, eventType) if eventType == ccs.TextFiledEventType.attach_with_ime then local textField = tolua.cast(sender,"TextField") textField:runAction(CCMoveTo:create(0.175, CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0))) self._displayValueLabel:setText("detach with IME password") elseif eventType == ccs.TextFiledEventType.detach_with_ime then local textField = tolua.cast(sender,"TextField") textField:runAction(CCMoveTo:create(0.175, CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0))) self._displayValueLabel:setText("detach with IME password") elseif eventType == ccs.TextFiledEventType.insert_text then self._displayValueLabel:setText("insert words password") elseif eventType == ccs.TextFiledEventType.delete_backward then self._displayValueLabel:setText("delete word password") end end local textField = TextField:create() textField:setPasswordEnabled(true) textField:setPasswordStyleText("*") textField:setTouchEnabled(true) textField:setFontName(getFont()) textField:setFontSize(30) textField:setPlaceHolder("input password here") textField:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) textField:addEventListenerTextField(textFieldEvent) self._uiLayer:addWidget(textField) end function UITextFieldPasswordTest.create() local scene = CCScene:create() local layer = UITextFieldPasswordTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIPanelTest = class("UIPanelTest",UIScene) function UIPanelTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIPanelTest) return target end function UIPanelTest:initExtend() self:init() local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("Panel") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local background = self._uiLayer:getWidgetByName("background_Panel") local layout = Layout:create() layout:setSize(CCSize(280, 150)) local backgroundSize = background:getSize() layout:setPosition(CCPoint((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - layout:getSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - layout:getSize().height) / 2)) self._uiLayer:addWidget(layout) local button = Button:create() button:setTouchEnabled(true) button:loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", "") button:setPosition(CCPoint(button:getSize().width / 2, layout:getSize().height - button:getSize().height / 2)) layout:addChild(button) local textButton = Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosgui/backtotopnormal.png", "cocosgui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(CCPoint(layout:getSize().width / 2, layout:getSize().height / 2)) layout:addChild(textButton) local button_scale9 = Button:create() button_scale9:setTouchEnabled(true) button_scale9:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") button_scale9:setScale9Enabled(true) button_scale9:setSize(CCSize(100, button_scale9:getContentSize().height)) button_scale9:setPosition(CCPoint(layout:getSize().width - button_scale9:getSize().width / 2, button_scale9:getSize().height / 2)) layout:addChild(button_scale9) end function UIPanelTest.create() local scene = CCScene:create() local layer = UIPanelTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIPanelColorTest = class("UIPanelColorTest",UIScene) function UIPanelColorTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIPanelColorTest) return target end function UIPanelColorTest:initExtend() self:init() local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("Panel color render") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 2.925)) self._uiLayer:addWidget(alert) local background = self._uiLayer:getWidgetByName("background_Panel") local layout = Layout:create() layout:setBackGroundColorType(ccs.LayoutBackGroundColorType.solid) layout:setBackGroundColor(ccc3(128, 128, 128)) layout:setSize(CCSize(280, 150)) local backgroundSize = background:getContentSize() layout:setPosition(CCPoint((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - layout:getSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - layout:getSize().height) / 2)) self._uiLayer:addWidget(layout) local button = Button:create() button:setTouchEnabled(true) button:loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", "") button:setPosition(CCPoint(button:getSize().width / 2, layout:getSize().height - button:getSize().height / 2)) layout:addChild(button) local textButton = Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosgui/backtotopnormal.png", "cocosgui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(CCPoint(layout:getSize().width / 2, layout:getSize().height / 2)) layout:addChild(textButton) local button_scale9 = Button:create() button_scale9:setTouchEnabled(true) button_scale9:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") button_scale9:setScale9Enabled(true) button_scale9:setSize(CCSize(100, button_scale9:getContentSize().height)) button_scale9:setPosition(CCPoint(layout:getSize().width - button_scale9:getSize().width / 2, button_scale9:getSize().height / 2)) layout:addChild(button_scale9) end function UIPanelColorTest.create() local scene = CCScene:create() local layer = UIPanelColorTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIPanelGradientTest = class("UIPanelGradientTest",UIScene) function UIPanelGradientTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIPanelGradientTest) return target end function UIPanelGradientTest:initExtend() self:init() local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("Panel color Gradient") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 2.925)) self._uiLayer:addWidget(alert) local background = self._uiLayer:getWidgetByName("background_Panel") local layout = Layout:create() layout:setBackGroundColorType(ccs.LayoutBackGroundColorType.gradient) layout:setBackGroundColor(ccc3(64, 64, 64), ccc3(192, 192, 192)) layout:setSize(CCSize(280, 150)) local backgroundSize = background:getContentSize() layout:setPosition(CCPoint((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - layout:getSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - layout:getSize().height) / 2)) self._uiLayer:addWidget(layout) local button = Button:create() button:setTouchEnabled(true) button:loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", "") button:setPosition(CCPoint(button:getSize().width / 2, layout:getSize().height - button:getSize().height / 2)) layout:addChild(button) local textButton = Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosgui/backtotopnormal.png", "cocosgui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(CCPoint(layout:getSize().width / 2, layout:getSize().height / 2)) layout:addChild(textButton) local button_scale9 = Button:create() button_scale9:setTouchEnabled(true) button_scale9:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") button_scale9:setScale9Enabled(true) button_scale9:setSize(CCSize(100, button_scale9:getContentSize().height)) button_scale9:setPosition(CCPoint(layout:getSize().width - button_scale9:getSize().width / 2, button_scale9:getSize().height / 2)) layout:addChild(button_scale9) end function UIPanelGradientTest.create() local scene = CCScene:create() local layer = UIPanelGradientTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIPanelBackGroundImageTest = class("UIPanelBackGroundImageTest",UIScene) function UIPanelBackGroundImageTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIPanelBackGroundImageTest) return target end function UIPanelBackGroundImageTest:initExtend() self:init() local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("Panel background image") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 2.925)) self._uiLayer:addWidget(alert) local background = self._uiLayer:getWidgetByName("background_Panel") local layout = Layout:create() layout:setClippingEnabled(true) layout:setBackGroundImage("cocosgui/Hello.png") layout:setSize(CCSize(280, 150)) local backgroundSize = background:getContentSize() layout:setPosition(CCPoint((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - layout:getSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - layout:getSize().height) / 2)) self._uiLayer:addWidget(layout) local button = Button:create() button:setTouchEnabled(true) button:loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", "") button:setPosition(CCPoint(button:getSize().width / 2, layout:getSize().height - button:getSize().height / 2)) layout:addChild(button) local textButton = Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosgui/backtotopnormal.png", "cocosgui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(CCPoint(layout:getSize().width / 2, layout:getSize().height / 2)) layout:addChild(textButton) local button_scale9 = Button:create() button_scale9:setTouchEnabled(true) button_scale9:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") button_scale9:setScale9Enabled(true) button_scale9:setSize(CCSize(100, button_scale9:getContentSize().height)) button_scale9:setPosition(CCPoint(layout:getSize().width - button_scale9:getSize().width / 2, button_scale9:getSize().height / 2)) layout:addChild(button_scale9) end function UIPanelBackGroundImageTest.create() local scene = CCScene:create() local layer = UIPanelBackGroundImageTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIPanelBackGroundImageScale9Test = class("UIPanelBackGroundImageScale9Test",UIScene) function UIPanelBackGroundImageScale9Test.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIPanelBackGroundImageScale9Test) return target end function UIPanelBackGroundImageScale9Test:initExtend() self:init() local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("Panel background image scale9") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 2.925)) self._uiLayer:addWidget(alert) local background = self._uiLayer:getWidgetByName("background_Panel") local layout = Layout:create() layout:setBackGroundImageScale9Enabled(true) layout:setBackGroundImage("cocosgui/green_edit.png") layout:setSize(CCSize(280, 150)) local backgroundSize = background:getContentSize() layout:setPosition(CCPoint((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - layout:getSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - layout:getSize().height) / 2)) self._uiLayer:addWidget(layout) local button = Button:create() button:setTouchEnabled(true) button:loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", "") button:setPosition(CCPoint(button:getSize().width / 2, layout:getSize().height - button:getSize().height / 2)) layout:addChild(button) local textButton = Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosgui/backtotopnormal.png", "cocosgui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(CCPoint(layout:getSize().width / 2, layout:getSize().height / 2)) layout:addChild(textButton) local button_scale9 = Button:create() button_scale9:setTouchEnabled(true) button_scale9:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") button_scale9:setScale9Enabled(true) button_scale9:setSize(CCSize(100, button_scale9:getContentSize().height)) button_scale9:setPosition(CCPoint(layout:getSize().width - button_scale9:getSize().width / 2, button_scale9:getSize().height / 2)) layout:addChild(button_scale9) end function UIPanelBackGroundImageScale9Test.create() local scene = CCScene:create() local layer = UIPanelBackGroundImageScale9Test.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIPanelLayoutLinearVerticalTest = class("UIPanelLayoutLinearVerticalTest",UIScene) function UIPanelLayoutLinearVerticalTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIPanelLayoutLinearVerticalTest) return target end function UIPanelLayoutLinearVerticalTest:initExtend() self:init() local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("Panel Layout Linear Vertical") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 2.925)) self._uiLayer:addWidget(alert) local background = self._uiLayer:getWidgetByName("background_Panel") local layout = Layout:create() layout:setLayoutType(ccs.LayoutType.linearVertical) layout:setSize(CCSize(280, 150)) local backgroundSize = background:getContentSize() layout:setPosition(CCPoint((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - layout:getSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - layout:getSize().height) / 2)) self._uiLayer:addWidget(layout) local button = Button:create() button:setTouchEnabled(true) button:loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", "") layout:addChild(button) local lp1 = LinearLayoutParameter:create() button:setLayoutParameter(lp1) lp1:setGravity(ccs.UILinearGravity.centerHorizontal) lp1:setMargin({ left = 0, top = 5, right = 0, bottom = 10 }) local textButton = Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosgui/backtotopnormal.png", "cocosgui/backtotoppressed.png", "") textButton:setTitleText("Text Button") layout:addChild(textButton) local lp2 = LinearLayoutParameter:create() textButton:setLayoutParameter(lp2) lp2:setGravity(ccs.UILinearGravity.centerHorizontal) lp2:setMargin({left = 0, top = 10, right = 0, bottom = 10} ) local button_scale9 = Button:create() button_scale9:setTouchEnabled(true) button_scale9:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") button_scale9:setScale9Enabled(true) button_scale9:setSize(CCSize(100, button_scale9:getContentSize().height)) layout:addChild(button_scale9) local lp3 = LinearLayoutParameter:create() button_scale9:setLayoutParameter(lp3) lp3:setGravity(ccs.UILinearGravity.centerHorizontal) lp3:setMargin({ left = 0, top = 10, right = 0, bottom = 10 } ) end function UIPanelLayoutLinearVerticalTest.create() local scene = CCScene:create() local layer = UIPanelLayoutLinearVerticalTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIPanelLayoutLinearHorizontalTest = class("UIPanelLayoutLinearHorizontalTest",UIScene) function UIPanelLayoutLinearHorizontalTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIPanelLayoutLinearHorizontalTest) return target end function UIPanelLayoutLinearHorizontalTest:initExtend() self:init() local widgetSize = self._widget:getSize() local alert = Label:create() alert:setText("Panel Layout Linear Horizontal") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 2.925)) self._uiLayer:addWidget(alert) local background = self._uiLayer:getWidgetByName("background_Panel") local layout = Layout:create() layout:setLayoutType(ccs.LayoutType.linearHorizontal) layout:setClippingEnabled(true) layout:setSize(CCSize(280, 150)) local backgroundSize = background:getContentSize() layout:setPosition(CCPoint((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - layout:getSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - layout:getSize().height) / 2)) self._uiLayer:addWidget(layout) local button = Button:create() button:setTouchEnabled(true) button:loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", "") layout:addChild(button) local lp1 = LinearLayoutParameter:create() button:setLayoutParameter(lp1) lp1:setGravity(ccs.UILinearGravity.centerVertical) lp1:setMargin({left = 0, top = 10, right = 0, bottom = 10} ) local textButton = Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosgui/backtotopnormal.png", "cocosgui/backtotoppressed.png", "") textButton:setTitleText("Text Button") layout:addChild(textButton) local lp2 = LinearLayoutParameter:create() textButton:setLayoutParameter(lp2) lp2:setGravity(ccs.UILinearGravity.centerVertical) lp2:setMargin({left = 0,top = 10,right = 0,bottom = 10}) local button_scale9 = Button:create() button_scale9:setTouchEnabled(true) button_scale9:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") button_scale9:setScale9Enabled(true) button_scale9:setSize(CCSize(100, button_scale9:getContentSize().height)) layout:addChild(button_scale9) local lp3 = LinearLayoutParameter:create() button_scale9:setLayoutParameter(lp3) lp3:setGravity(ccs.UILinearGravity.centerVertical) lp3:setMargin({left = 0, top = 10, right = 0, bottom = 10}) end function UIPanelLayoutLinearHorizontalTest.create() local scene = CCScene:create() local layer = UIPanelLayoutLinearHorizontalTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIScrollViewVerticalTest = class("UIScrollViewVerticalTest",UIScene) UIScrollViewVerticalTest._displayValueLabel = nil function UIScrollViewVerticalTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIScrollViewVerticalTest) return target end function UIScrollViewVerticalTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("Move by vertical direction") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + self._displayValueLabel:getContentSize().height * 1.5)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("ScrollView") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 2.925)) self._uiLayer:addWidget(alert) local background = self._uiLayer:getWidgetByName("background_Panel") local scrollView = ScrollView:create() scrollView:setTouchEnabled(true) scrollView:setSize(CCSize(280, 150)) local backgroundSize = background:getContentSize() scrollView:setPosition(CCPoint((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - scrollView:getSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - scrollView:getSize().height) / 2)) self._uiLayer:addWidget(scrollView) local imageView = ImageView:create() imageView:loadTexture("cocosgui/ccicon.png") local innerWidth = scrollView:getSize().width local innerHeight = scrollView:getSize().height + imageView:getSize().height scrollView:setInnerContainerSize(CCSize(innerWidth, innerHeight)) local button = Button:create() button:setTouchEnabled(true) button:loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", "") button:setPosition(CCPoint(innerWidth / 2, scrollView:getInnerContainerSize().height - button:getSize().height / 2)) scrollView:addChild(button) local textButton = Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosgui/backtotopnormal.png", "cocosgui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(CCPoint(innerWidth / 2, button:getBottomInParent() - button:getSize().height)) scrollView:addChild(textButton) local button_scale9 = Button:create() button_scale9:setTouchEnabled(true) button_scale9:setScale9Enabled(true) button_scale9:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") button_scale9:setSize(CCSize(100, button_scale9:getContentSize().height)) button_scale9:setPosition(CCPoint(innerWidth / 2, textButton:getBottomInParent() - textButton:getSize().height)) scrollView:addChild(button_scale9) imageView:setPosition(CCPoint(innerWidth / 2, imageView:getSize().height / 2)) scrollView:addChild(imageView) end function UIScrollViewVerticalTest.create() local scene = CCScene:create() local layer = UIScrollViewVerticalTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIScrollViewHorizontalTest = class("UIScrollViewHorizontalTest",UIScene) UIScrollViewHorizontalTest._displayValueLabel = nil function UIScrollViewHorizontalTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIScrollViewHorizontalTest) return target end function UIScrollViewHorizontalTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("Move by horizontal direction") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + self._displayValueLabel:getContentSize().height * 1.5)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("ScrollView") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 2.925)) self._uiLayer:addWidget(alert) local background = self._uiLayer:getWidgetByName("background_Panel") local scrollView = ScrollView:create() scrollView:setBounceEnabled(true) scrollView:setDirection(ccs.SCROLLVIEW_DIR.horizontal) scrollView:setTouchEnabled(true) scrollView:setSize(CCSize(280, 150)) scrollView:setInnerContainerSize(scrollView:getSize()) local backgroundSize = background:getContentSize() scrollView:setPosition(CCPoint((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - scrollView:getSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - scrollView:getSize().height) / 2)) self._uiLayer:addWidget(scrollView) local imageView = ImageView:create() imageView:loadTexture("cocosgui/ccicon.png") local innerWidth = scrollView:getSize().width + imageView:getSize().width local innerHeight = scrollView:getSize().height scrollView:setInnerContainerSize(CCSize(innerWidth, innerHeight)) local button = Button:create() button:setTouchEnabled(true) button:loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", "") button:setPosition(CCPoint(button:getSize().width / 2, scrollView:getInnerContainerSize().height - button:getSize().height / 2)) scrollView:addChild(button) local textButton = Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosgui/backtotopnormal.png", "cocosgui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(CCPoint(button:getRightInParent() + button:getSize().width / 2, button:getBottomInParent() - button:getSize().height / 2)) scrollView:addChild(textButton) local button_scale9 = Button:create() button_scale9:setTouchEnabled(true) button_scale9:setScale9Enabled(true) button_scale9:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") button_scale9:setSize(CCSize(100, button_scale9:getContentSize().height)) button_scale9:setPosition(CCPoint(textButton:getRightInParent() + textButton:getSize().width / 2, textButton:getBottomInParent() - textButton:getSize().height / 2)) scrollView:addChild(button_scale9) imageView:setPosition(CCPoint(innerWidth - imageView:getSize().width / 2, button_scale9:getBottomInParent() - button_scale9:getSize().height / 2)) scrollView:addChild(imageView) end function UIScrollViewHorizontalTest.create() local scene = CCScene:create() local layer = UIScrollViewHorizontalTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIPageViewTest = class("UIPageViewTest",UIScene) UIPageViewTest._displayValueLabel = nil function UIPageViewTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIPageViewTest) return target end function UIPageViewTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("Move by horizontal direction") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + self._displayValueLabel:getContentSize().height * 1.5)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("PageView") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 2.925)) self._uiLayer:addWidget(alert) local background = self._uiLayer:getWidgetByName("background_Panel") local pageView = PageView:create() pageView:setTouchEnabled(true) pageView:setSize(CCSize(240, 130)) local backgroundSize = background:getContentSize() pageView:setPosition(CCPoint((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - pageView:getSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - pageView:getSize().height) / 2)) for i = 1 , 3 do local layout = Layout:create() layout:setSize(CCSize(240, 130)) local imageView = ImageView:create() imageView:setTouchEnabled(true) imageView:setScale9Enabled(true) imageView:loadTexture("cocosgui/scrollviewbg.png") imageView:setSize(CCSize(240, 130)) imageView:setPosition(CCPoint(layout:getSize().width / 2, layout:getSize().height / 2)) layout:addChild(imageView) local label = Label:create() local pageInfo = string.format("page %d", i) label:setText(pageInfo) label:setFontName(getFont()) label:setFontSize(30) label:setColor(ccc3(192, 192, 192)) label:setPosition(CCPoint(layout:getSize().width / 2, layout:getSize().height / 2)) layout:addChild(label) pageView:addPage(layout) end local function pageViewEvent(sender, eventType) if eventType == ccs.PageViewEventType.turning then local pageView = tolua.cast(sender, "PageView") local pageInfo = string.format("page %d " , pageView:getCurPageIndex() + 1) self._displayValueLabel:setText(pageInfo) end end pageView:addEventListenerPageView(pageViewEvent) self._uiLayer:addWidget(pageView) end function UIPageViewTest.create() local scene = CCScene:create() local layer = UIPageViewTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIListViewVerticalTest = class("UIListViewVerticalTest",UIScene) UIListViewVerticalTest._displayValueLabel = nil UIListViewVerticalTest._count = 0 UIListViewVerticalTest._array = nil function UIListViewVerticalTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIListViewVerticalTest) return target end function UIListViewVerticalTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("Move by vertical direction") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + self._displayValueLabel:getContentSize().height * 1.5)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("ListView") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 2.925)) self._uiLayer:addWidget(alert) local background = self._uiLayer:getWidgetByName("background_Panel") self._count = 0 self._array = CCArray:create() self._array:retain() for i = 0,19 do local objectInfo = string.format("object_%d",i) self._array:addObject(CCString:create(objectInfo)) end local lv = ListView:create() lv:setDirection(ccs.ListViewDirection.vertical) lv:setTouchEnabled(true) lv:setBounceEnabled(true) lv:setBackGroundImageScale9Enabled(true) lv:setBackGroundImage("cocosgui/green_edit.png") lv:setSize(CCSizeMake(240, 130)) local backgroundSize = background:getContentSize() lv:setPosition(ccp((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - lv:getSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - lv:getSize().height) / 2)) local function listViewEvent(sender, eventType) if eventType == LISTVIEW_ONSELECTEDITEM_START then print("select child index = ",sender:getCurSelectedIndex()) elseif eventType == LISTVIEW_ONSELECTEDITEM_END then print("select child index = ",sender:getCurSelectedIndex()) end end lv:addEventListenerListView(listViewEvent) self._uiLayer:addWidget(lv) --create model local default_button = Button:create() default_button:setName("TextButton") default_button:setTouchEnabled(true) default_button:loadTextures("cocosgui/backtotoppressed.png", "cocosgui/backtotopnormal.png", "") local default_item = Layout:create() default_item:setTouchEnabled(true) default_item:setSize(default_button:getSize()) default_button:setPosition(ccp(default_item:getSize().width / 2, default_item:getSize().height / 2)) default_item:addChild(default_button) --set model lv:setItemModel(default_item) --add default item local count = self._array:count() for i = 1, math.floor(count / 4) do lv:pushBackDefaultItem() end --insert default item for i = 1 ,math.floor(count/4) do lv:insertDefaultItem(0) end --add custom item for i = 1, math.floor(count / 4) do local custom_button = Button:create() custom_button:setName("TextButton") custom_button:setTouchEnabled(true) custom_button:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") custom_button:setScale9Enabled(true) custom_button:setSize(default_button:getSize()) local custom_item = Layout:create() custom_item:setSize(custom_button:getSize()) custom_button:setPosition(ccp(custom_item:getSize().width / 2, custom_item:getSize().height / 2)) custom_item:addChild(custom_button) lv:pushBackCustomItem(custom_item) end --insert custom item local items = lv:getItems() local items_count = items:count() for i = 1, math.floor(count / 4) do local custom_button = Button:create() custom_button:setName("TextButton") custom_button:setTouchEnabled(true) custom_button:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") custom_button:setScale9Enabled(true) custom_button:setSize(default_button:getSize()) local custom_item = Layout:create() custom_item:setSize(custom_button:getSize()) custom_button:setPosition(ccp(custom_item:getSize().width / 2, custom_item:getSize().height / 2)) custom_item:addChild(custom_button) lv:insertCustomItem(custom_item, items_count) end --set item data items_count = items:count() for i = 1,math.floor(items_count) do local item = lv:getItem(i - 1) local button = tolua.cast(item:getChildByName("TextButton"),"Button") local index = lv:getIndex(item) button:setTitleText(self._array:objectAtIndex(index):getCString()) end --remove last item lv:removeLastItem() --remove item by index items_count = items:count() lv:removeItem(items_count - 1) --set all items layout gravity lv:setGravity(LISTVIEW_GRAVITY_CENTER_VERTICAL) end function UIListViewVerticalTest.create() local scene = CCScene:create() local layer = UIListViewVerticalTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIListViewHorizontalTest = class("UIListViewHorizontalTest",UIScene) UIListViewHorizontalTest._displayValueLabel = nil UIListViewHorizontalTest._count = 0 UIListViewHorizontalTest._array = nil function UIListViewHorizontalTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIListViewHorizontalTest) return target end function UIListViewHorizontalTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("Move by horizontal direction") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + self._displayValueLabel:getContentSize().height * 1.5)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("ListView") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 2.925)) self._uiLayer:addWidget(alert) local background = self._uiLayer:getWidgetByName("background_Panel") self._count = 0 self._array = CCArray:create() self._array:retain() for i=0,19 do local objectInfo = string.format("object_%d",i) self._array:addObject(CCString:create(objectInfo)) end local lv = ListView:create() lv:setDirection(SCROLLVIEW_DIR_HORIZONTAL) lv:setTouchEnabled(true) lv:setBounceEnabled(true) lv:setBackGroundImageScale9Enabled(true) lv:setBackGroundImage("cocosgui/green_edit.png") lv:setSize(CCSizeMake(240, 130)) local backgroundSize = background:getContentSize() lv:setPosition(ccp((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - lv:getSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - lv:getSize().height) / 2)) local function listViewEvent(sender, eventType) if eventType == LISTVIEW_ONSELECTEDITEM_START then print("select child index = ",sender:getCurSelectedIndex()) elseif eventType == LISTVIEW_ONSELECTEDITEM_END then print("select child index = ",sender:getCurSelectedIndex()) end end lv:addEventListenerListView(listViewEvent) self._uiLayer:addWidget(lv) --create model local default_button = Button:create() default_button:setName("TextButton") default_button:setTouchEnabled(true) default_button:loadTextures("cocosgui/backtotoppressed.png", "cocosgui/backtotopnormal.png", "") local default_item = Layout:create() default_item:setTouchEnabled(true) default_item:setSize(default_button:getSize()) default_button:setPosition(ccp(default_item:getSize().width / 2, default_item:getSize().height / 2)) default_item:addChild(default_button) --set model lv:setItemModel(default_item) --add default item local count = self._array:count() for i = 1,math.floor(count / 4 ) do lv:pushBackDefaultItem() end -- insert default item for i = 1,math.floor(count / 4) do lv:insertDefaultItem(0) end -- add custom item for i = 1,math.floor(count / 4) do local custom_button = Button:create() custom_button:setName("TextButton") custom_button:setTouchEnabled(true) custom_button:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") custom_button:setScale9Enabled(true) custom_button:setSize(default_button:getSize()) local custom_item = Layout:create() custom_item:setSize(custom_button:getSize()) custom_button:setPosition(ccp(custom_item:getSize().width / 2, custom_item:getSize().height / 2)) custom_item:addChild(custom_button) lv:pushBackCustomItem(custom_item) end --insert custom item local items = lv:getItems() local items_count = items:count() for i = 1, math.floor(count/4) do local custom_button = Button:create() custom_button:setName("TextButton") custom_button:setTouchEnabled(true) custom_button:loadTextures("cocosgui/button.png", "cocosgui/buttonHighlighted.png", "") custom_button:setScale9Enabled(true) custom_button:setSize(default_button:getSize()) local custom_item = Layout:create() custom_item:setSize(custom_button:getSize()) custom_button:setPosition(ccp(custom_item:getSize().width / 2, custom_item:getSize().height / 2)) custom_item:addChild(custom_button) lv:insertCustomItem(custom_item, items_count) end --set item data items_count = items:count() for i = 1, items_count do local item = lv:getItem(i - 1) local button = tolua.cast(item:getChildByName("TextButton"),"Button") local index = lv:getIndex(item) button:setTitleText(self._array:objectAtIndex(index):getCString()) end -- remove last item lv:removeLastItem() --remove item by index items_count = items:count() lv:removeItem(items_count - 1) --set all items layout gravity lv:setGravity(LISTVIEW_GRAVITY_CENTER_VERTICAL) --set items margin lv:setItemsMargin(2) end function UIListViewHorizontalTest.create() local scene = CCScene:create() local layer = UIListViewHorizontalTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIDragPanelTest = class("UIDragPanelTest",UIScene) UIDragPanelTest._displayValueLabel = nil function UIDragPanelTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIDragPanelTest) return target end function UIDragPanelTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("No Event") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + self._displayValueLabel:getSize().height * 1.5)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("DragPanel") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 2.925)) self._uiLayer:addWidget(alert) local sc = ScrollView:create() sc:setBackGroundColor(ccc3(0,255,0)) sc:setBackGroundColorType(ccs.LayoutBackGroundColorType.solid) sc:setDirection(ccs.SCROLLVIEW_DIR.both) sc:setInnerContainerSize(CCSize(480, 320)) sc:setSize(CCSize(100,100)) sc:setPosition(CCPoint(100,100)) sc:scrollToPercentBothDirection(CCPoint(50, 50), 1, true) local iv = ImageView:create() iv:loadTexture("cocosgui/Hello.png") iv:setPosition(CCPoint(240, 160)) sc:addChild(iv) self._uiLayer:addWidget(sc) end function UIDragPanelTest.create() local scene = CCScene:create() local layer = UIDragPanelTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UIDragPanelBounceTest = class("UIDragPanelBounceTest",UIScene) UIDragPanelBounceTest._displayValueLabel = nil function UIDragPanelBounceTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIDragPanelBounceTest) return target end function UIDragPanelBounceTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("No Event") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + self._displayValueLabel:getSize().height * 1.5)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("DragPanel Bounce") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 2.925)) self._uiLayer:addWidget(alert) local sc = ScrollView:create() sc:setBackGroundColor(ccc3(0, 255 , 0)) sc:setBackGroundColorType(ccs.LayoutBackGroundColorType.solid) sc:setBounceEnabled(true) sc:setDirection(ccs.SCROLLVIEW_DIR.both) sc:setInnerContainerSize(CCSize(480, 320)) sc:setSize(CCSize(100,100)) sc:setPosition(CCPoint(100,100)) sc:scrollToPercentBothDirection(CCPoint(50, 50), 1, true) local iv = ImageView:create() iv:loadTexture("cocosgui/Hello.png") iv:setPosition(CCPoint(240, 160)) sc:addChild(iv) self._uiLayer:addWidget(sc) end function UIDragPanelBounceTest.create() local scene = CCScene:create() local layer = UIDragPanelBounceTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local UINodeContainerTest = class("UINodeContainerTest",UIScene) UINodeContainerTest._displayValueLabel = nil function UINodeContainerTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UINodeContainerTest) return target end function UINodeContainerTest:initExtend() self:init() local widgetSize = self._widget:getSize() self._displayValueLabel = Label:create() self._displayValueLabel:setText("NodeContainer Add CCNode") self._displayValueLabel:setFontName(getFont()) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(CCPoint(0.5, -1)) self._displayValueLabel:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 + self._displayValueLabel:getContentSize().height * 1.5)) self._uiLayer:addWidget(self._displayValueLabel) local alert = Label:create() alert:setText("NodeContainer") alert:setFontName(getFont()) alert:setFontSize(30) alert:setColor(ccc3(159, 168, 176)) alert:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getSize().height * 1.75)) self._uiLayer:addWidget(alert) local nodeContainer = Widget:create() nodeContainer:setPosition(CCPoint(widgetSize.width / 2.0, widgetSize.height / 2.0)) self._uiLayer:addWidget(nodeContainer) -- local sprite = CCSprite:create("cocosgui/ccicon.png") -- sprite:setPosition(CCPoint(0, sprite:boundingBox().size.height / 4)) -- nodeContainer:addRenderer(sprite, 0) end function UINodeContainerTest.create() local scene = CCScene:create() local layer = UINodeContainerTest.extend(CCLayer:create()) layer:initExtend() scene:addChild(layer) return scene end local cocoStudioGuiArray = { { title = "UIButtonTest", func = function () return UIButtonTest.create() end, }, { title = "UIButtonScale9Test", func = function () return UIButtonScale9Test.create() end, }, { title = "ButtonPressedActionTest", func = function () return UIButtonPressedActionTest.create() end, }, { title = "UITextButtonTest", func = function () return UITextButtonTest.create() end, }, { title = "UITextButtonScale9Test", func = function () return UITextButtonScale9Test.create() end, }, { title = "UICheckBoxTest", func = function () return UICheckBoxTest.create() end, }, { title = "UISliderTest", func = function () return UISliderTest.create() end, }, { title = "UISliderScale9Test", func = function () return UISliderScale9Test.create() end, }, { title = "UIImageViewTest", func = function ( ) return UIImageViewTest.create() end, }, { title = "UIImageViewScale9Test", func = function ( ) return UIImageViewScale9Test.create() end, }, { title = "UILoadingBarLeftTest", func = function ( ) return UILoadingBarLeftTest.create() end, }, { title = "UILoadingBarRightTest", func = function ( ) return UILoadingBarRightTest.create() end, }, { title = "UILoadingBarLeftScale9Test", func = function ( ) return UILoadingBarLeftScale9Test.create() end, }, { title = "UILoadingBarRightScale9Test", func = function ( ) return UILoadingBarRightScale9Test.create() end, }, { title = "UILabelAtlasTest", func = function ( ) return UILabelAtlasTest.create() end, }, { title = "UILabelBMFontTest", func = function ( ) return UILabelBMFontTest.create() end, }, { title = "UILabelTest", func = function ( ) return UILabelTest.create() end, }, { title = "UITextAreaTest", func = function ( ) return UITextAreaTest.create() end, }, { title = "UITextFieldTest", func = function ( ) return UITextFieldTest.create() end, }, { title = "UITextFieldMaxLengthTest", func = function ( ) return UITextFieldMaxLengthTest.create() end, }, { title = "UITextFieldPasswordTest", func = function ( ) return UITextFieldPasswordTest.create() end, }, { title = "UIPanelTest", func = function ( ) return UIPanelTest.create() end, }, { title = "UIPanelColorTest", func = function ( ) return UIPanelColorTest.create() end, }, { title = "UIPanelGradientTest", func = function ( ) return UIPanelGradientTest.create() end, }, { title = "UIPanelBackGroundImageTest", func = function ( ) return UIPanelBackGroundImageTest.create() end, }, { title = "UIPanelBackGroundImageScale9Test", func = function ( ) return UIPanelBackGroundImageScale9Test.create() end, }, { title = "UIPanelLayoutLinearVerticalTest", func = function ( ) return UIPanelLayoutLinearVerticalTest.create() end, }, { title = "UIPanelLayoutLinearHorizontalTest", func = function ( ) return UIPanelLayoutLinearHorizontalTest.create() end, }, { title = "UIScrollViewVerticalTest", func = function ( ) return UIScrollViewVerticalTest.create() end, }, { title = "UIScrollViewHorizontalTest", func = function ( ) return UIScrollViewHorizontalTest.create() end, }, { title = "UIPageViewTest", func = function ( ) return UIPageViewTest.create() end, }, { title = "UIListViewVerticalTest", func = function () return UIListViewVerticalTest.create() end, }, { title = "UIListViewHorizontalTest", func = function () return UIListViewHorizontalTest.create() end, }, { title = "UIDragPanelTest", func = function () return UIDragPanelTest.create() end, }, { title = "UIDragPanelBounceTest", func = function () return UIDragPanelBounceTest.create() end, }, { title = "UINodeContainerTest", func = function () return UINodeContainerTest.create() end, }, } function guiSceneManager.nextUIScene() guiSceneManager.currentUISceneIdx = (guiSceneManager.currentUISceneIdx + 1) % table.getn(cocoStudioGuiArray) if 0 == guiSceneManager.currentUISceneIdx then guiSceneManager.currentUISceneIdx = table.getn(cocoStudioGuiArray) end return cocoStudioGuiArray[guiSceneManager.currentUISceneIdx].func() end function guiSceneManager.previousUIScene() guiSceneManager.currentUISceneIdx = guiSceneManager.currentUISceneIdx - 1 if guiSceneManager.currentUISceneIdx <= 0 then guiSceneManager.currentUISceneIdx = guiSceneManager.currentUISceneIdx + table.getn(cocoStudioGuiArray) end return cocoStudioGuiArray[guiSceneManager.currentUISceneIdx].func() end function guiSceneManager.currentUIScene() return cocoStudioGuiArray[guiSceneManager.currentUISceneIdx].func() end function runCocosGUITestScene() local scene = guiSceneManager.currentUIScene() CCDirector:sharedDirector():replaceScene(scene) end
mit
ffxiphoenix/darkstar
scripts/globals/mobskills/Osmosis.lua
13
1247
--------------------------------------------- -- Osmosis -- -- Description: Steals an enemy's HP and one beneficial status effect. Ineffective against undead. -- Type: Magical --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local effect = target:stealStatusEffect(); if (effect ~= nil and mob:hasStatusEffect(effect:getType()) == false) then -- add to myself mob:addStatusEffect(effect:getType(), effect:getPower(), effect:getTickCount(), effect:getDuration()); end local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_DARK,dmgmod,TP_MAB_BONUS,1); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_DARK,MOBPARAM_IGNORE_SHADOWS); if (target:isUndead() == false) then target:delHP(dmg); mob:addHP(dmg); skill:setMsg(MSG_DRAIN_HP); else skill:setMsg(MSG_NO_EFFECT); end return dmg; end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Lower_Jeuno/npcs/Ghebi_Damomohe.lua
17
4285
----------------------------------- -- Area: Lower Jeuno -- NPC: Ghebi Damomohe -- Type: Standard Merchant -- Starts and Finishes Quest: Tenshodo Membership -- @zone 245 -- @pos 16 0 -5 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,TENSHODO_MEMBERSHIP)~= QUEST_COMPLETED and trade:hasItemQty(548,1) == true and trade:getItemCount() == 1) then player:startEvent(0x006c); -- Finish Quest (don't need fame or starting quest) elseif (player:hasKeyItem(PSOXJA_PASS)==false and (trade:hasItemQty(1692,1) or trade:hasItemQty(1694,1) or trade:hasItemQty(1693,1)) and trade:getItemCount() == 1) then --Carmine Chip (Ex) - Snow Lizard or Frost Lizard --Gray Chip (Ex) - Diremite Stalker (at Tower near Ranguemont), Diremite Assaulter, Diremite --Cyan Chip (Ex) - Treasure Chest Mimics player:startEvent(0x0034); end -- cs 51 for "Wrong Gem" on Pso'Xja pass. Not sure which gems should trigger this. end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local CoPMission = player:getCurrentMission(COP); local CoPStatus = player:getVar("PromathiaStatus"); local PsoXjaPass = player:hasKeyItem(PSOXJA_PASS); local GetGems = player:getVar("PXPassGetGems"); if (player:getFameLevel(JEUNO) >= 3 and player:getQuestStatus(JEUNO,TENSHODO_MEMBERSHIP) == QUEST_AVAILABLE) then player:startEvent(0x006a,8); -- Start Quest (need fame 3 jeuno) elseif (CoPMission == DARKNESS_NAMED and PsoXjaPass == false and GetGems == 0) then player:startEvent(54); -- Gimme gems for Pso'Xja pass elseif (GetGems == 1) then player:startEvent(53); elseif (player:hasKeyItem(TENSHODO_APPLICATION_FORM) == true) then player:startEvent(0x006b); -- Finish Quest else player:startEvent(0x006a,4); -- Menu without quest 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 == 0x006a and option == 0) then stock = {0x1135,144, -- Rice Ball 0x1169,2700, -- Eel Kabob 0x1173,3} -- Garlic Cracker showShop(player, NORG, stock); elseif (csid == 0x006a and option == 2) then player:addQuest(JEUNO,TENSHODO_MEMBERSHIP); elseif (csid == 0x006b) then player:tradeComplete(); if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,548); else player:addTitle(TENSHODO_MEMBER); player:delKeyItem(TENSHODO_APPLICATION_FORM); player:addKeyItem(TENSHODO_MEMBERS_CARD); player:messageSpecial(KEYITEM_OBTAINED,TENSHODO_MEMBERS_CARD); player:addItem(548); player:messageSpecial(ITEM_OBTAINED,548); player:addFame(JEUNO,30); player:completeQuest(JEUNO,TENSHODO_MEMBERSHIP); end elseif (csid == 0x006c) then player:addTitle(TENSHODO_MEMBER); player:addKeyItem(TENSHODO_MEMBERS_CARD); player:messageSpecial(KEYITEM_OBTAINED,TENSHODO_MEMBERS_CARD); player:messageSpecial(ITEM_OBTAINED,548); player:addFame(JEUNO,30); player:completeQuest(JEUNO,TENSHODO_MEMBERSHIP); elseif (csid == 0x0034) then player:tradeComplete(); player:addKeyItem(PSOXJA_PASS); player:messageSpecial(KEYITEM_OBTAINED,PSOXJA_PASS); player:addGil(500); player:messageSpecial(GIL_OBTAINED,500); player:setVar("PXPassGetGems",0); elseif (csid == 54) then player:setVar("PXPassGetGems",1); end end;
gpl-3.0
AfuSensi/Mr.Green-MTA-Resources
resources/[web]/irc/scripts/handling.lua
4
10884
--------------------------------------------------------------------- -- Project: irc -- Author: MCvarial -- Contact: mcvarial@gmail.com -- Version: 1.0.0 -- Date: 31.10.2010 --------------------------------------------------------------------- ------------------------------------ -- Handling ------------------------------------ addEventHandler("onSockOpened",root, function (socket) for server,info in pairs (servers) do if info[1] == socket then servers[server][15] = true if servers[server][5] then ircRaw(server,"PASS "..servers[server][5]) end ircRaw(server,"USER echobot MCvarial MCv :Echobot by MCvarial") ircRaw(server,"NICK "..info[4]) return end end end ) addEventHandler("onSockData",root, function (socket,data) if string.find(data,"Could not resolve your hostname: Domain name not found; using your IP address",0) then localIP = string.sub(gettok(data,18,32),2,-2) end for server,info in pairs (servers) do if info[1] == socket then for i,line in ipairs (split(data,10)) do if line ~= "" then triggerEvent("onIRCRaw",server,line) end end return end end end ) addEvent("onIRCRaw") addEventHandler("onIRCRaw",root, function (data) servers[source][11] = getTickCount() local t = split(data,32) if t[1] == "PING" then if t[2] then ircRaw(source,"PONG "..string.sub(t[2],2)) else ircRaw(source,"PONG :REPLY") end end if t[2] == "376" then --users[(createElement("irc-user"))] = {ircGetServerNick(source),"+iwxz","?","?","?",{}} triggerEvent("onIRCConnect",source) end if t[2] == "001" then servers[source][2] = t[7] servers[source][15] = true end if t[2] == "002" then servers[source][3] = string.sub(t[7],1,-2) end if t[2] == "JOIN" then local nick = getNickFromRaw(data) local user = ircGetUserFromNick(nick) local channel = ircGetChannelFromName(getMessageFromRaw(data)) local vhost = gettok(gettok(data,1,32),2,33) if nick == ircGetServerNick(source) then if not channel then table.insert(servers[source][14],getMessageFromRaw(data)) channel = createElement("irc-channel") channels[channel] = {getMessageFromRaw(data),"+nst","Unknown",{},false,true,false} setElementParent(channel,source) end end if user then users[user][3] = vhost table.insert(users[user][6],channel) else user = createElement("irc-user") users[user] = {nick,"+iwxz",vhost,"?","?",{channel}} setElementParent(user,source) end triggerEvent("onIRCUserJoin",user,channel,vhost) end if t[2] == "NICK" then local oldnick = getNickFromRaw(data) local newnick = string.sub(t[3],1,-2) local user = ircGetUserFromNick(oldnick) users[user][1] = newnick triggerEvent("onIRCUserChangeNick",user,oldnick,newnick) end if t[2] == "PART" then local user = ircGetUserFromNick(getNickFromRaw(data)) local reason = getMessageFromRaw(data) local channel = ircGetChannelFromName(t[3]) or ircGetChannelFromName(string.sub(t[3],1,-2)) for i,chan in ipairs (users[user][6]) do if channel == chan then table.remove(users[user][6],i) break end end if userlevels[channel][user] then userlevels[channel][user] = nil end triggerEvent("onIRCUserPart",user,channel,reason) end if t[2] == "KICK" then local user = ircGetUserFromNick(t[4]) local reason = getMessageFromRaw(data) local channel = ircGetChannelFromName(t[3]) local kicker = ircGetUserFromNick(getNickFromRaw(data)) for i,chan in ipairs (users[user][6]) do if channel == chan then table.remove(users[user][6],i) break end end triggerEvent("onIRCUserKick",user,channel,reason,kicker) if t[4] == ircGetServerNick(source) then ircJoin(source,t[3]) end end if t[2] == "353" then local nicks = split(getMessageFromRaw(data),32) local channel = ircGetChannelFromName(t[5]) for i,nick in ipairs (nicks) do local nick,level = getNickAndLevel(nick) local user = ircGetUserFromNick(nick) if user then table.insert(users[user][6],channel) else user = createElement("irc-user") users[user] = {nick,"+iwxz","?","?","?",{channel}} setElementParent(user,source) end if not userlevels[channel] then userlevels[channel] = {} end if not userlevels[channel][user] then userlevels[channel][user] = 0 end if userlevels[channel][user] ~= level then triggerEvent("onIRCLevelChange",user,channel,userlevels[channel][user],level) userlevels[channel][user] = level end end end if t[2] == "433" then triggerEvent("onIRCFailConnect",source,"Nickname already in use") ircChangeNick(source,t[4].."_") if servers[source][8] then ircRaw(source,"PRIVMSG NickServ :GHOST "..t[4].." "..servers[source][8]) ircChangeNick(source,t[4]) end end if t[2] == "PRIVMSG" then local user = ircGetUserFromNick(getNickFromRaw(data)) local message = getMessageFromRaw(data) local channel = ircGetChannelFromName(t[3]) if t[3] == ircGetServerNick(source) then triggerEvent("onIRCPrivateMessage",user,message) else triggerEvent("onIRCMessage",user,channel,message) end end if t[2] == "NOTICE" then local user = ircGetUserFromNick(getNickFromRaw(data)) if user then if t[3] == ircGetServerNick(source) then triggerEvent("onIRCPrivateNotice",user,getMessageFromRaw(data)) else triggerEvent("onIRCNotice",user,ircGetChannelFromName(t[3]),getMessageFromRaw(data)) end end end if t[2] == "QUIT" then local nick = getNickFromRaw(data) local user = ircGetUserFromNick(nick) triggerEvent("onIRCUserQuit",user,getMessageFromRaw(data)) users[user] = nil destroyElement(user) if nick == string.sub(ircGetServerNick(source),1,-2) then ircChangeNick(source,nick) end if userlevels[channel] and userlevels[channel][user] then userlevels[channel][user] = nil end end if t[1] == "ERROR" then triggerEvent("onIRCFailConnect",source,getMessageFromRaw(data)) end end ) addEvent("onIRCConnect") addEventHandler("onIRCConnect",root, function () for i,raw in ipairs (servers[source][16]) do ircRaw(source,raw) end servers[source][16] = {} end ) setTimer(function () for i,server in ipairs (ircGetServers()) do if (getTickCount() - servers[server][11]) > 180000 then servers[server][11] = getTickCount() ircReconnect(server,"Connection timed out") elseif (getTickCount() - servers[server][11]) > 120000 then ircRaw(server,"PING") end end end,30000,0)
mit
jacks0nX/cqui
UI/Screens/TechTree.lua
2
72497
-- =========================================================================== -- TechTree -- Tabs set to 4 spaces retaining tab. -- -- The tech "Index" is the internal ID the gamecore used to track the tech. -- This value is essentially the database (db) row id minus 1 since it's 0 based. -- (e.g., TECH_MINING has a db rowid of 3, so it's gamecore index is 2.) -- -- Items exist in one of 8 "rows" that span horizontally and within a -- "column" based on the era and cost. -- -- Rows Start Eras-> -- -3 _____ _____ -- -2 /-|_____|----/-|_____| -- -1 | _____ | Nodes -- 0 O----%-|_____|----' -- 1 -- 2 -- 3 -- 4 -- -- =========================================================================== include( "ToolTipHelper" ); include( "SupportFunctions" ); include( "Civ6Common" ); -- Tutorial check support include( "TechAndCivicSupport"); -- (Already includes Civ6Common and InstanceManager) PopulateUnlockablesForTech include( "TechFilterFunctions" ); include( "ModalScreen_PlayerYieldsHelper" ); -- =========================================================================== -- DEBUG -- Toggle these for temporary debugging help. -- =========================================================================== local m_debugFilterEraMaxIndex :number = -1; -- (-1 default) Only load up to a specific ERA (Value less than 1 to disable) local m_debugOutputTechInfo :boolean= false; -- (false default) Send to console detailed information on tech? local m_debugShowIDWithName :boolean= false; -- (false default) Show the ID before the name in each node. local m_debugShowAllMarkers :boolean= false; -- (false default) Show all player markers in the timline; even if they haven't been met. -- =========================================================================== -- CONSTANTS -- =========================================================================== -- Graphic constants local PIC_BOLT_OFF :string = "Controls_BoltOff"; local PIC_BOLT_ON :string = "Controls_BoltOn"; local PIC_BOOST_OFF :string = "BoostTech"; local PIC_BOOST_ON :string = "BoostTechOn"; local PIC_DEFAULT_ERA_BACKGROUND:string = "TechTree_BGAncient"; local PIC_MARKER_PLAYER :string = "Tree_TimePipPlayer"; local PIC_MARKER_OTHER :string = "Controls_TimePip"; local PIC_METER_BACK :string = "Tree_Meter_GearBack"; local PIC_METER_BACK_DONE :string = "TechTree_Meter_Done"; local SIZE_ART_ERA_OFFSET_X :number = 40; -- How far to push each era marker local SIZE_ART_ERA_START_X :number = 40; -- How far to set the first era marker local SIZE_MARKER_PLAYER_X :number = 122; -- Marker of player local SIZE_MARKER_PLAYER_Y :number = 42; -- " local SIZE_MARKER_OTHER_X :number = 34; -- Marker of other players local SIZE_MARKER_OTHER_Y :number = 37; -- " local SIZE_NODE_X :number = 370; -- Item node dimensions local SIZE_NODE_Y :number = 84; local SIZE_OPTIONS_X :number = 200; local SIZE_OPTIONS_Y :number = 150; local SIZE_PATH :number = 40; local SIZE_PATH_HALF :number = SIZE_PATH / 2; local SIZE_TIMELINE_AREA_Y :number = 41; local SIZE_TOP_AREA_Y :number = 60; local SIZE_WIDESCREEN_HEIGHT :number = 768; local PATH_MARKER_OFFSET_X :number = 20; local PATH_MARKER_OFFSET_Y :number = 50; local PATH_MARKER_NUMBER_0_9_OFFSET :number = 20; local PATH_MARKER_NUMBER_10_OFFSET :number = 15; -- Other constants local COLUMN_WIDTH :number = 250; -- Space of node and line(s) after it to the next node local COLUMNS_NODES_SPAN :number = 2; -- How many colunms do the nodes span local DATA_FIELD_LIVEDATA :string = "_LIVEDATA"; -- The current status of an item. local DATA_FIELD_PLAYERINFO :string = "_PLAYERINFO";-- Holds a table with summary information on that player. local DATA_FIELD_UIOPTIONS :string = "_UIOPTIONS"; -- What options the player has selected for this screen. local DATA_ICON_PREFIX :string = "ICON_"; local ERA_ART :table = {}; local ITEM_STATUS :table = { BLOCKED = 1, READY = 2, CURRENT = 3, RESEARCHED = 4, }; local LINE_LENGTH_BEFORE_CURVE :number = 20; -- How long to make a line before a node before it curves local PADDING_TIMELINE_LEFT :number = 250; local PADDING_NODE_STACK_Y :number = 0; local PADDING_PAST_ERA_LEFT :number = 90; local PARALLAX_SPEED :number = 1.1; -- Speed for how much slower background moves (1.0=regular speed, 0.5=half speed) local PARALLAX_ART_SPEED :number = 1.2; -- Speed for how much slower background moves (1.0=regular speed, 0.5=half speed) local PREREQ_ID_TREE_START :string = "_TREESTART"; -- Made up, unique value, to mark a non-node tree start local ROW_MAX :number = 4; -- Highest level row above 0 local ROW_MIN :number = -3; -- Lowest level row below 0 local STATUS_ART :table = {}; local TIMELINE_LEFT_PADDING :number = 320; local TREE_START_ROW :number = 0; -- Which virtual "row" does tree start on? local TREE_START_COLUMN :number = 0; -- Which virtual "column" does tree start on? (Can be negative!) local TREE_START_NONE_ID :number = -999; -- Special, unique value, to mark no special tree start node. local TXT_BOOSTED :string = Locale.Lookup("LOC_BOOST_BOOSTED"); local TXT_TO_BOOST :string = Locale.Lookup("LOC_BOOST_TO_BOOST"); local VERTICAL_CENTER :number = (SIZE_NODE_Y) / 2; local MAX_BEFORE_TRUNC_TO_BOOST :number = 310; local MAX_BEFORE_TRUNC_KEY_LABEL:number = 100; -- CQUI CONSTANTS local CQUI_STATUS_MESSAGE_TECHS :number = 4; -- Number to distinguish tech messages STATUS_ART[ITEM_STATUS.BLOCKED] = { Name="BLOCKED", TextColor0=0xff202726, TextColor1=0x00000000, FillTexture="TechTree_GearButtonTile_Disabled.dds",BGU=0,BGV=(SIZE_NODE_Y*3), IsButton=false, BoltOn=false, IconBacking=PIC_METER_BACK }; STATUS_ART[ITEM_STATUS.READY] = { Name="READY", TextColor0=0xaaffffff, TextColor1=0x88000000, FillTexture=nil, BGU=0,BGV=0, IsButton=true, BoltOn=false, IconBacking=PIC_METER_BACK }; STATUS_ART[ITEM_STATUS.CURRENT] = { Name="CURRENT", TextColor0=0xaaffffff, TextColor1=0x88000000, FillTexture=nil, BGU=0,BGV=(SIZE_NODE_Y*4), IsButton=false, BoltOn=true, IconBacking=PIC_METER_BACK }; STATUS_ART[ITEM_STATUS.RESEARCHED] = { Name="RESEARCHED", TextColor0=0xaaffffff, TextColor1=0x88000000, FillTexture="TechTree_GearButtonTile_Done.dds", BGU=0,BGV=(SIZE_NODE_Y*5), IsButton=false, BoltOn=true, IconBacking=PIC_METER_BACK_DONE }; -- =========================================================================== -- MEMBERS / VARIABLES -- =========================================================================== local m_kNodeIM :table = InstanceManager:new( "NodeInstance", "Top", Controls.NodeScroller ); local m_kLineIM :table = InstanceManager:new( "LineImageInstance", "LineImage",Controls.NodeScroller ); local m_kEraArtIM :table = InstanceManager:new( "EraArtInstance", "Top", Controls.FarBackArtScroller ); local m_kEraLabelIM :table = InstanceManager:new( "EraLabelInstance", "Top", Controls.ArtScroller ); local m_kEraDotIM :table = InstanceManager:new( "EraDotInstance", "Dot", Controls.ScrollbarBackgroundArt ); local m_kMarkerIM :table = InstanceManager:new( "PlayerMarkerInstance", "Top", Controls.TimelineScrollbar ); local m_kSearchResultIM :table = InstanceManager:new( "SearchResultInstance", "Root", Controls.SearchResultsStack); local m_kPathMarkerIM :table = InstanceManager:new( "TechPathMarker", "Top", Controls.NodeScroller); local m_researchHash :number; local m_width :number= SIZE_MIN_SPEC_X; -- Screen Width (default / min spec) local m_height :number= SIZE_MIN_SPEC_Y; -- Screen Height (default / min spec) local m_previousHeight :number= SIZE_MIN_SPEC_Y; -- Screen Height (default / min spec) local m_scrollWidth :number= SIZE_MIN_SPEC_X; -- Width of the scroll bar local m_kEras :table = {}; -- type to costs local m_maxColumns :number= 0; -- # of columns (highest column #) local m_ePlayer :number= -1; local m_kAllPlayersTechData :table = {}; -- All data for local players. local m_kCurrentData :table = {}; -- Current set of data. local m_kItemDefaults :table = {}; -- Static data about items local m_kNodeGrid :table = {}; -- Static data about node location once it's laid out local m_uiNodes :table = {}; local m_uiConnectorSets :table = {}; local m_kFilters :table = {}; local m_shiftDown :boolean = false; local m_ToggleTechTreeId; -- CQUI variables local CQUI_halfwayNotified :table = {}; -- =========================================================================== -- Return string respresenation of a prereq table -- =========================================================================== function GetPrereqsString( prereqs:table ) local out:string = ""; for _,prereq in pairs(prereqs) do if prereq == PREREQ_ID_TREE_START then out = "n/a "; else out = out .. m_kItemDefaults[prereq].Type .. " "; -- Add space between techs end end return "[" .. string.sub(out,1,string.len(out)-1) .. "]"; -- Remove trailing space end -- =========================================================================== function SetCurrentNode( hash:number ) if hash ~= nil then local localPlayerTechs = Players[Game.GetLocalPlayer()]:GetTechs(); -- Get the complete path to the tech local pathToTech = localPlayerTechs:GetResearchPath( hash ); local tParameters = {}; tParameters[PlayerOperations.PARAM_TECH_TYPE] = pathToTech; if m_shiftDown then tParameters[PlayerOperations.PARAM_INSERT_MODE] = PlayerOperations.VALUE_APPEND; else tParameters[PlayerOperations.PARAM_INSERT_MODE] = PlayerOperations.VALUE_EXCLUSIVE; end UI.RequestPlayerOperation(Game.GetLocalPlayer(), PlayerOperations.RESEARCH, tParameters); UI.PlaySound("Confirm_Tech_TechTree"); else UI.DataError("Attempt to change current tree item with NIL hash!"); end end -- =========================================================================== -- If the next item isn't immediate, show a path of #s traversing the tree -- to the desired node. -- =========================================================================== function RealizePathMarkers() local pTechs :table = Players[Game.GetLocalPlayer()]:GetTechs(); local kNodeIds :table = pTechs:GetResearchQueue(); -- table: index, IDs m_kPathMarkerIM:ResetInstances(); for i,nodeNumber in pairs(kNodeIds) do local pathPin = m_kPathMarkerIM:GetInstance(); if(i < 10) then pathPin.NodeNumber:SetOffsetX(PATH_MARKER_NUMBER_0_9_OFFSET); else pathPin.NodeNumber:SetOffsetX(PATH_MARKER_NUMBER_10_OFFSET); end pathPin.NodeNumber:SetText(tostring(i)); for j,node in pairs(m_kItemDefaults) do if node.Index == nodeNumber then local x:number = m_uiNodes[node.Type].x; local y:number = m_uiNodes[node.Type].y; pathPin.Top:SetOffsetX(x-PATH_MARKER_OFFSET_X); pathPin.Top:SetOffsetY(y-PATH_MARKER_OFFSET_Y); end end end end -- =========================================================================== -- Convert a virtual column # and row # to actual pixels within the -- scrollable tree area. -- =========================================================================== function ColumnRowToPixelXY( column:number, row:number) local horizontal :number = ((column-1) * COLUMNS_NODES_SPAN * COLUMN_WIDTH) + PADDING_TIMELINE_LEFT + PADDING_PAST_ERA_LEFT; local vertical :number = PADDING_NODE_STACK_Y + (SIZE_WIDESCREEN_HEIGHT / 2) + (row * SIZE_NODE_Y); return horizontal, vertical; end -- =========================================================================== -- Get the width of the scroll panel -- =========================================================================== function GetMaxScrollWidth() return m_maxColumns + (m_maxColumns * COLUMN_WIDTH) + TIMELINE_LEFT_PADDING; end -- =========================================================================== -- Take the default item data and build the nodes that work with it. -- One time creation, any dynamic pieces should be -- -- No state specific data (e.g., selected node) should be set here in order -- to reuse the nodes across viewing other players' trees for single seat -- multiplayer or if a (spy) game rule allows looking at another's tree. -- =========================================================================== function AllocateUI() m_uiNodes = {}; m_kNodeIM:ResetInstances(); m_uiConnectorSets = {}; m_kLineIM:ResetInstances(); --[[ Layout logic for purely pre-reqs... In the existing Tech Tree there are many lines running across nodes using this algorithm as a smarter method than just "pushing a node forward" when a crossed node occurs needs to be implemented. If this gets completely re-written, it's likely a method that tracks the entire traceback of the line and then "untangles" by pushing node(s) forward should be explored. -TRON ]] -- Layout the nodes in columns based on increasing cost within an era. -- Loop items, put into era columns. for _,item in pairs(m_kItemDefaults) do local era :table = m_kEras[item.EraType]; if era.Columns[item.Cost] == nil then era.Columns[item.Cost] = {}; end table.insert( era.Columns[item.Cost], item.Type ); era.NumColumns = table.count( era.Columns ); -- This isn't great; set every iteration! end -- Loop items again, assigning column based off of total columns used for _,item in pairs(m_kItemDefaults) do local era :table = m_kEras[item.EraType]; local i :number = 0; local isFound :boolean = false; for cost,columns in orderedPairs( era.Columns ) do if cost ~= "__orderedIndex" then -- skip temp table used for order i = i + 1; for _,itemType in ipairs(columns) do if itemType == item.Type then item.Column = i; isFound = true; break; end end if isFound then break; end end end era.Columns.__orderedIndex = nil; end -- Determine total # of columns prior to a given era, and max columns overall. local priorColumns:number = 0; m_maxColumns = 0; for i=1,table.count(m_kEras),1 do for era,eraData in pairs(m_kEras) do if eraData.Index == i then -- Ensure indexed order eraData.PriorColumns = priorColumns; priorColumns = priorColumns + eraData.NumColumns + 1; -- Add one for era art between if i==table.count(m_kEras) then -- Last era determins total # of columns in tree m_maxColumns = priorColumns; end break; end end end -- Set nodes in the rows specified and columns computed above. m_kNodeGrid = {}; for i = ROW_MIN,ROW_MAX,1 do m_kNodeGrid[i] = {}; end for _,item in pairs(m_kItemDefaults) do local era :table = m_kEras[item.EraType]; local columnNum :number = era.PriorColumns + item.Column; m_kNodeGrid[item.UITreeRow][columnNum] = item.Type; end -- Era divider information m_kEraArtIM:ResetInstances(); m_kEraLabelIM:ResetInstances(); m_kEraDotIM:ResetInstances(); for era,eraData in pairs(m_kEras) do local instArt :table = m_kEraArtIM:GetInstance(); if eraData.BGTexture ~= nil then instArt.BG:SetTexture( eraData.BGTexture ); else UI.DataError("Tech tree is unable to find an EraTechBackgroundTexture entry for era '"..eraData.Description.."'; using a default."); instArt.BG:SetTexture(PIC_DEFAULT_ERA_BACKGROUND); end local startx, _ = ColumnRowToPixelXY( eraData.PriorColumns + 1, 0); instArt.Top:SetOffsetX( (startx ) * (1/PARALLAX_ART_SPEED) ); instArt.Top:SetOffsetY( (SIZE_WIDESCREEN_HEIGHT * 0.5) - (instArt.BG:GetSizeY()*0.5) ); instArt.Top:SetSizeVal(eraData.NumColumns*SIZE_NODE_X, 600); local inst:table = m_kEraLabelIM:GetInstance(); local eraMarkerx, _ = ColumnRowToPixelXY( eraData.PriorColumns + 1, 0) - PADDING_PAST_ERA_LEFT; -- Need to undo the padding in place that nodes use to get past the era marker column inst.Top:SetOffsetX( (eraMarkerx - (SIZE_NODE_X*0.5)) * (1/PARALLAX_SPEED) ); inst.EraTitle:SetText( Locale.Lookup("LOC_GAME_ERA_DESC",eraData.Description) ); -- Dots on scrollbar local markerx:number = (eraData.PriorColumns / m_maxColumns) * Controls.ScrollbarBackgroundArt:GetSizeX(); if markerx > 0 then local inst:table = m_kEraDotIM:GetInstance(); inst.Dot:SetOffsetX(markerx); end end local playerId = Game.GetLocalPlayer(); if (playerId == -1) then return; end -- Actually build UI nodes for _,item in pairs(m_kItemDefaults) do local tech = GameInfo.Technologies[item.Index]; local techType = tech and tech.TechnologyType; local unlockableTypes = GetUnlockablesForTech_Cached(techType, playerId); local node :table; local numUnlocks :number = 0; if unlockableTypes ~= nil then for _, unlockItem in ipairs(unlockableTypes) do local typeInfo = GameInfo.Types[unlockItem[1]]; numUnlocks = numUnlocks + 1; end end node = m_kNodeIM:GetInstance(); node.Top:SetTag( item.Hash ); -- Set the hash of the technology to the tag of the node (for tutorial to be able to callout) local era:table = m_kEras[item.EraType]; -- Horizontal # = All prior nodes across all previous eras + node position in current era (based on cost vs. other nodes in that era) local horizontal, vertical = ColumnRowToPixelXY(era.PriorColumns + item.Column, item.UITreeRow ); -- Add data fields to UI component node.Type = techType; -- Dynamically add "Type" field to UI node for quick look ups in item data table. node.x = horizontal; -- Granted x,y can be looked up via GetOffset() but caching the values here for node.y = vertical - VERTICAL_CENTER; -- other LUA functions to use removes the necessity of a slow C++ roundtrip. if node["unlockIM"] ~= nil then node["unlockIM"]:DestroyInstances() end node["unlockIM"] = InstanceManager:new( "UnlockInstance", "UnlockIcon", node.UnlockStack ); if node["unlockGOV"] ~= nil then node["unlockGOV"]:DestroyInstances() end node["unlockGOV"] = InstanceManager:new( "GovernmentIcon", "GovernmentInstanceGrid", node.UnlockStack ); PopulateUnlockablesForTech(playerId, item.Index, node["unlockIM"], function() SetCurrentNode(item.Hash); end); -- What happens when clicked function OpenPedia() LuaEvents.OpenCivilopedia(techType); end node.NodeButton:RegisterCallback( Mouse.eLClick, function() SetCurrentNode(item.Hash); end); node.OtherStates:RegisterCallback( Mouse.eLClick, function() SetCurrentNode(item.Hash); end); -- Only wire up Civilopedia handlers if not in a on-rails tutorial; as clicking it can take a player off the rails... if IsTutorialRunning()==false then node.NodeButton:RegisterCallback( Mouse.eRClick, OpenPedia); node.OtherStates:RegisterCallback( Mouse.eRClick, OpenPedia); end -- Set position and save. node.Top:SetOffsetVal( horizontal, vertical); m_uiNodes[item.Type] = node; end if Controls.TreeStart ~= nil then local h,v = ColumnRowToPixelXY( TREE_START_COLUMN, TREE_START_ROW ); Controls.TreeStart:SetOffsetVal( h+SIZE_NODE_X-42,v-71 ); -- TODO: Science-out the magic (numbers). end -- Determine the lines between nodes. -- NOTE: Potentially move this to view, since lines are constantly change in look, but -- it makes sense to have at least the routes computed here since they are -- consistent regardless of the look. for type,item in pairs(m_kItemDefaults) do local node:table = m_uiNodes[item.Type]; for _,prereqId in pairs(item.Prereqs) do local previousRow :number = 0; local previousColumn:number = 0; if prereqId == PREREQ_ID_TREE_START then previousRow = TREE_START_ROW; previousColumn = TREE_START_COLUMN; else local prereq :table = m_kItemDefaults[prereqId]; previousRow = prereq.UITreeRow; previousColumn = m_kEras[prereq.EraType].PriorColumns + prereq.Column; end local startColumn :number = m_kEras[item.EraType].PriorColumns + item.Column; local column :number = startColumn; local isEarlyBend :boolean= false; local isAtPrior :boolean= false; while( not isAtPrior ) do column = column - 1; -- Move backwards one -- If a node is found, make sure it's the previous node this is looking for. if (m_kNodeGrid[previousRow][column] ~= nil) then if m_kNodeGrid[previousRow][column] == prereqId then isAtPrior = true; end elseif column <= TREE_START_COLUMN then isAtPrior = true; end if (not isAtPrior) and m_kNodeGrid[item.UITreeRow][column] ~= nil then -- Was trying to hold off bend until start, but it looks to cross -- another node, so move the bend to the end. isEarlyBend = true; end if column < 0 then UI.DataError("Tech tree could not find prior for '"..prereqId.."'"); break; end end if previousRow == TREE_START_NONE_ID then -- Nothing goes before this, not even a fake start area. elseif previousRow < item.UITreeRow or previousRow > item.UITreeRow then -- Obtain grid pieces to ____________________ -- use in order to draw ___ ________| | -- lines. |L2 |L1 | NODE | -- |___|________| | -- _____________________ |L3 | x1 |____________________| -- | |___________|___| -- | PREVIOUS NODE | L5 |L4 | -- | |___________|___| -- |_____________________| x2 -- local inst :table = m_kLineIM:GetInstance(); local line1 :table = inst.LineImage; inst = m_kLineIM:GetInstance(); local line2 :table = inst.LineImage; inst = m_kLineIM:GetInstance(); local line3 :table = inst.LineImage; inst = m_kLineIM:GetInstance(); local line4 :table = inst.LineImage; inst = m_kLineIM:GetInstance(); local line5 :table = inst.LineImage; -- Find all the empty space before the node before to make a bend. local LineEndX1:number = 0; local LineEndX2:number = 0; if isEarlyBend then LineEndX1 = (node.x - LINE_LENGTH_BEFORE_CURVE ) ; LineEndX2, _ = ColumnRowToPixelXY( column, item.UITreeRow ); LineEndX2 = LineEndX2 + SIZE_NODE_X; else LineEndX1, _ = ColumnRowToPixelXY( column, item.UITreeRow ); LineEndX2, _ = ColumnRowToPixelXY( column, item.UITreeRow ); LineEndX1 = LineEndX1 + SIZE_NODE_X + LINE_LENGTH_BEFORE_CURVE; LineEndX2 = LineEndX2 + SIZE_NODE_X; end local prevY :number = 0; -- y position of the previous node being connected to if previousRow < item.UITreeRow then prevY = node.y-((item.UITreeRow-previousRow)*SIZE_NODE_Y);-- above line2:SetTexture("Controls_TreePathDashSE"); line4:SetTexture("Controls_TreePathDashES"); else prevY = node.y+((previousRow-item.UITreeRow)*SIZE_NODE_Y);-- below line2:SetTexture("Controls_TreePathDashNE"); line4:SetTexture("Controls_TreePathDashEN"); end line1:SetOffsetVal(LineEndX1 + SIZE_PATH_HALF, node.y - SIZE_PATH_HALF); line1:SetSizeVal( node.x - LineEndX1 - SIZE_PATH_HALF, SIZE_PATH); line1:SetTexture("Controls_TreePathDashEW"); line2:SetOffsetVal(LineEndX1 - SIZE_PATH_HALF, node.y - SIZE_PATH_HALF); line2:SetSizeVal( SIZE_PATH, SIZE_PATH); line3:SetOffsetVal(LineEndX1 - SIZE_PATH_HALF, math.min(node.y + SIZE_PATH_HALF, prevY + SIZE_PATH_HALF) ); line3:SetSizeVal( SIZE_PATH, math.abs(node.y - prevY) - SIZE_PATH ); line3:SetTexture("Controls_TreePathDashNS"); line4:SetOffsetVal(LineEndX1 - SIZE_PATH_HALF, prevY - SIZE_PATH_HALF); line4:SetSizeVal( SIZE_PATH, SIZE_PATH); line5:SetSizeVal( LineEndX1 - LineEndX2 - SIZE_PATH_HALF, SIZE_PATH ); line5:SetOffsetVal(LineEndX2, prevY - SIZE_PATH_HALF); line1:SetTexture("Controls_TreePathDashEW"); -- Directly store the line (not instance) with a key name made up of this type and the prereq's type. m_uiConnectorSets[item.Type..","..prereqId] = {line1,line2,line3,line4,line5}; else -- Prereq is on the same row local inst:table = m_kLineIM:GetInstance(); local line:table = inst.LineImage; line:SetTexture("Controls_TreePathDashEW"); local end1, _ = ColumnRowToPixelXY( column, item.UITreeRow ); end1 = end1 + SIZE_NODE_X; line:SetOffsetVal(end1, node.y - SIZE_PATH_HALF); line:SetSizeVal( node.x - end1, SIZE_PATH); -- Directly store the line (not instance) with a key name made up of this type and the prereq's type. m_uiConnectorSets[item.Type..","..prereqId] = {line}; end end end Controls.NodeScroller:CalculateSize(); Controls.NodeScroller:ReprocessAnchoring(); Controls.ArtScroller:CalculateSize(); Controls.FarBackArtScroller:CalculateSize(); Controls.NodeScroller:RegisterScrollCallback( OnScroll ); -- We use a separate BG within the PeopleScroller control since it needs to scroll with the contents Controls.ModalBG:SetHide(true); Controls.ModalScreenClose:RegisterCallback(Mouse.eLClick, OnClose); Controls.ModalScreenTitle:SetText(Locale.ToUpper(Locale.Lookup("LOC_TECH_TREE_HEADER"))); end -- =========================================================================== -- UI Event -- Callback when the main scroll panel is scrolled. -- =========================================================================== function OnScroll( control:table, percent:number ) -- Parallax Controls.ArtScroller:SetScrollValue( percent ); Controls.FarBackArtScroller:SetScrollValue( percent ); -- Audio if percent==0 or percent==1.0 then UI.PlaySound("UI_TechTree_ScrollTick_End"); else UI.PlaySound("UI_TechTree_ScrollTick"); end end -- =========================================================================== -- Display the state of the tree (filter, node display, etc...) based on the -- active player's item data. -- =========================================================================== function View( playerTechData:table ) -- Output the node states for the tree for _,node in pairs(m_uiNodes) do local item :table = m_kItemDefaults[node.Type]; -- static item data local live :table = playerTechData[DATA_FIELD_LIVEDATA][node.Type]; -- live (changing) data local artInfo :table = STATUS_ART[live.Status]; -- art/styles for this state if(live.Status == ITEM_STATUS.RESEARCHED) then for _,prereqId in pairs(item.Prereqs) do if(prereqId ~= PREREQ_ID_TREE_START) then local prereq :table = m_kItemDefaults[prereqId]; local previousRow :number = prereq.UITreeRow; local previousColumn:number = m_kEras[prereq.EraType].PriorColumns; for lineNum,line in pairs(m_uiConnectorSets[item.Type..","..prereqId]) do if(lineNum == 1 or lineNum == 5) then line:SetTexture("Controls_TreePathEW"); end if( lineNum == 3) then line:SetTexture("Controls_TreePathNS"); end if(lineNum==2)then if previousRow < item.UITreeRow then line:SetTexture("Controls_TreePathSE"); else line:SetTexture("Controls_TreePathNE"); end end if(lineNum==4)then if previousRow < item.UITreeRow then line:SetTexture("Controls_TreePathES"); else line:SetTexture("Controls_TreePathEN"); end end end end end end node.NodeName:SetColor( artInfo.TextColor0, 0 ); node.NodeName:SetColor( artInfo.TextColor1, 1 ); if m_debugShowIDWithName then node.NodeName:SetText( tostring(item.Index).." "..Locale.Lookup(item.Name) ); -- Debug output else node.NodeName:SetText( Locale.ToUpper( Locale.Lookup(item.Name) )); -- Normal output end if live.Turns > 0 then node.Turns:SetHide( false ); node.Turns:SetColor( artInfo.TextColor0, 0 ); node.Turns:SetColor( artInfo.TextColor1, 1 ); node.Turns:SetText( Locale.Lookup("LOC_TECH_TREE_TURNS",live.Turns) ); else node.Turns:SetHide( true ); end if item.IsBoostable and live.Status ~= ITEM_STATUS.RESEARCHED then node.BoostIcon:SetHide( false ); node.BoostText:SetHide( false ); node.BoostText:SetColor( artInfo.TextColor0, 0 ); node.BoostText:SetColor( artInfo.TextColor1, 1 ); local boostText:string; if live.IsBoosted then boostText = TXT_BOOSTED.." "..item.BoostText; node.BoostIcon:SetTexture( PIC_BOOST_ON ); node.BoostMeter:SetHide( true ); else boostText = TXT_TO_BOOST.." "..item.BoostText; node.BoostedBack:SetHide( true ); node.BoostIcon:SetTexture( PIC_BOOST_OFF ); node.BoostMeter:SetHide( false ); local boostAmount = (item.BoostAmount*.01) + (live.Progress/ live.Cost); node.BoostMeter:SetPercent( boostAmount ); end TruncateStringWithTooltip(node.BoostText, MAX_BEFORE_TRUNC_TO_BOOST, boostText); else node.BoostIcon:SetHide( true ); node.BoostText:SetHide( true ); node.BoostedBack:SetHide( true ); node.BoostMeter:SetHide( true ); end if live.Status == ITEM_STATUS.CURRENT then node.GearAnim:SetHide( false ); else node.GearAnim:SetHide( true ); end if live.Progress > 0 then node.ProgressMeter:SetHide( false ); node.ProgressMeter:SetPercent(live.Progress / live.Cost); else node.ProgressMeter:SetHide( true ); end -- Show/Hide Recommended Icon if live.IsRecommended and live.AdvisorType ~= nil then node.RecommendedIcon:SetIcon(live.AdvisorType); node.RecommendedIcon:SetHide(false); else node.RecommendedIcon:SetHide(true); end -- Set art for icon area if(node.Type ~= nil) then local iconName :string = DATA_ICON_PREFIX .. node.Type; if (artInfo.Name == "BLOCKED") then node.IconBacking:SetHide(true); iconName = iconName .. "_FOW"; node.BoostMeter:SetColor(0x66ffffff); node.BoostIcon:SetColor(0x66000000); else node.IconBacking:SetHide(false); iconName = iconName; node.BoostMeter:SetColor(0xffffffff); node.BoostIcon:SetColor(0xffffffff); end local textureOffsetX, textureOffsetY, textureSheet = IconManager:FindIconAtlas(iconName, 42); if (textureOffsetX ~= nil) then node.Icon:SetTexture( textureOffsetX, textureOffsetY, textureSheet ); end end if artInfo.IsButton then node.OtherStates:SetHide( true ); node.NodeButton:SetTextureOffsetVal( artInfo.BGU, artInfo.BGV ); else node.OtherStates:SetHide( false ); node.OtherStates:SetTextureOffsetVal( artInfo.BGU, artInfo.BGV ); end if artInfo.FillTexture ~= nil then node.FillTexture:SetHide( false ); node.FillTexture:SetTexture( artInfo.FillTexture ); else node.FillTexture:SetHide( true ); end if artInfo.BoltOn then node.Bolt:SetTexture(PIC_BOLT_ON); else node.Bolt:SetTexture(PIC_BOLT_OFF); end node.NodeButton:SetToolTipString(ToolTipHelper.GetToolTip(item.Type, Game.GetLocalPlayer())); node.IconBacking:SetTexture(artInfo.IconBacking); -- Darken items not making it past filter. local currentFilter:table = playerTechData[DATA_FIELD_UIOPTIONS].filter; if currentFilter == nil or currentFilter.Func == nil or currentFilter.Func( item.Type ) then node.FilteredOut:SetHide( true ); else node.FilteredOut:SetHide( false ); end end -- Fill in where the markers (representing players) are at: m_kMarkerIM:ResetInstances(); local PADDING :number = 24; local thisPlayerID :number = Game.GetLocalPlayer(); local markers :table = m_kCurrentData[DATA_FIELD_PLAYERINFO].Markers; for _,markerStat in ipairs( markers ) do -- Only build a marker if a player has started researching... if markerStat.HighestColumn ~= -1 then local instance :table = m_kMarkerIM:GetInstance(); if markerStat.IsPlayerHere then -- Representing the player viewing the tree instance.Portrait:SetHide( true ); instance.TurnGrid:SetHide( false ); instance.TurnLabel:SetText( Locale.Lookup("LOC_TECH_TREE_TURN_NUM" )); --instance.TurnNumber:SetText( tostring(Game.GetCurrentGameTurn()) ); local turn = Game.GetCurrentGameTurn(); instance.TurnNumber:SetText(tostring(turn)); local turnLabelWidth = PADDING + instance.TurnLabel:GetSizeX() + instance.TurnNumber:GetSizeX(); instance.TurnGrid:SetSizeX( turnLabelWidth ); instance.Marker:SetTexture( PIC_MARKER_PLAYER ); instance.Marker:SetSizeVal( SIZE_MARKER_PLAYER_X, SIZE_MARKER_PLAYER_Y ); else -- An other player instance.TurnGrid:SetHide( true ); instance.Marker:SetTexture( PIC_MARKER_OTHER ); instance.Marker:SetSizeVal( SIZE_MARKER_OTHER_X, SIZE_MARKER_OTHER_Y ); end -- Different content in marker based on if there is just 1 player in the column, or more than 1 local tooltipString :string = Locale.Lookup("LOC_TREE_ERA", Locale.Lookup(GameInfo.Eras[markerStat.HighestEra].Name) ).."[NEWLINE]"; local numOfPlayersAtThisColumn :number = table.count(markerStat.PlayerNums); if numOfPlayersAtThisColumn < 2 then instance.Num:SetHide( true ); local playerNum :number = markerStat.PlayerNums[1]; local pPlayerConfig :table = PlayerConfigurations[playerNum]; tooltipString = tooltipString.. Locale.Lookup(pPlayerConfig:GetPlayerName()); -- ??TRON: Temporary using player name until leaderame is fixed if not markerStat.IsPlayerHere then local iconName:string = "ICON_"..pPlayerConfig:GetLeaderTypeName(); local textureOffsetX:number, textureOffsetY:number, textureSheet:string = IconManager:FindIconAtlas(iconName); instance.Portrait:SetHide( false ); instance.Portrait:SetTexture( textureOffsetX, textureOffsetY, textureSheet ); end else instance.Portrait:SetHide( true ); instance.Num:SetHide( false ); instance.Num:SetText(tostring(numOfPlayersAtThisColumn)); for i,playerNum in ipairs(markerStat.PlayerNums) do local pPlayerConfig :table = PlayerConfigurations[playerNum]; --[[ ??TRON debug: The human player, player 0, has whack values! No leader name coming from engine! local name = pPlayerConfig:GetPlayerName(); local nick = pPlayerConfig:GetNickName(); local leader = pPlayerConfig:GetLeaderName(); local civ = pPlayerConfig:GetCivilizationTypeName(); local isHuman = pPlayerConfig:IsHuman(); print("debug info:",name,nick,leader,civ,isHuman); ]] --tooltipString = tooltipString.. Locale.Lookup(pPlayerConfig:GetLeaderName()); tooltipString = tooltipString.. Locale.Lookup(pPlayerConfig:GetPlayerName()); -- ??TRON: Temporary using player name until leaderame is fixed if i < numOfPlayersAtThisColumn then tooltipString = tooltipString.."[NEWLINE]"; end end end instance.Marker:SetToolTipString( tooltipString ); local MARKER_OFFSET_START:number = 20; local markerPercent :number = math.clamp( markerStat.HighestColumn / m_maxColumns, 0, 1 ); local markerX :number = MARKER_OFFSET_START + (markerPercent * m_scrollWidth ); instance.Top:SetOffsetVal(markerX ,0); end end RealizePathMarkers(); RealizeFilterPulldown(); RealizeKeyPanel(); RealizeTutorialNodes(); end -- =========================================================================== -- Load all the 'live' data for a player. -- =========================================================================== function GetLivePlayerData( ePlayer:number, eCompletedTech:number ) -- If first time, initialize player data tables. local data :table = m_kAllPlayersTechData[ePlayer]; if data == nil then -- Initialize player's top level tables: data = {}; data[DATA_FIELD_LIVEDATA] = {}; data[DATA_FIELD_PLAYERINFO] = {}; data[DATA_FIELD_UIOPTIONS] = {}; -- Initialize data, and sub tables within the top tables. data[DATA_FIELD_PLAYERINFO].Player = ePlayer; -- Number of this player data[DATA_FIELD_PLAYERINFO].Markers = {}; -- Hold a condenced, UI-ready version of stats data[DATA_FIELD_PLAYERINFO].Stats = {}; -- Hold stats on where each player is (based on what this player can see) end local kPlayer :table = Players[ePlayer]; local playerTechs :table = kPlayer:GetTechs(); local currentTechID :number = playerTechs:GetResearchingTech(); -- DEBUG: Output header to console. if m_debugOutputTechInfo then print(" Item Id Status Progress $ Era Prereqs"); print("------------------------------ --- ---------- --------- --- ---------------- --------------------------"); end -- Loop through all items and place in appropriate buckets as well -- read in the associated information for it. for type,item in pairs(m_kItemDefaults) do local status :number = ITEM_STATUS.BLOCKED; local turnsLeft :number = playerTechs:GetTurnsToResearch(item.Index); if playerTechs:HasTech(item.Index) or item.Index == eCompletedTech then status = ITEM_STATUS.RESEARCHED; turnsLeft = 0; elseif item.Index == currentTechID then status = ITEM_STATUS.CURRENT; turnsLeft = playerTechs:GetTurnsLeft(); elseif playerTechs:CanResearch(item.Index) then status = ITEM_STATUS.READY; end data[DATA_FIELD_LIVEDATA][type] = { Cost = playerTechs:GetResearchCost(item.Index), IsBoosted = playerTechs:HasBoostBeenTriggered(item.Index), Progress = playerTechs:GetResearchProgress(item.Index), Status = status, Turns = turnsLeft } -- DEBUG: Output to console detailed information about the tech. if m_debugOutputTechInfo then local this:table = data[DATA_FIELD_LIVEDATA][type]; print( string.format("%30s %-3d %-10s %4d/%-4d %3d %-16s %s", type,item.Index, STATUS_ART[status].Name, this.Progress, this.Cost, this.Turns, item.EraType, GetPrereqsString(item.Prereqs) )); end end local players = Game.GetPlayers{Major = true}; -- Determine where all players are. local playerVisibility = PlayersVisibility[ePlayer]; if playerVisibility ~= nil then for i, otherPlayer in ipairs(players) do local playerID :number = otherPlayer:GetID(); local playerTech :table = players[i]:GetTechs(); local currentTech :number = playerTech:GetResearchingTech(); data[DATA_FIELD_PLAYERINFO].Stats[playerID] = { CurrentID = currentTech, -- tech currently being researched HasMet = kPlayer:GetDiplomacy():HasMet(playerID) or playerID==ePlayer or m_debugShowAllMarkers; HighestColumn = -1, -- where they are in the timeline HighestEra = "" }; -- The latest tech a player may be researching may not be the one -- furthest along in time; so go through ALL the techs and track -- the highest column of all researched tech. local highestColumn :number = -1; local highestEra :string = ""; for _,item in pairs(m_kItemDefaults) do if playerTech:HasTech(item.Index) then local column:number = item.Column + m_kEras[item.EraType].PriorColumns; if column > highestColumn then highestColumn = column; highestEra = item.EraType; end end end data[DATA_FIELD_PLAYERINFO].Stats[playerID].HighestColumn = highestColumn; data[DATA_FIELD_PLAYERINFO].Stats[playerID].HighestEra = highestEra; end end -- All player data is added.. build markers data based on player data. local checkedID:table = {}; data[DATA_FIELD_PLAYERINFO].Markers = {}; for playerID:number, targetPlayer:table in pairs(data[DATA_FIELD_PLAYERINFO].Stats) do -- Only look for IDs that haven't already been merged into a marker. if checkedID[playerID] == nil and targetPlayer.HasMet then checkedID[playerID] = true; local markerData:table = {}; if data[DATA_FIELD_PLAYERINFO].Markers[playerID] ~= nil then markerData = data[DATA_FIELD_PLAYERINFO].Markers[playerID]; markerData.HighestColumn = targetPlayer.HighestColumn; markerData.HighestEra = targetPlayer.HighestEra; markerData.IsPlayerHere = (playerID == ePlayer); else markerData = { HighestColumn = targetPlayer.HighestColumn, -- Which column this marker should be placed HighestEra = targetPlayer.HighestEra, IsPlayerHere = (playerID == ePlayer), PlayerNums = {playerID}} -- All players who share this marker spot table.insert( data[DATA_FIELD_PLAYERINFO].Markers, markerData ); end -- SPECIAL CASE: Current player starts at column 0 so it's immediately visible on timeline: if playerID == ePlayer and markerData.HighestColumn == -1 then markerData.HighestColumn = 0; local firstEra:table = nil; for _,era in pairs(m_kEras) do if firstEra == nil or era.Index < firstEra.Index then firstEra = era; end end markerData.HighestEra = firstEra.Index; end -- Traverse all the IDs and merge them with this one. for anotherID:number, anotherPlayer:table in pairs(data[DATA_FIELD_PLAYERINFO].Stats) do -- Don't add if: it's ourself, if hasn't researched at least 1 tech, if we haven't met if playerID ~= anotherID and anotherPlayer.HighestColumn > -1 and anotherPlayer.HasMet then if markerData.HighestColumn == data[DATA_FIELD_PLAYERINFO].Stats[anotherID].HighestColumn then checkedID[anotherID] = true; -- Need to do this check if player's ID didn't show up first in the list in creating the marker. if anotherID == ePlayer then markerData.IsPlayerHere = true; end local foundAnotherID:boolean = false; for _, playernumsID in pairs(markerData.PlayerNums) do if not foundAnotherID and playernumsID == anotherID then foundAnotherID = true; end end if not foundAnotherID then table.insert( markerData.PlayerNums, anotherID ); end end end end end end return data; end -- =========================================================================== function OnLocalPlayerTurnBegin() local ePlayer :number = Game.GetLocalPlayer(); if ePlayer ~= -1 then --local kPlayer :table = Players[ePlayer]; if m_ePlayer ~= ePlayer then m_ePlayer = ePlayer; m_kCurrentData = GetLivePlayerData( ePlayer ); end -------------------------------------------------------------------------- -- CQUI Check for Tech Progress -- Get the current tech local kPlayer :table = Players[ePlayer]; local playerTechs :table = kPlayer:GetTechs(); local currentTechID :number = playerTechs:GetResearchingTech(); local isCurrentBoosted :boolean = playerTechs:HasBoostBeenTriggered(currentTechID); -- Make sure there is a technology selected before continuing with checks if currentTechID ~= -1 then local techName = GameInfo.Technologies[currentTechID].Name; local techType = GameInfo.Technologies[currentTechID].Type; local currentCost = playerTechs:GetResearchCost(currentTechID); local currentProgress = playerTechs:GetResearchProgress(currentTechID); local currentYield = playerTechs:GetScienceYield(); local percentageToBeDone = (currentProgress + currentYield) / currentCost; local percentageNextTurn = (currentProgress + currentYield*2) / currentCost; local CQUI_halfway:number = 0.5; -- Finds boost amount, always 50 in base game, China's +10% modifier is not applied here for row in GameInfo.Boosts() do if(row.ResearchType == techType) then CQUI_halfway = (100 - row.Boost) / 100; break; end end --If playing as china, apply boost modifier. Not sure where I can query this value... if(PlayerConfigurations[Game.GetLocalPlayer()]:GetCivilizationTypeName() == "CIVILIZATION_CHINA") then CQUI_halfway = CQUI_halfway - .1; end -- Is it greater than 50% and has yet to be displayed? if isCurrentBoosted then CQUI_halfwayNotified[techName] = true; elseif percentageNextTurn >= CQUI_halfway and isCurrentBoosted == false and CQUI_halfwayNotified[techName] ~= true then LuaEvents.CQUI_AddStatusMessage("The current Technology, " .. Locale.Lookup( techName ) .. ", is one turn away from maximum Eureka potential.", 10, CQUI_STATUS_MESSAGE_TECHS); CQUI_halfwayNotified[techName] = true; end end -- end of techID check -------------------------------------------------------------------------- end -- end of playerID check end -- =========================================================================== -- EVENT -- Player turn is ending -- =========================================================================== function OnLocalPlayerTurnEnd() -- If current data set is for the player, save back any changes into -- the table of player tables. local ePlayer :number = Game.GetLocalPlayer(); if ePlayer ~= -1 then if m_kCurrentData[DATA_FIELD_PLAYERINFO].Player == ePlayer then m_kAllPlayersTechData[ePlayer] = m_kCurrentData; end end end -- =========================================================================== function OnResearchChanged( ePlayer:number, eTech:number ) if ePlayer == Game.GetLocalPlayer() then m_ePlayer = ePlayer; m_kCurrentData = GetLivePlayerData( m_ePlayer, -1 ); if not ContextPtr:IsHidden() then View( m_kCurrentData ); end end end -- =========================================================================== function OnResearchComplete( ePlayer:number, eTech:number) if ePlayer == Game.GetLocalPlayer() then m_ePlayer = ePlayer; m_kCurrentData = GetLivePlayerData( m_ePlayer, eTech ); if not ContextPtr:IsHidden() then View( m_kCurrentData ); end -------------------------------------------------------------------------- -- CQUI Completion Notification -- Get the current tech local kPlayer :table = Players[ePlayer]; local currentTechID :number = eTech; -- Make sure there is a technology selected before continuing with checks if currentTechID ~= -1 then local techName = GameInfo.Technologies[currentTechID].Name; LuaEvents.CQUI_AddStatusMessage("The Technology, " .. Locale.Lookup( techName ) .. ", is completed.", 10, CQUI_STATUS_MESSAGE_TECHS); end -- end of techID check -------------------------------------------------------------------------- end end -- =========================================================================== -- Initially size static UI elements -- (or re-size if screen resolution changed) -- =========================================================================== function Resize() m_width, m_height = UIManager:GetScreenSizeVal(); -- Cache screen dimensions m_scrollWidth = m_width - 80; -- Scrollbar area (where markers are placed) slightly smaller than screen width -- Determine how far art will span. -- First obtain the size of the tree by taking the visible size and multiplying it by the ratio of the full content local scrollPanelX:number = (Controls.NodeScroller:GetSizeX() / Controls.NodeScroller:GetRatio()); local artAndEraScrollWidth:number = scrollPanelX * (1/PARALLAX_SPEED); Controls.ArtParchmentDecoTop:SetSizeX( artAndEraScrollWidth ); Controls.ArtParchmentDecoBottom:SetSizeX( artAndEraScrollWidth ); Controls.ArtParchmentRippleTop:SetSizeX( artAndEraScrollWidth ); Controls.ArtParchmentRippleBottom:SetSizeX( artAndEraScrollWidth ); Controls.ForceSizeX:SetSizeX( artAndEraScrollWidth ); Controls.ArtScroller:CalculateSize(); Controls.ArtCornerGrungeTR:ReprocessAnchoring(); Controls.ArtCornerGrungeBR:ReprocessAnchoring(); local PADDING_DUE_TO_LAST_BACKGROUND_ART_IMAGE:number = 100; local backArtScrollWidth:number = scrollPanelX * (1/PARALLAX_ART_SPEED); Controls.Background:SetSizeX( backArtScrollWidth + PADDING_DUE_TO_LAST_BACKGROUND_ART_IMAGE ); Controls.Background:SetSizeY( SIZE_WIDESCREEN_HEIGHT - (SIZE_TIMELINE_AREA_Y-8) ); Controls.FarBackArtScroller:CalculateSize(); end -- =========================================================================== function OnUpdateUI( type:number, tag:string, iData1:number, iData2:number, strData1:string) if type == SystemUpdateUI.ScreenResize then Resize(); end end -- =========================================================================== -- Obtain the data from the DB that doesn't change -- Base costs and relationships (prerequisites) -- RETURN: A table of node data (techs/civics/etc...) with a prereq for each entry. -- =========================================================================== function PopulateItemData( tableName:string, tableColumn:string, prereqTableName:string, itemColumn:string, prereqColumn:string) -- Build main item table. m_kItemDefaults = {}; local index :number = 0; function GetHash(t) local r = GameInfo.Types[t]; if(r) then return r.Hash; else return 0; end end for row:table in GameInfo[tableName]() do local entry:table = {}; entry.Type = row[tableColumn]; entry.Name = row.Name; entry.BoostText = ""; entry.Column = -1; entry.Cost = row.Cost; entry.Description = row.Description and Locale.Lookup( row.Description ); entry.EraType = row.EraType; entry.Hash = GetHash(entry.Type); --entry.Icon = row.Icon; entry.Index = index; entry.IsBoostable = false; entry.Prereqs = {}; entry.UITreeRow = row.UITreeRow; entry.Unlocks = {}; -- Each unlock has: unlockType, iconUnavail, iconAvail, tooltip -- Boost? for boostRow in GameInfo.Boosts() do if boostRow.TechnologyType == entry.Type then entry.BoostText = Locale.Lookup( boostRow.TriggerDescription ); entry.IsBoostable = true; entry.BoostAmount = boostRow.Boost; break; end end for prereqRow in GameInfo[prereqTableName]() do if prereqRow[itemColumn] == entry.Type then table.insert( entry.Prereqs, prereqRow[prereqColumn] ); end end -- If no prereqs were found, set item to special tree start value if table.count(entry.Prereqs) == 0 then table.insert(entry.Prereqs, PREREQ_ID_TREE_START); end -- Warn if DB has an out of bounds entry. if entry.UITreeRow < ROW_MIN or entry.UITreeRow > ROW_MAX then UI.DataError("UITreeRow for '"..entry.Type.."' has an out of bound UITreeRow="..tostring(entry.UITreeRow).." MIN="..tostring(ROW_MIN).." MAX="..tostring(ROW_MAX)); end -- Only build up a limited number of eras if debug information is forcing a subset. if m_debugFilterEraMaxIndex < 1 or ( m_debugFilterEraMaxIndex ~= -1 and m_kEras[entry.EraType] ~= nil ) then m_kItemDefaults[entry.Type] = entry; index = index + 1; end end end -- =========================================================================== -- Create a hash table of EraType to its chronological index. -- =========================================================================== function PopulateEraData() m_kEras = {}; for row:table in GameInfo.Eras() do if m_debugFilterEraMaxIndex < 1 or row.ChronologyIndex <= m_debugFilterEraMaxIndex then m_kEras[row.EraType] = { BGTexture = row.EraTechBackgroundTexture, NumColumns = 0, Description = Locale.Lookup(row.Name), Index = row.ChronologyIndex, PriorColumns= -1, Columns = {} -- column data } end end end -- =========================================================================== -- -- =========================================================================== function PopulateFilterData() -- Hard coded/special filters: -- Load entried into filter table from TechFilters XML data --[[ TODO: Only add filters based on what is in the game database. ??TRON for row in GameInfo.TechFilters() do table.insert( m_kFilters, { row.IconString, row.Description, g_TechFilters[row.Type] }); end ]] m_kFilters = {}; table.insert( m_kFilters, { Func=nil, Description="LOC_TECH_FILTER_NONE", Icon=nil } ); --table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_RECOMMENDED"], Description="LOC_TECH_FILTER_RECOMMENDED", Icon="[ICON_Recommended]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_FOOD"], Description="LOC_TECH_FILTER_FOOD", Icon="[ICON_Food]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_SCIENCE"], Description="LOC_TECH_FILTER_SCIENCE", Icon="[ICON_Science]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_PRODUCTION"], Description="LOC_TECH_FILTER_PRODUCTION", Icon="[ICON_Production]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_CULTURE"], Description="LOC_TECH_FILTER_CULTURE", Icon="[ICON_Culture]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_GOLD"], Description="LOC_TECH_FILTER_GOLD", Icon="[ICON_Gold]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_FAITH"], Description="LOC_TECH_FILTER_FAITH", Icon="[ICON_Faith]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_HOUSING"], Description="LOC_TECH_FILTER_HOUSING", Icon="[ICON_Housing]" }); --table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_AMENITIES"], Description="LOC_TECH_FILTER_AMENITIES", Icon="[ICON_Amenities]" }); --table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_HEALTH"], Description="LOC_TECH_FILTER_HEALTH", Icon="[ICON_Health]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_UNITS"], Description="LOC_TECH_FILTER_UNITS", Icon="[ICON_Units]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_IMPROVEMENTS"], Description="LOC_TECH_FILTER_IMPROVEMENTS", Icon="[ICON_Improvements]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_WONDERS"], Description="LOC_TECH_FILTER_WONDERS", Icon="[ICON_Wonders]" }); for i,filter in ipairs(m_kFilters) do local filterLabel = Locale.Lookup( filter.Description ); local filterIconText = filter.Icon; local controlTable = {}; Controls.FilterPulldown:BuildEntry( "FilterItemInstance", controlTable ); -- If a text icon exists, use it and bump the label in the button over. --[[ TODO: Uncomment if icons are added. if filterIconText ~= nil and filterIconText ~= "" then controlTable.IconText:SetText( Locale.Lookup(filterIconText) ); controlTable.DescriptionText:SetOffsetX(24); else controlTable.IconText:SetText( "" ); controlTable.DescriptionText:SetOffsetX(4); end ]] controlTable.DescriptionText:SetOffsetX(8); controlTable.DescriptionText:SetText( filterLabel ); -- Callback controlTable.Button:RegisterCallback( Mouse.eLClick, function() OnFilterClicked(filter); end ); end Controls.FilterPulldown:CalculateInternals(); end -- =========================================================================== -- Populate Full Text Search -- =========================================================================== function PopulateSearchData() -- Populate Full Text Search local searchContext = "Technologies"; if(Search.CreateContext(searchContext, "[COLOR_LIGHTBLUE]", "[ENDCOLOR]", "...")) then for row in GameInfo.Technologies() do local description = row.Description and Locale.Lookup(row.Description) or ""; Search.AddData(searchContext, row.TechnologyType, Locale.Lookup(row.Name), description); end for row in GameInfo.Improvements() do if(row.PrereqTech) then Search.AddData(searchContext, row.PrereqTech, Locale.Lookup("LOC_" .. row.PrereqTech .. "_NAME"), Locale.Lookup(row.Name)); end end for row in GameInfo.Units() do if(row.PrereqTech) then Search.AddData(searchContext, row.PrereqTech, Locale.Lookup("LOC_" .. row.PrereqTech .. "_NAME"), Locale.Lookup(row.Name)); end end for row in GameInfo.Buildings() do if(row.PrereqTech) then Search.AddData(searchContext, row.PrereqTech, Locale.Lookup("LOC_" .. row.PrereqTech .. "_NAME"), Locale.Lookup(row.Name)); end end for row in GameInfo.Districts() do if(row.PrereqTech) then Search.AddData(searchContext, row.PrereqTech, Locale.Lookup("LOC_" .. row.PrereqTech .. "_NAME"), Locale.Lookup(row.Name)); end end for row in GameInfo.Resources() do if(row.PrereqTech) then Search.AddData(searchContext, row.PrereqTech, Locale.Lookup("LOC_" .. row.PrereqTech .. "_NAME"), Locale.Lookup(row.Name)); end end Search.Optimize(searchContext); end end -- =========================================================================== -- Update the Filter text with the current label. -- =========================================================================== function RealizeFilterPulldown() local pullDownButton = Controls.FilterPulldown:GetButton(); if m_kCurrentData[DATA_FIELD_UIOPTIONS].filter == nil or m_kCurrentData[DATA_FIELD_UIOPTIONS].filter.Func== nil then pullDownButton:SetText( " "..Locale.Lookup("LOC_TREE_FILTER_W_DOTS")); else local description:string = m_kCurrentData[DATA_FIELD_UIOPTIONS].filter.Description; pullDownButton:SetText( " "..Locale.Lookup( description )); end end -- =========================================================================== -- filterLabel, Readable lable of the current filter. -- filterFunc, The funciton filter to apply to each node as it's built, -- nil will reset the filters to none. -- =========================================================================== function OnFilterClicked( filter ) m_kCurrentData[DATA_FIELD_UIOPTIONS].filter = filter; View( m_kCurrentData ) end -- =========================================================================== function OnOpen() UI.PlaySound("UI_Screen_Open"); View( m_kCurrentData ); ContextPtr:SetHide(false); -- From ModalScreen_PlayerYieldsHelper RefreshYields(); -- From Civ6_styles: FullScreenVignetteConsumer Controls.ScreenAnimIn:SetToBeginning(); Controls.ScreenAnimIn:Play(); LuaEvents.TechTree_OpenTechTree(); Controls.SearchEditBox:TakeFocus(); end -- =========================================================================== -- Show the Key panel based on the state -- =========================================================================== function RealizeKeyPanel() if UserConfiguration.GetShowTechTreeKey() then Controls.KeyPanel:SetHide( false ); UI.PlaySound("UI_TechTree_Filter_Open"); else if(not ContextPtr:IsHidden()) then UI.PlaySound("UI_TechTree_Filter_Closed"); Controls.KeyPanel:SetHide( true ); end end if Controls.KeyPanel:IsHidden() then Controls.ToggleKeyButton:SetText(Locale.Lookup("LOC_TREE_SHOW_KEY")); Controls.ToggleKeyButton:SetSelected(false); else Controls.ToggleKeyButton:SetText(Locale.Lookup("LOC_TREE_HIDE_KEY")); Controls.ToggleKeyButton:SetSelected(true); end end -- =========================================================================== -- Reparents all tutorial controls, guarantee they will be on top of the -- nodes and lines dynamically added. -- =========================================================================== function RealizeTutorialNodes() Controls.CompletedTechNodePointer:Reparent(); Controls.IncompleteTechNodePointer:Reparent(); Controls.UnavailableTechNodePointer:Reparent(); Controls.ChooseWritingPointer:Reparent(); Controls.ActiveTechNodePointer:Reparent(); Controls.TechUnlocksPointer:Reparent(); end -- =========================================================================== -- Show/Hide key panel -- =========================================================================== function OnClickToggleKey() if Controls.KeyPanel:IsHidden() then UserConfiguration.SetShowTechTreeKey(true); else UserConfiguration.SetShowTechTreeKey(false); end RealizeKeyPanel(); end -- =========================================================================== function OnClickFiltersPulldown() if Controls.FilterPulldown:IsOpen() then UI.PlaySound("UI_TechTree_Filter_Open"); else UI.PlaySound("UI_TechTree_Filter_Closed"); end end -- =========================================================================== -- Main close function all exit points should call. -- =========================================================================== function Close() UI.PlaySound("UI_Screen_Close"); ContextPtr:SetHide(true); LuaEvents.TechTree_CloseTechTree(); Controls.SearchResultsPanelContainer:SetHide(true); end -- =========================================================================== -- Close via click -- =========================================================================== function OnClose() Close(); end -- =========================================================================== -- Input -- UI Event Handler -- =========================================================================== function KeyDownHandler( key:number ) if key == Keys.VK_SHIFT then m_shiftDown = true; -- let it fall through end return false; end function KeyUpHandler( key:number ) if key == Keys.VK_SHIFT then m_shiftDown = false; -- let it fall through end if key == Keys.VK_ESCAPE then Close(); return true; end if key == Keys.VK_RETURN then -- Don't let enter propigate or it will hit action panel which will raise a screen (potentially this one again) tied to the action. return true; end return false; end function OnInputHandler( pInputStruct:table ) local uiMsg = pInputStruct:GetMessageType(); if uiMsg == KeyEvents.KeyDown then return KeyDownHandler( pInputStruct:GetKey() ); end if uiMsg == KeyEvents.KeyUp then return KeyUpHandler( pInputStruct:GetKey() ); end return false; end -- =========================================================================== -- UI Event Handler -- =========================================================================== function OnShutdown() -- Clean up events LuaEvents.LaunchBar_CloseTechTree.Remove( OnClose ); LuaEvents.LaunchBar_RaiseTechTree.Remove( OnOpen ); LuaEvents.ResearchChooser_RaiseTechTree.Remove( OnOpen ); LuaEvents.Tutorial_TechTreeScrollToNode.Remove( OnTutorialScrollToNode ); Events.LocalPlayerTurnBegin.Remove( OnLocalPlayerTurnBegin ); Events.LocalPlayerTurnEnd.Remove( OnLocalPlayerTurnEnd ); Events.ResearchChanged.Remove( OnResearchChanged ); Events.ResearchQueueChanged.Remove( OnResearchChanged ); Events.ResearchCompleted.Remove( OnResearchComplete ); Events.SystemUpdateUI.Remove( OnUpdateUI ); Search.DestroyContext("Technologies"); end function OnSearchBarGainFocus() Controls.SearchEditBox:ClearString(); Controls.SearchResultsPanelContainer:SetHide(true); end function OnSearchBarLoseFocus() Controls.SearchEditBox:SetText(Locale.Lookup("LOC_TREE_SEARCH_W_DOTS")); end -- =========================================================================== -- Centers scroll panel (if possible) on a specfic type. -- =========================================================================== function ScrollToNode( typeName:string ) local percent:number = 0; local x = m_uiNodes[typeName].x - ( m_width * 0.5); local size = (m_width / Controls.NodeScroller:GetRatio()) - m_width; percent = math.clamp( x / size, 0, 1); Controls.NodeScroller:SetScrollValue(percent); m_kSearchResultIM:DestroyInstances(); Controls.SearchResultsPanelContainer:SetHide(true); end -- =========================================================================== -- LuaEvent -- =========================================================================== function OnTutorialScrollToNode( typeName:string ) ScrollToNode( typeName ); end -- =========================================================================== -- Input Hotkey Event -- =========================================================================== function OnInputActionTriggered( actionId ) if actionId == m_ToggleTechTreeId then UI.PlaySound("Play_UI_Click"); if(ContextPtr:IsHidden()) then LuaEvents.LaunchBar_RaiseTechTree(); else OnClose(); end end end function OnSearchCharCallback() local str = Controls.SearchEditBox:GetText(); local has_found = {}; if str ~= nil and str ~= Locale.Lookup("LOC_TREE_SEARCH_W_DOTS") then local results = Search.Search("Technologies", str); m_kSearchResultIM:DestroyInstances(); if (results and #results > 0) then for i, v in ipairs(results) do if has_found[v[1]] == nil then -- v[1]chnologyType -- v[2] == Name of Technology w/ search term highlighted. -- v[3] == Snippet of Technology description w/ search term highlighted. local instance = m_kSearchResultIM:GetInstance(); local techType:number; local i:number = 0; for row in GameInfo.Technologies() do if row.TechnologyType == v[1] then techType = i; end i = i + 1; end -- Going to take this out right now... we may decide we want this back. --if instance["unlockIM"] ~= nil then -- instance["unlockIM"]:DestroyInstances() --end --instance["unlockIM"] = InstanceManager:new( "UnlockInstance", "UnlockIcon", instance.SearchUnlockStack ); --PopulateUnlockablesForTech(Players[Game.GetLocalPlayer()]:GetID(), techType, instance["unlockIM"], function() ScrollToNode(v[1]); end); -- Search results already localized. instance.Name:SetText(Locale.ToUpper(v[2])); local iconName :string = DATA_ICON_PREFIX .. v[1]; instance.SearchIcon:SetIcon(iconName); instance.Button:RegisterCallback(Mouse.eLClick, function() ScrollToNode(v[1]); end ); instance.Button:SetToolTipString(ToolTipHelper.GetToolTip(v[1], Game.GetLocalPlayer())); has_found[v[1]] = true; end end Controls.SearchResultsStack:CalculateSize(); Controls.SearchResultsStack:ReprocessAnchoring(); Controls.SearchResultsPanel:CalculateSize(); Controls.SearchResultsPanelContainer:SetHide(false); else Controls.SearchResultsPanelContainer:SetHide(true); end end end -- =========================================================================== -- Load all static information as well as display information for the -- current local player. -- =========================================================================== function Initialize() --profile.runtime("start"); PopulateEraData(); PopulateItemData("Technologies","TechnologyType","TechnologyPrereqs","Technology","PrereqTech"); PopulateFilterData(); PopulateSearchData(); AllocateUI(); -- May be observation mode. m_ePlayer = Game.GetLocalPlayer(); if (m_ePlayer == -1) then return; end Resize(); m_kCurrentData = GetLivePlayerData( m_ePlayer ); View( m_kCurrentData ); -- UI Events ContextPtr:SetInputHandler( OnInputHandler, true ); ContextPtr:SetShutdown( OnShutdown ); Controls.FilterPulldown:GetButton():RegisterCallback( Mouse.eLClick, OnClickFiltersPulldown ); Controls.FilterPulldown:RegisterSelectionCallback( OnClickFiltersPulldown ); Controls.SearchEditBox:RegisterStringChangedCallback(OnSearchCharCallback); Controls.SearchEditBox:RegisterHasFocusCallback( OnSearchBarGainFocus); Controls.SearchEditBox:RegisterCommitCallback( OnSearchBarLoseFocus); Controls.ToggleKeyButton:RegisterCallback(Mouse.eLClick, OnClickToggleKey); -- LUA Events LuaEvents.LaunchBar_CloseTechTree.Add( OnClose ); LuaEvents.LaunchBar_RaiseTechTree.Add( OnOpen ); LuaEvents.ResearchChooser_RaiseTechTree.Add( OnOpen ); LuaEvents.Tutorial_TechTreeScrollToNode.Add( OnTutorialScrollToNode ); -- Game engine Event Events.LocalPlayerTurnBegin.Add( OnLocalPlayerTurnBegin ); Events.LocalPlayerTurnEnd.Add( OnLocalPlayerTurnEnd ); Events.LocalPlayerChanged.Add(AllocateUI); Events.ResearchChanged.Add( OnResearchChanged ); Events.ResearchQueueChanged.Add( OnResearchChanged ); Events.ResearchCompleted.Add( OnResearchComplete ); Events.SystemUpdateUI.Add( OnUpdateUI ); -- Hot Key Handling m_ToggleTechTreeId = Input.GetActionId("ToggleTechTree"); if m_ToggleTechTreeId ~= nil then Events.InputActionTriggered.Add( OnInputActionTriggered ); end -- Key Label Truncation to Tooltip TruncateStringWithTooltip(Controls.AvailableLabelKey, MAX_BEFORE_TRUNC_KEY_LABEL, Controls.AvailableLabelKey:GetText()); TruncateStringWithTooltip(Controls.UnavailableLabelKey, MAX_BEFORE_TRUNC_KEY_LABEL, Controls.UnavailableLabelKey:GetText()); TruncateStringWithTooltip(Controls.ResearchingLabelKey, MAX_BEFORE_TRUNC_KEY_LABEL, Controls.ResearchingLabelKey:GetText()); TruncateStringWithTooltip(Controls.CompletedLabelKey, MAX_BEFORE_TRUNC_KEY_LABEL, Controls.CompletedLabelKey:GetText()); -- CQUI add exceptions to the 50% notifications by putting techs into the CQUI_halfwayNotified table CQUI_halfwayNotified["LOC_TECH_POTTERY_NAME"] = true; CQUI_halfwayNotified["LOC_TECH_MINING_NAME"] = true; CQUI_halfwayNotified["LOC_TECH_ANIMAL_HUSBANDRY_NAME"] = true; end Initialize();
mit
jacks0nX/cqui
BTS/Choosers/TradeRouteChooser.lua
2
64837
print("Better Trade Screen loaded") -- =========================================================================== -- Settings -- =========================================================================== local alignTradeRouteYields = true local showSortOrdersPermanently = false ------------------------------------------------------------------------------- -- TRADE PANEL ------------------------------------------------------------------------------- include("InstanceManager"); include("SupportFunctions"); local m_RouteChoiceIM : table = InstanceManager:new("RouteChoiceInstance", "Top", Controls.RouteChoiceStack); local m_originCity : table = nil; -- City where the trade route will begin local m_destinationCity : table = nil; -- City where the trade route will end, nil if none selected local m_pTradeOverviewContext : table = nil; -- Trade Overview context local m_LastRouteForTrader : table = {}; -- Last route taken by the trader. local m_TraderAutomated : table = {}; local m_TraderAutomatedSettings : table = {}; -- These can be set by other contexts to have a route selected automatically after the chooser opens local m_postOpenSelectPlayerID:number = -1; local m_postOpenSelectCityID:number = -1; -- Filtered and unfiltered lists of possible destinations local m_unfilteredDestinations:table = {}; local m_filteredDestinations:table = {}; -- Stores filter list and tracks the currently selected list local m_filterList:table = {}; local m_filterCount:number = 0; local m_filterSelected:number = 1; -- This is updated from the Trade Overview panel, to stop UI bugs. local m_TradeOverviewIsOpen:boolean = false; -- SORT CONSTANTS local SORT_BY_ID:table = { FOOD = 1; PRODUCTION = 2; GOLD = 3; SCIENCE = 4; CULTURE = 5; FAITH = 6; TURNS_TO_COMPLETE = 7; } local SORT_ASCENDING = 1 local SORT_DESCENDING = -1 local m_shiftDown:boolean = false; -- Stores the sort settings. local m_SortBySettings = {}; -- Default is ascending in turns to complete trade route m_SortBySettings[1] = { SortByID = SORT_BY_ID.TURNS_TO_COMPLETE, SortOrder = SORT_ASCENDING }; local m_CompareFunctionByID = {}; m_CompareFunctionByID[SORT_BY_ID.FOOD] = function(a, b) return CompareByFood(a, b); end; m_CompareFunctionByID[SORT_BY_ID.PRODUCTION] = function(a, b) return CompareByProduction(a, b); end; m_CompareFunctionByID[SORT_BY_ID.GOLD] = function(a, b) return CompareByGold(a, b); end; m_CompareFunctionByID[SORT_BY_ID.SCIENCE] = function(a, b) return CompareByScience(a, b); end; m_CompareFunctionByID[SORT_BY_ID.CULTURE] = function(a, b) return CompareByCulture(a, b); end; m_CompareFunctionByID[SORT_BY_ID.FAITH] = function(a, b) return CompareByFaith(a, b); end; m_CompareFunctionByID[SORT_BY_ID.TURNS_TO_COMPLETE] = function(a, b) return CompareByTurnsToComplete(a, b); end; -- =========================================================================== -- Refresh -- =========================================================================== function Refresh() local selectedUnit:table = UI.GetHeadSelectedUnit(); if selectedUnit == nil then Close(); return; end m_originCity = Cities.GetCityInPlot(selectedUnit:GetX(), selectedUnit:GetY()); if m_originCity == nil then Close(); return; end RefreshHeader(); RefreshTopPanel(); RefreshSortBar(); RefreshChooserPanel(); end function RefreshHeader() if m_originCity then Controls.Header_OriginText:SetText(Locale.Lookup("LOC_ROUTECHOOSER_TO_DESTINATION", Locale.ToUpper(m_originCity:GetName()))); end end function RefreshTopPanel() if m_destinationCity and m_originCity then -- Update City Banner Controls.CityName:SetText(Locale.ToUpper(m_destinationCity:GetName())); local backColor:number, frontColor:number = UI.GetPlayerColors( m_destinationCity:GetOwner() ); local darkerBackColor:number = DarkenLightenColor(backColor,(-85),238); local brighterBackColor:number = DarkenLightenColor(backColor,90,255); Controls.BannerBase:SetColor( backColor ); Controls.BannerDarker:SetColor( darkerBackColor ); Controls.BannerLighter:SetColor( brighterBackColor ); Controls.CityName:SetColor( frontColor ); -- Update Trading Post Icon if m_destinationCity:GetTrade():HasActiveTradingPost(m_originCity:GetOwner()) then Controls.TradingPostIcon:SetHide(false); else Controls.TradingPostIcon:SetHide(true); end -- Update City-State Quest Icon Controls.CityStateQuestIcon:SetHide(true); local questsManager : table = Game.GetQuestsManager(); local questTooltip : string = Locale.Lookup("LOC_CITY_STATES_QUESTS"); if (questsManager ~= nil and Game.GetLocalPlayer() ~= nil) then local tradeRouteQuestInfo:table = GameInfo.Quests["QUEST_SEND_TRADE_ROUTE"]; if (tradeRouteQuestInfo ~= nil) then if (questsManager:HasActiveQuestFromPlayer(Game.GetLocalPlayer(), m_destinationCity:GetOwner(), tradeRouteQuestInfo.Index)) then questTooltip = questTooltip .. "[NEWLINE]" .. tradeRouteQuestInfo.IconString .. questsManager:GetActiveQuestName(Game.GetLocalPlayer(), m_destinationCity:GetOwner(), tradeRouteQuestInfo.Index); Controls.CityStateQuestIcon:SetHide(false); -- print("Setting tooltip to " .. questTooltip); Controls.CityStateQuestIcon:SetToolTipString(questTooltip); end end end -- Update turns to complete route local tradePathLength, tripsToDestination, turnsToCompleteRoute = GetRouteInfo(m_originCity, m_destinationCity); Controls.TurnsToComplete:SetColor( frontColor ); Controls.TurnsToComplete:SetText(turnsToCompleteRoute); -- Update Resource Lists local originReceivedResources:boolean = false; local originTooltipText:string = ""; Controls.OriginResourceList:DestroyAllChildren(); for yieldInfo in GameInfo.Yields() do local yieldValue, sourceText = GetYieldForCity(yieldInfo.Index, m_destinationCity, true); if (yieldValue > 0 ) or alignTradeRouteYields then if (originTooltipText ~= "" and (yieldValue > 0)) then originTooltipText = originTooltipText .. "[NEWLINE]"; end originTooltipText = originTooltipText .. sourceText; -- Custom offset because of background texture if (yieldInfo.YieldType == "YIELD_FOOD") then AddResourceEntry(yieldInfo, yieldValue, sourceText, Controls.OriginResourceList, 5); else AddResourceEntry(yieldInfo, yieldValue, sourceText, Controls.OriginResourceList); end originReceivedResources = true; end end Controls.OriginResources:SetToolTipString(originTooltipText); Controls.OriginResourceHeader:SetText(Locale.Lookup("LOC_ROUTECHOOSER_RECEIVES_RESOURCE", Locale.Lookup(m_originCity:GetName()))); Controls.OriginResourceList:ReprocessAnchoring(); if originReceivedResources then Controls.OriginReceivesNoBenefitsLabel:SetHide(true); else Controls.OriginReceivesNoBenefitsLabel:SetHide(false); end local destinationReceivedResources:boolean = false; local destinationTooltipText:string = ""; Controls.DestinationResourceList:DestroyAllChildren(); for yieldInfo in GameInfo.Yields() do local yieldValue, sourceText = GetYieldForCity(yieldInfo.Index, m_destinationCity, false); if (yieldValue > 0 ) or alignTradeRouteYields then if (destinationTooltipText ~= "") then destinationTooltipText = destinationTooltipText .. "[NEWLINE]"; end destinationTooltipText = destinationTooltipText .. sourceText; AddResourceEntry(yieldInfo, yieldValue, sourceText, Controls.DestinationResourceList); if yieldValue > 0 then destinationReceivedResources = true; end end end Controls.DestinationResources:SetToolTipString(destinationTooltipText); Controls.DestinationResourceHeader:SetText(Locale.Lookup("LOC_ROUTECHOOSER_RECEIVES_RESOURCE", Locale.Lookup(m_destinationCity:GetName()))); Controls.DestinationResourceList:ReprocessAnchoring(); if destinationReceivedResources then Controls.DestinationReceivesNoBenefitsLabel:SetHide(true); else Controls.DestinationReceivesNoBenefitsLabel:SetHide(false); end -- Show Panel Controls.CurrentSelectionContainer:SetHide(false); -- Hide Status Message Controls.StatusMessage:SetHide(true); else -- Hide Panel Controls.CurrentSelectionContainer:SetHide(true); -- Show Status Message Controls.StatusMessage:SetHide(false); end end function RefreshChooserPanel() local tradeManager:table = Game.GetTradeManager(); -- Reset Destinations m_unfilteredDestinations = {}; local players:table = Game:GetPlayers(); for i, player in ipairs(players) do local cities:table = player:GetCities(); for j, city in cities:Members() do -- Can we start a trade route with this city? if tradeManager:CanStartRoute(m_originCity:GetOwner(), m_originCity:GetID(), city:GetOwner(), city:GetID()) then table.insert(m_unfilteredDestinations, city); end end end -- Update Filters RefreshFilters(); -- Update Destination Choice Stack RefreshStack(); -- Send Trade Route Paths to Engine UILens.ClearLayerHexes( LensLayers.TRADE_ROUTE ); local pathPlots : table = {}; for index, city in ipairs(m_filteredDestinations) do pathPlots = tradeManager:GetTradeRoutePath(m_originCity:GetOwner(), m_originCity:GetID(), city:GetOwner(), city:GetID() ); local kVariations:table = {}; local lastElement : number = table.count(pathPlots); table.insert(kVariations, {"TradeRoute_Destination", pathPlots[lastElement]} ); UILens.SetLayerHexesPath( LensLayers.TRADE_ROUTE, Game.GetLocalPlayer(), pathPlots, kVariations ); end end -- =========================================================================== -- Routes stack Function -- =========================================================================== function RefreshStack() local tradeManager:table = Game.GetTradeManager(); local tradeRoutes = {} -- Filter Destinations by active Filter if m_filterList[m_filterSelected].FilterFunction ~= nil then m_filterList[m_filterSelected].FilterFunction(); else m_filteredDestinations = m_unfilteredDestinations; end -- Create trade routes to be sorted for index, city in ipairs(m_filteredDestinations) do local tradeRoute = { OriginCityPlayer = m_originCity:GetOwner(), OriginCityID = m_originCity:GetID(), DestinationCityPlayer = city:GetOwner(), DestinationCityID = city:GetID() }; table.insert(tradeRoutes, tradeRoute) end SortTradeRoutes( tradeRoutes, m_SortBySettings ); -- Add Destinations to Stack m_RouteChoiceIM:ResetInstances(); local numberOfDestinations:number = 0; for index, tradeRoute in ipairs(tradeRoutes) do -- print("Adding route: " .. getTradeRouteString( tradeRoute )) local destinationPlayer:table = Players[tradeRoute.DestinationCityPlayer]; local destinationCity:table = destinationPlayer:GetCities():FindID(tradeRoute.DestinationCityID); AddCityToDestinationStack(destinationCity); numberOfDestinations = numberOfDestinations + 1; end Controls.RouteChoiceStack:CalculateSize(); Controls.RouteChoiceScrollPanel:CalculateSize(); -- Adjust offset to center destination scrollpanel/stack if Controls.RouteChoiceScrollPanel:GetScrollBar():IsHidden() then Controls.RouteChoiceScrollPanel:SetOffsetX(5); else Controls.RouteChoiceScrollPanel:SetOffsetX(13); end -- Show No Available Trade Routes message if nothing to select if numberOfDestinations > 0 then Controls.StatusMessage:SetText(Locale.Lookup("LOC_ROUTECHOOSER_SELECT_DESTINATION")); else Controls.StatusMessage:SetText(Locale.Lookup("LOC_ROUTECHOOSER_NO_TRADE_ROUTES")); end end function AddCityToDestinationStack(city:table) local cityEntry:table = m_RouteChoiceIM:GetInstance(); -- Update Selector Brace if m_destinationCity ~= nil and city:GetName() == m_destinationCity:GetName() then cityEntry.SelectorBrace:SetHide(false); else cityEntry.SelectorBrace:SetHide(true); end -- Setup city banner cityEntry.CityName:SetText(Locale.ToUpper(city:GetName())); local backColor:number, frontColor:number = UI.GetPlayerColors( city:GetOwner() ); local darkerBackColor:number = DarkenLightenColor(backColor,(-85),238); local brighterBackColor:number = DarkenLightenColor(backColor,90,255); cityEntry.BannerBase:SetColor( backColor ); cityEntry.BannerDarker:SetColor( darkerBackColor ); cityEntry.BannerLighter:SetColor( brighterBackColor ); cityEntry.CityName:SetColor( frontColor ); cityEntry.TradingPostIcon:SetColor( frontColor ); -- Update Trading Post Icon if city:GetTrade():HasActiveTradingPost(m_originCity:GetOwner()) then cityEntry.TradingPostIcon:SetHide(false); else cityEntry.TradingPostIcon:SetHide(true); end -- Update City-State Quest Icon cityEntry.CityStateQuestIcon:SetHide(true); local questsManager : table = Game.GetQuestsManager(); local questTooltip : string = Locale.Lookup("LOC_CITY_STATES_QUESTS"); if (questsManager ~= nil and Game.GetLocalPlayer() ~= nil) then local tradeRouteQuestInfo:table = GameInfo.Quests["QUEST_SEND_TRADE_ROUTE"]; if (tradeRouteQuestInfo ~= nil) then if (questsManager:HasActiveQuestFromPlayer(Game.GetLocalPlayer(), city:GetOwner(), tradeRouteQuestInfo.Index)) then questTooltip = questTooltip .. "[NEWLINE]" .. tradeRouteQuestInfo.IconString .. questsManager:GetActiveQuestName(Game.GetLocalPlayer(), city:GetOwner(), tradeRouteQuestInfo.Index); cityEntry.CityStateQuestIcon:SetHide(false); cityEntry.CityStateQuestIcon:SetToolTipString(questTooltip); end end end -- Update turns to complete route local tradePathLength, tripsToDestination, turnsToCompleteRoute = GetRouteInfo(m_originCity, city); local tooltipString = ( "Total amount of[ICON_Turn]to complete this trade route[NEWLINE]" .. "--------------------------------------------------------[NEWLINE]" .. "Trade Route[ICON_Movement]: " .. tradePathLength .. "[NEWLINE]" .. "Trips to destination: " .. tripsToDestination .. "[NEWLINE]" .. "If started, route will complete in[ICON_Turn]: " .. Game.GetCurrentGameTurn() + turnsToCompleteRoute); cityEntry.TurnsToComplete:SetText(turnsToCompleteRoute); cityEntry.TurnsToComplete:SetToolTipString( tooltipString ); cityEntry.TurnsToComplete:SetColor( frontColor ); -- Setup resources local tooltipText = ""; cityEntry.ResourceList:DestroyAllChildren(); for yieldInfo in GameInfo.Yields() do local yieldValue, sourceText = GetYieldForCity(yieldInfo.Index, city, true); if (yieldValue > 0 ) or alignTradeRouteYields then if (tooltipText ~= "" and yieldValue > 0) then tooltipText = tooltipText .. "[NEWLINE]"; end tooltipText = tooltipText .. sourceText; AddResourceEntry(yieldInfo, yieldValue, sourceText, cityEntry.ResourceList); end end cityEntry.Button:SetToolTipString(tooltipText); -- Setup callback cityEntry.Button:SetVoids(city:GetOwner(), city:GetID()); cityEntry.Button:RegisterCallback( Mouse.eLClick, OnTradeRouteSelected ); -- Process Anchoring cityEntry.ResourceList:ReprocessAnchoring(); end function AddResourceEntry(yieldInfo:table, yieldValue:number, sourceText:string, stackControl:table, customOffset) local entryInstance:table = {}; ContextPtr:BuildInstanceForControl( "ResourceEntryInstance", entryInstance, stackControl ); local icon:string, text:string = FormatYieldText(yieldInfo, yieldValue); if yieldValue > 0 then entryInstance.ResourceEntryIcon:SetText(icon); entryInstance.ResourceEntryText:SetText(text); if (customOffset) then entryInstance.ResourceEntryIcon:SetOffsetX(customOffset); entryInstance.ResourceEntryText:SetOffsetX(customOffset); end -- Update text Color if (yieldInfo.YieldType == "YIELD_FOOD") then entryInstance.ResourceEntryText:SetColorByName("ResFoodLabelCS"); elseif (yieldInfo.YieldType == "YIELD_PRODUCTION") then entryInstance.ResourceEntryText:SetColorByName("ResProductionLabelCS"); elseif (yieldInfo.YieldType == "YIELD_GOLD") then entryInstance.ResourceEntryText:SetColorByName("ResGoldLabelCS"); elseif (yieldInfo.YieldType == "YIELD_SCIENCE") then entryInstance.ResourceEntryText:SetColorByName("ResScienceLabelCS"); elseif (yieldInfo.YieldType == "YIELD_CULTURE") then entryInstance.ResourceEntryText:SetColorByName("ResCultureLabelCS"); elseif (yieldInfo.YieldType == "YIELD_FAITH") then entryInstance.ResourceEntryText:SetColorByName("ResFaithLabelCS"); end else entryInstance.ResourceEntryIcon:SetHide(true); entryInstance.ResourceEntryText:SetHide(true); end end -- =========================================================================== -- Filter functions -- =========================================================================== function RefreshFilters() local tradeManager:table = Game.GetTradeManager(); -- Clear entries Controls.DestinationFilterPulldown:ClearEntries(); m_filterList = {}; m_filterCount = 0; -- Add All Filter AddFilter(Locale.Lookup("LOC_ROUTECHOOSER_FILTER_ALL"), nil); -- Add "International Routes" Filter AddFilter(Locale.Lookup("LOC_TRADE_FILTER_INTERNATIONAL_ROUTES_TEXT") , FilterByInternational); -- Add "City States with Trade Quest" Filter AddFilter(Locale.Lookup("LOC_TRADE_FILTER_CS_WITH_QUEST_TOOLTIP"), FilterByCityStatesWithTradeQuest); -- Add Filters by Civ for index, city in ipairs(m_unfilteredDestinations) do if not IsCityState(Players[city:GetOwner()]) then local playerConfig:table = PlayerConfigurations[city:GetOwner()]; local name = Locale.Lookup(GameInfo.Civilizations[playerConfig:GetCivilizationTypeID()].Name); AddFilter(name, function() FilterByCiv(playerConfig:GetCivilizationTypeID()) end); end end -- Add City State Filter for index, city in ipairs(m_unfilteredDestinations) do local pPlayerInfluence:table = Players[city:GetOwner()]:GetInfluence(); if pPlayerInfluence:CanReceiveInfluence() then -- If the city's owner can receive influence then it is a city state so add the city state filter AddFilter(Locale.Lookup("LOC_ROUTECHOOSER_FILTER_CITYSTATES"), FilterByCityStates); break; end end --[[ -- Add Filters by Resource for index, city in ipairs(m_unfilteredDestinations) do for yieldInfo in GameInfo.Yields() do local yieldValue = GetYieldForCity(yieldInfo.Index, city, true); if (yieldValue ~= 0 ) then AddFilter(Locale.Lookup(yieldInfo.Name), function() FilterByResource(yieldInfo.Index) end); end end end --]] -- Add filters to pulldown for index, filter in ipairs(m_filterList) do AddFilterEntry(index); end -- Select first filter Controls.FilterButton:SetText(m_filterList[m_filterSelected].FilterText); -- Calculate Internals Controls.DestinationFilterPulldown:CalculateInternals(); UpdateFilterArrow(); end function AddFilter(filterName:string, filterFunction) -- Make sure we don't add duplicate filters for index, filter in ipairs(m_filterList) do if filter.FilterText == filterName then return; end end m_filterCount = m_filterCount + 1; m_filterList[m_filterCount] = {FilterText=filterName, FilterFunction=filterFunction}; end function AddFilterEntry(filterIndex:number) local filterEntry:table = {}; Controls.DestinationFilterPulldown:BuildEntry( "FilterEntry", filterEntry ); filterEntry.Button:SetText(m_filterList[filterIndex].FilterText); filterEntry.Button:SetVoids(i, filterIndex); end function OnFilterSelected(index:number, filterIndex:number) m_filterSelected = filterIndex; Controls.FilterButton:SetText(m_filterList[m_filterSelected].FilterText); Refresh(); end function FilterByInternational() -- Clear Filter m_filteredDestinations = {}; -- Filter by Yield Index for index, city in ipairs(m_unfilteredDestinations) do local player:table = Players[city:GetOwner()]; if player:GetID() ~= Game.GetLocalPlayer() then table.insert(m_filteredDestinations, city); end end end function FilterByCiv(civTypeID:number) -- Clear Filter m_filteredDestinations = {}; -- Filter by Civ Type ID for index, city in ipairs(m_unfilteredDestinations) do local playerConfig:table = PlayerConfigurations[city:GetOwner()]; if playerConfig:GetCivilizationTypeID() == civTypeID then table.insert(m_filteredDestinations, city); end end end function FilterByResource(yieldIndex:number) -- Clear Filter m_filteredDestinations = {}; -- Filter by Yield Index for index, city in ipairs(m_unfilteredDestinations) do local yieldValue = GetYieldForCity(yieldIndex, city, true); if (yieldValue ~= 0 ) then table.insert(m_filteredDestinations, city); end end end function FilterByCityStates() -- Clear Filter m_filteredDestinations = {}; -- Filter only cities which aren't full civs meaning they're city-states for index, city in ipairs(m_unfilteredDestinations) do local playerConfig:table = PlayerConfigurations[city:GetOwner()]; if playerConfig:GetCivilizationLevelTypeID() ~= CivilizationLevelTypes.CIVILIZATION_LEVEL_FULL_CIV then table.insert(m_filteredDestinations, city); end end end function FilterByCityStatesWithTradeQuest() -- Clear Filter m_filteredDestinations = {}; -- Filter only cities which aren't full civs meaning they're city-states for index, city in ipairs(m_unfilteredDestinations) do local player:table = Players[city:GetOwner()]; if (IsCityStateWithTradeQuest( player )) then table.insert(m_filteredDestinations, city); end end end -- =========================================================================== -- Trade Routes Sorter -- =========================================================================== function SortTradeRoutes( tradeRoutes:table, sortSettings:table ) if tableLength(m_SortBySettings) > 0 then table.sort(tradeRoutes, function(a, b) return CompleteCompareBy(a, b, sortSettings); end ) end end function InsertSortEntry( sortByID:number, sortOrder:number, sortSettings:table ) local sortEntry = { SortByID = sortByID, SortOrder = sortOrder }; -- Only insert if it does not exist local sortEntryIndex = findIndex (sortSettings, sortEntry, CompareSortEntries); if sortEntryIndex == -1 then -- print("Inserting " .. sortEntry.SortByID); table.insert(sortSettings, sortEntry); else -- If it exists, just update the sort oder -- print("Index: " .. sortEntryIndex); sortSettings[sortEntryIndex].SortOrder = sortOrder; end end function RemoveSortEntry( sortByID:number, sortSettings:table ) local sortEntry = { SortByID = sortByID, SortOrder = sortOrder }; -- Only delete if it exists local sortEntryIndex:number = findIndex(sortSettings, sortEntry, CompareSortEntries); if (sortEntryIndex > 0) then table.remove(sortSettings, sortEntryIndex); end end -- --------------------------------------------------------------------------- -- Compare functions -- --------------------------------------------------------------------------- -- Checks for the same ID, not the same order function CompareSortEntries( sortEntry1:table, sortEntry2:table) if sortEntry1.SortByID == sortEntry2.SortByID then return true; end return false; end -- Uses the list of compare functions, to make one global compare function function CompleteCompareBy( tradeRoute1:table, tradeRoute2:table, sortSettings:table ) for index, sortEntry in ipairs(sortSettings) do local compareFunction = m_CompareFunctionByID[sortEntry.SortByID]; local compareResult:boolean = compareFunction(tradeRoute1, tradeRoute2); if compareResult then if (sortEntry.SortOrder == SORT_DESCENDING) then return false; else return true; end elseif not CheckEquality( tradeRoute1, tradeRoute2, compareFunction ) then if (sortEntry.SortOrder == SORT_DESCENDING) then return true; else return false; end end end -- If it reaches here, we used all the settings, and all of them were equal. -- Do net yield compare. 'not' because order should be in descending return CompareByNetYield(tradeRoute1, tradeRoute2); end function CompareByFood( tradeRoute1:table, tradeRoute2:table ) return CompareByYield (GameInfo.Yields["YIELD_FOOD"].Index, tradeRoute1, tradeRoute2); end function CompareByProduction( tradeRoute1:table, tradeRoute2:table ) return CompareByYield (GameInfo.Yields["YIELD_PRODUCTION"].Index, tradeRoute1, tradeRoute2); end function CompareByGold( tradeRoute1:table, tradeRoute2:table ) return CompareByYield (GameInfo.Yields["YIELD_GOLD"].Index, tradeRoute1, tradeRoute2); end function CompareByScience( tradeRoute1:table, tradeRoute2:table ) return CompareByYield (GameInfo.Yields["YIELD_SCIENCE"].Index, tradeRoute1, tradeRoute2); end function CompareByCulture( tradeRoute1:table, tradeRoute2:table ) return CompareByYield (GameInfo.Yields["YIELD_CULTURE"].Index, tradeRoute1, tradeRoute2); end function CompareByFaith( tradeRoute1:table, tradeRoute2:table ) return CompareByYield (GameInfo.Yields["YIELD_FAITH"].Index, tradeRoute1, tradeRoute2); end function CompareByYield( yieldIndex:number, tradeRoute1:table, tradeRoute2:table ) local originPlayer1:table = Players[tradeRoute1.OriginCityPlayer]; local destinationPlayer1:table = Players[tradeRoute1.DestinationCityPlayer]; local originCity1:table = originPlayer1:GetCities():FindID(tradeRoute1.OriginCityID); local destinationCity1:table = destinationPlayer1:GetCities():FindID(tradeRoute1.DestinationCityID); local originPlayer2:table = Players[tradeRoute2.OriginCityPlayer]; local destinationPlayer2:table = Players[tradeRoute2.DestinationCityPlayer]; local originCity2:table = originPlayer2:GetCities():FindID(tradeRoute2.OriginCityID); local destinationCity2:table = destinationPlayer2:GetCities():FindID(tradeRoute2.DestinationCityID); local yieldForRoute1 = GetYieldFromCity(yieldIndex, originCity1, destinationCity1); local yieldForRoute2 = GetYieldFromCity(yieldIndex, originCity2, destinationCity2); return yieldForRoute1 < yieldForRoute2; end function CompareByTurnsToComplete( tradeRoute1:table, tradeRoute2:table ) local originPlayer1:table = Players[tradeRoute1.OriginCityPlayer]; local destinationPlayer1:table = Players[tradeRoute1.DestinationCityPlayer]; local originCity1:table = originPlayer1:GetCities():FindID(tradeRoute1.OriginCityID); local destinationCity1:table = destinationPlayer1:GetCities():FindID(tradeRoute1.DestinationCityID); local originPlayer2:table = Players[tradeRoute2.OriginCityPlayer]; local destinationPlayer2:table = Players[tradeRoute2.DestinationCityPlayer]; local originCity2:table = originPlayer2:GetCities():FindID(tradeRoute2.OriginCityID); local destinationCity2:table = destinationPlayer2:GetCities():FindID(tradeRoute2.DestinationCityID); local tradePathLength1, tripsToDestination1, turnsToCompleteRoute1 = GetRouteInfo(originCity1, destinationCity1); local tradePathLength2, tripsToDestination2, turnsToCompleteRoute2 = GetRouteInfo(originCity2, destinationCity2); return turnsToCompleteRoute1 < turnsToCompleteRoute2; end function CompareByNetYield( tradeRoute1:table, tradeRoute2:table ) local originPlayer1:table = Players[tradeRoute1.OriginCityPlayer]; local destinationPlayer1:table = Players[tradeRoute1.DestinationCityPlayer]; local originCity1:table = originPlayer1:GetCities():FindID(tradeRoute1.OriginCityID); local destinationCity1:table = destinationPlayer1:GetCities():FindID(tradeRoute1.DestinationCityID); local originPlayer2:table = Players[tradeRoute2.OriginCityPlayer]; local destinationPlayer2:table = Players[tradeRoute2.DestinationCityPlayer]; local originCity2:table = originPlayer2:GetCities():FindID(tradeRoute2.OriginCityID); local destinationCity2:table = destinationPlayer2:GetCities():FindID(tradeRoute2.DestinationCityID); local yieldForRoute1:number = 0; local yieldForRoute2:number = 0; for yieldInfo in GameInfo.Yields() do yieldForRoute1 = yieldForRoute1 + GetYieldFromCity(yieldInfo.Index, originCity1, destinationCity1); yieldForRoute2 = yieldForRoute2 + GetYieldFromCity(yieldInfo.Index, originCity2, destinationCity2); end -- Flipped comparison because it should be descending return yieldForRoute1 > yieldForRoute2; end -- =========================================================================== -- Sort bar functions -- =========================================================================== -- Hides all the ascending/descending arrows function ResetSortBar() Controls.FoodDescArrow:SetHide(true); Controls.ProductionDescArrow:SetHide(true); Controls.GoldDescArrow:SetHide(true); Controls.ScienceDescArrow:SetHide(true); Controls.CultureDescArrow:SetHide(true); Controls.FaithDescArrow:SetHide(true); Controls.TurnsToCompleteDescArrow:SetHide(true); Controls.FoodAscArrow:SetHide(true); Controls.ProductionAscArrow:SetHide(true); Controls.GoldAscArrow:SetHide(true); Controls.ScienceAscArrow:SetHide(true); Controls.CultureAscArrow:SetHide(true); Controls.FaithAscArrow:SetHide(true); Controls.TurnsToCompleteAscArrow:SetHide(true); end function RefreshSortBar() RefreshSortButtons( m_SortBySettings ); if showSortOrdersPermanently or m_shiftDown then -- Hide the order texts HideSortOrderLabels(); -- Show them based on current settings ShowSortOrderLabels(); end end function ShowSortOrderLabels() -- Refresh and show sort orders RefreshSortOrderLabels( m_SortBySettings ); end function HideSortOrderLabels() Controls.FoodSortOrder:SetHide(true); Controls.ProductionSortOrder:SetHide(true); Controls.GoldSortOrder:SetHide(true); Controls.ScienceSortOrder:SetHide(true); Controls.CultureSortOrder:SetHide(true); Controls.FaithSortOrder:SetHide(true); Controls.TurnsToCompleteSortOrder:SetHide(true); end -- Shows and hides arrows based on the passed sort order function SetSortArrow( ascArrow:table, descArrow:table, sortOrder:number ) if sortOrder == SORT_ASCENDING then descArrow:SetHide(true); ascArrow:SetHide(false); else descArrow:SetHide(false); ascArrow:SetHide(true); end end function RefreshSortButtons( sortSettings:table ) -- Hide all arrows ResetSortBar(); -- Set disabled color Controls.FoodSortButton:SetColorByName("ButtonDisabledCS"); Controls.ProductionSortButton:SetColorByName("ButtonDisabledCS"); Controls.GoldSortButton:SetColorByName("ButtonDisabledCS"); Controls.ScienceSortButton:SetColorByName("ButtonDisabledCS"); Controls.CultureSortButton:SetColorByName("ButtonDisabledCS"); Controls.FaithSortButton:SetColorByName("ButtonDisabledCS"); Controls.TurnsToCompleteSortButton:SetColorByName("ButtonDisabledCS"); -- Go through settings and display arrows for index, sortEntry in ipairs(sortSettings) do if sortEntry.SortByID == SORT_BY_ID.FOOD then SetSortArrow(Controls.FoodAscArrow, Controls.FoodDescArrow, sortEntry.SortOrder) Controls.FoodSortButton:SetColorByName("ButtonCS"); elseif sortEntry.SortByID == SORT_BY_ID.PRODUCTION then SetSortArrow(Controls.ProductionAscArrow, Controls.ProductionDescArrow, sortEntry.SortOrder) Controls.ProductionSortButton:SetColorByName("ButtonCS"); elseif sortEntry.SortByID == SORT_BY_ID.GOLD then SetSortArrow(Controls.GoldAscArrow, Controls.GoldDescArrow, sortEntry.SortOrder) Controls.GoldSortButton:SetColorByName("ButtonCS"); elseif sortEntry.SortByID == SORT_BY_ID.SCIENCE then SetSortArrow(Controls.ScienceAscArrow, Controls.ScienceDescArrow, sortEntry.SortOrder) Controls.ScienceSortButton:SetColorByName("ButtonCS"); elseif sortEntry.SortByID == SORT_BY_ID.CULTURE then SetSortArrow(Controls.CultureAscArrow, Controls.CultureDescArrow, sortEntry.SortOrder) Controls.CultureSortButton:SetColorByName("ButtonCS"); elseif sortEntry.SortByID == SORT_BY_ID.FAITH then SetSortArrow(Controls.FaithAscArrow, Controls.FaithDescArrow, sortEntry.SortOrder) Controls.FaithSortButton:SetColorByName("ButtonCS"); elseif sortEntry.SortByID == SORT_BY_ID.TURNS_TO_COMPLETE then SetSortArrow(Controls.TurnsToCompleteAscArrow, Controls.TurnsToCompleteDescArrow, sortEntry.SortOrder) Controls.TurnsToCompleteSortButton:SetColorByName("ButtonCS"); end end end function RefreshSortOrderLabels( sortSettings:table ) for index, sortEntry in ipairs(sortSettings) do if sortEntry.SortByID == SORT_BY_ID.FOOD then Controls.FoodSortOrder:SetHide(false); Controls.FoodSortOrder:SetText(index); Controls.FoodSortOrder:SetColorByName("ResFoodLabelCS"); elseif sortEntry.SortByID == SORT_BY_ID.PRODUCTION then Controls.ProductionSortOrder:SetHide(false); Controls.ProductionSortOrder:SetText(index); Controls.ProductionSortOrder:SetColorByName("ResProductionLabelCS"); elseif sortEntry.SortByID == SORT_BY_ID.GOLD then Controls.GoldSortOrder:SetHide(false); Controls.GoldSortOrder:SetText(index); Controls.GoldSortOrder:SetColorByName("ResGoldLabelCS"); elseif sortEntry.SortByID == SORT_BY_ID.SCIENCE then Controls.ScienceSortOrder:SetHide(false); Controls.ScienceSortOrder:SetText(index); Controls.ScienceSortOrder:SetColorByName("ResScienceLabelCS"); elseif sortEntry.SortByID == SORT_BY_ID.CULTURE then Controls.CultureSortOrder:SetHide(false); Controls.CultureSortOrder:SetText(index); Controls.CultureSortOrder:SetColorByName("ResCultureLabelCS"); elseif sortEntry.SortByID == SORT_BY_ID.FAITH then Controls.FaithSortOrder:SetHide(false); Controls.FaithSortOrder:SetText(index); Controls.FaithSortOrder:SetColorByName("ResFaithLabelCS"); elseif sortEntry.SortByID == SORT_BY_ID.TURNS_TO_COMPLETE then Controls.TurnsToCompleteSortOrder:SetHide(false); Controls.TurnsToCompleteSortOrder:SetText(index); end end end -- =========================================================================== -- General Helper functions -- =========================================================================== function FormatYieldText(yieldInfo, yieldAmount) local text:string = ""; local iconString = ""; if (yieldInfo.YieldType == "YIELD_FOOD") then iconString = "[ICON_Food]"; elseif (yieldInfo.YieldType == "YIELD_PRODUCTION") then iconString = "[ICON_Production]"; elseif (yieldInfo.YieldType == "YIELD_GOLD") then iconString = "[ICON_Gold]"; elseif (yieldInfo.YieldType == "YIELD_SCIENCE") then iconString = "[ICON_Science]"; elseif (yieldInfo.YieldType == "YIELD_CULTURE") then iconString = "[ICON_Culture]"; elseif (yieldInfo.YieldType == "YIELD_FAITH") then iconString = "[ICON_Faith]"; end if (yieldAmount >= 0) then text = text .. "+"; end text = text .. yieldAmount; return iconString, text; end function tableLength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end function reverseTable(T) table_length = tableLength(T); for i=1, math.floor(table_length / 2) do local tmp = T[i] T[i] = T[table_length - i + 1] T[table_length - i + 1] = tmp end end function findIndex(T, searchItem, compareFunc) for index, item in ipairs(T) do if compareFunc(item, searchItem) then return index; end end return -1; end -- Checks if the player is a civ, other than the local player function IsOtherCiv( player:table ) if player:GetID() ~= Game.GetLocalPlayer() then return true end return false end function IsCityState( player:table ) local playerInfluence:table = player:GetInfluence(); if playerInfluence:CanReceiveInfluence() then return true end return false end function IsCityStateWithTradeQuest( player:table ) local questsManager : table = Game.GetQuestsManager(); local questTooltip : string = Locale.Lookup("LOC_CITY_STATES_QUESTS"); if (questsManager ~= nil and Game.GetLocalPlayer() ~= nil) then local tradeRouteQuestInfo:table = GameInfo.Quests["QUEST_SEND_TRADE_ROUTE"]; if (tradeRouteQuestInfo ~= nil) then if (questsManager:HasActiveQuestFromPlayer(Game.GetLocalPlayer(), player:GetID(), tradeRouteQuestInfo.Index)) then return true end end end return false end -- --------------------------------------------------------------------------- -- Trade route helper functions -- --------------------------------------------------------------------------- function RenewTradeRoutes() local renewedRoute:boolean = false; local pPlayerUnits:table = Players[Game.GetLocalPlayer()]:GetUnits(); for i, pUnit in pPlayerUnits:Members() do -- Find Each Trade Unit local unitInfo:table = GameInfo.Units[pUnit:GetUnitType()]; local unitID:number = pUnit:GetID(); if unitInfo.MakeTradeRoute == true and m_TraderAutomated[unitID] then -- Ignore trade units that have a pending operation if not pUnit:HasPendingOperations() then local destinationCity:table = nil; local tradeManager:table = Game.GetTradeManager(); local originCity:table = Cities.GetCityInPlot(pUnit:GetX(), pUnit:GetY()); if m_TraderAutomatedSettings[unitID] ~= nil and tableLength(m_TraderAutomatedSettings[unitID]) > 0 then local tradeRoutes:table = {}; local players:table = Game:GetPlayers(); -- Build list of trade routes for i, player in ipairs(players) do local cities:table = player:GetCities(); for j, city in cities:Members() do -- Can we start a trade route with this city? if tradeManager:CanStartRoute(originCity:GetOwner(), originCity:GetID(), city:GetOwner(), city:GetID()) then local tradeRoute = { OriginCityPlayer = originCity:GetOwner(), OriginCityID = originCity:GetID(), DestinationCityPlayer = city:GetOwner(), DestinationCityID = city:GetID() }; table.insert(tradeRoutes, tradeRoute); end end end -- Sort them based on the settings saved when the route was begun SortTradeRoutes( tradeRoutes, m_TraderAutomatedSettings[unitID] ); -- Get destination based on the top entry local destinationPlayer:table = Players[tradeRoutes[1].DestinationCityPlayer]; destinationCity = destinationPlayer:GetCities():FindID(tradeRoutes[1].DestinationCityID); elseif m_LastRouteForTrader[unitID] ~= nil then local destinationPlayer:table = Players[m_LastRouteForTrader[unitID].DestinationCityPlayer]; destinationCity = destinationPlayer:GetCities():FindID(m_LastRouteForTrader[unitID].DestinationCityID); end if destinationCity ~= nil and tradeManager:CanStartRoute(originCity:GetOwner(), originCity:GetID(), destinationCity:GetOwner(), destinationCity:GetID()) then local operationParams = {}; operationParams[UnitOperationTypes.PARAM_X0] = destinationCity:GetX(); operationParams[UnitOperationTypes.PARAM_Y0] = destinationCity:GetY(); operationParams[UnitOperationTypes.PARAM_X1] = originCity:GetX(); operationParams[UnitOperationTypes.PARAM_Y1] = originCity:GetY(); if (UnitManager.CanStartOperation(pUnit, UnitOperationTypes.MAKE_TRADE_ROUTE, nil, operationParams)) then -- print("Trader " .. unitID .. " renewed its trade route: " .. GetTradeRouteString(m_LastRouteForTrader[unitID])) -- TODO: Send notification for renewing routes UnitManager.RequestOperation(pUnit, UnitOperationTypes.MAKE_TRADE_ROUTE, operationParams); if not renewedRoute then renewedRoute = true; end else -- print("Could not start a route"); end else -- print("Could not renew a route. Missing route info, or the destination is no longer a valid trade route destination."); end end end end -- Play sound, if a route was renewed. if renewedRoute then UI.PlaySound("START_TRADE_ROUTE"); end end function SetLastRouteForTrader( routeInfo:table ) m_LastRouteForTrader[routeInfo.TraderUnitID] = routeInfo; end function SetTraderAutomated( traderID:number, isAutomated:boolean ) m_TraderAutomated[traderID] = isAutomated; if (not isAutomated) then m_TraderAutomatedSettings[traderID] = nil; end end function TradeRouteSelected( cityOwner:number, cityID:number ) local player:table = Players[cityOwner]; if player then local pCity:table = player:GetCities():FindID(cityID); if pCity then m_destinationCity = pCity; else error("Unable to find city '"..tostring(cityID).."' for creating a trade route."); end end Refresh(); end function GetYieldForCity(yieldIndex:number, city:table, originCity:boolean) local tradeManager = Game.GetTradeManager(); local yieldInfo = GameInfo.Yields[yieldIndex]; local totalValue = 0; local partialValue = 0; local sourceText = ""; -- From route if (originCity) then partialValue = tradeManager:CalculateOriginYieldFromPotentialRoute(m_originCity:GetOwner(), m_originCity:GetID(), city:GetOwner(), city:GetID(), yieldIndex); else partialValue = tradeManager:CalculateDestinationYieldFromPotentialRoute(m_originCity:GetOwner(), m_originCity:GetID(), city:GetOwner(), city:GetID(), yieldIndex); end totalValue = totalValue + partialValue; if (partialValue > 0 and yieldInfo ~= nil) then if (sourceText ~= "") then sourceText = sourceText .. "[NEWLINE]"; end sourceText = sourceText .. Locale.Lookup("LOC_ROUTECHOOSER_YIELD_SOURCE_DISTRICTS", partialValue, yieldInfo.IconString, yieldInfo.Name, city:GetName()); end -- From path if (originCity) then partialValue = tradeManager:CalculateOriginYieldFromPath(m_originCity:GetOwner(), m_originCity:GetID(), city:GetOwner(), city:GetID(), yieldIndex); else partialValue = tradeManager:CalculateDestinationYieldFromPath(m_originCity:GetOwner(), m_originCity:GetID(), city:GetOwner(), city:GetID(), yieldIndex); end totalValue = totalValue + partialValue; if (partialValue > 0 and yieldInfo ~= nil) then if (sourceText ~= "") then sourceText = sourceText .. "[NEWLINE]"; end sourceText = sourceText .. Locale.Lookup("LOC_ROUTECHOOSER_YIELD_SOURCE_TRADING_POSTS", partialValue, yieldInfo.IconString, yieldInfo.Name); end -- From modifiers local resourceID = -1; if (originCity) then partialValue = tradeManager:CalculateOriginYieldFromModifiers(m_originCity:GetOwner(), m_originCity:GetID(), city:GetOwner(), city:GetID(), yieldIndex, resourceID); else partialValue = tradeManager:CalculateDestinationYieldFromModifiers(m_originCity:GetOwner(), m_originCity:GetID(), city:GetOwner(), city:GetID(), yieldIndex, resourceID); end totalValue = totalValue + partialValue; if (partialValue > 0 and yieldInfo ~= nil) then if (sourceText ~= "") then sourceText = sourceText .. "[NEWLINE]"; end sourceText = sourceText .. Locale.Lookup("LOC_ROUTECHOOSER_YIELD_SOURCE_BONUSES", partialValue, yieldInfo.IconString, yieldInfo.Name); end return totalValue, sourceText; end -- Returns yield for the origin city function GetYieldFromCity( yieldIndex:number, originCity:table, destinationCity:table ) local tradeManager = Game.GetTradeManager(); -- From route local yieldValue = tradeManager:CalculateOriginYieldFromPotentialRoute(originCity:GetOwner(), originCity:GetID(), destinationCity:GetOwner(), destinationCity:GetID(), yieldIndex); -- From path yieldValue = yieldValue + tradeManager:CalculateOriginYieldFromPath(originCity:GetOwner(), originCity:GetID(), destinationCity:GetOwner(), destinationCity:GetID(), yieldIndex); -- From modifiers local resourceID = -1; yieldValue = yieldValue + tradeManager:CalculateOriginYieldFromModifiers(originCity:GetOwner(), originCity:GetID(), destinationCity:GetOwner(), destinationCity:GetID(), yieldIndex, resourceID); return yieldValue; end -- Returns length of trade path, number of trips to destination, turns to complete route function GetRouteInfo(originCity:table, destinationCity:table) local eSpeed = GameConfiguration.GetGameSpeedType(); if GameInfo.GameSpeeds[eSpeed] ~= nil then local iSpeedCostMultiplier = GameInfo.GameSpeeds[eSpeed].CostMultiplier; local tradeManager = Game.GetTradeManager(); local pathPlots = tradeManager:GetTradeRoutePath(originCity:GetOwner(), originCity:GetID(), destinationCity:GetOwner(), destinationCity:GetID() ); local tradePathLength:number = tableLength(pathPlots) - 1; local multiplierConstant:number = 0.1; local tripsToDestination = 1 + math.floor(iSpeedCostMultiplier/tradePathLength * multiplierConstant); --print("Error: Playing on an unrecognized speed. Defaulting to standard for route turns calculation"); local turnsToCompleteRoute = (tradePathLength * 2 * tripsToDestination); return tradePathLength, tripsToDestination, turnsToCompleteRoute; else -- print("Speed type index " .. eSpeed); -- print("Error: Could not find game speed type. Defaulting to first entry in table"); local iSpeedCostMultiplier = GameInfo.GameSpeeds[1].CostMultiplier; local tradeManager = Game.GetTradeManager(); local pathPlots = tradeManager:GetTradeRoutePath(originCity:GetOwner(), originCity:GetID(), destinationCity:GetOwner(), destinationCity:GetID() ); local tradePathLength:number = tableLength(pathPlots) - 1; local multiplierConstant:number = 0.1; local tripsToDestination = 1 + math.floor(iSpeedCostMultiplier/tradePathLength * multiplierConstant); local turnsToCompleteRoute = (tradePathLength * 2 * tripsToDestination); return tradePathLength, tripsToDestination, turnsToCompleteRoute; end end function GetTradeRouteString( tradeRoute:table ) local originPlayer:table = Players[tradeRoute.OriginCityPlayer]; local originCity:table = originPlayer:GetCities():FindID(tradeRoute.OriginCityID); local destinationPlayer:table = Players[tradeRoute.DestinationCityPlayer]; local destinationCity:table = destinationPlayer:GetCities():FindID(tradeRoute.DestinationCityID); local s:string = Locale.Lookup(originCity:GetName()) .. "-" .. Locale.Lookup(destinationCity:GetName()) return s; end -- Checks equality with the passed sorting compare function function CheckEquality( tradeRoute1:table, tradeRoute2:table, compareFunction ) if not compareFunction(tradeRoute1, tradeRoute2) then if not compareFunction(tradeRoute2, tradeRoute1) then return true; end end return false; end -- =========================================================================== -- Look at the plot of the destination city. -- Not always done when selected, as sometimes the TradeOverview will be -- open and it's going to perform it's own lookat. -- =========================================================================== function RealizeLookAtDestinationCity() if m_destinationCity == nil then UI.DataError("TradeRouteChooser cannot look at a NIL destination."); return; end local locX :number = m_destinationCity:GetX(); local locY :number = m_destinationCity:GetY(); local screenXOff:number = 0.6; -- Change offset if the TradeOveriew (exists and) is open as well. if m_pTradeOverviewContext and (not m_pTradeOverviewContext:IsHidden()) then screenXOff = 0.42; end UI.LookAtPlotScreenPosition( locX, locY, screenXOff, 0.5 ); -- Look at 60% over from left side of screen end -- =========================================================================== -- UI Button Callback -- =========================================================================== function OnTradeRouteSelected( cityOwner:number, cityID:number ) TradeRouteSelected( cityOwner, cityID ); RealizeLookAtDestinationCity(); LuaEvents.TradeRouteChooser_RouteConsidered(); end function OnRepeatRouteCheckbox() if not Controls.RepeatRouteCheckbox:IsChecked() then Controls.FromTopSortEntryCheckbox:SetCheck(false); end end function OnFromTopSortEntryCheckbox() -- FromTopSortEntryCheckbox is tied to RepeatRouteCheckbox if Controls.FromTopSortEntryCheckbox:IsChecked() then Controls.RepeatRouteCheckbox:SetCheck(true); end end function RequestTradeRoute() local selectedUnit = UI.GetHeadSelectedUnit(); if m_destinationCity and selectedUnit then local operationParams = {}; operationParams[UnitOperationTypes.PARAM_X0] = m_destinationCity:GetX(); operationParams[UnitOperationTypes.PARAM_Y0] = m_destinationCity:GetY(); operationParams[UnitOperationTypes.PARAM_X1] = selectedUnit:GetX(); operationParams[UnitOperationTypes.PARAM_Y1] = selectedUnit:GetY(); if (UnitManager.CanStartOperation(selectedUnit, UnitOperationTypes.MAKE_TRADE_ROUTE, nil, operationParams)) then UnitManager.RequestOperation(selectedUnit, UnitOperationTypes.MAKE_TRADE_ROUTE, operationParams); UI.SetInterfaceMode(InterfaceModeTypes.SELECTION); UI.PlaySound("START_TRADE_ROUTE"); -- Add the automated settings local selectedUnitID:number = selectedUnit:GetID(); if Controls.RepeatRouteCheckbox:IsChecked() then m_TraderAutomated[selectedUnitID] = true; LuaEvents.TradeRouteChooser_TraderAutomated(selectedUnitID, true); if Controls.FromTopSortEntryCheckbox:IsChecked() then -- Store a copy of the sort settings. m_TraderAutomatedSettings[selectedUnitID] = DeepCopy(m_SortBySettings); else m_TraderAutomatedSettings[selectedUnitID] = nil; end else m_TraderAutomated[selectedUnitID] = false; LuaEvents.TradeRouteChooser_TraderAutomated(selectedUnitID, false); end end return true; end return false; end function UpdateFilterArrow() if Controls.DestinationFilterPulldown:IsOpen() then Controls.PulldownOpenedArrow:SetHide(true); Controls.PulldownClosedArrow:SetHide(false); else Controls.PulldownOpenedArrow:SetHide(false); Controls.PulldownClosedArrow:SetHide(true); end end -- --------------------------------------------------------------------------- -- Sort bar insert buttons -- --------------------------------------------------------------------------- function OnSortByFood() -- If shift is not being pressed, reset sort settings if not m_shiftDown then m_SortBySettings = {}; end -- Sort based on currently showing icon toggled if Controls.FoodDescArrow:IsHidden() then InsertSortEntry(SORT_BY_ID.FOOD, SORT_DESCENDING, m_SortBySettings); else InsertSortEntry(SORT_BY_ID.FOOD, SORT_ASCENDING, m_SortBySettings); end Refresh(); end function OnSortByProduction() -- If shift is not being pressed, reset sort settings if not m_shiftDown then m_SortBySettings = {}; end -- Sort based on currently showing icon toggled if Controls.ProductionDescArrow:IsHidden() then InsertSortEntry(SORT_BY_ID.PRODUCTION, SORT_DESCENDING, m_SortBySettings); else InsertSortEntry(SORT_BY_ID.PRODUCTION, SORT_ASCENDING, m_SortBySettings); end Refresh(); end function OnSortByGold() -- If shift is not being pressed, reset sort settings if not m_shiftDown then m_SortBySettings = {}; end -- Sort based on currently showing icon toggled if Controls.GoldDescArrow:IsHidden() then InsertSortEntry(SORT_BY_ID.GOLD, SORT_DESCENDING, m_SortBySettings); else InsertSortEntry(SORT_BY_ID.GOLD, SORT_ASCENDING, m_SortBySettings); end Refresh(); end function OnSortByScience() -- If shift is not being pressed, reset sort settings if not m_shiftDown then m_SortBySettings = {}; end -- Sort based on currently showing icon toggled if Controls.ScienceDescArrow:IsHidden() then InsertSortEntry(SORT_BY_ID.SCIENCE, SORT_DESCENDING, m_SortBySettings); else InsertSortEntry(SORT_BY_ID.SCIENCE, SORT_ASCENDING, m_SortBySettings); end Refresh(); end function OnSortByCulture() -- If shift is not being pressed, reset sort settings if not m_shiftDown then m_SortBySettings = {}; end -- Sort based on currently showing icon toggled if Controls.CultureDescArrow:IsHidden() then InsertSortEntry(SORT_BY_ID.CULTURE, SORT_DESCENDING, m_SortBySettings); else InsertSortEntry(SORT_BY_ID.CULTURE, SORT_ASCENDING, m_SortBySettings); end Refresh(); end function OnSortByFaith() -- If shift is not being pressed, reset sort settings if not m_shiftDown then m_SortBySettings = {}; end -- Sort based on currently showing icon toggled if Controls.FaithDescArrow:IsHidden() then InsertSortEntry(SORT_BY_ID.FAITH, SORT_DESCENDING, m_SortBySettings); else InsertSortEntry(SORT_BY_ID.FAITH, SORT_ASCENDING, m_SortBySettings); end Refresh(); end function OnSortByTurnsToComplete() -- If shift is not being pressed, reset sort settings if not m_shiftDown then m_SortBySettings = {}; end -- Sort based on currently showing icon toggled if Controls.TurnsToCompleteDescArrow:IsHidden() then InsertSortEntry(SORT_BY_ID.TURNS_TO_COMPLETE, SORT_DESCENDING, m_SortBySettings); else InsertSortEntry(SORT_BY_ID.TURNS_TO_COMPLETE, SORT_ASCENDING, m_SortBySettings); end Refresh(); end -- --------------------------------------------------------------------------- -- Sort bar delete buttons -- --------------------------------------------------------------------------- function OnNotSortByFood() RemoveSortEntry( SORT_BY_ID.FOOD, m_SortBySettings); Refresh(); end function OnNotSortByProduction() RemoveSortEntry( SORT_BY_ID.PRODUCTION, m_SortBySettings); Refresh(); end function OnNotSortByGold() RemoveSortEntry( SORT_BY_ID.GOLD, m_SortBySettings); Refresh(); end function OnNotSortByScience() RemoveSortEntry( SORT_BY_ID.SCIENCE, m_SortBySettings); Refresh(); end function OnNotSortByCulture() RemoveSortEntry( SORT_BY_ID.CULTURE, m_SortBySettings); Refresh(); end function OnNotSortByFaith() RemoveSortEntry( SORT_BY_ID.FAITH, m_SortBySettings); Refresh(); end function OnNotSortByTurnsToComplete() RemoveSortEntry( SORT_BY_ID.TURNS_TO_COMPLETE, m_SortBySettings); Refresh(); end -- =========================================================================== -- Rise/Hide and refresh Trade UI -- =========================================================================== function OnInterfaceModeChanged( oldMode:number, newMode:number ) if (oldMode == InterfaceModeTypes.MAKE_TRADE_ROUTE) then Close(); end if (newMode == InterfaceModeTypes.MAKE_TRADE_ROUTE) then Open(); end end function OnClose() Close(); if UI.GetInterfaceMode() == InterfaceModeTypes.MAKE_TRADE_ROUTE then UI.SetInterfaceMode(InterfaceModeTypes.SELECTION); end end function Close() LuaEvents.TradeRouteChooser_SetTradeUnitStatus(""); ContextPtr:SetHide(true); LuaEvents.TradeRouteChooser_Close(); if UILens.IsLensActive("TradeRoute") then -- Make sure to switch back to default lens UILens.SetActive("Default"); end end function Open() LuaEvents.TradeRouteChooser_SetTradeUnitStatus("LOC_HUD_UNIT_PANEL_CHOOSING_TRADE_ROUTE"); ContextPtr:SetHide(false); m_destinationCity = nil; Controls.RepeatRouteCheckbox:SetCheck(false); Controls.FromTopSortEntryCheckbox:SetCheck(false); -- Play Open Animation Controls.RouteChooserSlideAnim:SetToBeginning(); Controls.RouteChooserSlideAnim:Play(); -- Switch to TradeRoute Lens UILens.SetActive("TradeRoute"); if m_postOpenSelectPlayerID ~= -1 then TradeRouteSelected( m_postOpenSelectPlayerID, m_postOpenSelectCityID ); RealizeLookAtDestinationCity(); -- Reset values m_postOpenSelectPlayerID = -1; m_postOpenSelectCityID = -1; end LuaEvents.TradeRouteChooser_Open(); if not m_TradeOverviewIsOpen then local selectedUnit:table = UI.GetHeadSelectedUnit(); local selectedUnitID:number = selectedUnit:GetID(); if m_LastRouteForTrader[selectedUnitID] ~= nil then -- print("Last route for trader " .. selectedUnitID .. ": " .. GetTradeRouteString(m_LastRouteForTrader[selectedUnitID])); local destinationPlayer:table = Players[m_LastRouteForTrader[selectedUnitID].DestinationCityPlayer]; m_destinationCity = destinationPlayer:GetCities():FindID(m_LastRouteForTrader[selectedUnitID].DestinationCityID); else -- print("No last route was found for trader " .. selectedUnitID); end end Refresh(); end function CheckNeedsToOpen() local selectedUnit:table = UI.GetHeadSelectedUnit(); if selectedUnit ~= nil then local selectedUnitInfo:table = GameInfo.Units[selectedUnit:GetUnitType()]; if selectedUnitInfo ~= nil and selectedUnitInfo.MakeTradeRoute == true then local activityType:number = UnitManager.GetActivityType(selectedUnit); if activityType == ActivityTypes.ACTIVITY_AWAKE and selectedUnit:GetMovesRemaining() > 0 then -- If we're open and this is a trade unit then just refresh if not ContextPtr:IsHidden() then Refresh(); else UI.SetInterfaceMode(InterfaceModeTypes.MAKE_TRADE_ROUTE); end -- Early out so we don't call Close() return; end end end -- If we're open and this unit is not a trade unit then close if not ContextPtr:IsHidden() then Close(); end end function SetTradeOverviewStatus( isOpen:boolean ) m_TradeOverviewIsOpen = isOpen; end -- =========================================================================== -- UI Events -- =========================================================================== function OnInit( isReload:boolean ) if isReload then LuaEvents.GameDebug_GetValues( "TradeRouteChooser" ); end end function OnShutdown() -- Cache values for hotloading... LuaEvents.GameDebug_AddValue("TradeRouteChooser", "filterIndex", m_filterSelected ); LuaEvents.GameDebug_AddValue("TradeRouteChooser", "destinationCity", m_destinationCity ); end -- =========================================================================== -- LUA Event -- Set cached values back after a hotload. -- ===========================================================================s function OnGameDebugReturn( context:string, contextTable:table ) if context ~= "TradeRouteChooser" then return; end m_filterSelected = contextTable["filterIndex"]; m_destinationCity = contextTable["destinationCity"]; Refresh(); end -- =========================================================================== -- GAME Event -- City was selected so close route chooser -- =========================================================================== function OnCitySelectionChanged(owner, ID, i, j, k, bSelected, bEditable) if not ContextPtr:IsHidden() and owner == Game.GetLocalPlayer() then OnClose(); end end -- =========================================================================== -- GAME Event -- Unit was selected so close route chooser -- =========================================================================== function OnUnitSelectionChanged( playerID : number, unitID : number, hexI : number, hexJ : number, hexK : number, bSelected : boolean, bEditable : boolean ) -- Make sure we're the local player and not observing if playerID ~= Game.GetLocalPlayer() or playerID == -1 then return; end -- If this is a de-selection event then close if not bSelected then OnClose(); return; end if not m_TradeOverviewIsOpen then CheckNeedsToOpen(); else -- print("Trade Overview was open. Not auto opening trade panel.") end end function OnLocalPlayerTurnEnd() if(GameConfiguration.IsHotseat()) then OnClose(); end end function OnPlayerTurnActivated( playerID:number, isFirstTime:boolean ) if playerID == Game.GetLocalPlayer() then RenewTradeRoutes(); end end function OnUnitActivityChanged( playerID :number, unitID :number, eActivityType :number) -- Make sure we're the local player and not observing if playerID ~= Game.GetLocalPlayer() or playerID == -1 then return; end CheckNeedsToOpen(); end function OnPolicyChanged( ePlayer ) if not ContextPtr:IsHidden() and ePlayer == Game.GetLocalPlayer() then Refresh(); end end -- =========================================================================== -- Input -- UI Event Handler -- =========================================================================== function KeyDownHandler( key:number ) if key == Keys.VK_SHIFT then m_shiftDown = true; if not showSortOrdersPermanently then ShowSortOrderLabels(); end -- let it fall through end return false; end function KeyUpHandler( key:number ) if key == Keys.VK_SHIFT then m_shiftDown = false; if not showSortOrdersPermanently then HideSortOrderLabels(); end -- let it fall through end if key == Keys.VK_RETURN then if m_destinationCity then RequestTradeRoute(); end -- Dont let it fall through return true; end if key == Keys.VK_ESCAPE then OnClose(); return true; end return false; end function OnInputHandler( pInputStruct:table ) local uiMsg = pInputStruct:GetMessageType(); if uiMsg == KeyEvents.KeyDown then return KeyDownHandler( pInputStruct:GetKey() ); end if uiMsg == KeyEvents.KeyUp then return KeyUpHandler( pInputStruct:GetKey() ); end return false; end -- =========================================================================== function OnSelectRouteFromOverview( destinationOwnerID:number, destinationCityID:number ) if not ContextPtr:IsHidden() then -- If we're already open then select the route TradeRouteSelected( destinationOwnerID, destinationCityID ); else -- If we're not open then set the route to be selected after we open the panel m_postOpenSelectPlayerID = destinationOwnerID; m_postOpenSelectCityID = destinationCityID; -- Check to see if we need to open CheckNeedsToOpen(); end end -- =========================================================================== -- Setup -- =========================================================================== function Initialize() -- Context Events ContextPtr:SetInitHandler( OnInit ); ContextPtr:SetShutdown( OnShutdown ); ContextPtr:SetInputHandler( OnInputHandler, true ); -- Lua Events LuaEvents.GameDebug_Return.Add( OnGameDebugReturn ); -- Context Events LuaEvents.TradeOverview_SelectRouteFromOverview.Add( OnSelectRouteFromOverview ); LuaEvents.TradeOverview_UpdateContextStatus.Add( SetTradeOverviewStatus ); LuaEvents.TradeOverview_SetLastRoute.Add( SetLastRouteForTrader ); LuaEvents.TraderOverview_SetTraderAutomated.Add( SetTraderAutomated ); -- Game Engine Events Events.InterfaceModeChanged.Add( OnInterfaceModeChanged ); Events.CitySelectionChanged.Add( OnCitySelectionChanged ); Events.UnitSelectionChanged.Add( OnUnitSelectionChanged ); Events.UnitActivityChanged.Add( OnUnitActivityChanged ); Events.LocalPlayerTurnEnd.Add( OnLocalPlayerTurnEnd ); Events.GovernmentPolicyChanged.Add( OnPolicyChanged ); Events.GovernmentPolicyObsoleted.Add( OnPolicyChanged ); Events.PlayerTurnActivated.Add( OnPlayerTurnActivated ); -- Control Events Controls.BeginRouteButton:RegisterCallback( eLClick, RequestTradeRoute ); Controls.BeginRouteButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); Controls.FilterButton:RegisterCallback( eLClick, UpdateFilterArrow ); Controls.DestinationFilterPulldown:RegisterSelectionCallback( OnFilterSelected ); Controls.Header_CloseButton:RegisterCallback( eLClick, OnClose ); -- Control events - checkboxes Controls.RepeatRouteCheckbox:RegisterCallback( eLClick, OnRepeatRouteCheckbox ); Controls.RepeatRouteCheckbox:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); Controls.FromTopSortEntryCheckbox:RegisterCallback( eLClick, OnFromTopSortEntryCheckbox ); Controls.FromTopSortEntryCheckbox:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); -- Control events - sort bar Controls.FoodSortButton:RegisterCallback( Mouse.eLClick, OnSortByFood); Controls.FoodSortButton:RegisterCallback( Mouse.eRClick, OnNotSortByFood); Controls.FoodSortButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); Controls.ProductionSortButton:RegisterCallback( Mouse.eLClick, OnSortByProduction); Controls.ProductionSortButton:RegisterCallback( Mouse.eRClick, OnNotSortByProduction); Controls.ProductionSortButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); Controls.GoldSortButton:RegisterCallback( Mouse.eLClick, OnSortByGold); Controls.GoldSortButton:RegisterCallback( Mouse.eRClick, OnNotSortByGold); Controls.GoldSortButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); Controls.ScienceSortButton:RegisterCallback( Mouse.eLClick, OnSortByScience); Controls.ScienceSortButton:RegisterCallback( Mouse.eRClick, OnNotSortByScience); Controls.ScienceSortButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); Controls.CultureSortButton:RegisterCallback( Mouse.eLClick, OnSortByCulture); Controls.CultureSortButton:RegisterCallback( Mouse.eRClick, OnNotSortByCulture); Controls.CultureSortButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); Controls.FaithSortButton:RegisterCallback( Mouse.eLClick, OnSortByFaith); Controls.FaithSortButton:RegisterCallback( Mouse.eRClick, OnNotSortByFaith); Controls.FaithSortButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); Controls.TurnsToCompleteSortButton:RegisterCallback( Mouse.eLClick, OnSortByTurnsToComplete); Controls.TurnsToCompleteSortButton:RegisterCallback( Mouse.eRClick, OnNotSortByTurnsToComplete); Controls.TurnsToCompleteSortButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); -- Obtain refrence to another context. m_pTradeOverviewContext = ContextPtr:LookUpControl("/InGame/TradeOverview"); end Initialize();
mit
ffxiphoenix/darkstar
scripts/zones/Port_Bastok/npcs/Zoby_Quhyo.lua
36
1693
----------------------------------- -- Area: Port Bastok -- NPC: Zoby Quhyo -- Only sells when Bastok controlls Elshimo Lowlands -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); 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) RegionOwner = GetRegionOwner(ELSHIMOLOWLANDS); if (RegionOwner ~= BASTOK) then player:showText(npc,ZOBYQUHYO_CLOSED_DIALOG); else player:showText(npc,ZOBYQUHYO_OPEN_DIALOG); stock = { 0x0272, 234, --Black Pepper 0x0264, 55, --Kazham Peppers 0x1150, 55, --Kazham Pineapple 0x0278, 110, --Kukuru Bean 0x1126, 36, --Mithran Tomato 0x0276, 88, --Ogre Pumpkin 0x0583, 1656 --Phalaenopsis } showShop(player,BASTOK,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Caedarva_Mire/npcs/_272.lua
29
3652
----------------------------------- -- Area: Caedarva Mire -- Door: Runic Seal -- @pos 486 -23 -500 79 ----------------------------------- package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/besieged"); require("scripts/zones/Caedarva_Mire/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(LEUJAOAM_ASSAULT_ORDERS)) then local assaultid = player:getCurrentAssault(); local recommendedLevel = getRecommendedAssaultLevel(assaultid); local armband = 0; if (player:hasKeyItem(ASSAULT_ARMBAND)) then armband = 1; end if (assaultid ~= 0) then player:startEvent(0x008C, assaultid, -4, 0, recommendedLevel, 0, armband); else player:messageSpecial(NOTHING_HAPPENS); end else player:messageSpecial(NOTHING_HAPPENS); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option,target) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local assaultid = player:getCurrentAssault(); local cap = bit.band(option, 0x03); if (cap == 0) then cap = 99; elseif (cap == 1) then cap = 70; elseif (cap == 2) then cap = 60; else cap = 50; end player:setVar("AssaultCap", cap); local party = player:getParty(); if (party ~= nil) then for i,v in ipairs(party) do if (not (v:hasKeyItem(LEUJAOAM_ASSAULT_ORDERS) and v:getCurrentAssault() == assaultid)) then player:messageText(target,MEMBER_NO_REQS, false); player:instanceEntry(target,1); return; elseif (v:getZone() == player:getZone() and v:checkDistance(player) > 50) then player:messageText(target,MEMBER_TOO_FAR, false); player:instanceEntry(target,1); return; end end end player:createInstance(player:getCurrentAssault(), 69); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,target) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x82 or (csid == 0x8C and option == 4)) then player:setPos(0,0,0,0,69); end end; ----------------------------------- -- onInstanceLoaded ----------------------------------- function onInstanceCreated(player,target,instance) if (instance) then instance:setLevelCap(player:getVar("AssaultCap")); player:setVar("AssaultCap", 0); player:setInstance(instance); player:instanceEntry(target,4); player:delKeyItem(LEUJAOAM_ASSAULT_ORDERS); player:delKeyItem(ASSAULT_ARMBAND); if (party ~= nil) then for i,v in ipairs(party) do if v:getID() ~= player:getID() and v:getZone() == player:getZone() then v:setInstance(instance); v:startEvent(0x82, 0); v:delKeyItem(LEUJAOAM_ASSAULT_ORDERS); end end end else player:messageText(target,CANNOT_ENTER, false); player:instanceEntry(target,3); end end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Apollyon/mobs/Grave_Digger.lua
33
1024
----------------------------------- -- Area: Apollyon SE -- NPC: Grave_Digger ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) GetMobByID(16933021):updateEnmity(target); GetMobByID(16933022):updateEnmity(target); GetMobByID(16933023):updateEnmity(target); GetMobByID(16933024):updateEnmity(target); GetMobByID(16933025):updateEnmity(target); GetMobByID(16933026):updateEnmity(target); GetMobByID(16933027):updateEnmity(target); GetMobByID(16933028):updateEnmity(target); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Kazham/npcs/Nenepp.lua
15
4356
----------------------------------- -- Area: Kazham -- NPC: Nenepp -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); require("scripts/globals/pathfind"); local path = { 29.014000, -11.00000, -183.884000, 31.023000, -11.00000, -183.538000, 33.091000, -11.00000, -183.738000 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- -- item IDs -- 483 Broken Mithran Fishing Rod -- 22 Workbench -- 1008 Ten of Coins -- 1157 Sands of Silence -- 1158 Wandering Bulb -- 904 Giant Fish Bones -- 4599 Blackened Toad -- 905 Wyvern Skull -- 1147 Ancient Salt -- 4600 Lucky Egg function onTrade(player,npc,trade) local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, THE_OPO_OPO_AND_I); local progress = player:getVar("OPO_OPO_PROGRESS"); local failed = player:getVar("OPO_OPO_FAILED"); local goodtrade = trade:hasItemQty(4600,1); local badtrade = (trade:hasItemQty(483,1) or trade:hasItemQty(22,1) or trade:hasItemQty(1157,1) or trade:hasItemQty(1158,1) or trade:hasItemQty(904,1) or trade:hasItemQty(1008,1) or trade:hasItemQty(905,1) or trade:hasItemQty(4599,1) or trade:hasItemQty(1147,1)); if (OpoOpoAndIStatus == QUEST_ACCEPTED) then if progress == 9 or failed == 10 then if goodtrade then player:startEvent(0x00F1); elseif badtrade then player:startEvent(0x00EE); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, THE_OPO_OPO_AND_I); local progress = player:getVar("OPO_OPO_PROGRESS"); local failed = player:getVar("OPO_OPO_FAILED"); local retry = player:getVar("OPO_OPO_RETRY"); if (OpoOpoAndIStatus == QUEST_ACCEPTED) then if retry >= 1 then -- has failed on future npc so disregard previous successful trade player:startEvent(0x00CE); npc:wait(-1); elseif (progress == 9 or failed == 10) then player:startEvent(0x00D4); -- asking for lucky egg elseif (progress >= 10 or failed >= 11) then player:startEvent(0x00FA); -- happy with lucky egg end else player:startEvent(0x00CE); npc:wait(-1); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x00F1) then -- correct trade, finished quest and receive opo opo crown and 3 pamamas local FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 4) then player:tradeComplete(); player:addFame(KAZHAM, WIN_FAME*75); player:completeQuest(OUTLANDS, THE_OPO_OPO_AND_I); player:addItem(13870); -- opo opo crown player:messageSpecial(ITEM_OBTAINED,13870); player:addItem(4468,3); -- 3 pamamas player:messageSpecial(ITEM_OBTAINED,4468,3); player:setVar("OPO_OPO_PROGRESS",0); player:setVar("OPO_OPO_FAILED", 0); player:setVar("OPO_OPO_RETRY", 0); player:setTitle(257); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED); end elseif (csid == 0x00EE) then -- wrong trade, restart at first opo player:setVar("OPO_OPO_FAILED",1); player:setVar("OPO_OPO_RETRY",10); else npc:wait(0); end end;
gpl-3.0
ffxiphoenix/darkstar
scripts/globals/spells/mages_ballad_ii.lua
31
1186
----------------------------------------- -- Spell: Mage's Ballad II -- Gradually restores target's MP. ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local power = 2; local iBoost = caster:getMod(MOD_BALLAD_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_BALLAD,power,0,duration,caster:getID(), 0, 2)) then spell:setMsg(75); end return EFFECT_BALLAD; end;
gpl-3.0
lxl1140989/sdk-for-tb
feeds/luci/applications/luci-statistics/luasrc/statistics/datatree.lua
77
4394
--[[ Luci statistics - rrd data tree builder (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.statistics.datatree", package.seeall) local util = require("luci.util") local sys = require("luci.sys") local fs = require("nixio.fs") local uci = require("luci.model.uci").cursor() local sections = uci:get_all("luci_statistics") Instance = util.class() function Instance.__init__( self, host ) self._host = host or sections.collectd.Hostname or sys.hostname() self._libdir = sections.collectd.PluginDir or "/usr/lib/collectd" self._rrddir = sections.collectd_rrdtool.DataDir or "/tmp/rrd" self._libdir = self._libdir:gsub("/$","") self._rrddir = self._rrddir:gsub("/$","") self._plugins = { } self:_scan() end function Instance._mkpath( self, plugin, pinstance ) local dir = self._rrddir .. "/" .. self._host if type(plugin) == "string" and plugin:len() > 0 then dir = dir .. "/" .. plugin if type(pinstance) == "string" and pinstance:len() > 0 then dir = dir .. "-" .. pinstance end end return dir end function Instance._ls( self, ... ) local ditr = fs.dir(self:_mkpath(...)) if ditr then local dirs = { } while true do local d = ditr() if not d then break end dirs[#dirs+1] = d end return dirs end end function Instance._notzero( self, table ) for k in pairs(table) do return true end return false end function Instance._scan( self ) local dirs = self:_ls() if not dirs then return end -- for i, plugin in ipairs( dirs ) do -- if plugin:match("%w+.so") then -- self._plugins[ plugin:gsub("%.so$", "") ] = { } -- end -- end for _, dir in ipairs(dirs) do if dir ~= "." and dir ~= ".." and fs.stat(self:_mkpath(dir)).type == "dir" then local plugin = dir:gsub("%-.+$", "") if not self._plugins[plugin] then self._plugins[plugin] = { } end end end for plugin, instances in pairs( self._plugins ) do local dirs = self:_ls() if type(dirs) == "table" then for i, dir in ipairs(dirs) do if dir:find( plugin .. "%-" ) or dir == plugin then local instance = "" if dir ~= plugin then instance = dir:gsub( plugin .. "%-", "", 1 ) end instances[instance] = { } end end end for instance, data_instances in pairs( instances ) do dirs = self:_ls(plugin, instance) if type(dirs) == "table" then for i, file in ipairs(dirs) do if file:find("%.rrd") then file = file:gsub("%.rrd","") local data_type local data_instance if file:find("%-") then data_type = file:gsub( "%-.+","" ) data_instance = file:gsub( "[^%-]-%-", "", 1 ) else data_type = file data_instance = "" end if not data_instances[data_type] then data_instances[data_type] = { data_instance } else table.insert( data_instances[data_type], data_instance ) end end end end end end end function Instance.plugins( self ) local rv = { } for plugin, val in pairs( self._plugins ) do if self:_notzero( val ) then table.insert( rv, plugin ) end end return rv end function Instance.plugin_instances( self, plugin ) local rv = { } for instance, val in pairs( self._plugins[plugin] ) do table.insert( rv, instance ) end return rv end function Instance.data_types( self, plugin, instance ) local rv = { } local p = self._plugins[plugin] if type(p) == "table" and type(p[instance]) == "table" then for type, val in pairs(p[instance]) do table.insert( rv, type ) end end return rv end function Instance.data_instances( self, plugin, instance, dtype ) local rv = { } local p = self._plugins[plugin] if type(p) == "table" and type(p[instance]) == "table" and type(p[instance][dtype]) == "table" then for i, instance in ipairs(p[instance][dtype]) do table.insert( rv, instance ) end end return rv end function Instance.host_instances( self ) local hosts_path = fs.glob(self._rrddir..'/*') local hosts = { } if hosts_path then local path for path in hosts_path do hosts[#hosts+1] = fs.basename(path) end end return hosts end
gpl-2.0
RodneyMcKay/x_hero_siege
game/scripts/vscripts/abilities/heroes/hero_archmage.lua
1
5464
function march_of_the_machines_spawn( keys ) local caster = keys.caster local ability = keys.ability local casterLoc = caster:GetAbsOrigin() local targetLoc = keys.target_points[1] local duration = ability:GetLevelSpecialValueFor( "duration", ability:GetLevel() - 1 ) local distance = ability:GetLevelSpecialValueFor( "distance", ability:GetLevel() - 1 ) local radius = ability:GetLevelSpecialValueFor( "radius", ability:GetLevel() - 1 ) local collision_radius = ability:GetLevelSpecialValueFor( "collision_radius", ability:GetLevel() - 1 ) local projectile_speed = ability:GetLevelSpecialValueFor( "speed", ability:GetLevel() - 1 ) local machines_per_sec = ability:GetLevelSpecialValueFor ( "machines_per_sec", ability:GetLevel() - 1 ) local dummyModifierName = "modifier_march_of_the_machines_dummy_datadriven" -- Find forward vector local forwardVec = targetLoc - casterLoc forwardVec = forwardVec:Normalized() -- Find backward vector local backwardVec = casterLoc - targetLoc backwardVec = backwardVec:Normalized() -- Find middle point of the spawning line local middlePoint = casterLoc + ( radius * backwardVec ) -- Find perpendicular vector local v = middlePoint - casterLoc local dx = -v.y local dy = v.x local perpendicularVec = Vector( dx, dy, v.z ) perpendicularVec = perpendicularVec:Normalized() -- Create dummy to store data in case of multiple instances are called local dummy = CreateUnitByName( "npc_dummy_unit", caster:GetAbsOrigin(), false, caster, caster, caster:GetTeamNumber() ) ability:ApplyDataDrivenModifier( caster, dummy, dummyModifierName, {} ) dummy.march_of_the_machines_num = 0 -- Create timer to spawn projectile Timers:CreateTimer( function() -- Get random location for projectile local random_distance = RandomInt( -radius, radius ) local spawn_location = middlePoint + perpendicularVec * random_distance local velocityVec = Vector( forwardVec.x, forwardVec.y, 0 ) -- Spawn projectiles local projectileTable = { Ability = ability, EffectName = "particles/units/heroes/hero_morphling/morphling_waveform.vpcf", vSpawnOrigin = spawn_location, fDistance = distance, fStartRadius = collision_radius, fEndRadius = collision_radius, Source = caster, bHasFrontalCone = false, bReplaceExisting = false, bProvidesVision = false, iUnitTargetTeam = DOTA_UNIT_TARGET_TEAM_ENEMY, iUnitTargetType = DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, vVelocity = velocityVec * projectile_speed } ProjectileManager:CreateLinearProjectile( projectileTable ) -- Increment the counter dummy.march_of_the_machines_num = dummy.march_of_the_machines_num + 1 -- Check if the number of machines have been reached if dummy.march_of_the_machines_num == machines_per_sec * duration then dummy:Destroy() return nil else return 1 / machines_per_sec end end) end function RainOfIce( event ) local caster = event.target local ability = event.ability local radius = ability:GetLevelSpecialValueFor("radius", ability:GetLevel() -1) local radius_explosion = ability:GetLevelSpecialValueFor("radius_explosion", ability:GetLevel() -1) local damage_per_unit = ability:GetLevelSpecialValueFor("damage_per_unit", ability:GetLevel() -1) local stun_duration = ability:GetLevelSpecialValueFor("stun_duration", ability:GetLevel() -1) local explosions_per_tick = ability:GetLevelSpecialValueFor("explosions_per_tick", ability:GetLevel() -1) local delay = ability:GetLevelSpecialValueFor("delay", ability:GetLevel() -1) StartAnimation(caster, {duration = 1.0, activity = ACT_DOTA_CAST_ABILITY_1, rate = 1.0}) for i = 1, explosions_per_tick do local point = caster:GetAbsOrigin() + RandomInt(1,radius-(math.floor(radius_explosion/2.0)))*RandomVector(1) local units = FindUnitsInRadius(caster:GetTeam(), point, nil, radius_explosion, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_HERO , DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_CLOSEST, false) for _,unit in pairs(units) do Timers:CreateTimer( delay,function () ApplyDamage({victim = unit, attacker = caster, damage = damage_per_unit, damage_type = DAMAGE_TYPE_MAGICAL}) unit:AddNewModifier(caster, nil, "modifier_stunned", {duration = stun_duration}) end) end local moonstrike = ParticleManager:CreateParticle("particles/custom/human/blood_mage/invoker_sun_strike_team_immortal2.vpcf",PATTACH_CUSTOMORIGIN,caster) ParticleManager:SetParticleControl(moonstrike, 0, point) local moontrike_inner = ParticleManager:CreateParticle("particles/econ/items/crystal_maiden/crystal_maiden_maiden_of_icewrack/maiden_freezing_field_cracks_arcana.vpcf",PATTACH_CUSTOMORIGIN,caster) ParticleManager:SetParticleControl(moontrike_inner, 0, point) local moonstrike_outer = ParticleManager:CreateParticle("particles/econ/items/crystal_maiden/crystal_maiden_maiden_of_icewrack/maiden_freezing_field_darkcore_arcana1.vpcf", PATTACH_CUSTOMORIGIN, nil) ParticleManager:SetParticleControl(moonstrike_outer, 0, point) ParticleManager:SetParticleControl(moonstrike_outer, 2, Vector(11,0,0)) Timers:CreateTimer(delay - 0.1, function() local moonstrike = ParticleManager:CreateParticle("particles/econ/items/crystal_maiden/crystal_maiden_maiden_of_icewrack/maiden_freezing_field_explosion_arcana1.vpcf", PATTACH_CUSTOMORIGIN, caster) ParticleManager:SetParticleControl(moonstrike, 0, point) caster:EmitSound("Hero_Invoker.SunStrike.Ignite") end) end end
gpl-2.0
ffxiphoenix/darkstar
scripts/zones/GM_Home/Zone.lua
25
1251
----------------------------------- -- -- Zone: GM Home (210) -- -- Some cs event info: -- 0 = Abyssea Debug -- 1 = Mogsack Debug -- ... -- 139 = Janken challenges player to "Rock, Paper, Scissors" -- ... -- 140 = Camera test. -- 141 = "Press confirm button to proceed" nonworking test. -- ----------------------------------- package.loaded["scripts/zones/GM_Home/TextIDs"] = nil; ----------------------------------- require("scripts/zones/GM_Home/TextIDs"); require("scripts/globals/zone"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; return cs; 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
shahabsaf1/merbot.cl
bot/bot.lua
1
6839
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") local f = assert(io.popen('/usr/bin/git describe --tags', 'r')) VERSION = assert(f:read('*a')) f:close() -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) -- vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) -- See plugins/isup.lua as an example for cron _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages -- if msg.out then -- print('\27[36mNot valid: msg from us\27[39m') -- return false -- end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end -- if msg.from.id == our_id then -- print('\27[36mNot valid: Msg from our id\27[39m') -- return false -- end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then print('\27[36mNot valid: Telegram message\27[39m') return false end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "banhammer", "channels", "greeter", "groupmanager", "help", "id", "invite", "plugins", "version"}, sudo_users = {119989724}, disabled_channels = {}, moderation = {data = 'data/moderation.json'} } serialize_to_file(config, './data/config.lua') print ('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) --vardump (chat) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 5 mins postpone (cron_plugins, false, 5*60.0) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
azekillDIABLO/Voxellar
mods/NODES/default/mapgen.lua
1
42915
-- -- Aliases for map generators -- minetest.register_alias("mapgen_stone", "default:stone") minetest.register_alias("mapgen_dirt", "default:dirt") minetest.register_alias("mapgen_dirt_with_grass", "default:dirt_with_grass") minetest.register_alias("mapgen_sand", "default:sand") minetest.register_alias("mapgen_water_source", "default:water_source") minetest.register_alias("mapgen_river_water_source", "default:river_water_source") minetest.register_alias("mapgen_lava_source", "default:lava_source") minetest.register_alias("mapgen_gravel", "default:gravel") minetest.register_alias("mapgen_desert_stone", "default:desert_stone") minetest.register_alias("mapgen_desert_sand", "default:desert_sand") minetest.register_alias("mapgen_dirt_with_snow", "default:dirt_with_snow") minetest.register_alias("mapgen_snowblock", "default:snowblock") minetest.register_alias("mapgen_snow", "default:snow") minetest.register_alias("mapgen_ice", "default:ice") minetest.register_alias("mapgen_sandstone", "default:sandstone") -- Flora minetest.register_alias("mapgen_tree", "default:tree") minetest.register_alias("mapgen_leaves", "default:leaves") minetest.register_alias("mapgen_apple", "default:apple") minetest.register_alias("mapgen_jungletree", "default:jungletree") minetest.register_alias("mapgen_jungleleaves", "default:jungleleaves") minetest.register_alias("mapgen_junglegrass", "default:junglegrass") minetest.register_alias("mapgen_pine_tree", "default:pine_tree") minetest.register_alias("mapgen_pine_needles", "default:pine_needles") -- Dungeons minetest.register_alias("mapgen_cobble", "default:cobble") minetest.register_alias("mapgen_stair_cobble", "stairs:stair_cobble") minetest.register_alias("mapgen_mossycobble", "default:mossycobble") minetest.register_alias("mapgen_stair_desert_stone", "stairs:stair_desert_stone") minetest.register_alias("mapgen_sandstonebrick", "default:sandstonebrick") minetest.register_alias("mapgen_stair_sandstone_block", "stairs:stair_sandstone_block") -- -- Register ores -- -- Blob ores -- These first to avoid other ores in blobs -- Mgv6 function default.register_mgv6_blob_ores() -- Clay -- This first to avoid clay in sand blobs minetest.register_ore({ ore_type = "blob", ore = "default:clay", wherein = {"default:sand"}, clust_scarcity = 16 * 16 * 16, clust_size = 5, y_min = -15, y_max = 0, noise_threshold = 0.0, noise_params = { offset = 0.5, scale = 0.2, spread = {x = 5, y = 5, z = 5}, seed = -316, octaves = 1, persist = 0.0 }, }) -- Sand minetest.register_ore({ ore_type = "blob", ore = "default:sand", wherein = {"default:stone", "default:desert_stone"}, clust_scarcity = 16 * 16 * 16, clust_size = 5, y_min = -31, y_max = 0, noise_threshold = 0.0, noise_params = { offset = 0.5, scale = 0.2, spread = {x = 5, y = 5, z = 5}, seed = 2316, octaves = 1, persist = 0.0 }, }) -- Dirt minetest.register_ore({ ore_type = "blob", ore = "default:dirt", wherein = {"default:stone"}, clust_scarcity = 16 * 16 * 16, clust_size = 5, y_min = -31, y_max = 31000, noise_threshold = 0.0, noise_params = { offset = 0.5, scale = 0.2, spread = {x = 5, y = 5, z = 5}, seed = 17676, octaves = 1, persist = 0.0 }, }) -- Gravel minetest.register_ore({ ore_type = "blob", ore = "default:gravel", wherein = {"default:stone"}, clust_scarcity = 16 * 16 * 16, clust_size = 5, y_min = -31000, y_max = 31000, noise_threshold = 0.0, noise_params = { offset = 0.5, scale = 0.2, spread = {x = 5, y = 5, z = 5}, seed = 766, octaves = 1, persist = 0.0 }, }) end -- All mapgens except mgv6 function default.register_blob_ores() -- Clay minetest.register_ore({ ore_type = "blob", ore = "default:clay", wherein = {"default:sand"}, clust_scarcity = 16 * 16 * 16, clust_size = 5, y_min = -15, y_max = 0, noise_threshold = 0.0, noise_params = { offset = 0.5, scale = 0.2, spread = {x = 5, y = 5, z = 5}, seed = -316, octaves = 1, persist = 0.0 }, }) -- Silver sand minetest.register_ore({ ore_type = "blob", ore = "default:silver_sand", wherein = {"default:stone"}, clust_scarcity = 16 * 16 * 16, clust_size = 5, y_min = -31000, y_max = 31000, noise_threshold = 0.0, noise_params = { offset = 0.5, scale = 0.2, spread = {x = 5, y = 5, z = 5}, seed = 2316, octaves = 1, persist = 0.0 }, biomes = {"icesheet_ocean", "tundra", "tundra_beach", "tundra_ocean", "taiga", "taiga_ocean", "snowy_grassland", "snowy_grassland_ocean", "grassland", "grassland_dunes", "grassland_ocean", "coniferous_forest", "coniferous_forest_dunes", "coniferous_forest_ocean", "deciduous_forest", "deciduous_forest_shore", "deciduous_forest_ocean", "cold_desert", "cold_desert_ocean", "savanna", "savanna_shore", "savanna_ocean", "rainforest", "rainforest_swamp", "rainforest_ocean", "underground", "floatland_grassland", "floatland_grassland_ocean", "floatland_coniferous_forest", "floatland_coniferous_forest_ocean"} }) -- Dirt minetest.register_ore({ ore_type = "blob", ore = "default:dirt", wherein = {"default:stone"}, clust_scarcity = 16 * 16 * 16, clust_size = 5, y_min = -31, y_max = 31000, noise_threshold = 0.0, noise_params = { offset = 0.5, scale = 0.2, spread = {x = 5, y = 5, z = 5}, seed = 17676, octaves = 1, persist = 0.0 }, biomes = {"taiga", "snowy_grassland", "grassland", "coniferous_forest", "deciduous_forest", "deciduous_forest_shore", "savanna", "savanna_shore", "rainforest", "rainforest_swamp", "floatland_grassland", "floatland_coniferous_forest"} }) -- Gravel minetest.register_ore({ ore_type = "blob", ore = "default:gravel", wherein = {"default:stone"}, clust_scarcity = 16 * 16 * 16, clust_size = 5, y_min = -31000, y_max = 31000, noise_threshold = 0.0, noise_params = { offset = 0.5, scale = 0.2, spread = {x = 5, y = 5, z = 5}, seed = 766, octaves = 1, persist = 0.0 }, biomes = {"icesheet_ocean", "tundra", "tundra_beach", "tundra_ocean", "taiga", "taiga_ocean", "snowy_grassland", "snowy_grassland_ocean", "grassland", "grassland_dunes", "grassland_ocean", "coniferous_forest", "coniferous_forest_dunes", "coniferous_forest_ocean", "deciduous_forest", "deciduous_forest_shore", "deciduous_forest_ocean", "cold_desert", "cold_desert_ocean", "savanna", "savanna_shore", "savanna_ocean", "rainforest", "rainforest_swamp", "rainforest_ocean", "underground", "floatland_grassland", "floatland_grassland_ocean", "floatland_coniferous_forest", "floatland_coniferous_forest_ocean"} }) end -- Scatter ores -- All mapgens function default.register_ores() -- Coal minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_coal", wherein = "default:stone", clust_scarcity = 8 * 8 * 8, clust_num_ores = 9, clust_size = 3, y_min = 1025, y_max = 31000, }) minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_coal", wherein = "default:stone", clust_scarcity = 8 * 8 * 8, clust_num_ores = 8, clust_size = 3, y_min = -31000, y_max = 64, }) minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_coal", wherein = "default:stone", clust_scarcity = 24 * 24 * 24, clust_num_ores = 27, clust_size = 6, y_min = -31000, y_max = 0, }) -- Iron minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_iron", wherein = "default:stone", clust_scarcity = 9 * 9 * 9, clust_num_ores = 12, clust_size = 3, y_min = 1025, y_max = 31000, }) minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_iron", wherein = "default:stone", clust_scarcity = 7 * 7 * 7, clust_num_ores = 5, clust_size = 3, y_min = -31000, y_max = 0, }) minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_iron", wherein = "default:stone", clust_scarcity = 24 * 24 * 24, clust_num_ores = 27, clust_size = 6, y_min = -31000, y_max = -64, }) -- Copper minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_copper", wherein = "default:stone", clust_scarcity = 9 * 9 * 9, clust_num_ores = 5, clust_size = 3, y_min = 1025, y_max = 31000, }) minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_copper", wherein = "default:stone", clust_scarcity = 12 * 12 * 12, clust_num_ores = 4, clust_size = 3, y_min = -63, y_max = -16, }) minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_copper", wherein = "default:stone", clust_scarcity = 9 * 9 * 9, clust_num_ores = 5, clust_size = 3, y_min = -31000, y_max = -64, }) -- Tin minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_tin", wherein = "default:stone", clust_scarcity = 10 * 10 * 10, clust_num_ores = 5, clust_size = 3, y_min = 1025, y_max = 31000, }) minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_tin", wherein = "default:stone", clust_scarcity = 13 * 13 * 13, clust_num_ores = 4, clust_size = 3, y_min = -127, y_max = -32, }) minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_tin", wherein = "default:stone", clust_scarcity = 10 * 10 * 10, clust_num_ores = 5, clust_size = 3, y_min = -31000, y_max = -128, }) -- Gold minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_gold", wherein = "default:stone", clust_scarcity = 13 * 13 * 13, clust_num_ores = 5, clust_size = 3, y_min = 1025, y_max = 31000, }) minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_gold", wherein = "default:stone", clust_scarcity = 15 * 15 * 15, clust_num_ores = 3, clust_size = 2, y_min = -255, y_max = -64, }) minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_gold", wherein = "default:stone", clust_scarcity = 13 * 13 * 13, clust_num_ores = 5, clust_size = 3, y_min = -31000, y_max = -256, }) -- Mese crystal minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_mese", wherein = "default:stone", clust_scarcity = 14 * 14 * 14, clust_num_ores = 5, clust_size = 3, y_min = 1025, y_max = 31000, }) minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_mese", wherein = "default:stone", clust_scarcity = 18 * 18 * 18, clust_num_ores = 3, clust_size = 2, y_min = -255, y_max = -64, }) minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_mese", wherein = "default:stone", clust_scarcity = 14 * 14 * 14, clust_num_ores = 5, clust_size = 3, y_min = -31000, y_max = -256, }) -- Diamond minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_diamond", wherein = "default:stone", clust_scarcity = 15 * 15 * 15, clust_num_ores = 4, clust_size = 3, y_min = 1025, y_max = 31000, }) minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_diamond", wherein = "default:stone", clust_scarcity = 17 * 17 * 17, clust_num_ores = 4, clust_size = 3, y_min = -255, y_max = -128, }) minetest.register_ore({ ore_type = "scatter", ore = "default:stone_with_diamond", wherein = "default:stone", clust_scarcity = 15 * 15 * 15, clust_num_ores = 4, clust_size = 3, y_min = -31000, y_max = -256, }) -- Mese block minetest.register_ore({ ore_type = "scatter", ore = "default:mese", wherein = "default:stone", clust_scarcity = 36 * 36 * 36, clust_num_ores = 3, clust_size = 2, y_min = 1025, y_max = 31000, }) minetest.register_ore({ ore_type = "scatter", ore = "default:mese", wherein = "default:stone", clust_scarcity = 36 * 36 * 36, clust_num_ores = 3, clust_size = 2, y_min = -31000, y_max = -1024, }) end -- -- Register biomes -- -- All mapgens except mgv6 function default.register_biomes(upper_limit) -- Icesheet minetest.register_biome({ name = "icesheet", node_dust = "default:snowblock", node_top = "default:snowblock", depth_top = 1, node_filler = "default:snowblock", depth_filler = 3, node_stone = "default:ice", node_water_top = "default:ice", depth_water_top = 10, --node_water = "", node_river_water = "default:ice", node_riverbed = "default:gravel", depth_riverbed = 2, y_min = -8, y_max = upper_limit, heat_point = 0, humidity_point = 73, }) minetest.register_biome({ name = "icesheet_ocean", node_dust = "default:snowblock", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", node_water_top = "default:ice", depth_water_top = 10, --node_water = "", --node_river_water = "", y_min = -112, y_max = -9, heat_point = 0, humidity_point = 73, }) -- Tundra minetest.register_biome({ name = "tundra", node_dust = "default:snowblock", --node_top = , --depth_top = , --node_filler = , --depth_filler = , --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:gravel", depth_riverbed = 2, y_min = 2, y_max = upper_limit, heat_point = 0, humidity_point = 40, }) minetest.register_biome({ name = "tundra_beach", --node_dust = "", node_top = "default:gravel", depth_top = 1, node_filler = "default:gravel", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:gravel", depth_riverbed = 2, y_min = -3, y_max = 1, heat_point = 0, humidity_point = 40, }) minetest.register_biome({ name = "tundra_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:gravel", depth_riverbed = 2, y_min = -112, y_max = -4, heat_point = 0, humidity_point = 40, }) -- Taiga minetest.register_biome({ name = "taiga", node_dust = "default:snow", node_top = "default:dirt_with_snow", depth_top = 1, node_filler = "default:dirt", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = 2, y_max = upper_limit, heat_point = 25, humidity_point = 70, }) minetest.register_biome({ name = "taiga_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = -112, y_max = 1, heat_point = 25, humidity_point = 70, }) -- Snowy grassland minetest.register_biome({ name = "snowy_grassland", node_dust = "default:snow", node_top = "default:dirt_with_snow", depth_top = 1, node_filler = "default:dirt", depth_filler = 1, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = 5, y_max = upper_limit, heat_point = 20, humidity_point = 35, }) minetest.register_biome({ name = "snowy_grassland_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = -112, y_max = 4, heat_point = 20, humidity_point = 35, }) -- Grassland minetest.register_biome({ name = "grassland", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 1, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = 6, y_max = upper_limit, heat_point = 50, humidity_point = 35, }) minetest.register_biome({ name = "grassland_dunes", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = 5, y_max = 5, heat_point = 50, humidity_point = 35, }) minetest.register_biome({ name = "grassland_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = -112, y_max = 4, heat_point = 50, humidity_point = 35, }) -- Coniferous forest minetest.register_biome({ name = "coniferous_forest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = 6, y_max = upper_limit, heat_point = 45, humidity_point = 70, }) minetest.register_biome({ name = "coniferous_forest_dunes", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = 5, y_max = 5, heat_point = 45, humidity_point = 70, }) minetest.register_biome({ name = "coniferous_forest_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = -112, y_max = 4, heat_point = 45, humidity_point = 70, }) -- Deciduous forest minetest.register_biome({ name = "deciduous_forest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = 1, y_max = upper_limit, heat_point = 60, humidity_point = 68, }) minetest.register_biome({ name = "deciduous_forest_shore", --node_dust = "", node_top = "default:dirt", depth_top = 1, node_filler = "default:dirt", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = -1, y_max = 0, heat_point = 60, humidity_point = 68, }) minetest.register_biome({ name = "deciduous_forest_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = -112, y_max = -2, heat_point = 60, humidity_point = 68, }) -- Desert minetest.register_biome({ name = "desert", --node_dust = "", node_top = "default:desert_sand", depth_top = 1, node_filler = "default:desert_sand", depth_filler = 1, node_stone = "default:desert_stone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = 5, y_max = upper_limit, heat_point = 92, humidity_point = 16, }) minetest.register_biome({ name = "desert_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, node_stone = "default:desert_stone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = -112, y_max = 4, heat_point = 92, humidity_point = 16, }) -- Sandstone desert minetest.register_biome({ name = "sandstone_desert", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 1, node_stone = "default:sandstone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = 5, y_max = upper_limit, heat_point = 60, humidity_point = 0, }) minetest.register_biome({ name = "sandstone_desert_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, node_stone = "default:sandstone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = -112, y_max = 4, heat_point = 60, humidity_point = 0, }) -- Cold desert minetest.register_biome({ name = "cold_desert", --node_dust = "", node_top = "default:silver_sand", depth_top = 1, node_filler = "default:silver_sand", depth_filler = 1, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = 5, y_max = upper_limit, heat_point = 40, humidity_point = 0, }) minetest.register_biome({ name = "cold_desert_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = -112, y_max = 4, heat_point = 40, humidity_point = 0, }) -- Savanna minetest.register_biome({ name = "savanna", --node_dust = "", node_top = "default:dirt_with_dry_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 1, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = 1, y_max = upper_limit, heat_point = 89, humidity_point = 42, }) minetest.register_biome({ name = "savanna_shore", --node_dust = "", node_top = "default:dirt", depth_top = 1, node_filler = "default:dirt", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = -1, y_max = 0, heat_point = 89, humidity_point = 42, }) minetest.register_biome({ name = "savanna_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = -112, y_max = -2, heat_point = 89, humidity_point = 42, }) -- Rainforest minetest.register_biome({ name = "rainforest", --node_dust = "", node_top = "default:dirt_with_rainforest_litter", depth_top = 1, node_filler = "default:dirt", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = 1, y_max = upper_limit, heat_point = 86, humidity_point = 65, }) minetest.register_biome({ name = "rainforest_swamp", --node_dust = "", node_top = "default:dirt", depth_top = 1, node_filler = "default:dirt", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = -1, y_max = 0, heat_point = 86, humidity_point = 65, }) minetest.register_biome({ name = "rainforest_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", node_riverbed = "default:sand", depth_riverbed = 2, y_min = -112, y_max = -2, heat_point = 86, humidity_point = 65, }) -- Underground minetest.register_biome({ name = "underground", --node_dust = "", --node_top = "", --depth_top = , --node_filler = "", --depth_filler = , --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -31000, y_max = -113, heat_point = 50, humidity_point = 50, }) end -- Biomes for floatlands function default.register_floatland_biomes(floatland_level, shadow_limit) -- Coniferous forest minetest.register_biome({ name = "floatland_coniferous_forest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", --node_riverbed = "", --depth_riverbed = , y_min = floatland_level + 2, y_max = 31000, heat_point = 50, humidity_point = 70, }) -- Coniferous forest ocean minetest.register_biome({ name = "floatland_coniferous_forest_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", --node_riverbed = "", --depth_riverbed = , y_min = shadow_limit, y_max = floatland_level + 1, heat_point = 50, humidity_point = 70, }) -- Grassland minetest.register_biome({ name = "floatland_grassland", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 1, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", --node_riverbed = "", --depth_riverbed = , y_min = floatland_level + 2, y_max = 31000, heat_point = 50, humidity_point = 35, }) -- Grassland ocean minetest.register_biome({ name = "floatland_grassland_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", --node_riverbed = "", --depth_riverbed = , y_min = shadow_limit, y_max = floatland_level + 1, heat_point = 50, humidity_point = 35, }) -- Sandstone desert minetest.register_biome({ name = "floatland_sandstone_desert", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 1, node_stone = "default:sandstone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", --node_riverbed = "", --depth_riverbed = , y_min = floatland_level + 2, y_max = 31000, heat_point = 50, humidity_point = 0, }) -- Sandstone desert ocean minetest.register_biome({ name = "floatland_sandstone_desert_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, node_stone = "default:sandstone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", --node_riverbed = "", --depth_riverbed = , y_min = shadow_limit, y_max = floatland_level + 1, heat_point = 50, humidity_point = 0, }) end -- -- Register decorations -- -- Mgv6 function default.register_mgv6_decorations() -- Papyrus minetest.register_decoration({ deco_type = "simple", place_on = {"default:dirt_with_grass"}, sidelen = 16, noise_params = { offset = -0.3, scale = 0.7, spread = {x = 100, y = 100, z = 100}, seed = 354, octaves = 3, persist = 0.7 }, y_min = 1, y_max = 1, decoration = "default:papyrus", height = 2, height_max = 4, spawn_by = "default:water_source", num_spawn_by = 1, }) -- Cacti minetest.register_decoration({ deco_type = "simple", place_on = {"default:desert_sand"}, sidelen = 16, noise_params = { offset = -0.012, scale = 0.024, spread = {x = 100, y = 100, z = 100}, seed = 230, octaves = 3, persist = 0.6 }, y_min = 1, y_max = 30, decoration = "default:cactus", height = 3, height_max = 4, }) -- Long grasses for length = 1, 5 do minetest.register_decoration({ deco_type = "simple", place_on = {"default:dirt_with_grass"}, sidelen = 16, noise_params = { offset = 0, scale = 0.007, spread = {x = 100, y = 100, z = 100}, seed = 329, octaves = 3, persist = 0.6 }, y_min = 1, y_max = 30, decoration = "default:grass_"..length, }) end -- Dry shrubs minetest.register_decoration({ deco_type = "simple", place_on = {"default:desert_sand", "default:dirt_with_snow"}, sidelen = 16, noise_params = { offset = 0, scale = 0.035, spread = {x = 100, y = 100, z = 100}, seed = 329, octaves = 3, persist = 0.6 }, y_min = 1, y_max = 30, decoration = "default:dry_shrub", }) end -- All mapgens except mgv6 local function register_grass_decoration(offset, scale, length) minetest.register_decoration({ deco_type = "simple", place_on = {"default:dirt_with_grass", "default:sand"}, sidelen = 16, noise_params = { offset = offset, scale = scale, spread = {x = 200, y = 200, z = 200}, seed = 329, octaves = 3, persist = 0.6 }, biomes = {"grassland", "grassland_dunes", "deciduous_forest", "coniferous_forest", "coniferous_forest_dunes", "floatland_grassland", "floatland_coniferous_forest"}, y_min = 1, y_max = 31000, decoration = "default:grass_" .. length, }) end local function register_dry_grass_decoration(offset, scale, length) minetest.register_decoration({ deco_type = "simple", place_on = {"default:dirt_with_dry_grass"}, sidelen = 16, noise_params = { offset = offset, scale = scale, spread = {x = 200, y = 200, z = 200}, seed = 329, octaves = 3, persist = 0.6 }, biomes = {"savanna"}, y_min = 1, y_max = 31000, decoration = "default:dry_grass_" .. length, }) end function default.register_decorations() -- Apple tree and log minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_grass"}, sidelen = 16, noise_params = { offset = 0.036, scale = 0.022, spread = {x = 250, y = 250, z = 250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"deciduous_forest"}, y_min = 1, y_max = 31000, schematic = minetest.get_modpath("default") .. "/schematics/apple_tree.mts", flags = "place_center_x, place_center_z", rotation = "random", }) minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_grass"}, sidelen = 16, noise_params = { offset = 0.0018, scale = 0.0011, spread = {x = 250, y = 250, z = 250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"deciduous_forest"}, y_min = 1, y_max = 31000, schematic = minetest.get_modpath("default") .. "/schematics/apple_log.mts", flags = "place_center_x", rotation = "random", }) -- Jungle tree and log minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_rainforest_litter", "default:dirt"}, sidelen = 16, fill_ratio = 0.1, biomes = {"rainforest", "rainforest_swamp"}, y_min = -1, y_max = 31000, schematic = minetest.get_modpath("default") .. "/schematics/jungle_tree.mts", flags = "place_center_x, place_center_z", rotation = "random", }) minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_rainforest_litter", "default:dirt"}, sidelen = 16, fill_ratio = 0.005, biomes = {"rainforest", "rainforest_swamp"}, y_min = 1, y_max = 31000, schematic = minetest.get_modpath("default") .. "/schematics/jungle_log.mts", flags = "place_center_x", rotation = "random", }) -- Taiga and temperate coniferous forest pine tree and log minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_snow", "default:dirt_with_grass"}, sidelen = 16, noise_params = { offset = 0.036, scale = 0.022, spread = {x = 250, y = 250, z = 250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"taiga", "coniferous_forest", "floatland_coniferous_forest"}, y_min = 2, y_max = 31000, schematic = minetest.get_modpath("default") .. "/schematics/pine_tree.mts", flags = "place_center_x, place_center_z", }) minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_snow", "default:dirt_with_grass"}, sidelen = 80, noise_params = { offset = 0.0018, scale = 0.0011, spread = {x = 250, y = 250, z = 250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"taiga", "coniferous_forest"}, y_min = 1, y_max = 31000, schematic = minetest.get_modpath("default") .. "/schematics/pine_log.mts", flags = "place_center_x", rotation = "random", }) -- Acacia tree and log minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_dry_grass"}, sidelen = 16, noise_params = { offset = 0, scale = 0.002, spread = {x = 250, y = 250, z = 250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"savanna"}, y_min = 1, y_max = 31000, schematic = minetest.get_modpath("default") .. "/schematics/acacia_tree.mts", flags = "place_center_x, place_center_z", rotation = "random", }) minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_dry_grass"}, sidelen = 16, noise_params = { offset = 0, scale = 0.001, spread = {x = 250, y = 250, z = 250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"savanna"}, y_min = 1, y_max = 31000, schematic = minetest.get_modpath("default") .. "/schematics/acacia_log.mts", flags = "place_center_x", rotation = "random", }) -- Aspen tree and log minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_grass"}, sidelen = 16, noise_params = { offset = 0.0, scale = -0.015, spread = {x = 250, y = 250, z = 250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"deciduous_forest"}, y_min = 1, y_max = 31000, schematic = minetest.get_modpath("default") .. "/schematics/aspen_tree.mts", flags = "place_center_x, place_center_z", }) minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_grass"}, sidelen = 16, noise_params = { offset = 0.0, scale = -0.0008, spread = {x = 250, y = 250, z = 250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"deciduous_forest"}, y_min = 1, y_max = 31000, schematic = minetest.get_modpath("default") .. "/schematics/aspen_log.mts", flags = "place_center_x", rotation = "random", }) -- Large cactus minetest.register_decoration({ deco_type = "schematic", place_on = {"default:desert_sand"}, sidelen = 16, noise_params = { offset = -0.0003, scale = 0.0009, spread = {x = 200, y = 200, z = 200}, seed = 230, octaves = 3, persist = 0.6 }, biomes = {"desert"}, y_min = 5, y_max = 31000, schematic = minetest.get_modpath("default") .. "/schematics/large_cactus.mts", flags = "place_center_x", rotation = "random", }) -- Cactus minetest.register_decoration({ deco_type = "simple", place_on = {"default:desert_sand"}, sidelen = 16, noise_params = { offset = -0.0003, scale = 0.0009, spread = {x = 200, y = 200, z = 200}, seed = 230, octaves = 3, persist = 0.6 }, biomes = {"desert"}, y_min = 5, y_max = 31000, decoration = "default:cactus", height = 2, height_max = 5, }) -- Papyrus minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt"}, sidelen = 16, noise_params = { offset = -0.3, scale = 0.7, spread = {x = 200, y = 200, z = 200}, seed = 354, octaves = 3, persist = 0.7 }, biomes = {"savanna_shore"}, y_min = 0, y_max = 0, schematic = minetest.get_modpath("default") .. "/schematics/papyrus.mts", }) -- Bush minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_grass", "default:dirt_with_snow"}, sidelen = 16, noise_params = { offset = -0.004, scale = 0.01, spread = {x = 100, y = 100, z = 100}, seed = 137, octaves = 3, persist = 0.7, }, biomes = {"snowy_grassland", "grassland", "deciduous_forest", "floatland_grassland"}, y_min = 1, y_max = 31000, schematic = minetest.get_modpath("default") .. "/schematics/bush.mts", flags = "place_center_x, place_center_z", }) -- Acacia bush minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_dry_grass"}, sidelen = 16, noise_params = { offset = -0.004, scale = 0.01, spread = {x = 100, y = 100, z = 100}, seed = 90155, octaves = 3, persist = 0.7, }, biomes = {"savanna"}, y_min = 1, y_max = 31000, schematic = minetest.get_modpath("default") .. "/schematics/acacia_bush.mts", flags = "place_center_x, place_center_z", }) -- Grasses register_grass_decoration(-0.03, 0.09, 5) register_grass_decoration(-0.015, 0.075, 4) register_grass_decoration(0, 0.06, 3) register_grass_decoration(0.015, 0.045, 2) register_grass_decoration(0.03, 0.03, 1) -- Dry grasses register_dry_grass_decoration(0.01, 0.05, 5) register_dry_grass_decoration(0.03, 0.03, 4) register_dry_grass_decoration(0.05, 0.01, 3) register_dry_grass_decoration(0.07, -0.01, 2) register_dry_grass_decoration(0.09, -0.03, 1) -- Junglegrass minetest.register_decoration({ deco_type = "simple", place_on = {"default:dirt_with_rainforest_litter"}, sidelen = 16, fill_ratio = 0.1, biomes = {"rainforest"}, y_min = 1, y_max = 31000, decoration = "default:junglegrass", }) -- Dry shrub minetest.register_decoration({ deco_type = "simple", place_on = {"default:desert_sand", "default:sand", "default:silver_sand"}, sidelen = 16, noise_params = { offset = 0, scale = 0.02, spread = {x = 200, y = 200, z = 200}, seed = 329, octaves = 3, persist = 0.6 }, biomes = {"desert", "sandstone_desert", "cold_desert"}, y_min = 2, y_max = 31000, decoration = "default:dry_shrub", }) -- Coral reef minetest.register_decoration({ deco_type = "schematic", place_on = {"default:sand"}, noise_params = { offset = -0.15, scale = 0.1, spread = {x = 100, y = 100, z = 100}, seed = 7013, octaves = 3, persist = 1, }, biomes = { "desert_ocean", "savanna_ocean", "rainforest_ocean", }, y_min = -8, y_max = -2, schematic = minetest.get_modpath("default") .. "/schematics/corals.mts", flags = "place_center_x, place_center_z", rotation = "random", }) end -- -- Detect mapgen, flags and parameters to select functions -- -- Get setting or default local mgv7_spflags = minetest.get_mapgen_setting("mgv7_spflags") or "mountains, ridges, nofloatlands" local captures_float = string.match(mgv7_spflags, "floatlands") local captures_nofloat = string.match(mgv7_spflags, "nofloatlands") local mgv7_floatland_level = minetest.get_mapgen_setting("mgv7_floatland_level") or 1280 local mgv7_shadow_limit = minetest.get_mapgen_setting("mgv7_shadow_limit") or 1024 minetest.clear_registered_biomes() minetest.clear_registered_ores() minetest.clear_registered_decorations() local mg_name = minetest.get_mapgen_setting("mg_name") if mg_name == "v6" then default.register_mgv6_blob_ores() default.register_ores() default.register_mgv6_decorations() elseif mg_name == "v7" and captures_float == "floatlands" and captures_nofloat ~= "nofloatlands" then -- Mgv7 with floatlands default.register_biomes(mgv7_shadow_limit - 1) default.register_floatland_biomes(mgv7_floatland_level, mgv7_shadow_limit) default.register_blob_ores() default.register_ores() default.register_decorations() else default.register_biomes(31000) default.register_blob_ores() default.register_ores() default.register_decorations() end
lgpl-2.1
Quenty/NevermoreEngine
src/loader/src/PackageInfoUtils.lua
1
8267
--[=[ Utility methods to build a virtual graph of the existing package information set @private @class PackageInfoUtils ]=] local BounceTemplateUtils = require(script.Parent.BounceTemplateUtils) local LoaderConstants = require(script.Parent.LoaderConstants) local Queue = require(script.Parent.Queue) local ScriptInfoUtils = require(script.Parent.ScriptInfoUtils) local Utils = require(script.Parent.Utils) local PackageInfoUtils = {} function PackageInfoUtils.createPackageInfo(packageFolder, explicitDependencySet, scriptInfoLookup, fullName) assert(typeof(packageFolder) == "Instance", "Bad packageFolder") assert(type(explicitDependencySet) == "table", "Bad explicitDependencySet") assert(type(scriptInfoLookup) == "table", "Bad scriptInfoLookup") assert(type(fullName) == "string", "Bad fullName") return Utils.readonly({ name = packageFolder.Name; fullName = fullName; instance = packageFolder; explicitDependencySet = explicitDependencySet; dependencySet = false; -- will be filled in later, contains ALL expected dependencies scriptInfoLookup = scriptInfoLookup; }) end function PackageInfoUtils.createDependencyQueueInfo(packageInfo, implicitDependencySet) assert(type(packageInfo) == "table", "Bad packageInfo") assert(type(implicitDependencySet) == "table", "Bad implicitDependencySet") return Utils.readonly({ packageInfo = packageInfo; implicitDependencySet = implicitDependencySet; }) end function PackageInfoUtils.fillDependencySet(packageInfoList) assert(type(packageInfoList) == "table", "Bad packageInfoList") local queue = Queue.new() local seen = {} do local topDependencySet = {} for _, packageInfo in pairs(packageInfoList) do if not seen[packageInfo] then topDependencySet[packageInfo] = packageInfo seen[packageInfo] = true queue:PushRight(PackageInfoUtils.createDependencyQueueInfo(packageInfo, topDependencySet)) end end end -- Flaw: We can enter this dependency chain from multiple paths (we're a cyclic directed graph, not a tree) -- TODO: Determine node_modules behavior and copy it (hopefully any link upwards words) -- For now we do breadth first resolution of this to ensure minimal dependencies are accumulated for deep trees while not queue:IsEmpty() do local queueInfo = queue:PopLeft() assert(not queueInfo.packageInfo.dependencySet, "Already wrote dependencySet") local dependencySet = PackageInfoUtils .computePackageDependencySet(queueInfo.packageInfo, queueInfo.implicitDependencySet) queueInfo.packageInfo.dependencySet = dependencySet -- Process all explicit dependencies for the next level for packageInfo, _ in pairs(queueInfo.packageInfo.explicitDependencySet) do if not seen[packageInfo] then seen[packageInfo] = true queue:PushRight(PackageInfoUtils.createDependencyQueueInfo(packageInfo, dependencySet)) end end end end function PackageInfoUtils.computePackageDependencySet(packageInfo, implicitDependencySet) assert(type(packageInfo) == "table", "Bad packageInfo") assert(type(implicitDependencySet) == "table", "Bad implicitDependencySet") -- assume folders with the same name are the same module local dependencyNameMap = {} -- Set implicit dependencies if LoaderConstants.INCLUDE_IMPLICIT_DEPENDENCIES then for entry, _ in pairs(implicitDependencySet) do dependencyNameMap[entry.name] = entry end end -- These override implicit ones for entry, _ in pairs(packageInfo.explicitDependencySet) do dependencyNameMap[entry.name] = entry end -- clear ourself as a dependency dependencyNameMap[packageInfo.name] = nil -- Note we leave conflicting scripts here as unresolved. This will output an error later. local dependencySet = {} for _, entry in pairs(dependencyNameMap) do dependencySet[entry] = true end return dependencySet end function PackageInfoUtils.getOrCreatePackageInfo(packageFolder, packageInfoMap, scope, defaultReplicationType) assert(typeof(packageFolder) == "Instance", "Bad packageFolder") assert(type(packageInfoMap) == "table", "Bad packageInfoMap") assert(type(scope) == "string", "Bad scope") assert(defaultReplicationType, "No defaultReplicationType") if packageInfoMap[packageFolder] then return packageInfoMap[packageFolder] end local scriptInfoLookup = ScriptInfoUtils.createScriptInfoLookup() ScriptInfoUtils.populateScriptInfoLookup( packageFolder, scriptInfoLookup, defaultReplicationType) local explicitDependencySet = {} local fullName if scope == "" then fullName = packageFolder.Name else fullName = scope .. "/" .. packageFolder.Name end local packageInfo = PackageInfoUtils .createPackageInfo(packageFolder, explicitDependencySet, scriptInfoLookup, fullName) packageInfoMap[packageFolder] = packageInfo -- Fill this after we've registered ourselves, in case we're somehow in a recursive dependency set PackageInfoUtils.fillExplicitPackageDependencySet( explicitDependencySet, packageFolder, packageInfoMap, defaultReplicationType) return packageInfo end function PackageInfoUtils.getPackageInfoListFromDependencyFolder(folder, packageInfoMap, defaultReplicationType) assert(typeof(folder) == "Instance" and folder:IsA("Folder"), "Bad folder") assert(type(packageInfoMap) == "table", "Bad packageInfoMap") assert(defaultReplicationType, "No defaultReplicationType") local packageInfoList = {} -- Assume we are at the dependency level for _, instance in pairs(folder:GetChildren()) do if instance:IsA("Folder") then -- We loop through each "@quenty" or "@blah" and convert to a package if instance.Name:sub(1, 1) == "@" then local scope = instance.Name for _, child in pairs(instance:GetChildren()) do PackageInfoUtils.tryLoadPackageFromInstance(packageInfoList, packageInfoMap, child, scope, defaultReplicationType) end else PackageInfoUtils.tryLoadPackageFromInstance(packageInfoList, packageInfoMap, instance, "", defaultReplicationType) end else warn(("Unknown instance in dependencyFolder - %q"):format(instance:GetFullName())) end end return packageInfoList end function PackageInfoUtils.tryLoadPackageFromInstance( packageInfoList, packageInfoMap, instance, scope, defaultReplicationType) assert(type(packageInfoList) == "table", "Bad packageInfoList") assert(type(packageInfoMap) == "table", "Bad packageInfoMap") assert(typeof(instance) == "Instance", "Bad instance") assert(type(scope) == "string", "Bad scope") assert(defaultReplicationType, "No defaultReplicationType") if BounceTemplateUtils.isBounceTemplate(instance) then return end if instance:IsA("Folder") or instance:IsA("ModuleScript") then table.insert(packageInfoList, PackageInfoUtils.getOrCreatePackageInfo( instance, packageInfoMap, scope, defaultReplicationType)) elseif instance:IsA("ObjectValue") then local value = instance.Value if value and (value:IsA("Folder") or value:IsA("ModuleScript")) then table.insert(packageInfoList, PackageInfoUtils.getOrCreatePackageInfo( value, packageInfoMap, scope, defaultReplicationType)) else error(("Invalid %q ObjectValue in package linking to nothing cannot be resolved into package dependency\n\t-> %s") :format(instance.Name, instance:GetFullName())) end end end -- Explicit dependencies are dependencies that are are explicitly listed. -- These dependencies are available to this package and ANY dependent packages below function PackageInfoUtils.fillExplicitPackageDependencySet( explicitDependencySet, packageFolder, packageInfoMap, defaultReplicationType) assert(type(explicitDependencySet) == "table", "Bad explicitDependencySet") assert(typeof(packageFolder) == "Instance", "Bad packageFolder") assert(type(packageInfoMap) == "table", "Bad packageInfoMap") assert(defaultReplicationType, "No defaultReplicationType") for _, item in pairs(packageFolder:GetChildren()) do if (item:IsA("Folder") or item:IsA("Camera")) and item.Name == ScriptInfoUtils.DEPENDENCY_FOLDER_NAME then local packageInfoList = PackageInfoUtils.getPackageInfoListFromDependencyFolder( item, packageInfoMap, defaultReplicationType) for _, packageInfo in pairs(packageInfoList) do explicitDependencySet[packageInfo] = true end end end end return PackageInfoUtils
mit
farrajota/human_pose_estimation_torch
tests/crop_comparison.lua
1
2804
--[[ Test the data generator. --]] require 'torch' require 'paths' require 'string' disp = require 'display' torch.manualSeed(4) paths.dofile('../projectdir.lua') -- Project directory utils = paths.dofile('../util/utils.lua') local opts = paths.dofile('../options.lua') opt = opts.parse(arg) opt.dataset = 'lsp' opt.rotRate=0 paths.dofile('../dataset.lua') paths.dofile('../data.lua') dataset = loadDataset() -- load dataset train+val+test sets mode = 'train' idx = 3500 local function rnd(x) return math.max(-2*x,math.min(2*x,torch.randn(1)[1]*x)) end local r = 0 -- set rotation to 0 -- Load image + keypoints + other data local img, keypoints, c, s, nJoints = loadImgKeypointsFn_(dataset[mode], idx) local s_ = s -- Do rotation + scaling if mode == 'train' then -- Scale and rotation augmentation --s = s * torch.uniform(1-opt.scale, 1+opt.scale) s = s * (2 ^ rnd(opt.scale)) r = rnd(opt.rotate) --r = torch.uniform(-opt.rotate, opt.rotate) if torch.uniform() <= opt.rotRate then r = 0 end end ---------------------------------------------------------------------------- -- my crop ----------------------------------------------------------------- ---------------------------------------------------------------------------- -- Crop image + craft heatmap local kps1 = {} local img_transf1 = mycrop(img, c, s, r, opt.inputRes) local heatmap1 = torch.zeros(nJoints, opt.outputRes, opt.outputRes) for i = 1,nJoints do if keypoints[i][1] > 1 then -- Checks that there is a ground truth annotation local new_kp = mytransform(keypoints[i], c, s, r, opt.outputRes) drawGaussian(heatmap1[i], new_kp:int(), opt.hmGauss) table.insert(kps1, new_kp:totable()) end end disp.image(img_transf1,{title='my crop'}) ---------------------------------------------------------------------------- -- crop2 ------------------------------------------------------------------ ---------------------------------------------------------------------------- -- Crop image + craft heatmap local kps2 = {} local img_transf2 = crop2(img, c, s, r, opt.inputRes) local heatmap2 = torch.zeros(nJoints, opt.outputRes, opt.outputRes) for i = 1,nJoints do if keypoints[i][1] > 1 then -- Checks that there is a ground truth annotation local new_kp = transform(torch.add(keypoints[i],1), c, s, r, opt.outputRes) drawGaussian(heatmap2[i], new_kp, opt.hmGauss) table.insert(kps2, new_kp:totable()) end end disp.image(img_transf2,{title='crop2'}) disp.image(torch.csub(img_transf1:float(),img_transf2:float()),{title='difference'}) disp.image(torch.csub(heatmap1:float(),heatmap2:float()),{title='difference heatmaps'}) print('Keypoints my:') print(torch.FloatTensor(kps1)) print('Keypoints crop2:') print(torch.FloatTensor(kps2))
mit
ffxiphoenix/darkstar
scripts/zones/Chamber_of_Oracles/npcs/Pedestal_of_Light.lua
17
2270
----------------------------------- -- Area: Chamber of Oracles -- NPC: Pedestal of Light -- Involved in Zilart Mission 7 -- @pos 199 -2 36 168 ------------------------------------- package.loaded["scripts/zones/Chamber_of_Oracles/TextIDs"] = nil; ------------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Chamber_of_Oracles/TextIDs"); ------------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ZilartStatus = player:getVar("ZilartStatus"); if (player:getCurrentMission(ZILART) == THE_CHAMBER_OF_ORACLES) then if (player:hasKeyItem(LIGHT_FRAGMENT)) then player:delKeyItem(LIGHT_FRAGMENT); player:setVar("ZilartStatus",ZilartStatus + 16); player:messageSpecial(YOU_PLACE_THE,LIGHT_FRAGMENT); if (ZilartStatus == 255) then player:startEvent(0x0001); end elseif (ZilartStatus == 255) then -- Execute cutscene if the player is interrupted. player:startEvent(0x0001); else player:messageSpecial(IS_SET_IN_THE_PEDESTAL,LIGHT_FRAGMENT); end elseif (player:hasCompletedMission(ZILART,THE_CHAMBER_OF_ORACLES)) then player:messageSpecial(HAS_LOST_ITS_POWER,LIGHT_FRAGMENT); else player:messageSpecial(PLACED_INTO_THE_PEDESTAL); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (csid == 0x0001) then player:addTitle(LIGHTWEAVER); player:setVar("ZilartStatus",2); player:addKeyItem(PRISMATIC_FRAGMENT); player:messageSpecial(KEYITEM_OBTAINED,PRISMATIC_FRAGMENT); player:completeMission(ZILART,THE_CHAMBER_OF_ORACLES); player:addMission(ZILART,RETURN_TO_DELKFUTTS_TOWER); end end;
gpl-3.0
hewei-chn/resurgence
examples/tutorial-constants.lua
6
1473
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --[[ --]] -- we need at least 0.5.1 assert(proxy.PROXY_VERSION >= 0x00501, "you need at least mysql-proxy 0.5.1 to run this module") --- -- read_query() gets the client query before it reaches the server -- -- @param packet the mysql-packet sent by client -- -- we have several constants defined, e.g.: -- * _VERSION -- -- * proxy.PROXY_VERSION -- * proxy.COM_* -- * proxy.MYSQL_FIELD_* -- function read_query( packet ) if packet:byte() == proxy.COM_QUERY then print("get got a Query: " .. packet:sub(2)) -- proxy.PROXY_VERSION is the proxy version as HEX number -- 0x00501 is 0.5.1 print("we are: " .. string.format("%05x", proxy.PROXY_VERSION)) print("lua is: " .. _VERSION) end end
gpl-2.0
AfuSensi/Mr.Green-MTA-Resources
resources/[admin]/admin/server/admin_sync.lua
1
11755
--[[********************************** * * Multi Theft Auto - Admin Panel * * admin_sync.lua * * Original File by lil_Toady * **************************************]] function aSynchCoroutineFunc( type, data ) local source = source -- Needed if checkClient( false, source, 'aSync', type ) then return end local cor = aSyncCoroutine local tableOut = {} local theSource = _root if client and not hasObjectPermissionTo ( client, "general.adminpanel" ) then type = "loggedout" elseif ( type == "player" ) then if not isElement( data ) then return end aPlayers[source]["sync"] = data tableOut["mute"] = isPlayerMuted ( data ) tableOut["freeze"] = isPlayerFrozen ( data ) tableOut["money"] = getPlayerMoney ( data ) tableOut["username"] = getPlayerUserName ( data ) or "N/A" tableOut["version"] = aPlayers[data]["version"] tableOut["accountname"] = getPlayerAccountName ( data ) or "N/A" tableOut["groups"] = "None" tableOut["acdetected"] = getPlayerACDetectedList( data ) tableOut["d3d9dll"] = getPlayerD3D9DLLHash( data ) tableOut["imgmodsnum"] = getPlayerImgModsCount( data ) local account = getPlayerAccount ( data ) if ( isGuestAccount ( account ) ) then tableOut["groups"] = "Not logged in" else local groups = aclGetAccountGroups ( account ) if ( #groups <= 0 ) then tableOut["groups"] = "None" else tableOut["groups"] = table.concat(table.reverse(groups), ", ") end end theSource = data elseif ( type == "players" ) then for id, player in ipairs(getElementsByType("player")) do if aPlayers[player] then tableOut[player] = {} tableOut[player]["name"] = getPlayerName ( player ) tableOut[player]["IP"] = getPlayerIP ( player ) tableOut[player]["username"] = getPlayerUserName ( player ) or "N/A" tableOut[player]["version"] = aPlayers[player]["version"] tableOut[player]["accountname"] = getPlayerAccountName ( player ) or "N/A" tableOut[player]["serial"] = getPlayerSerial ( player ) tableOut[player]["country"] = aPlayers[player]["country"] tableOut[player]["admin"] = hasObjectPermissionTo ( player, "general.adminpanel" ) tableOut[player]["acdetected"] = getPlayerACDetectedList( player ) tableOut[player]["d3d9dll"] = getPlayerD3D9DLLHash( player ) tableOut[player]["imgmodsnum"] = getPlayerImgModsCount( player ) end end elseif ( type == "resources" ) then local resourceTable = getResources() local tick = getTickCount() local antiCorMessageSpam = 0 for id, resource in ipairs(resourceTable) do local name = getResourceName ( resource ) local state = getResourceState ( resource ) local type = getResourceInfo ( resource, "type" ) local _,numsettings = aGetResourceSettings(name,true) tableOut[id] = {} tableOut[id]["name"] = name tableOut[id]["numsettings"] = numsettings tableOut[id]["state"] = state tableOut[id]["type"] = type tableOut[id]["fullName"] = getResourceInfo(resource, "name") or "Unknown" tableOut[id]["author"] = getResourceInfo(resource, "author") or "Unknown" tableOut[id]["version"] = getResourceInfo(resource, "version") or "Unknown" if ( getTickCount() > tick + 100 ) then -- Execution exceeded 100ms so pause and resume in 100ms setTimer(function() local status = coroutine.status(cor) if (status == "suspended") then coroutine.resume(cor) elseif (status == "dead") then cor = nil end end, 100, 1) if (antiCorMessageSpam == 0) then outputChatBox("Please wait, resource list still loading... Don't try refresh.", source, 255, 255, 0) end antiCorMessageSpam = antiCorMessageSpam + 1 coroutine.yield() tick = getTickCount() end end elseif ( type == "admins" ) then for id, player in ipairs(getElementsByType("player")) do if aPlayers[player] then tableOut[player] = {} tableOut[player]["admin"] = hasObjectPermissionTo ( player, "general.adminpanel" ) if ( tableOut[player]["admin"] ) then tableOut[player]["chat"] = aPlayers[player]["chat"] end tableOut[player]["groups"] = "None" local account = getPlayerAccount ( player ) if ( isGuestAccount ( account ) ) then tableOut[player]["groups"] = "Not logged in" else local groups = aclGetAccountGroups ( account ) if ( #groups <= 0 ) then tableOut[player]["groups"] = "None" else tableOut[player]["groups"] = table.concat(table.reverse(groups), ", ") end end end end elseif ( type == "server" ) then tableOut["name"] = getServerName() tableOut["players"] = getMaxPlayers() tableOut["game"] = getGameType() tableOut["map"] = getMapName() tableOut["password"] = getServerPassword() tableOut["fps"] = getFPSLimit() elseif ( type == "rights" ) then for gi, group in ipairs ( aclListGroups() ) do for oi, object in ipairs ( aclGroupListObjects ( group ) ) do if ( ( object == data ) or ( object == "user.*" ) ) then for ai, acl in ipairs ( aclGroupListACL ( group ) ) do for ri, right in ipairs ( aclListRights ( acl ) ) do local access = aclGetRight ( acl, string ) if ( access ) then table.insert ( tableOut, right ) end end end break end end end elseif ( type == "bansdirty" ) then tableOut = nil g_Bans = nil elseif ( type == "bans" or type == "bansmore" ) then if not g_Bans then local bans = getBans() g_Bans = {} -- Reverse for i = #bans,1,-1 do table.insert( g_Bans, bans[i] ) end end local from = ( tonumber( data ) or 0 ) + 1 local to = math.min( from+24, #g_Bans ) tableOut.total = #g_Bans for b=from,to do i = b - from + 1 ban = g_Bans[b] local seconds = getBanTime(ban) tableOut[i] = {} tableOut[i].nick = getBanUsername(ban) or getBanNick(ban) tableOut[i].seconds = seconds tableOut[i].banner = getBanAdmin(ban) tableOut[i].ip = getBanIP(ban) tableOut[i].serial = getBanSerial(ban) tableOut[i].reason = getBanReason(ban) end elseif ( type == "messages" ) then local unread, total = 0, 0 for id, msg in ipairs ( aReports ) do if ( not msg.read ) then unread = unread + 1 end total = total + 1 end tableOut["unread"] = unread tableOut["total"] = total end if (isElement(source)) then -- Incase the source has quit during coroutine loading triggerClientEvent ( source, "aClientSync", theSource, type, tableOut ) end end addEvent("aSync", true) addEventHandler("aSync", _root, function(type, data) aSyncCoroutine = coroutine.create(aSynchCoroutineFunc) coroutine.resume(aSyncCoroutine, type, data) end ) addEvent ( "onPlayerMoneyChange", false ) addEventHandler ( "onResourceStart", getResourceRootElement ( getThisResource () ), function() setTimer ( function() for id, player in ipairs ( getElementsByType ( "player" ) ) do if aPlayers[player] then local money = getPlayerMoney ( player ) local prev = aPlayers[player]["money"] if ( money ~= prev ) then triggerEvent ( "onPlayerMoneyChange", player, prev, money ) aPlayers[player]["money"] = money end end end end, 1500, 0 ) end ) addEventHandler ( "onPlayerMoneyChange", _root, function ( prev, new ) for player, sync in pairs ( aPlayers ) do if ( sync["sync"] == source ) then triggerClientEvent ( player, "aClientSync", source, "player", { ["money"] = new } ) end end end ) addEventHandler ( "onPlayerMute", _root, function ( state ) for player, sync in pairs ( aPlayers ) do if ( sync["sync"] == source ) then triggerClientEvent ( player, "aClientSync", source, "player", { ["mute"] = state } ) end end end ) addEventHandler ( "onPlayerFreeze", _root, function ( state ) for player, sync in pairs ( aPlayers ) do if ( sync["sync"] == source ) then triggerClientEvent ( player, "aClientSync", source, "player", { ["freeze"] = state } ) end end end ) addEvent ( "aPermissions", true ) addEventHandler ( "aPermissions", _root, function() if checkClient( false, source, 'aPermissions' ) then return end if ( hasObjectPermissionTo ( source, "general.adminpanel" ) ) then local tableOut = {} for gi, group in ipairs ( aclGroupList() ) do for oi, object in ipairs ( aclGroupListObjects ( group ) ) do if ( ( object == aclGetAccount ( source ) ) or ( object == "user.*" ) ) then for ai, acl in ipairs ( aclGroupListACL ( group ) ) do for ri, right in ipairs ( aclListRights ( acl ) ) do local access = aclGetRight ( acl, right ) if ( access ) then table.insert ( tableOut, right ) end end end break end end end triggerClientEvent ( source, "aPermissions", source, tableOut ) end end ) addEventHandler ( "onBan", _root, function() setTimer( triggerEvent, 200, 1, "aSync", _root, "bansdirty" ) end ) addEventHandler ( "onUnban", _root, function() setTimer( triggerEvent, 200, 1, "aSync", _root, "bansdirty" ) end ) function table.reverse(t) local newt = {} for idx,item in ipairs(t) do newt[#t - idx + 1] = item end return newt end function table.cmp(t1, t2) if not t1 or not t2 or #t1 ~= #t2 then return false end for k,v in pairs(t1) do if v ~= t2[k] then return false end end return true end function table.compare(tab1,tab2) if tab1 and tab2 then if tab1 == tab2 then return true end if type(tab1) == 'table' and type(tab2) == 'table' then if table.size(tab1) ~= table.size(tab2) then return false end for index, content in pairs(tab1) do if not table.compare(tab2[index],content) then return false end end return true end end return false end function table.size(tab) local length = 0 if tab then for _ in pairs(tab) do length = length + 1 end end return length end ---------------------------------------- -- AC getPlayer functions ---------------------------------------- function getPlayerACDetectedList( player ) return getPlayerACInfo( player ).DetectedAC end function getPlayerD3D9DLLHash( player ) return getPlayerACInfo( player ).d3d9MD5 end function getPlayerImgModsCount( player ) return #getPlayerModInfoStore( player ).list end function getPlayerImgModsList( player ) return getPlayerModInfoStore( player ).list end ---------------------------------------- -- Save mod info info ---------------------------------------- addEventHandler( "onPlayerModInfo", root, function ( filename, modList ) local store = getPlayerModInfoStore( source ) for _,mod in ipairs(modList) do -- Check each modified item if not store.dic[mod.name] then store.dic[mod.name] = true table.insert( store.list, mod ) end end end ) addEventHandler( "onResourceStart", resourceRoot, function() for _,player in ipairs( getElementsByType("player") ) do resendPlayerModInfo( player ) end end ) addEventHandler( "onPlayerQuit", root, function() modInfoStore[ source ] = nil end ) ---------------------------------------- -- Place to save mod info about each player ---------------------------------------- modInfoStore = {} function getPlayerModInfoStore( player ) if not modInfoStore[ player ] then modInfoStore[ player ] = {} modInfoStore[ player ].dic = {} modInfoStore[ player ].list = {} end return modInfoStore[ player ] end ---------------------------------------- -- Backwards compat version of getPlayerACInfo ---------------------------------------- _getPlayerACInfo = getPlayerACInfo function getPlayerACInfo( player ) if not _getPlayerACInfo then return { ["DetectedAC"]="", ["d3d9MD5"]="", ["d3d9Size"]=0 } end return _getPlayerACInfo( player ) end
mit
kondrak/ProDBG
bin/macosx/tundra/scripts/tundra/tools/vbcc.lua
25
1563
module(..., package.seeall) local native = require "tundra.native" function apply(env, options) -- load the generic C toolset first tundra.unitgen.load_toolset("generic-cpp", env) -- Also add assembly support. tundra.unitgen.load_toolset("generic-asm", env) local vbcc_root = assert(native.getenv("VBCC"), "VBCC environment variable must be set") env:set_many { ["NATIVE_SUFFIXES"] = { ".c", ".cpp", ".cc", ".cxx", ".s", ".asm", ".a", ".o" }, ["OBJECTSUFFIX"] = ".o", ["LIBPREFIX"] = "", ["LIBSUFFIX"] = ".a", ["VBCC_ROOT"] = vbcc_root, ["CC"] = vbcc_root .. "$(SEP)bin$(SEP)vc$(HOSTPROGSUFFIX)", ["LIB"] = vbcc_root .. "$(SEP)bin$(SEP)vlink$(HOSTPROGSUFFIX)", ["LD"] = vbcc_root .. "$(SEP)bin$(SEP)vc$(HOSTPROGSUFFIX)", ["ASM"] = vbcc_root .. "$(SEP)bin$(SEP)vasmm68k_mot$(HOSTPROGSUFFIX)", ["VBCC_SDK_INC"] = vbcc_root .. "$(SEP)include$(SEP)sdk", ["_OS_CCOPTS"] = "", ["_OS_CXXOPTS"] = "", ["CCCOM"] = "$(CC) $(_OS_CCOPTS) -c $(CPPDEFS:p-D) $(CPPPATH:f:p-I) $(CCOPTS) $(CCOPTS_$(CURRENT_VARIANT:u)) -o $(@) $(<)", ["ASMCOM"] = "$(ASM) -quiet -Fhunk -phxass $(ASMOPTS) $(ASMOPTS_$(CURRENT_VARIANT:u)) $(ASMDEFS:p-D) $(ASMINCPATH:f:p-I) -I$(VBCC_SDK_INC) -o $(@) $(<)", ["PROGOPTS"] = "", ["PROGCOM"] = "$(LD) $(PROGOPTS) $(LIBPATH:p-L) $(LIBS:p-l) -o $(@) $(<)", ["PROGPREFIX"] = "", ["LIBOPTS"] = "", ["LIBCOM"] = "$(LIB) -r $(LIBOPTS) -o $(@) $(<)", ["ASMINC_KEYWORDS"] = { "INCLUDE", "include" }, ["ASMINC_BINARY_KEYWORDS"] = { "INCBIN", "incbin" }, } end
mit
ffxiphoenix/darkstar
scripts/zones/The_Eldieme_Necropolis/TextIDs.lua
9
2300
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6543; -- Obtained: <item> GIL_OBTAINED = 6544; -- Obtained <number> gil KEYITEM_OBTAINED = 6546; -- Obtained key item: <keyitem> SOLID_STONE = 7368; -- This door is made of solid stone. -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7387; -- You unlock the chest! CHEST_FAIL = 7388; -- Fails to open the chest. CHEST_TRAP = 7389; -- The chest was trapped! CHEST_WEAK = 7390; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7391; -- The chest was a mimic! CHEST_MOOGLE = 7392; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7393; -- The chest was but an illusion... CHEST_LOCKED = 7394; -- The chest appears to be locked. -- Quests NOTHING_OUT_OF_ORDINARY = 6557; -- There is nothing out of the ordinary here. SENSE_OF_FOREBODING = 6558; -- You are suddenly overcome with a sense of foreboding... NOTHING_HAPPENED = 7328; -- Nothing happened... RETURN_RIBBON_TO_HER = 7341; -- You can hear a voice from somewhere. (...return...ribbon to...her...) THE_BRAZIER_IS_LIT = 7355; -- The brazier is lit. REFUSE_TO_LIGHT = 7356; -- Unexpectedly, therefuses to light. LANTERN_GOES_OUT = 7357; -- For some strange reason, the light of thegoes out... THE_LIGHT_DIMLY = 7358; -- lights dimly. It doesn't look like this will be effective yet.?Prompt? THE_LIGHT_HAS_INTENSIFIED = 7359; -- The light of thehas intensified. THE_LIGHT_IS_FULLY_LIT = 7360; -- is fully lit! SPIRIT_INCENSE_EMITS_PUTRID_ODOR = 7397; -- emits a putrid odor and burns up. Your attempt this time has failed...?Prompt? SARCOPHAGUS_CANNOT_BE_OPENED = 7414; -- It is a stone sarcophagus with the lid sealed tight. It cannot be opened. -- conquest Base CONQUEST_BASE = 0; -- Strange Apparatus DEVICE_NOT_WORKING = 7304; -- The device is not working. SYS_OVERLOAD = 7313; -- arning! Sys...verload! Enterin...fety mode. ID eras...d YOU_LOST_THE = 7318; -- You lost the #.
gpl-3.0
usstwxy/luarocks
src/luarocks/upload/multipart.lua
25
2800
local multipart = {} local File = {} local unpack = unpack or table.unpack math.randomseed(os.time()) -- socket.url.escape(s) from LuaSocket 3.0rc1 function multipart.url_escape(s) return (string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02x", string.byte(c)) end)) end function File:mime() if not self.mimetype then local mimetypes_ok, mimetypes = pcall(require, "mimetypes") if mimetypes_ok then self.mimetype = mimetypes.guess(self.fname) end self.mimetype = self.mimetype or "application/octet-stream" end return self.mimetype end function File:content() local fd = io.open(self.fname, "rb") if not fd then return nil, "Failed to open file: "..self.fname end local data = fd:read("*a") fd:close() return data end local function rand_string(len) local shuffled = {} for i = 1, len do local r = math.random(97, 122) if math.random() >= 0.5 then r = r - 32 end shuffled[i] = r end return string.char(unpack(shuffled)) end -- multipart encodes params -- returns encoded string,boundary -- params is an a table of tuple tables: -- params = { -- {key1, value2}, -- {key2, value2}, -- key3: value3 -- } function multipart.encode(params) local tuples = { } for i = 1, #params do tuples[i] = params[i] end for k,v in pairs(params) do if type(k) == "string" then table.insert(tuples, {k, v}) end end local chunks = {} for _, tuple in ipairs(tuples) do local k,v = unpack(tuple) k = multipart.url_escape(k) local buffer = { 'Content-Disposition: form-data; name="' .. k .. '"' } local content if type(v) == "table" and v.__class == File then buffer[1] = buffer[1] .. ('; filename="' .. v.fname:gsub(".*/", "") .. '"') table.insert(buffer, "Content-type: " .. v:mime()) content = v:content() else content = v end table.insert(buffer, "") table.insert(buffer, content) table.insert(chunks, table.concat(buffer, "\r\n")) end local boundary while not boundary do boundary = "Boundary" .. rand_string(16) for _, chunk in ipairs(chunks) do if chunk:find(boundary) then boundary = nil break end end end local inner = "\r\n--" .. boundary .. "\r\n" return table.concat({ "--", boundary, "\r\n", table.concat(chunks, inner), "\r\n", "--", boundary, "--", "\r\n" }), boundary end function multipart.new_file(fname, mime) local self = {} setmetatable(self, { __index = File }) self.__class = File self.fname = fname self.mimetype = mime return self end return multipart
mit
ffxiphoenix/darkstar
scripts/zones/Windurst_Walls/npcs/Pakke-Pokke.lua
38
1040
----------------------------------- -- Area: Windurst Walls -- NPC: Pakke-Pokke -- Type: Standard NPC -- @zone: 239 -- @pos -3.464 -17.25 125.635 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0059); 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
noooway/love2d_arkanoid_tutorial
3-13_Score/buttons.lua
8
2279
local vector = require "vector" local buttons = {} function buttons.new_button( o ) return( { position = o.position or vector( 300, 300 ), width = o.width or 100, height = o.height or 50, text = o.text or "hello", image = o.image or nil, quad = o.quad or nil, quad_when_selected = o.quad_when_selected or nil, selected = false } ) end function buttons.update_button( single_button, dt ) local mouse_pos = vector( love.mouse.getPosition() ) if( buttons.inside( single_button, mouse_pos ) ) then single_button.selected = true else single_button.selected = false end end function buttons.draw_button( single_button ) if single_button.selected then if single_button.image and single_button.quad_when_selected then love.graphics.draw( single_button.image, single_button.quad_when_selected, single_button.position.x, single_button.position.y ) else love.graphics.rectangle( 'line', single_button.position.x, single_button.position.y, single_button.width, single_button.height ) local r, g, b, a = love.graphics.getColor() love.graphics.setColor( 255, 0, 0, 100 ) love.graphics.print( single_button.text, single_button.position.x, single_button.position.y ) love.graphics.setColor( r, g, b, a ) end else if single_button.image and single_button.quad then love.graphics.draw( single_button.image, single_button.quad, single_button.position.x, single_button.position.y ) else love.graphics.rectangle( 'line', single_button.position.x, single_button.position.y, single_button.width, single_button.height ) love.graphics.print( single_button.text, single_button.position.x, single_button.position.y ) end end end function buttons.inside( single_button, pos ) return single_button.position.x < pos.x and pos.x < ( single_button.position.x + single_button.width ) and single_button.position.y < pos.y and pos.y < ( single_button.position.y + single_button.height ) end function buttons.mousereleased( single_button, x, y, button ) return single_button.selected end return buttons
mit
noooway/love2d_arkanoid_tutorial
3-14_Fonts/buttons.lua
8
2279
local vector = require "vector" local buttons = {} function buttons.new_button( o ) return( { position = o.position or vector( 300, 300 ), width = o.width or 100, height = o.height or 50, text = o.text or "hello", image = o.image or nil, quad = o.quad or nil, quad_when_selected = o.quad_when_selected or nil, selected = false } ) end function buttons.update_button( single_button, dt ) local mouse_pos = vector( love.mouse.getPosition() ) if( buttons.inside( single_button, mouse_pos ) ) then single_button.selected = true else single_button.selected = false end end function buttons.draw_button( single_button ) if single_button.selected then if single_button.image and single_button.quad_when_selected then love.graphics.draw( single_button.image, single_button.quad_when_selected, single_button.position.x, single_button.position.y ) else love.graphics.rectangle( 'line', single_button.position.x, single_button.position.y, single_button.width, single_button.height ) local r, g, b, a = love.graphics.getColor() love.graphics.setColor( 255, 0, 0, 100 ) love.graphics.print( single_button.text, single_button.position.x, single_button.position.y ) love.graphics.setColor( r, g, b, a ) end else if single_button.image and single_button.quad then love.graphics.draw( single_button.image, single_button.quad, single_button.position.x, single_button.position.y ) else love.graphics.rectangle( 'line', single_button.position.x, single_button.position.y, single_button.width, single_button.height ) love.graphics.print( single_button.text, single_button.position.x, single_button.position.y ) end end end function buttons.inside( single_button, pos ) return single_button.position.x < pos.x and pos.x < ( single_button.position.x + single_button.width ) and single_button.position.y < pos.y and pos.y < ( single_button.position.y + single_button.height ) end function buttons.mousereleased( single_button, x, y, button ) return single_button.selected end return buttons
mit
noooway/love2d_arkanoid_tutorial
3-15_MoreSounds/buttons.lua
8
2279
local vector = require "vector" local buttons = {} function buttons.new_button( o ) return( { position = o.position or vector( 300, 300 ), width = o.width or 100, height = o.height or 50, text = o.text or "hello", image = o.image or nil, quad = o.quad or nil, quad_when_selected = o.quad_when_selected or nil, selected = false } ) end function buttons.update_button( single_button, dt ) local mouse_pos = vector( love.mouse.getPosition() ) if( buttons.inside( single_button, mouse_pos ) ) then single_button.selected = true else single_button.selected = false end end function buttons.draw_button( single_button ) if single_button.selected then if single_button.image and single_button.quad_when_selected then love.graphics.draw( single_button.image, single_button.quad_when_selected, single_button.position.x, single_button.position.y ) else love.graphics.rectangle( 'line', single_button.position.x, single_button.position.y, single_button.width, single_button.height ) local r, g, b, a = love.graphics.getColor() love.graphics.setColor( 255, 0, 0, 100 ) love.graphics.print( single_button.text, single_button.position.x, single_button.position.y ) love.graphics.setColor( r, g, b, a ) end else if single_button.image and single_button.quad then love.graphics.draw( single_button.image, single_button.quad, single_button.position.x, single_button.position.y ) else love.graphics.rectangle( 'line', single_button.position.x, single_button.position.y, single_button.width, single_button.height ) love.graphics.print( single_button.text, single_button.position.x, single_button.position.y ) end end end function buttons.inside( single_button, pos ) return single_button.position.x < pos.x and pos.x < ( single_button.position.x + single_button.width ) and single_button.position.y < pos.y and pos.y < ( single_button.position.y + single_button.height ) end function buttons.mousereleased( single_button, x, y, button ) return single_button.selected end return buttons
mit
noooway/love2d_arkanoid_tutorial
3-11_WallTiles/buttons.lua
8
2279
local vector = require "vector" local buttons = {} function buttons.new_button( o ) return( { position = o.position or vector( 300, 300 ), width = o.width or 100, height = o.height or 50, text = o.text or "hello", image = o.image or nil, quad = o.quad or nil, quad_when_selected = o.quad_when_selected or nil, selected = false } ) end function buttons.update_button( single_button, dt ) local mouse_pos = vector( love.mouse.getPosition() ) if( buttons.inside( single_button, mouse_pos ) ) then single_button.selected = true else single_button.selected = false end end function buttons.draw_button( single_button ) if single_button.selected then if single_button.image and single_button.quad_when_selected then love.graphics.draw( single_button.image, single_button.quad_when_selected, single_button.position.x, single_button.position.y ) else love.graphics.rectangle( 'line', single_button.position.x, single_button.position.y, single_button.width, single_button.height ) local r, g, b, a = love.graphics.getColor() love.graphics.setColor( 255, 0, 0, 100 ) love.graphics.print( single_button.text, single_button.position.x, single_button.position.y ) love.graphics.setColor( r, g, b, a ) end else if single_button.image and single_button.quad then love.graphics.draw( single_button.image, single_button.quad, single_button.position.x, single_button.position.y ) else love.graphics.rectangle( 'line', single_button.position.x, single_button.position.y, single_button.width, single_button.height ) love.graphics.print( single_button.text, single_button.position.x, single_button.position.y ) end end end function buttons.inside( single_button, pos ) return single_button.position.x < pos.x and pos.x < ( single_button.position.x + single_button.width ) and single_button.position.y < pos.y and pos.y < ( single_button.position.y + single_button.height ) end function buttons.mousereleased( single_button, x, y, button ) return single_button.selected end return buttons
mit
ffxiphoenix/darkstar
scripts/zones/Upper_Jeuno/npcs/Emitt.lua
28
3228
----------------------------------- -- Area: Upper Jeuno -- NPC: Emitt -- @pos -95 0 160 244 ------------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/conquest"); require("scripts/zones/Upper_Jeuno/TextIDs"); local guardnation = OTHER; -- SANDORIA, BASTOK, WINDURST, OTHER(Jeuno). local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Menu1 = getArg1(guardnation,player); local Menu3 = conquestRanking(); local Menu6 = getArg6(player); local Menu7 = player:getCP(); player:startEvent(0x7ffb,Menu1,0,Menu3,0,0,Menu6,Menu7,0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); if (player:getNation() == 0) then inventory = SandInv; size = table.getn(SandInv); elseif (player:getNation() == 1) then inventory = BastInv; size = table.getn(BastInv); else inventory = WindInv; size = table.getn(WindInv); end if (option >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then CPVerify = 1; if (player:getCP() >= inventory[Item + 1]) then CPVerify = 0; end; player:updateEvent(2,CPVerify,inventory[Item + 2]); -- can't equip = 2 ? break; end; end; end; end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %u",option); if (option == 1) then duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then if (player:getFreeSlotsCount() >= 1) then -- Logic to impose limits on exp bands if (option >= 32933 and option <= 32935) then if (checkConquestRing(player) > 0) then player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]); break; else player:setVar("CONQUEST_RING_TIMER",getConquestTally()); end end itemCP = inventory[Item + 1]; player:delCP(itemCP); player:addItem(inventory[Item + 2],1); player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]); end; break; end; end; end; end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Sauromugue_Champaign/npcs/Cavernous_Maw.lua
16
2985
----------------------------------- -- Area: Sauromugue Champaign -- NPC: Cavernous Maw -- Teleports Players to Sauromugue_Champaign_S -- @pos 369 8 -227 120 ----------------------------------- package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/missions"); require("scripts/globals/campaign"); require("scripts/zones/Sauromugue_Champaign/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) == false) then player:startEvent(500,2); elseif (ENABLE_WOTG == 1 and hasMawActivated(player,2)) then if (player:getCurrentMission(WOTG) == BACK_TO_THE_BEGINNING and (player:getQuestStatus(CRYSTAL_WAR, CLAWS_OF_THE_GRIFFON) == QUEST_COMPLETED or player:getQuestStatus(CRYSTAL_WAR, THE_TIGRESS_STRIKES) == QUEST_COMPLETED or player:getQuestStatus(CRYSTAL_WAR, FIRES_OF_DISCONTENT) == QUEST_COMPLETED)) then player:startEvent(501); else player:startEvent(904); 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:",csid); -- printf("RESULT:",option); if (csid == 500) then local r = math.random(1,3); player:addKeyItem(PURE_WHITE_FEATHER); player:messageSpecial(KEYITEM_OBTAINED,PURE_WHITE_FEATHER); player:completeMission(WOTG,CAVERNOUS_MAWS); player:addMission(WOTG,BACK_TO_THE_BEGINNING); if (r == 1) then player:addNationTeleport(MAW,1); toMaw(player,1); -- go to Batallia_Downs[S] elseif (r == 2) then player:addNationTeleport(MAW,2); toMaw(player,3); -- go to Rolanberry_Fields_[S] elseif (r == 3) then player:addNationTeleport(MAW,4); toMaw(player,5); -- go to Sauromugue_Champaign_[S] end; elseif (csid == 904 and option == 1) then toMaw(player,5); -- go to Sauromugue_Champaign_[S] elseif (csid == 501) then player:completeMission(WOTG, BACK_TO_THE_BEGINNING); player:addMission(WOTG, CAIT_SITH); player:addTitle(CAIT_SITHS_ASSISTANT); toMaw(player,5); end; end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Newton_Movalpolos/npcs/Moblin_Showman.lua
16
1026
----------------------------------- -- Area: Newton Movalpolos -- NPC: Moblin Showman - Bugbear Matman -- @pos 124.544 19.988 -60.670 12 ----------------------------------- package.loaded["scripts/zones/Newton_Movalpolos/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Newton_Movalpolos/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (GetMobAction(16826570) == 0 and trade:hasItemQty(1878,1) and trade:getItemCount() == 1) then -- Air tank player:tradeComplete(); player:showText(npc, SHOWMAN_ACCEPT); -- Moblin Showman's dialogue SpawnMob(16826570,300):updateClaim(player); -- Bugbear Matman else player:showText(npc, SHOWMAN_DECLINE); -- Moblin Showman refuses your trade end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, SHOWMAN_TRIGGER); end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Balgas_Dais/npcs/Burning_Circle.lua
17
2294
----------------------------------- -- Area: Balga's Dais -- NPC: Burning Circle -- Balga's Dais Burning Circle -- @pos 299 -123 345 146 ------------------------------------- package.loaded["scripts/zones/Balgas_Dais/TextIDs"] = nil; ------------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/bcnm"); require("scripts/zones/Balgas_Dais/TextIDs"); ---- 0: Rank 2 Final Mission for Bastok "The Emissary" and Sandy "Journey Abroad" ---- 1: Steamed Sprouts (BCNM 40, Star Orb) ---- 2: Divine Punishers (BCNM 60, Moon Orb) ---- 3: Saintly Invitation (Windurst mission 6-2) ---- 4: Treasure and Tribulations (BCNM 50, Comet Orb) ---- 5: Shattering Stars (MNK) ---- 6: Shattering Stars (WHM) ---- 7: Shattering Stars (SMN) ---- 8: Creeping Doom (BCNM 30, Sky Orb) ---- 9: Charming Trio (BCNM 20, Cloudy Orb) ---- 10: Harem Scarem (BCNM 30, Sky Orb) ---- 11: Early Bird Catches the Wyrm (KSNM 99, Themis Orb) ---- 12: Royal Succession (BCNM 40, Star Orb) ---- 13: Rapid Raptors (BCNM 50, Comet Orb) ---- 14: Wild Wild Whiskers (BCNM 60, Moon Orb) ---- 15: Season's Greetings (KSNM 30, Clotho Orb) ---- 16: Royale Ramble (KSNM 30, Lachesis Orb) ---- 17: Moa Constrictors (KSNM 30, Atropos Orb ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
ffxiphoenix/darkstar
scripts/globals/mobskills/Chains_of_Cowardice.lua
25
1179
--------------------------------------------- -- Chains of Apathy -- --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/keyitems"); require("scripts/zones/Empyreal_Paradox/TextIDs"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local targets = mob:getEnmityList(); for i,v in pairs(targets) do if (v:isPC()) then local race = v:getRace() if (race == 5 or race == 6) and not v:hasKeyItem(LIGHT_OF_HOLLA) then mob:showText(mob, PROMATHIA_TEXT + 2); return 0; end end end return 1; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_TERROR; local power = 30; local duration = 30; if target:isPC() and ((target:getRace() == 5 or target:getRace() == 6) and not target:hasKeyItem(LIGHT_OF_HOLLA)) then skill:setMsg(MobStatusEffectMove(mob, target, typeEffect, power, 0, duration)); else skill:setMsg(MSG_NO_EFFECT); end return typeEffect; end;
gpl-3.0
ffxiphoenix/darkstar
scripts/commands/addmission.lua
25
1173
--------------------------------------------------------------------------------------------------- -- func: @addmission <logID> <missionID> <player> -- desc: Adds a mission to the GM or target players log. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "iis" }; function onTrigger(player, logId, missionId, target) if (missionId == nil or logId == nil) then player:PrintToPlayer( "You must enter a valid log id and mission id!" ); player:PrintToPlayer( "@addmission <logID> <missionID> <player>" ); return; end if (target == nil) then target = player:getName(); end local targ = GetPlayerByName( target ); if (targ ~= nil) then targ:addMission( logId, missionId ); player:PrintToPlayer( string.format( "Added Mission for log %u with ID %u to %s", logId, missionId, target ) ); else player:PrintToPlayer( string.format( "Player named '%s' not found!", target ) ); player:PrintToPlayer( "@addmission <logID> <missionID> <player>" ); end end;
gpl-3.0
DarkJaguar91/DJBags
src/bank/BankFrame.lua
1
1163
local ADDON_NAME, ADDON = ... local bankFrame = {} bankFrame.__index = bankFrame function DJBagsRegisterBankFrame(self, bags) for k, v in pairs(bankFrame) do self[k] = v end ADDON.eventManager:Add('BANKFRAME_OPENED', self) ADDON.eventManager:Add('BANKFRAME_CLOSED', self) table.insert(UISpecialFrames, self:GetName()) self:RegisterForDrag("LeftButton") self:SetScript("OnDragStart", function(self, ...) self:StartMoving() end) self:SetScript("OnDragStop", function(self, ...) self:StopMovingOrSizing(...) end) self:SetUserPlaced(true) end function DJBagsBankTab_OnClick(tab) PanelTemplates_SetTab(DJBagsBankBar, tab.tab) if tab.tab == 1 then DJBagsBank:Show() DJBagsReagents:Hide() BankFrame.selectedTab = 1 BankFrame.activeTabIndex = 1 else DJBagsBank:Hide() DJBagsReagents:Show() BankFrame.selectedTab = 2 BankFrame.activeTabIndex = 2 end end function bankFrame:BANKFRAME_OPENED() self:Show() DJBagsBag:Show() end function bankFrame:BANKFRAME_CLOSED() self:Hide() end
mit
ffxiphoenix/darkstar
scripts/globals/weaponskills/piercing_arrow.lua
30
1643
----------------------------------- -- Piercing Arrow -- Archery weapon skill -- Skill level: 40 -- Ignores enemy's defense. Amount ignored varies with TP. -- The amount of defense ignored is 0% with 100TP, 35% with 200TP and 50% with 300TP. -- Typically does less damage than Flaming Arrow. -- Aligned with the Snow Gorget & Light Gorget. -- Aligned with the Snow Belt & Light Belt. -- Element: None -- Modifiers: STR:20% ; AGI:50% -- 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) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.16; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.25; 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; --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; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.2; params.agi_wsc = 0.5; end local damage, tpHits, extraHits = doRangedWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0