content
stringlengths 5
1.05M
|
|---|
-----------------------------------
-- Area: Ghelsba_Outpost
-- NPC: Armoury Crate
-- Ghelsba_Outpost Armoury_Crate
-------------------------------------
require("scripts/globals/bcnm")
require("scripts/globals/battlefield")
-----------------------------------
local loot =
{
-- BCNM Wings of Fury
[34] =
{
{
{itemid = 891, droprate = 1000}, -- Bat Fang
},
{
{itemid = 4900, droprate = 306}, -- Thunder Spirit Pact
{itemid = 4744, droprate = 319}, -- Scroll Of Invisible
{itemid = 4745, droprate = 125}, -- Scroll Of Sneak
{itemid = 4746, droprate = 222}, -- Scroll Of Deodorize
},
{
{itemid = 17786, droprate = 153},-- Ganko
{itemid = 18170, droprate = 139},-- Platoon Edge
{itemid = 16687, droprate = 83}, -- Platoon Axe
{itemid = 17571, droprate = 97}, -- Platoon Pole
{itemid = 17993, droprate = 125},-- Platoon Dagger
{itemid = 749, droprate = 444}, -- Mythril Beastcoin
{itemid = 773, droprate = 56}, -- Translucent Rock
},
{
{itemid = 17820, droprate = 111},-- Gunromaru
{itemid = 17993, droprate = 139},-- Platoon Dagger
{itemid = 18170, droprate = 139},-- Platoon Edge
{itemid = 18085, droprate = 42}, -- Platoon Lance
{itemid = 16959, droprate = 181},-- Platoon Sword
{itemid = 774, droprate = 97}, -- Purple Rock
{itemid = 769, droprate = 69}, -- Red Rock
{itemid = 776, droprate = 14}, -- White Rock
{itemid = 775, droprate = 28}, -- Black Rock
{itemid = 772, droprate = 28}, -- Green Rock
{itemid = 771, droprate = 14}, -- Yellow Rock
{itemid = 770, droprate = 69}, -- Blue Rock
},
{
{itemid = 0, droprate = 389}, -- nothing
{itemid = 13548, droprate = 167}, -- astral_ring
{itemid = 922, droprate = 444}, -- bat_wing
},
},
-- BCNM Petrifying Pair
[35] =
{
{
{itemid = 852, droprate = 1000}, -- Lizard Skin
},
{
{itemid = 0, droprate = 900}, -- nothing
{itemid = 13014, droprate = 100}, -- leaping_boots
},
{
{itemid = 15282, droprate = 50}, -- Katana Obi
{itemid = 15275, droprate = 75}, -- Rapier Belt
{itemid = 15278, droprate = 175}, -- Scythe Belt
{itemid = 694, droprate = 175}, -- Chestnut Log
{itemid = 690, droprate = 350}, -- Elm Log
{itemid = 652, droprate = 100}, -- Steel Ingot
},
{
{itemid = 0, droprate = 925}, -- nothing (50%)
{itemid = 15282, droprate = 50}, -- Katana Obi
{itemid = 15275, droprate = 75}, -- Rapier Belt
{itemid = 15278, droprate = 175}, -- Scythe Belt
{itemid = 694, droprate = 175}, -- Chestnut Log
{itemid = 690, droprate = 350}, -- Elm Log
{itemid = 652, droprate = 100}, -- Steel Ingot
},
{
{itemid = 15285, droprate = 105},-- Avatar Belt
{itemid = 15279, droprate = 105},-- Pick Belt
{itemid = 651, droprate = 131}, -- Iron Ingot
{itemid = 643, droprate = 131}, -- Chunk Of Iron Ore
{itemid = 644, droprate = 79}, -- Chunk Of Mythril Ore
{itemid = 736, droprate = 79}, -- Chunk Of Silver Ore
{itemid = 795, droprate = 131}, -- Lapis Lazuli
},
{
{itemid = 17867, droprate = 552},-- Jug Of Cold Carrion Broth
{itemid = 4877, droprate = 263}, -- Scroll Of Absorb-agi
{itemid = 4878, droprate = 210}, -- Scroll Of Absorb-int
{itemid = 4876, droprate = 289}, -- Scroll Of Absorb-vit
{itemid = 4868, droprate = 105}, -- Scroll Of Dispel
{itemid = 4751, droprate = 79}, -- Scroll Of Erase
{itemid = 5070, droprate = 421}, -- Scroll Of Magic Finale
{itemid = 4947, droprate = 79}, -- Scroll Of Utsusemi Ni
},
{
{itemid = 0, droprate = 736}, -- nothing (25%)
{itemid = 15271, droprate = 200}, -- Axe Belt
{itemid = 15272, droprate = 125}, -- Cestus Belt
{itemid = 809, droprate = 10}, -- Clear Topaz
{itemid = 15276, droprate = 75}, -- Dagger Belt
{itemid = 645, droprate = 100}, -- Darksteel Ore
{itemid = 15281, droprate = 25}, -- Gun Belt
{itemid = 4132, droprate = 175}, -- Hi-ether
{itemid = 15284, droprate = 200}, -- Lance Belt
{itemid = 796, droprate = 75}, -- Light Opal
{itemid = 15273, droprate = 175}, -- Mace Belt
{itemid = 653, droprate = 200}, -- Mythril Ingot
{itemid = 799, droprate = 25}, -- Onyx
{itemid = 15283, droprate = 250}, -- Sarashi
{itemid = 15277, droprate = 100}, -- Shield Belt
{itemid = 15280, droprate = 100}, -- Song Belt
{itemid = 15274, droprate = 150}, -- Staff Belt
{itemid = 744, droprate = 100}, -- Silver Ingot
{itemid = 806, droprate = 125}, -- Tourmaline
},
{
{itemid = 0, droprate = 2210}, -- nothing (50%)
{itemid = 15271, droprate = 200}, -- Axe Belt
{itemid = 15272, droprate = 125}, -- Cestus Belt
{itemid = 809, droprate = 10}, -- Clear Topaz
{itemid = 15276, droprate = 75}, -- Dagger Belt
{itemid = 645, droprate = 100}, -- Darksteel Ore
{itemid = 15281, droprate = 25}, -- Gun Belt
{itemid = 4132, droprate = 175}, -- Hi-ether
{itemid = 15284, droprate = 200}, -- Lance Belt
{itemid = 796, droprate = 75}, -- Light Opal
{itemid = 15273, droprate = 175}, -- Mace Belt
{itemid = 653, droprate = 200}, -- Mythril Ingot
{itemid = 799, droprate = 25}, -- Onyx
{itemid = 15283, droprate = 250}, -- Sarashi
{itemid = 15277, droprate = 100}, -- Shield Belt
{itemid = 15280, droprate = 100}, -- Song Belt
{itemid = 15274, droprate = 150}, -- Staff Belt
{itemid = 744, droprate = 100}, -- Silver Ingot
{itemid = 806, droprate = 125}, -- Tourmaline
},
},
-- BCNM Toadal Recall
[36] =
{
{
{itemid = 4386, droprate = 1000}, -- king_truffle
},
{
{itemid = 17880, droprate = 1000}, -- jug_of_seedbed_soil
},
{
{itemid = 0, droprate = 200}, -- nothing
{itemid = 12403, droprate = 200}, -- magicians_shield
{itemid = 12389, droprate = 200}, -- mercenarys_targe
{itemid = 12399, droprate = 200}, -- beaters_aspis
{itemid = 12394, droprate = 200}, -- pilferers_aspis
},
{
{itemid = 0, droprate = 250}, -- nothing
{itemid = 13667, droprate = 250}, -- trimmers_mantle
{itemid = 13671, droprate = 250}, -- genin_mantle
{itemid = 13663, droprate = 250}, -- warlocks_mantle
},
{
{itemid = 0, droprate = 625}, -- nothing
{itemid = 4947, droprate = 125}, -- scroll_of_utsusemi_ni
{itemid = 4714, droprate = 125}, -- scroll_of_phalanx
{itemid = 4751, droprate = 125}, -- scroll_of_erase
},
{
{itemid = 0, droprate = 250}, -- nothing
{itemid = 1601, droprate = 250}, -- mannequin_head
{itemid = 1602, droprate = 250}, -- mannequin_body
{itemid = 1603, droprate = 250}, -- mannequin_hands
},
},
}
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local battlefield = player:getBattlefield()
if battlefield then
tpz.battlefield.HandleLootRolls(battlefield, loot[battlefield:getID()], nil, npc)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
|
return function()
local Players = game:GetService("Players")
local CorePackages = game:GetService("CorePackages")
local Roact = require(CorePackages.Roact)
local Rodux = require(CorePackages.Rodux)
local RoactRodux = require(CorePackages.RoactRodux)
local UIBlox = require(CorePackages.UIBlox)
local PlayerList = script.Parent.Parent.Parent
local Reducers = PlayerList.Reducers
local Reducer = require(Reducers.Reducer)
local Components = script.Parent.Parent
local Connection = Components.Connection
local LayoutValues = require(Connection.LayoutValues)
local LayoutValuesProvider = LayoutValues.Provider
local CreateLayoutValues = require(PlayerList.CreateLayoutValues)
local PlayerEntry = require(script.Parent.PlayerEntry)
local AppDarkTheme = require(CorePackages.AppTempCommon.LuaApp.Style.Themes.DarkTheme)
local AppFont = require(CorePackages.AppTempCommon.LuaApp.Style.Fonts.Gotham)
local appStyle = {
Theme = AppDarkTheme,
Font = AppFont,
}
local function getFakeRelationship()
return {
isBlocked = false,
friendStatus = Enum.FriendStatus.FriendRequestSent,
isFollowing = false,
isFollower = false,
}
end
local function getFakeIconInfo()
return {
isPlaceOwner = true,
avatarIcon = nil,
specialGroupIcon = nil,
}
end
it("should create and destroy without errors", function()
local store = Rodux.Store.new(Reducer)
local element = Roact.createElement(RoactRodux.StoreProvider, {
store = store,
}, {
LayoutValuesProvider = Roact.createElement(LayoutValuesProvider, {
layoutValues = CreateLayoutValues(false)
}, {
ThemeProvider = Roact.createElement(UIBlox.Style.Provider, {
style = appStyle,
}, {
PlayerEntry = Roact.createElement(PlayerEntry, {
player = Players.LocalPlayer,
playerStats = {},
playerIconInfo = getFakeIconInfo(),
playerRelationship = getFakeRelationship(),
entrySize = 50,
titlePlayerEntry = false,
hasDivider = true,
gameStats = {},
})
})
})
})
local instance = Roact.mount(element)
Roact.unmount(instance)
end)
it("should create and destroy without errors tenfoot", function()
local store = Rodux.Store.new(Reducer)
local element = Roact.createElement(RoactRodux.StoreProvider, {
store = store,
}, {
LayoutValuesProvider = Roact.createElement(LayoutValuesProvider, {
layoutValues = CreateLayoutValues(true)
}, {
ThemeProvider = Roact.createElement(UIBlox.Style.Provider, {
style = appStyle,
}, {
PlayerEntry = Roact.createElement(PlayerEntry, {
player = Players.LocalPlayer,
playerStats = {},
playerIconInfo = getFakeIconInfo(),
playerRelationship = getFakeRelationship(),
entrySize = 150,
titlePlayerEntry = true,
hasDivider = false,
gameStats = {},
})
})
})
})
local instance = Roact.mount(element)
Roact.unmount(instance)
end)
end
|
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
--
-- This file is compatible with Lua 5.3
local class = require("class")
require("kaitaistruct")
--
-- TCP is one of the core Internet protocols on transport layer (AKA
-- OSI layer 4), providing stateful connections with error checking,
-- guarantees of delivery, order of segments and avoidance of duplicate
-- delivery.
TcpSegment = class.class(KaitaiStruct)
function TcpSegment:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function TcpSegment:_read()
self.src_port = self._io:read_u2be()
self.dst_port = self._io:read_u2be()
self.seq_num = self._io:read_u4be()
self.ack_num = self._io:read_u4be()
self.b12 = self._io:read_u1()
self.b13 = self._io:read_u1()
self.window_size = self._io:read_u2be()
self.checksum = self._io:read_u2be()
self.urgent_pointer = self._io:read_u2be()
self.body = self._io:read_bytes_full()
end
|
local h = require("null-ls.helpers")
local methods = require("null-ls.methods")
local CODE_ACTION = methods.internal.CODE_ACTION
return h.make_builtin({
method = CODE_ACTION,
filetypes = { "lua" },
generator_opts = {
command = "bash",
args = { "./test/scripts/sleep-and-echo.sh" },
timeout = 100,
on_output = function(params, done)
if not params.output then
return done()
end
return done({
{
title = "Slow mock action",
action = function()
print("I took too long!")
end,
},
})
end,
},
factory = h.generator_factory,
})
|
-- Copyright 2014-2019, Firaxis Games.
-- Hotloading note: The World Tracker button check now positions based on how many hooks are showing.
-- You'll need to save "LaunchBar" to see the tracker button appear.
include("InstanceManager")
include("TechAndCivicSupport")
include("SupportFunctions")
include("GameCapabilities")
g_TrackedItems = {} -- Populated by WorldTrackerItems_* scripts;
include("WorldTrackerItem_", true)
-- Include self contained additional tabs
g_ExtraIconData = {}
include("CivicsTreeIconLoader_", true)
include("cui_helper") -- CUI
include("cui_settings") -- CUI
include("cui_tracker_support") -- CUI
-- ===========================================================================
-- CONSTANTS
-- ===========================================================================
local RELOAD_CACHE_ID = "WorldTracker" -- Must be unique (usually the same as the file name)
local CHAT_COLLAPSED_SIZE = 99
local MAX_BEFORE_TRUNC_TRACKER = 180
local MAX_BEFORE_TRUNC_CHECK = 160
local MAX_BEFORE_TRUNC_TITLE = 225
local LAUNCH_BAR_PADDING = 50
local STARTING_TRACKER_OPTIONS_OFFSET = 75
local WORLD_TRACKER_PANEL_WIDTH = 300
-- ===========================================================================
-- GLOBALS
-- ===========================================================================
g_TrackedInstances = {} -- Any instances created as a result of g_trackedItems
-- ===========================================================================
-- MEMBERS
-- ===========================================================================
local m_hideAll = false
local m_hideChat = false
local m_hideCivics = false
local m_hideResearch = false
local m_dropdownExpanded = false
local m_unreadChatMsgs = 0 -- number of chat messages unseen due to the chat panel being hidden.
local m_researchInstance = {} -- Single instance wired up for the currently being researched tech
local m_civicsInstance = {} -- Single instance wired up for the currently being researched civic
-- CUI Tracker
local cui_TrackBar = {}
local wonderData = {}
local resourceData = {}
local borderData = {}
local tradeData = {}
local CuiWonderTT = {}
local CuiResourceTT = {}
local CuiBorderTT = {}
local CuiTradeTT = {}
TTManager:GetTypeControlTable("CuiWonderTT", CuiWonderTT)
TTManager:GetTypeControlTable("CuiResourceTT", CuiResourceTT)
TTManager:GetTypeControlTable("CuiBorderTT", CuiBorderTT)
TTManager:GetTypeControlTable("CuiTradeTT", CuiTradeTT)
local wonderInstance = InstanceManager:new("WonderInstance", "Top", Controls.WonderInstanceContainer)
local colorInstance = InstanceManager:new("ColorInstance", "Top", Controls.ColorInstanceContainer)
local resourceInstance = InstanceManager:new("ResourceInstance", "Top", Controls.ResourceInstanceContainer)
local resourceBarInstance = InstanceManager:new("ResourceBarInstance", "Top", Controls.ResourceBarInstanceContainer)
local borderInstance = InstanceManager:new("BorderInstance", "Top", Controls.BorderInstanceContainer)
local tradeInstance = InstanceManager:new("TradeInstance", "Top", Controls.TradeInstanceContainer)
-- CUI gossip combat log
local cui_GossipPanel = {}
local cui_GossipCount = 0
local cui_GossipLogs = {}
local cui_CombatPanel = {}
local cui_CombatCount = 0
local cui_CombatLogs = {}
local m_useGossipLog = CuiSettings:GetBoolean(CuiSettings.WT_GOSSIP_LOG)
local m_useCombatLog = CuiSettings:GetBoolean(CuiSettings.WT_COMBAT_LOG)
local cui_MaxLog = 50
local cui_LogPanelStatus = {}
cui_LogPanelStatus[1] = {main = 28, log = 24}
cui_LogPanelStatus[2] = {main = 82, log = 78}
cui_LogPanelStatus[3] = {main = 282, log = 278}
local cui_GossipState = CuiSettings:GetNumber(CuiSettings.GOSSIP_LOG_STATE)
local cui_CombatState = CuiSettings:GetNumber(CuiSettings.COMBAT_LOG_STATE)
--
local m_CachedModifiers = {}
local m_currentResearchID = -1
local m_lastResearchCompletedID = -1
local m_currentCivicID = -1
local m_lastCivicCompletedID = -1
local m_isTrackerAlwaysCollapsed = false -- Once the launch bar extends past the width of the world tracker, we always show the collapsed version of the backing for the tracker element
local m_isDirty = false -- Note: renamed from "refresh" which is a built in Forge mechanism; this is based on a gamecore event to check not frame update
-- ===========================================================================
-- FUNCTIONS
-- ===========================================================================
-- ===========================================================================
-- The following are a accessors for Expansions/MODs so they can obtain status
-- of the common panels but don't have access to toggling them.
-- ===========================================================================
function IsChatHidden()
return m_hideChat
end
function IsResearchHidden()
return m_hideResearch
end
function IsCivicsHidden()
return m_hideCivics
end
-- ===========================================================================
-- Checks all panels, static and dynamic as to whether or not they are hidden.
-- Returns true if they are.
-- ===========================================================================
function IsAllPanelsHidden()
local isHide = false
local uiChildren = Controls.PanelStack:GetChildren()
for i, uiChild in ipairs(uiChildren) do
if uiChild:IsVisible() then
return false
end
end
return true
end
-- ===========================================================================
function RealizeEmptyMessage()
-- First a quick check if all native panels are hidden.
if m_hideChat and m_hideCivics and m_hideResearch then
local isAllPanelsHidden = IsAllPanelsHidden() -- more expensive iteration
Controls.EmptyPanel:SetHide(isAllPanelsHidden == false)
else
Controls.EmptyPanel:SetHide(true)
end
end
-- ===========================================================================
function ToggleDropdown()
if m_dropdownExpanded then
m_dropdownExpanded = false
Controls.DropdownAnim:Reverse()
Controls.DropdownAnim:Play()
UI.PlaySound("Tech_Tray_Slide_Closed")
else
UI.PlaySound("Tech_Tray_Slide_Open")
m_dropdownExpanded = true
Controls.DropdownAnim:SetToBeginning()
Controls.DropdownAnim:Play()
end
end
-- ===========================================================================
function ToggleAll(hideAll)
-- Do nothing if value didn't change
if m_hideAll == hideAll then
return
end
m_hideAll = hideAll
if (not hideAll) then
Controls.PanelStack:SetHide(false)
UI.PlaySound("Tech_Tray_Slide_Open")
end
Controls.ToggleAllButton:SetCheck(not m_hideAll)
if (not m_isTrackerAlwaysCollapsed) then
Controls.TrackerHeading:SetHide(hideAll)
Controls.TrackerHeadingCollapsed:SetHide(not hideAll)
else
Controls.TrackerHeading:SetHide(true)
Controls.TrackerHeadingCollapsed:SetHide(false)
end
if (hideAll) then
UI.PlaySound("Tech_Tray_Slide_Closed")
if (m_dropdownExpanded) then
Controls.DropdownAnim:SetToBeginning()
m_dropdownExpanded = false
end
end
Controls.WorldTrackerAlpha:Reverse()
Controls.WorldTrackerSlide:Reverse()
CheckUnreadChatMessageCount()
LuaEvents.WorldTracker_ToggleCivicPanel(m_hideCivics or m_hideAll)
LuaEvents.WorldTracker_ToggleResearchPanel(m_hideResearch or m_hideAll)
end
-- ===========================================================================
function OnWorldTrackerAnimationFinished()
if (m_hideAll) then
Controls.PanelStack:SetHide(true)
end
end
-- ===========================================================================
-- When the launch bar is resized, make sure to adjust the world tracker
-- button position/size to accommodate it
-- ===========================================================================
function OnLaunchBarResized(buttonStackSize)
Controls.TrackerHeading:SetSizeX(buttonStackSize + LAUNCH_BAR_PADDING)
Controls.TrackerHeadingCollapsed:SetSizeX(buttonStackSize + LAUNCH_BAR_PADDING)
if (buttonStackSize > WORLD_TRACKER_PANEL_WIDTH - LAUNCH_BAR_PADDING) then
m_isTrackerAlwaysCollapsed = true
Controls.TrackerHeading:SetHide(true)
Controls.TrackerHeadingCollapsed:SetHide(false)
else
m_isTrackerAlwaysCollapsed = false
Controls.TrackerHeading:SetHide(m_hideAll)
Controls.TrackerHeadingCollapsed:SetHide(not m_hideAll)
end
Controls.ToggleAllButton:SetOffsetX(buttonStackSize - 7)
end
-- ===========================================================================
function RealizeStack()
Controls.PanelStack:CalculateSize()
if (m_hideAll) then
ToggleAll(true)
end
end
-- ===========================================================================
function UpdateResearchPanel(isHideResearch)
if not HasCapability("CAPABILITY_TECH_CHOOSER") then
isHideResearch = true
Controls.ResearchCheck:SetHide(true)
end
if isHideResearch ~= nil then
m_hideResearch = isHideResearch
end
m_researchInstance.MainPanel:SetHide(m_hideResearch)
Controls.ResearchCheck:SetCheck(not m_hideResearch)
LuaEvents.WorldTracker_ToggleResearchPanel(m_hideResearch or m_hideAll)
RealizeEmptyMessage()
RealizeStack()
-- Set the technology to show (or -1 if none)...
local iTech = m_currentResearchID
if m_currentResearchID == -1 then
iTech = m_lastResearchCompletedID
end
local ePlayer = Game.GetLocalPlayer()
local pPlayer = Players[ePlayer]
local pPlayerTechs = pPlayer:GetTechs()
local kTech = (iTech ~= -1) and GameInfo.Technologies[iTech] or nil
local kResearchData = GetResearchData(ePlayer, pPlayerTechs, kTech)
if iTech ~= -1 then
if m_currentResearchID == iTech then
kResearchData.IsCurrent = true
elseif m_lastResearchCompletedID == iTech then
kResearchData.IsLastCompleted = true
end
end
RealizeCurrentResearch(ePlayer, kResearchData, m_researchInstance)
-- No tech started (or finished)
if kResearchData == nil then
m_researchInstance.TitleButton:SetHide(false)
TruncateStringWithTooltip(
m_researchInstance.TitleButton,
MAX_BEFORE_TRUNC_TITLE,
Locale.ToUpper(Locale.Lookup("LOC_WORLD_TRACKER_CHOOSE_RESEARCH"))
)
else
-- CUI: add tooltip for research
m_researchInstance.IconButton:SetToolTipString(Locale.Lookup(kResearchData.ToolTip))
end
end
-- ===========================================================================
function UpdateCivicsPanel(hideCivics)
local ePlayer = Game.GetLocalPlayer()
if ePlayer == -1 then
return
end -- Autoplayer
if not HasCapability("CAPABILITY_CIVICS_CHOOSER") then
hideCivics = true
Controls.CivicsCheck:SetHide(true)
end
if hideCivics ~= nil then
m_hideCivics = hideCivics
end
m_civicsInstance.MainPanel:SetHide(m_hideCivics)
Controls.CivicsCheck:SetCheck(not m_hideCivics)
LuaEvents.WorldTracker_ToggleCivicPanel(m_hideCivics or m_hideAll)
RealizeEmptyMessage()
RealizeStack()
-- Set the civic to show (or -1 if none)...
local iCivic = m_currentCivicID
if iCivic == -1 then
iCivic = m_lastCivicCompletedID
end
local pPlayer = Players[ePlayer]
local pPlayerCulture = pPlayer:GetCulture()
local kCivic = (iCivic ~= -1) and GameInfo.Civics[iCivic] or nil
local kCivicData = GetCivicData(ePlayer, pPlayerCulture, kCivic)
if iCivic ~= -1 then
if m_currentCivicID == iCivic then
kCivicData.IsCurrent = true
elseif m_lastCivicCompletedID == iCivic then
kCivicData.IsLastCompleted = true
end
end
for _, iconData in pairs(g_ExtraIconData) do
iconData:Reset()
end
RealizeCurrentCivic(ePlayer, kCivicData, m_civicsInstance, m_CachedModifiers)
-- No civic started (or finished)
if kCivicData == nil then
m_civicsInstance.TitleButton:SetHide(false)
TruncateStringWithTooltip(
m_civicsInstance.TitleButton,
MAX_BEFORE_TRUNC_TITLE,
Locale.ToUpper(Locale.Lookup("LOC_WORLD_TRACKER_CHOOSE_CIVIC"))
)
else
TruncateStringWithTooltip(
m_civicsInstance.TitleButton,
MAX_BEFORE_TRUNC_TITLE,
m_civicsInstance.TitleButton:GetText()
)
-- CUI: add tooltip for civics
m_civicsInstance.IconButton:SetToolTipString(Locale.Lookup(kCivicData.ToolTip))
end
end
-- ===========================================================================
function UpdateChatPanel(hideChat)
m_hideChat = hideChat
Controls.ChatPanel:SetHide(m_hideChat)
Controls.ChatCheck:SetCheck(not m_hideChat)
RealizeEmptyMessage()
RealizeStack()
CheckUnreadChatMessageCount()
end
-- ===========================================================================
function CheckUnreadChatMessageCount()
-- Unhiding the chat panel resets the unread chat message count.
if (not hideAll and not m_hideChat) then
m_unreadChatMsgs = 0
UpdateUnreadChatMsgs()
LuaEvents.WorldTracker_OnChatShown()
end
end
-- ===========================================================================
function UpdateUnreadChatMsgs()
if (GameConfiguration.IsPlayByCloud()) then
Controls.ChatCheck:GetTextButton():SetText(Locale.Lookup("LOC_PLAY_BY_CLOUD_PANEL"))
elseif (m_unreadChatMsgs > 0) then
Controls.ChatCheck:GetTextButton():SetText(
Locale.Lookup("LOC_HIDE_CHAT_PANEL_UNREAD_MESSAGES", m_unreadChatMsgs)
)
else
Controls.ChatCheck:GetTextButton():SetText(Locale.Lookup("LOC_HIDE_CHAT_PANEL"))
end
end
-- ===========================================================================
-- Obtains full refresh and views most current research and civic IDs.
-- ===========================================================================
function Refresh()
local localPlayer = Game.GetLocalPlayer()
if localPlayer < 0 then
ToggleAll(true)
return
end
local pPlayerTechs = Players[localPlayer]:GetTechs()
m_currentResearchID = pPlayerTechs:GetResearchingTech()
-- Only reset last completed tech once a new tech has been selected
if m_currentResearchID >= 0 then
m_lastResearchCompletedID = -1
end
UpdateResearchPanel()
local pPlayerCulture = Players[localPlayer]:GetCulture()
m_currentCivicID = pPlayerCulture:GetProgressingCivic()
-- Only reset last completed civic once a new civic has been selected
if m_currentCivicID >= 0 then
m_lastCivicCompletedID = -1
end
UpdateCivicsPanel()
-- Hide world tracker by default if there are no tracker options enabled
if IsAllPanelsHidden() then
ToggleAll(true)
end
end
-- ===========================================================================
-- GAME EVENT
-- ===========================================================================
function OnLocalPlayerTurnBegin()
local localPlayer = Game.GetLocalPlayer()
if localPlayer ~= -1 then
m_isDirty = true
end
end
-- ===========================================================================
-- GAME EVENT
-- ===========================================================================
function OnCityInitialized(playerID, cityID)
if playerID == Game.GetLocalPlayer() then
m_isDirty = true
end
end
-- ===========================================================================
-- GAME EVENT
-- Buildings can change culture/science yield which can effect
-- "turns to complete" values
-- ===========================================================================
function OnBuildingChanged(plotX, plotY, buildingIndex, playerID, cityID, iPercentComplete)
if playerID == Game.GetLocalPlayer() then
m_isDirty = true
end
end
-- ===========================================================================
-- GAME EVENT
-- ===========================================================================
function OnDirtyCheck()
if m_isDirty then
Refresh()
m_isDirty = false
end
end
-- ===========================================================================
-- GAME EVENT
-- A civic item has changed, this may not be the current civic item
-- but an item deeper in the tree that was just boosted by a player action.
-- ===========================================================================
function OnCivicChanged(ePlayer, eCivic)
local localPlayer = Game.GetLocalPlayer()
if localPlayer ~= -1 and localPlayer == ePlayer then
ResetOverflowArrow(m_civicsInstance)
local pPlayerCulture = Players[localPlayer]:GetCulture()
m_currentCivicID = pPlayerCulture:GetProgressingCivic()
m_lastCivicCompletedID = -1
if eCivic == m_currentCivicID then
UpdateCivicsPanel()
end
end
end
-- ===========================================================================
-- GAME EVENT
-- ===========================================================================
function OnCivicCompleted(ePlayer, eCivic)
local localPlayer = Game.GetLocalPlayer()
if localPlayer ~= -1 and localPlayer == ePlayer then
m_currentCivicID = -1
m_lastCivicCompletedID = eCivic
UpdateCivicsPanel()
end
end
-- ===========================================================================
-- GAME EVENT
-- ===========================================================================
function OnCultureYieldChanged(ePlayer)
local localPlayer = Game.GetLocalPlayer()
if localPlayer ~= -1 and localPlayer == ePlayer then
UpdateCivicsPanel()
end
end
-- ===========================================================================
-- GAME EVENT
-- ===========================================================================
function OnInterfaceModeChanged(eOldMode, eNewMode)
if eNewMode == InterfaceModeTypes.VIEW_MODAL_LENS then
ContextPtr:SetHide(true)
end
if eOldMode == InterfaceModeTypes.VIEW_MODAL_LENS then
ContextPtr:SetHide(false)
end
end
-- ===========================================================================
-- GAME EVENT
-- A research item has changed, this may not be the current researched item
-- but an item deeper in the tree that was just boosted by a player action.
-- ===========================================================================
function OnResearchChanged(ePlayer, eTech)
if ShouldUpdateResearchPanel(ePlayer, eTech) then
ResetOverflowArrow(m_researchInstance)
UpdateResearchPanel()
end
end
-- ===========================================================================
-- This function was separated so behavior can be modified in mods/expasions
-- ===========================================================================
function ShouldUpdateResearchPanel(ePlayer, eTech)
local localPlayer = Game.GetLocalPlayer()
if localPlayer ~= -1 and localPlayer == ePlayer then
local pPlayerTechs = Players[localPlayer]:GetTechs()
m_currentResearchID = pPlayerTechs:GetResearchingTech()
-- Only reset last completed tech once a new tech has been selected
if m_currentResearchID >= 0 then
m_lastResearchCompletedID = -1
end
if eTech == m_currentResearchID then
return true
end
end
return false
end
-- ===========================================================================
function OnResearchCompleted(ePlayer, eTech)
if (ePlayer == Game.GetLocalPlayer()) then
m_currentResearchID = -1
m_lastResearchCompletedID = eTech
UpdateResearchPanel()
end
end
-- ===========================================================================
function OnUpdateDueToCity(ePlayer, cityID, plotX, plotY)
if (ePlayer == Game.GetLocalPlayer()) then
UpdateResearchPanel()
UpdateCivicsPanel()
end
end
-- ===========================================================================
function OnResearchYieldChanged(ePlayer)
local localPlayer = Game.GetLocalPlayer()
if localPlayer ~= -1 and localPlayer == ePlayer then
UpdateResearchPanel()
end
end
-- ===========================================================================
function OnMultiplayerChat(fromPlayer, toPlayer, text, eTargetType)
-- If the chat panels are hidden, indicate there are unread messages waiting on the world tracker panel toggler.
if (m_hideAll or m_hideChat) then
m_unreadChatMsgs = m_unreadChatMsgs + 1
UpdateUnreadChatMsgs()
end
end
-- ===========================================================================
-- UI Callback
-- ===========================================================================
function OnInit(isReload)
LateInitialize()
if isReload then
LuaEvents.GameDebug_GetValues(RELOAD_CACHE_ID)
else
Refresh() -- Standard refresh.
end
end
-- ===========================================================================
-- UI Callback
-- ===========================================================================
function OnShutdown()
Unsubscribe()
LuaEvents.GameDebug_AddValue(RELOAD_CACHE_ID, "m_currentResearchID", m_currentResearchID)
LuaEvents.GameDebug_AddValue(RELOAD_CACHE_ID, "m_lastResearchCompletedID", m_lastResearchCompletedID)
LuaEvents.GameDebug_AddValue(RELOAD_CACHE_ID, "m_currentCivicID", m_currentCivicID)
LuaEvents.GameDebug_AddValue(RELOAD_CACHE_ID, "m_lastCivicCompletedID", m_lastCivicCompletedID)
end
-- ===========================================================================
function OnGameDebugReturn(context, contextTable)
if context == RELOAD_CACHE_ID then
m_currentResearchID = contextTable["m_currentResearchID"]
m_lastResearchCompletedID = contextTable["m_lastResearchCompletedID"]
m_currentCivicID = contextTable["m_currentCivicID"]
m_lastCivicCompletedID = contextTable["m_lastCivicCompletedID"]
if m_currentResearchID == nil then
m_currentResearchID = -1
end
if m_lastResearchCompletedID == nil then
m_lastResearchCompletedID = -1
end
if m_currentCivicID == nil then
m_currentCivicID = -1
end
if m_lastCivicCompletedID == nil then
m_lastCivicCompletedID = -1
end
-- Don't call refresh, use cached data from last hotload.
UpdateResearchPanel()
UpdateCivicsPanel()
end
end
-- ===========================================================================
function OnTutorialGoalsShowing()
RealizeStack()
end
-- ===========================================================================
function OnTutorialGoalsHiding()
RealizeStack()
end
-- ===========================================================================
function Tutorial_ShowFullTracker()
Controls.ToggleAllButton:SetHide(true)
Controls.ToggleDropdownButton:SetHide(true)
UpdateCivicsPanel(false)
UpdateResearchPanel(false)
ToggleAll(false)
end
-- ===========================================================================
function Tutorial_ShowTrackerOptions()
Controls.ToggleAllButton:SetHide(false)
Controls.ToggleDropdownButton:SetHide(false)
end
-- FF16 ======================================================================
function Test()
local msg = "This is a text message.[NEWLINE]asdlfjlkadsjfl"
LuaEvents.Custom_GossipMessage(msg, 10, ReportingStatusTypes.GOSSIP)
LuaEvents.Custom_GossipMessage(msg, 10, ReportingStatusTypes.DEFAULT)
ContextPtr:SetInputHandler(
function(pInputStruct)
local uiMsg = pInputStruct:GetMessageType()
if uiMsg == KeyEvents.KeyUp then
local key = pInputStruct:GetKey()
if key == Keys.G then
LuaEvents.Custom_GossipMessage(msg, 10, ReportingStatusTypes.GOSSIP)
LuaEvents.Custom_GossipMessage(msg, 10, ReportingStatusTypes.DEFAULT)
return true
end
end
return false
end,
true
)
end
-- ===========================================================================
-- CUI Tracker Functions
-- ---------------------------------------------------------------------------
function RefreshWonderToolTip(tControl)
tControl:ClearToolTipCallback()
tControl:SetToolTipType("CuiWonderTT")
tControl:SetToolTipCallback(
function()
UpdateWonderToolTip(tControl)
end
)
end
-- ---------------------------------------------------------------------------
function UpdateWonderToolTip()
local localPlayerID = Game.GetLocalPlayer()
if localPlayerID == -1 then
return
end
wonderInstance:ResetInstances()
colorInstance:ResetInstances()
for _, wonder in ipairs(wonderData.Wonders) do
local wonderIcon = wonderInstance:GetInstance(CuiWonderTT.WonderIconStack)
wonderIcon.Icon:SetIcon(wonder.Icon)
local beenBuilt = wonder.BeenBuilt
local alpha = beenBuilt and 0.5 or 1.0
local back = beenBuilt and "Black" or "Clear"
wonderIcon.Icon:SetAlpha(alpha)
wonderIcon.Back:SetColorByName(back)
wonderIcon.Color1:SetColor(wonder.Color1)
wonderIcon.Color2:SetColor(wonder.Color2)
end
CuiWonderTT.WonderIconStack:CalculateSize()
for _, civ in ipairs(wonderData.Colors) do
local colorIndicator = colorInstance:GetInstance(CuiWonderTT.ColorIndicatorStack)
colorIndicator.CivName:SetText(civ.CivName)
colorIndicator.Color1:SetColor(civ.Color1)
colorIndicator.Color2:SetColor(civ.Color2)
end
CuiWonderTT.ColorIndicatorStack:CalculateSize()
local wonderStackY = CuiWonderTT.WonderIconStack:GetSizeY()
local colorStackY = CuiWonderTT.ColorIndicatorStack:GetSizeY()
local dividerY = math.max(wonderStackY, colorStackY)
CuiWonderTT.VerticalDivider:SetSizeY(dividerY)
CuiWonderTT.MainStack:CalculateSize()
CuiWonderTT.BG:DoAutoSize()
end
-- ---------------------------------------------------------------------------
function RefreshResourceToolTip(tControl)
tControl:ClearToolTipCallback()
tControl:SetToolTipType("CuiResourceTT")
tControl:SetToolTipCallback(
function()
UpdateResourceToolTip(tControl)
end
)
end
-- ---------------------------------------------------------------------------
function UpdateResourceToolTip()
local localPlayerID = Game.GetLocalPlayer()
if localPlayerID == -1 then
return
end
resourceInstance:ResetInstances()
resourceBarInstance:ResetInstances()
r_luxury = resourceData.Luxury
r_strategic = resourceData.Strategic
-- luxury
CuiResourceTT.LuxuryIconStack:SetHide(#r_luxury == 0)
CuiResourceTT.Divider:SetHide(#r_luxury == 0)
if not isExpansion2 and #r_luxury < 9 then
CuiResourceTT.Divider:SetSizeX(264)
else
CuiResourceTT.Divider:SetSizeX(346)
end
for _, item in ipairs(r_luxury) do
local icon = resourceInstance:GetInstance(CuiResourceTT.LuxuryIconStack)
CuiSetIconToSize(icon.Icon, item.Icon, 36)
icon.Text:SetText(item.Amount)
if item.Duplicate then
icon.Text:SetColorByName("ModStatusGreen")
elseif item.CanTrade then
icon.Text:SetColorByName("Black")
else
icon.Text:SetColorByName("Red")
end
end
CuiResourceTT.LuxuryIconStack:CalculateSize()
-- strategic
if isExpansion2 then
for _, item in ipairs(r_strategic) do
local icon = resourceBarInstance:GetInstance(CuiResourceTT.StrategicIconStack)
CuiSetIconToSize(icon.Icon, item.Icon, 36)
local perTurn = item.APerTurn - item.MPerTurn
local perTurnText = ""
if perTurn < 0 then
perTurnText = "[COLOR_Civ6Red]" .. perTurn .. "[ENDCOLOR]"
elseif perTurn > 0 then
perTurnText = "[COLOR_ModStatusGreen]+" .. perTurn .. "[ENDCOLOR]"
else
perTurnText = "-"
end
icon.PerTurn:SetText(perTurnText)
if item.Amount > item.Cap then
item.Amount = item.Cap
end
icon.Amount:SetText(item.Amount .. " / " .. item.Cap)
local percent = item.Amount / item.Cap
icon.PercentBar:SetPercent(percent)
end
CuiResourceTT.StrategicIconStack:CalculateSize()
else
for _, item in ipairs(r_strategic) do
local icon = resourceInstance:GetInstance(CuiResourceTT.StrategicIconStack)
CuiSetIconToSize(icon.Icon, item.Icon, 36)
icon.Text:SetText(item.Amount)
end
end
CuiResourceTT.MainStack:CalculateSize()
CuiResourceTT.BG:DoAutoSize()
end
-- ---------------------------------------------------------------------------
function RefreshBorderToolTip(tControl)
tControl:ClearToolTipCallback()
if #borderData.Leaders > 0 then
tControl:SetToolTipType("CuiBorderTT")
tControl:SetToolTipCallback(
function()
UpdateBorderToolTip(tControl)
end
)
end
end
-- ---------------------------------------------------------------------------
function UpdateBorderToolTip()
local localPlayerID = Game.GetLocalPlayer()
if localPlayerID == -1 then
return
end
borderInstance:ResetInstances()
CuiBorderTT.OpenBorderIcon:SetTexture(IconManager:FindIconAtlas("ICON_DIPLOACTION_OPEN_BORDERS", 50))
for _, leader in ipairs(borderData.Leaders) do
local icon = borderInstance:GetInstance(CuiBorderTT.OpenBorderStack)
icon.Icon:SetTexture(CuiLeaderTexture(leader.Icon, 45, leader.IsMet))
-- setup images
local importColor = leader.HasImport and "Green" or "White"
local exportColor = leader.HasExport and "Green" or "White"
icon.Import:SetColorByName(importColor)
icon.Export:SetColorByName(exportColor)
local isRestricted =
not leader.HasImport and not leader.CanImport and not leader.HasExport and not leader.CanImport
icon.Import:SetHide(isRestricted)
icon.Export:SetHide(isRestricted)
icon.Disable:SetHide(not isRestricted)
end
CuiBorderTT.OpenBorderStack:CalculateSize()
-- divider height
CuiBorderTT.Divider:SetHide(#borderData.Leaders == 0)
local stackHeight = CuiBorderTT.OpenBorderStack:GetSizeY()
CuiBorderTT.Divider:SetSizeY(math.max(190, stackHeight))
CuiBorderTT.MainStack:DoAutoSize()
CuiBorderTT.BG:DoAutoSize()
end
-- ---------------------------------------------------------------------------
function RefreshTradeToolTip(tControl)
tControl:ClearToolTipCallback()
if tradeData.Cap > 0 then
tControl:SetToolTipType("CuiTradeTT")
tControl:SetToolTipCallback(
function()
UpdateTradeToolTip(tControl)
end
)
end
end
-- ---------------------------------------------------------------------------
function UpdateTradeToolTip()
local localPlayerID = Game.GetLocalPlayer()
if localPlayerID == -1 then
return
end
if isNil(tradeData) then
return
end
local textActive = tradeData.Routes
if tradeData.Routes < tradeData.Cap then
textActive = "[COLOR_GREEN]" .. tradeData.Routes .. "[ENDCOLOR]"
elseif tradeData.Routes > tradeData.Cap then
textActive = "[COLOR_RED]" .. tradeData.Routes .. "[ENDCOLOR]"
end
CuiTradeTT.RoutesActive:SetText(textActive)
CuiTradeTT.RoutesCap:SetText("/" .. tradeData.Cap)
tradeInstance:ResetInstances()
CuiTradeTT.TraderIcon:SetTexture(IconManager:FindIconAtlas("ICON_UNIT_TRADER_PORTRAIT", 50))
for _, leader in ipairs(tradeData.Leaders) do
local icon = tradeInstance:GetInstance(CuiTradeTT.TradeRouteStack)
icon.Icon:SetTexture(CuiLeaderTexture(leader.Icon, 45, leader.IsMet))
if leader.IsTraded then
icon.TradeState:SetTexture("icon_yes.dds")
elseif not leader.IsMet or leader.IsWar then
icon.TradeState:SetTexture("icon_no.dds")
else
icon.TradeState:SetTexture("Espionage_OverlayFound")
end
end
CuiTradeTT.TradeRouteStack:CalculateSize()
-- divider height
CuiTradeTT.Divider:SetHide(#tradeData.Leaders == 0)
local stackHeight = CuiTradeTT.TradeRouteStack:GetSizeY()
CuiTradeTT.Divider:SetSizeY(math.max(190, stackHeight))
CuiTradeTT.MainStack:DoAutoSize()
CuiTradeTT.BG:DoAutoSize()
end
-- ===========================================================================
-- CUI City Manager Functions
-- ---------------------------------------------------------------------------
function CuiOnCityManager()
LuaEvents.CuiOnToggleCityManager()
end
-- ===========================================================================
-- CUI Log Functions
-- ---------------------------------------------------------------------------
function CuiUpdateLog(logString, displayTime, logType)
if logType == ReportingStatusTypes.GOSSIP then
CuiAddGossipLog(logString)
elseif logType == ReportingStatusTypes.DEFAULT then
CuiAddCombatLog(logString)
end
end
-- ---------------------------------------------------------------------------
function CuiTurnString()
local turnLookup = Locale.Lookup("{LOC_TOP_PANEL_CURRENT_TURN:upper} ")
turnString = "[COLOR_FLOAT_GOLD]" .. turnLookup .. Game.GetCurrentGameTurn() .. "[ENDCOLOR]"
return turnString
end
-- ---------------------------------------------------------------------------
function CuiAddGossipLog(logString)
if cui_GossipCount == 0 then
CuiAddLog(CuiTurnString(), cui_GossipPanel, cui_GossipLogs)
end
CuiAddLog(logString, cui_GossipPanel, cui_GossipLogs)
cui_GossipCount = cui_GossipCount + 1
cui_GossipPanel.NewLogNumber:SetText("[ICON_NEW] " .. cui_GossipCount)
end
-- ---------------------------------------------------------------------------
function CuiAddCombatLog(logString)
if cui_CombatCount == 0 then
CuiAddLog(CuiTurnString(), cui_CombatPanel, cui_CombatLogs)
end
CuiAddLog(logString, cui_CombatPanel, cui_CombatLogs)
cui_CombatCount = cui_CombatCount + 1
cui_CombatPanel.NewLogNumber:SetText("[ICON_NEW] " .. cui_CombatCount)
end
-- ---------------------------------------------------------------------------
function CuiAddLog(logString, logPanel, entries)
local instance = {}
ContextPtr:BuildInstanceForControl("LogInstance", instance, logPanel.LogStack)
instance.String:SetText(logString)
instance.LogRoot:SetSizeY(instance.String:GetSizeY() + 6)
table.insert(entries, instance)
-- Remove the earliest entry if the log limit has been reached
if #entries > cui_MaxLog then
logPanel.LogStack:ReleaseChild(entries[1].LogRoot)
table.remove(entries, 1)
end
-- Refresh log and reprocess size
logPanel.LogStack:CalculateSize()
logPanel.LogStack:ReprocessAnchoring()
end
-- ---------------------------------------------------------------------------
function CuiLogPanelResize(instance, state)
local status = cui_LogPanelStatus[state]
instance.MainPanel:SetSizeY(status.main)
instance.LogPanel:SetSizeY(status.log)
instance.LogStack:SetHide(state == 1)
instance.ButtomDivider:SetHide(state == 1)
end
-- ---------------------------------------------------------------------------
function CuiContractGossipLog()
cui_GossipState = cui_GossipState - 1
if cui_GossipState == 0 then
cui_GossipState = 3
end
CuiSettings:SetNumber(CuiSettings.GOSSIP_LOG_STATE, cui_GossipState)
CuiLogPanelResize(cui_GossipPanel, cui_GossipState)
end
-- ---------------------------------------------------------------------------
function CuiExpandGossipLog()
cui_GossipState = cui_GossipState + 1
if cui_GossipState == 4 then
cui_GossipState = 1
end
CuiSettings:SetNumber(CuiSettings.GOSSIP_LOG_STATE, cui_GossipState)
CuiLogPanelResize(cui_GossipPanel, cui_GossipState)
end
-- ---------------------------------------------------------------------------
function CuiContractCombatLog()
cui_CombatState = cui_CombatState - 1
if cui_CombatState == 0 then
cui_CombatState = 3
end
CuiSettings:SetNumber(CuiSettings.COMBAT_LOG_STATE, cui_CombatState)
CuiLogPanelResize(cui_CombatPanel, cui_CombatState)
end
-- ---------------------------------------------------------------------------
function CuiExpandCombatLog()
cui_CombatState = cui_CombatState + 1
if cui_CombatState == 4 then
cui_CombatState = 1
end
CuiSettings:SetNumber(CuiSettings.COMBAT_LOG_STATE, cui_CombatState)
CuiLogPanelResize(cui_CombatPanel, cui_CombatState)
end
-- ===========================================================================
-- CUI Panel Functions
-- ---------------------------------------------------------------------------
function CuiLogPanelSetup()
CuiRegCallback(cui_GossipPanel.TitleButton, CuiExpandGossipLog, CuiContractGossipLog)
CuiRegCallback(cui_CombatPanel.TitleButton, CuiExpandCombatLog, CuiContractCombatLog)
Controls.GossipLogCheck:RegisterCheckHandler(CuiOnLogCheckClick)
Controls.CombatLogCheck:RegisterCheckHandler(CuiOnLogCheckClick)
end
-- ---------------------------------------------------------------------------
function CuiTrackPanelSetup()
cui_TrackBar.WonderIcon:SetTexture(IconManager:FindIconAtlas("ICON_DISTRICT_WONDER", 32))
cui_TrackBar.ResourceIcon:SetTexture(IconManager:FindIconAtlas("ICON_DIPLOACTION_REQUEST_ASSISTANCE", 38))
cui_TrackBar.BorderIcon:SetTexture(IconManager:FindIconAtlas("ICON_DIPLOACTION_OPEN_BORDERS", 38))
cui_TrackBar.TradeIcon:SetTexture(IconManager:FindIconAtlas("ICON_DIPLOACTION_VIEW_TRADE", 38))
cui_TrackBar.TempAIcon:SetTexture(IconManager:FindIconAtlas("ICON_DIPLOACTION_DECLARE_SURPRISE_WAR", 38))
cui_TrackBar.TempBIcon:SetTexture(IconManager:FindIconAtlas("ICON_DIPLOACTION_ALLIANCE", 38))
cui_TrackBar.CityIcon:SetTexture(IconManager:FindIconAtlas("ICON_DISTRICT_CITY_CENTER", 32))
cui_TrackBar.CuiCityManager:RegisterCallback(Mouse.eLClick, CuiOnCityManager)
end
-- ---------------------------------------------------------------------------
function CuiOnPopulationChanged(isChanged)
CuiChangeIconColor(cui_TrackBar.CityIcon, isChanged)
end
-- ---------------------------------------------------------------------------
function CuiChangeIconColor(icon, isActive)
if isActive then
icon:SetColorByName("ModStatusGreenCS")
else
icon:SetColorByName("White")
end
end
-- ---------------------------------------------------------------------------
function CuiLogPanelRefresh()
m_useGossipLog = CuiSettings:GetBoolean(CuiSettings.WT_GOSSIP_LOG)
m_useCombatLog = CuiSettings:GetBoolean(CuiSettings.WT_COMBAT_LOG)
cui_GossipPanel.MainPanel:SetHide(not m_useGossipLog)
cui_CombatPanel.MainPanel:SetHide(not m_useCombatLog)
CuiLogPanelResize(cui_CombatPanel, cui_CombatState)
CuiLogPanelResize(cui_GossipPanel, cui_GossipState)
Controls.GossipLogCheck:SetCheck(m_useGossipLog)
Controls.CombatLogCheck:SetCheck(m_useCombatLog)
end
-- ---------------------------------------------------------------------------
function CuiLogCounterReset()
cui_GossipCount = 0
cui_GossipPanel.NewLogNumber:SetText("")
cui_CombatCount = 0
cui_CombatPanel.NewLogNumber:SetText("")
end
-- ---------------------------------------------------------------------------
function CuiTrackerRefresh()
local localPlayer = Players[Game.GetLocalPlayer()]
if localPlayer == nil then
return
end
wonderData = GetWonderData()
resourceData = GetResourceData()
borderData = GetBorderData()
tradeData = GetTradeData()
RefreshWonderToolTip(cui_TrackBar.WonderIcon)
RefreshResourceToolTip(cui_TrackBar.ResourceIcon)
RefreshBorderToolTip(cui_TrackBar.BorderIcon)
RefreshTradeToolTip(cui_TrackBar.TradeIcon)
CuiChangeIconColor(cui_TrackBar.ResourceIcon, resourceData.Active)
CuiChangeIconColor(cui_TrackBar.BorderIcon, borderData.Active)
CuiChangeIconColor(cui_TrackBar.TradeIcon, tradeData.Active)
end
-- ---------------------------------------------------------------------------
function CuiOnLogCheckClick()
m_useGossipLog = Controls.GossipLogCheck:IsChecked()
m_useCombatLog = Controls.CombatLogCheck:IsChecked()
CuiSettings:SetBoolean(CuiSettings.WT_GOSSIP_LOG, m_useGossipLog)
CuiSettings:SetBoolean(CuiSettings.WT_COMBAT_LOG, m_useCombatLog)
CuiLogPanelRefresh()
RealizeEmptyMessage()
RealizeStack()
end
-- ===========================================================================
function CuiInit()
ContextPtr:BuildInstanceForControl("CuiTrackerInstance", cui_TrackBar, Controls.PanelStack)
CuiTrackPanelSetup()
ContextPtr:BuildInstanceForControl("GossipLogInstance", cui_GossipPanel, Controls.PanelStack)
ContextPtr:BuildInstanceForControl("CombatLogInstance", cui_CombatPanel, Controls.PanelStack)
CuiLogPanelSetup()
-- Log Events
Events.StatusMessage.Add(CuiUpdateLog)
Events.LocalPlayerTurnEnd.Add(CuiLogCounterReset)
-- Tracker Events
Events.ImprovementAddedToMap.Add(CuiTrackerRefresh)
Events.ImprovementRemovedFromMap.Add(CuiTrackerRefresh)
Events.LoadGameViewStateDone.Add(CuiTrackerRefresh)
Events.LocalPlayerTurnBegin.Add(CuiTrackerRefresh)
LuaEvents.DiplomacyActionView_ShowIngameUI.Add(CuiTrackerRefresh)
-- Refresh
CuiLogPanelRefresh()
CuiTrackerRefresh()
LuaEvents.CuiLogSettingChange.Add(CuiLogPanelRefresh)
LuaEvents.CuiPlayerPopulationChanged.Add(CuiOnPopulationChanged)
end
-- ===========================================================================
-- Handling chat panel expansion
-- ===========================================================================
function OnChatPanel_OpenExpandedPanels()
--[[ TODO: Embiggen the chat panel to fill size! (Requires chat panel changes as well) ??TRON
Controls.ChatPanel:SetHide(true); -- Hide so it's not part of stack computation.
RealizeStack();
width, height = UIManager:GetScreenSizeVal();
local stackSize = Controls.PanelStack:GetSizeY(); -- Size of other stuff in the stack.
local minimapSize = 100;
local chatSize = math.max(199, height-(stackSize + minimapSize) );
Controls.ChatPanel:SetHide(false);
]]
Controls.ChatPanel:SetSizeY(199)
RealizeStack()
end
function OnChatPanel_CloseExpandedPanels()
Controls.ChatPanel:SetSizeY(CHAT_COLLAPSED_SIZE)
RealizeStack()
end
-- ===========================================================================
-- Add any UI from tracked items that are loaded.
-- Items are expected to be tables with the following fields:
-- Name localization key for the title name of panel
-- InstanceType the instance (in XML) to create for the control
-- SelectFunc if instance has "IconButton" the callback when pressed
-- ===========================================================================
function AttachDynamicUI()
for i, kData in ipairs(g_TrackedItems) do
local uiInstance = {}
ContextPtr:BuildInstanceForControl(kData.InstanceType, uiInstance, Controls.PanelStack)
if uiInstance.IconButton then
uiInstance.IconButton:RegisterCallback(
Mouse.eLClick,
function()
kData.SelectFunc()
end
)
end
table.insert(g_TrackedInstances, uiInstance)
if (uiInstance.TitleButton) then
uiInstance.TitleButton:LocalizeAndSetText(kData.Name)
end
end
end
-- ===========================================================================
function OnForceHide()
ContextPtr:SetHide(true)
end
-- ===========================================================================
function OnForceShow()
ContextPtr:SetHide(false)
end
-- ===========================================================================
function Subscribe()
Events.CityInitialized.Add(OnCityInitialized)
Events.BuildingChanged.Add(OnBuildingChanged)
Events.CivicChanged.Add(OnCivicChanged)
Events.CivicCompleted.Add(OnCivicCompleted)
Events.CultureYieldChanged.Add(OnCultureYieldChanged)
Events.InterfaceModeChanged.Add(OnInterfaceModeChanged)
Events.LocalPlayerTurnBegin.Add(OnLocalPlayerTurnBegin)
Events.MultiplayerChat.Add(OnMultiplayerChat)
Events.ResearchChanged.Add(OnResearchChanged)
Events.ResearchCompleted.Add(OnResearchCompleted)
Events.ResearchYieldChanged.Add(OnResearchYieldChanged)
Events.GameCoreEventPublishComplete.Add(OnDirtyCheck) -- This event is raised directly after a series of gamecore events.
Events.CityWorkerChanged.Add(OnUpdateDueToCity)
Events.CityFocusChanged.Add(OnUpdateDueToCity)
LuaEvents.LaunchBar_Resize.Add(OnLaunchBarResized)
LuaEvents.CivicChooser_ForceHideWorldTracker.Add(OnForceHide)
LuaEvents.CivicChooser_RestoreWorldTracker.Add(OnForceShow)
LuaEvents.ResearchChooser_ForceHideWorldTracker.Add(OnForceHide)
LuaEvents.ResearchChooser_RestoreWorldTracker.Add(OnForceShow)
LuaEvents.Tutorial_ForceHideWorldTracker.Add(OnForceHide)
LuaEvents.Tutorial_RestoreWorldTracker.Add(Tutorial_ShowFullTracker)
LuaEvents.Tutorial_EndTutorialRestrictions.Add(Tutorial_ShowTrackerOptions)
LuaEvents.TutorialGoals_Showing.Add(OnTutorialGoalsShowing)
LuaEvents.TutorialGoals_Hiding.Add(OnTutorialGoalsHiding)
LuaEvents.ChatPanel_OpenExpandedPanels.Add(OnChatPanel_OpenExpandedPanels)
LuaEvents.ChatPanel_CloseExpandedPanels.Add(OnChatPanel_CloseExpandedPanels)
end
-- ===========================================================================
function Unsubscribe()
Events.CityInitialized.Remove(OnCityInitialized)
Events.BuildingChanged.Remove(OnBuildingChanged)
Events.CivicChanged.Remove(OnCivicChanged)
Events.CivicCompleted.Remove(OnCivicCompleted)
Events.CultureYieldChanged.Remove(OnCultureYieldChanged)
Events.InterfaceModeChanged.Remove(OnInterfaceModeChanged)
Events.LocalPlayerTurnBegin.Remove(OnLocalPlayerTurnBegin)
Events.MultiplayerChat.Remove(OnMultiplayerChat)
Events.ResearchChanged.Remove(OnResearchChanged)
Events.ResearchCompleted.Remove(OnResearchCompleted)
Events.ResearchYieldChanged.Remove(OnResearchYieldChanged)
Events.GameCoreEventPublishComplete.Remove(OnDirtyCheck) -- This event is raised directly after a series of gamecore events.
Events.CityWorkerChanged.Remove(OnUpdateDueToCity)
Events.CityFocusChanged.Remove(OnUpdateDueToCity)
LuaEvents.LaunchBar_Resize.Remove(OnLaunchBarResized)
LuaEvents.CivicChooser_ForceHideWorldTracker.Remove(OnForceHide)
LuaEvents.CivicChooser_RestoreWorldTracker.Remove(OnForceShow)
LuaEvents.ResearchChooser_ForceHideWorldTracker.Remove(OnForceHide)
LuaEvents.ResearchChooser_RestoreWorldTracker.Remove(OnForceShow)
LuaEvents.Tutorial_ForceHideWorldTracker.Remove(OnForceHide)
LuaEvents.Tutorial_RestoreWorldTracker.Remove(Tutorial_ShowFullTracker)
LuaEvents.Tutorial_EndTutorialRestrictions.Remove(Tutorial_ShowTrackerOptions)
LuaEvents.TutorialGoals_Showing.Remove(OnTutorialGoalsShowing)
LuaEvents.TutorialGoals_Hiding.Remove(OnTutorialGoalsHiding)
LuaEvents.ChatPanel_OpenExpandedPanels.Remove(OnChatPanel_OpenExpandedPanels)
LuaEvents.ChatPanel_CloseExpandedPanels.Remove(OnChatPanel_CloseExpandedPanels)
end
-- ===========================================================================
function LateInitialize()
Subscribe()
-- InitChatPanel
if (UI.HasFeature("Chat") and (GameConfiguration.IsNetworkMultiplayer() or GameConfiguration.IsPlayByCloud())) then
UpdateChatPanel(false)
else
UpdateChatPanel(true)
Controls.ChatCheck:SetHide(true)
end
UpdateUnreadChatMsgs()
AttachDynamicUI()
end
-- ===========================================================================
function Initialize()
if not GameCapabilities.HasCapability("CAPABILITY_WORLD_TRACKER") then
ContextPtr:SetHide(true)
return
end
m_CachedModifiers = TechAndCivicSupport_BuildCivicModifierCache()
-- Create semi-dynamic instances; hack: change parent back to self for ordering:
ContextPtr:BuildInstanceForControl("ResearchInstance", m_researchInstance, Controls.PanelStack)
ContextPtr:BuildInstanceForControl("CivicInstance", m_civicsInstance, Controls.PanelStack)
m_researchInstance.IconButton:RegisterCallback(
Mouse.eLClick,
function()
LuaEvents.WorldTracker_OpenChooseResearch()
end
)
m_civicsInstance.IconButton:RegisterCallback(
Mouse.eLClick,
function()
LuaEvents.WorldTracker_OpenChooseCivic()
end
)
CuiInit() -- CUI
Controls.ChatPanel:ChangeParent(Controls.PanelStack)
Controls.TutorialGoals:ChangeParent(Controls.PanelStack)
-- Handle any text overflows with truncation and tooltip
local fullString = Controls.WorldTracker:GetText()
Controls.DropdownScroll:SetOffsetY(Controls.WorldTrackerHeader:GetSizeY() + STARTING_TRACKER_OPTIONS_OFFSET)
-- Hot-reload events
ContextPtr:SetInitHandler(OnInit)
ContextPtr:SetShutdown(OnShutdown)
LuaEvents.GameDebug_Return.Add(OnGameDebugReturn)
Controls.ChatCheck:SetCheck(true)
Controls.CivicsCheck:SetCheck(true)
Controls.ResearchCheck:SetCheck(true)
Controls.ToggleAllButton:SetCheck(true)
Controls.ChatCheck:RegisterCheckHandler(
function()
UpdateChatPanel(not m_hideChat)
end
)
Controls.CivicsCheck:RegisterCheckHandler(
function()
UpdateCivicsPanel(not m_hideCivics)
end
)
Controls.ResearchCheck:RegisterCheckHandler(
function()
UpdateResearchPanel(not m_hideResearch)
end
)
Controls.ToggleAllButton:RegisterCheckHandler(
function()
ToggleAll(not Controls.ToggleAllButton:IsChecked())
end
)
Controls.ToggleDropdownButton:RegisterCallback(Mouse.eLClick, ToggleDropdown)
Controls.WorldTrackerAlpha:RegisterEndCallback(OnWorldTrackerAnimationFinished)
-- CUI
-- LuaEvents.Custom_GossipMessage.Add(CuiUpdateLog);
-- Test();
end
Initialize()
|
--[[
Mana
This mod adds mana to players, a special attribute
License: WTFPL
]]
--[===[
Initialization
]===]
local S
if (minetest.get_modpath("intllib")) then
S = intllib.Getter()
else
S = function(s,a,...)a={a,...}return s:gsub("@(%d+)",function(n)return a[tonumber(n)]end)end
end
mana = {}
mana.playerlist = {}
mana.settings = {}
mana.settings.default_max = 200
mana.settings.default_regen = 1
mana.settings.regen_timer = 8
do
local default_max = tonumber(minetest.setting_get("mana_default_max"))
if default_max ~= nil then
mana.settings.default_max = default_max
end
local default_regen = tonumber(minetest.setting_get("mana_default_regen"))
if default_regen ~= nil then
mana.settings.default_regen = default_regen
end
local regen_timer = tonumber(minetest.setting_get("mana_regen_timer"))
if regen_timer ~= nil then
mana.settings.regen_timer = regen_timer
end
end
--[===[
API functions
]===]
function mana.set(playername, value)
if value < 0 then
minetest.log("info", "[mana] Warning: mana.set was called with negative value!")
value = 0
end
value = mana.round(value)
if value > mana.playerlist[playername].maxmana then
value = mana.playerlist[playername].maxmana
end
if mana.playerlist[playername].mana ~= value then
mana.playerlist[playername].mana = value
mana.hud_update(playername)
end
end
function mana.setmax(playername, value)
if value < 0 then
value = 0
minetest.log("info", "[mana] Warning: mana.setmax was called with negative value!")
end
value = mana.round(value)
if mana.playerlist[playername].maxmana ~= value then
mana.playerlist[playername].maxmana = value
if(mana.playerlist[playername].mana > value) then
mana.playerlist[playername].mana = value
end
mana.hud_update(playername)
end
end
function mana.setregen(playername, value)
mana.playerlist[playername].regen = value
end
function mana.get(playername)
return mana.playerlist[playername].mana
end
function mana.getmax(playername)
return mana.playerlist[playername].maxmana
end
function mana.getregen(playername)
return mana.playerlist[playername].regen
end
function mana.add_up_to(playername, value)
local t = mana.playerlist[playername]
value = mana.round(value)
if(t ~= nil and value >= 0) then
local excess
if((t.mana + value) > t.maxmana) then
excess = (t.mana + value) - t.maxmana
t.mana = t.maxmana
else
excess = 0
t.mana = t.mana + value
end
mana.hud_update(playername)
return true, excess
else
return false
end
end
function mana.add(playername, value)
local t = mana.playerlist[playername]
value = mana.round(value)
if(t ~= nil and ((t.mana + value) <= t.maxmana) and value >= 0) then
t.mana = t.mana + value
mana.hud_update(playername)
return true
else
return false
end
end
function mana.subtract(playername, value)
local t = mana.playerlist[playername]
value = mana.round(value)
if(t ~= nil and t.mana >= value and value >= 0) then
t.mana = t.mana -value
mana.hud_update(playername)
return true
else
return false
end
end
function mana.subtract_up_to(playername, value)
local t = mana.playerlist[playername]
value = mana.round(value)
if(t ~= nil and value >= 0) then
local missing
if((t.mana - value) < 0) then
missing = math.abs(t.mana - value)
t.mana = 0
else
missing = 0
t.mana = t.mana - value
end
mana.hud_update(playername)
return true, missing
else
return false
end
end
--[===[
File handling, loading data, saving data, setting up stuff for players.
]===]
-- Load the playerlist from a previous session, if available.
do
local filepath = minetest.get_worldpath().."/mana.mt"
local file = io.open(filepath, "r")
if file then
minetest.log("action", "[mana] mana.mt opened.")
local string = file:read()
io.close(file)
if(string ~= nil) then
local savetable = minetest.deserialize(string)
mana.playerlist = savetable.playerlist
minetest.debug("[mana] mana.mt successfully read.")
end
end
end
function mana.save_to_file()
local savetable = {}
savetable.playerlist = mana.playerlist
local savestring = minetest.serialize(savetable)
local filepath = minetest.get_worldpath().."/mana.mt"
local file = io.open(filepath, "w")
if file then
file:write(savestring)
io.close(file)
minetest.log("action", "[mana] Wrote mana data into "..filepath..".")
else
minetest.log("error", "[mana] Failed to write mana data into "..filepath..".")
end
end
minetest.register_on_respawnplayer(function(player)
local playername = player:get_player_name()
mana.set(playername, 0)
mana.hud_update(playername)
end)
minetest.register_on_leaveplayer(function(player)
local playername = player:get_player_name()
if not minetest.get_modpath("hudbars") ~= nil then
mana.hud_remove(playername)
end
mana.save_to_file()
end)
minetest.register_on_shutdown(function()
minetest.log("action", "[mana] Server shuts down. Rescuing data into mana.mt")
mana.save_to_file()
end)
minetest.register_on_joinplayer(function(player)
local playername = player:get_player_name()
if mana.playerlist[playername] == nil then
mana.playerlist[playername] = {}
mana.playerlist[playername].mana = 0
mana.playerlist[playername].maxmana = mana.settings.default_max
mana.playerlist[playername].regen = mana.settings.default_regen
mana.playerlist[playername].remainder = 0
end
if minetest.get_modpath("hudbars") ~= nil then
hb.init_hudbar(player, "mana", mana.get(playername), mana.getmax(playername))
else
mana.hud_add(playername)
end
end)
--[===[
Mana regeneration
]===]
mana.regen_timer = 0
minetest.register_globalstep(function(dtime)
mana.regen_timer = mana.regen_timer + dtime
if mana.regen_timer >= mana.settings.regen_timer then
local factor = math.floor(mana.regen_timer / mana.settings.regen_timer)
local players = minetest.get_connected_players()
for i=1, #players do
local name = players[i]:get_player_name()
if mana.playerlist[name] ~= nil then
if players[i]:get_hp() > 0 then
local plus = mana.playerlist[name].regen * factor
-- Compability check for version <= 1.0.2 which did not have the remainder field
if mana.playerlist[name].remainder ~= nil then
plus = plus + mana.playerlist[name].remainder
end
local plus_now = math.floor(plus)
local floor = plus - plus_now
if plus_now > 0 then
mana.add_up_to(name, plus_now)
else
mana.subtract_up_to(name, math.abs(plus_now))
end
mana.playerlist[name].remainder = floor
end
end
end
mana.regen_timer = mana.regen_timer % mana.settings.regen_timer
end
end)
--[===[
HUD functions
]===]
if minetest.get_modpath("hudbars") ~= nil then
hb.register_hudbar("mana", 0xFFFFFF, S("Mana"), { bar = "mana_bar.png", icon = "mana_icon.png", bgicon = "mana_bgicon.png" }, 0, mana.settings.default_max, false)
function mana.hud_update(playername)
local player = minetest.get_player_by_name(playername)
if player ~= nil then
hb.change_hudbar(player, "mana", mana.get(playername), mana.getmax(playername))
end
end
function mana.hud_remove(playername)
end
else
function mana.manastring(playername)
return S("Mana: @1/@2", mana.get(playername), mana.getmax(playername))
end
function mana.hud_add(playername)
local player = minetest.get_player_by_name(playername)
local id = player:hud_add({
hud_elem_type = "text",
position = { x = 0.5, y=1 },
text = mana.manastring(playername),
scale = { x = 0, y = 0 },
alignment = { x = 1, y = 0},
direction = 1,
number = 0xFFFFFF,
offset = { x = -262, y = -103}
})
mana.playerlist[playername].hudid = id
return id
end
function mana.hud_update(playername)
local player = minetest.get_player_by_name(playername)
player:hud_change(mana.playerlist[playername].hudid, "text", mana.manastring(playername))
end
function mana.hud_remove(playername)
local player = minetest.get_player_by_name(playername)
player:hud_remove(mana.playerlist[playername].hudid)
end
end
--[===[
Helper functions
]===]
mana.round = function(x)
return math.ceil(math.floor(x+0.5))
end
-- Addition to API for teleport functions - Axinite customization
local tpmanadrain = 100
function mana.checkmana(playername, drainrate)
if mana == nil then return true end
if not drainrate then drainrate = 1 end
local newdrain = math.floor(drainrate * tpmanadrain)
local manaval = mana.get(playername)
if manaval > newdrain then
mana.subtract(playername, newdrain)
return true
end
minetest.chat_send_player(playername, "Not enough mana. // Mana insuffisant.")
return false
end
--Addition Axinite - potion mana
minetest.register_craftitem("mana:potion", {
description = "Mana Potion",
inventory_image = "potion.png",
on_use = function(itemstack, user, pointed_thing)
mana.add_up_to(user:get_player_name(), 200)
itemstack:take_item()
return itemstack
end,
})
minetest.register_craft({
output = "mana:potion",
recipe = {
{"", "default:diamond", ""},
{"default:diamond", "vessels:glass_bottle", "default:diamond"},
{"", "default:diamond", ""}
}
})
|
--[[
Copyright 2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local http = require('http')
local HOST = "127.0.0.1"
local PORT = process.env.PORT or 10082
local body = "Hello world\n"
require('tap')(function(test)
test("http-client-server", function(expect)
local server = nil
local client = nil
server = http.createServer(expect(function(request, response)
p('server:onConnection req', request)
assert(request.method == "GET")
assert(request.url == "/foo")
-- Fixed because header parsing is not busted anymore
assert(request.headers.bar == "cats")
p('server:onConnection bare resp', response)
response:setHeader("Content-Type", "text/plain")
response:setHeader("Content-Length", #body)
response:finish(body)
end))
server:listen(PORT, HOST, function()
local req = http.request({
host = HOST,
port = PORT,
path = "/foo",
headers = {{"bar", "cats"}}
}, expect(function(response)
p('client:onResponse', response)
assert(response.statusCode == 200)
assert(response.httpVersion == '1.1')
server:close()
end))
req:on('error',function(...)print(...)end)
req:done()
end)
end)
end)
|
--[[
Copyright 2019 Manticore Games, Inc.
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.
--]]
-- Internal custom properties
local AS = require(script:GetCustomProperty("AS"))
local COMPONENT_ROOT = script:GetCustomProperty("ComponentRoot"):WaitForObject()
local TRIGGER = script:GetCustomProperty("Trigger"):WaitForObject()
local pickedUp = false
function OnBeginOverlap(trigger, other)
if other:IsA("Player") and not pickedUp then
pickedUp = true
Task.Wait(.3)
local resourcesLeft = COMPONENT_ROOT.serverUserData.resourcesLeft
if resourcesLeft then
--local resourceTable = {}
for resource, value in pairs(resourcesLeft) do
if resource ~= "Score" and value > 0 then
local dropValue = math.ceil(value * AS.GetDeadSloopDropPercentage(resource))
local oldAmount = other:GetResource(resource)
other:AddResource(resource, dropValue)
local newAmount = other:GetResource(resource)
Events.BroadcastToAllPlayers("ResourceAddedEvent", other, dropValue, resource, oldAmount, newAmount)
end
end
end
COMPONENT_ROOT:Destroy()
end
end
-- Initialize
TRIGGER.beginOverlapEvent:Connect(OnBeginOverlap)
TRIGGER.collision = Collision.FORCE_OFF
Task.Wait(2.7)
TRIGGER.collision = Collision.INHERIT
|
require 'uci'
local M = {}
local cursor = uci.cursor()
local modulePath = cursor.get('iot', 'common', 'modules') or '/usr/lib/lua/iot/modules/'
cursor:foreach("iot", "module", function(s)
local name = s['.name']
M[name] = {}
M[name].config = s
M[name].handler = loadfile(modulePath .. name .. '.lua')()
end)
return M
|
--.------------------------------------------------
--. Rules_37_To_36.lua (Version:1.0) --
--. Applies rules from core 37 to core 36 --
--.------------------------------------------------
--.--------------------
--. Prefix functions --
--.--------------------
module("CoreRules", package.seeall)
function rejectAll(Fields, Where)
return false
end
function replaceVersion (Fields)
if Fields.NVERSION == "'37'" then
return "'36'"
else
return Fields.NVERSION
end
end
function InitRules()
local NewTable = {
insert = {
lineFilter = rejectAll
}
,update = {
lineFilter = rejectAll
}
,delete = {
lineFilter = rejectAll
}
}
local ReplaceNVersion = {
insert = {
replaceValue = { NVERSION = replaceVersion }
}
,update = {
replaceValue = { NVERSION = replaceVersion }
}
}
local currentRules = {
-- OBJ_DEF -> Single Edit was added in Core 37
-- This is usually "Not Export" but we make sure
OBJ_DEF = {
insert = {
removeColumns = { SINGLE_EDIT = 1 }
}
,update = {
removeColumns = { SINGLE_EDIT = 1 }
}
}
-- Correct the NVersion Collumn
,EDIT_DEF = ReplaceNVersion
,EXT_DEF = ReplaceNVersion
,MENU_ITEM = ReplaceNVersion
-- New tables, cannot appear in script
,OPTRIGGERS = NewTable
,VCCHECKOUT = NewTable
,VCPLUGIN = NewTable
,VCPLUGIN = NewTable
,VCOBJDETAILS = NewTable
,VCOBJDETAILS = NewTable
,VCOBJDETAILS = NewTable
}
return currentRules
end
|
local t_man={}
moves={}
moves.up_=1
moves.dwn=2
moves.lft=3
moves.rgt=4
tetriminos={
{{0,0,1,0},--I
{0,0,1,0},
{0,0,1,0},
{0,0,1,0}},
{{0,1,0,0},--L
{0,1,0,0},
{0,1,1,0},
{0,0,0,0}},
{{0,0,1,0},--J
{0,0,1,0},
{0,1,1,0},
{0,0,0,0}},
{{0,0,0,0},--O
{0,1,1,0},
{0,1,1,0},
{0,0,0,0}},
{{0,1,0,0},--S
{0,1,1,0},
{0,0,1,0},
{0,0,0,0}},
{{0,0,1,0},--Z
{0,1,1,0},
{0,1,0,0},
{0,0,0,0}},
{{0,0,1,0},--T
{0,1,1,0},
{0,0,1,0},
{0,0,0,0}},
}
function t_man:newGame(_map,_begin_x,_begin_y,_next_b_x,_next_b_y,_grid_size,_grid_scale,_background,...)
t_man.map=_map
t_man.begin_x=_begin_x
t_man.begin_y=_begin_y
t_man.next_b_x=_next_b_x
t_man.next_b_y=_next_b_y
t_man.is_play=true
t_man.gameover=false
t_man.score = 0
t_man.grid_size=_grid_size
t_man.grid_scale=_grid_scale
t_man.background=_background
t_man.images={...}
t_man.cord_hand={x=(#_map[1]-#map[1]%2)/2-1,y=-3}
t_man.next_tetrimino=t_man:newTetrimino()
t_man.hand_tetrimino=t_man:newTetrimino()
end
function t_man:newTetrimino()
local tetrimino_model = tetriminos[love.math.random(1,#tetriminos)]
local color = love.math.random(1,#self.images)
local tetrimino={}
for row=1,4,1 do
tetrimino[row]={}
for col=1,4,1 do
tetrimino[row][col]=(tetrimino_model[row][col]~=0)and color or 0
end
end
return tetrimino
end
function t_man:updateHand()
if(not self.gameover)then
if(self.is_play)then
if(self:handCanFall())then
self.cord_hand.y=self.cord_hand.y+1
else
self:printHandOnMap()
self:resetHand()
end
end
end
end
function t_man:printHandOnMap()
for row = 4,1,-1 do
for col = 1,4,1 do
if(self.hand_tetrimino[row][col]~=0)then
if((self.cord_hand.y+row-1)<1)then self.gameover=true return end
self.map[self.cord_hand.y+row-1][self.cord_hand.x+col-1]=self.hand_tetrimino[row][col]
end
end
end
end
function t_man:handCanFall()
--returns true if finds something under
for row=4,1,-1 do
for col=1,4,1 do
if( self.hand_tetrimino[row][col]~=0 )then
if((self.cord_hand.y+row-1)==#self.map)then return false end
if((self.cord_hand.y+row)>=1 and (self.cord_hand.y+row)<=#self.map
and ((self.cord_hand.x+col-1)>=1 and (self.cord_hand.x+col-1)<=#self.map[1])
and self.map[self.cord_hand.y+row][self.cord_hand.x+col-1]~=0)then return false end
end
end
end
return true
end
function t_man:resetHand()
self:checkMap()
self.cord_hand={x=(#self.map[1]-#self.map[1]%2)/2-1,y=-3}
self.hand_tetrimino=self.next_tetrimino
self.next_tetrimino=self:newTetrimino()
end
function t_man:drawHand()
for row = 1,4,1 do
for col =1,4,1 do
if(self.hand_tetrimino[row][col]~=0)then
love.graphics.draw( self.images[self.hand_tetrimino[row][col]],
self.begin_x+self.grid_scale*self.grid_size*(self.cord_hand.x+col-2),
self.begin_y+self.grid_scale*self.grid_size*(self.cord_hand.y+row-2),
0,self.grid_scale,self.grid_scale,0,0,0,0 )
end
end
end
end
function t_man:rotateHand()
local temp_hand={}
local verify = true
for row=1,4,1 do
temp_hand[row]={}
for col=1,4,1 do
temp_hand[row][col]=self.hand_tetrimino[5-col][row]
if(temp_hand[row][col]~=0 and (self.cord_hand.x+col-1)>=1 and (self.cord_hand.y+row-1)>=1 and
(self.cord_hand.x+col-1)<=#self.map[1] and (self.cord_hand.y+row-1)<=#self.map and
self.map[self.cord_hand.y+row-1][self.cord_hand.x+col-1]~=0)then verify=false end
if(temp_hand[row][col]~=0 and
((self.cord_hand.y+row-1)>#self.map or
(self.cord_hand.x+col-1)>#self.map[1] or (self.cord_hand.x+row-1)<1)
)then verify=false end
end
end
if(verify)then self.hand_tetrimino=temp_hand end
end
function t_man:moveHand(direction)
if(direction==moves.dwn)then
while self:handCanFall() do self.cord_hand.y=self.cord_hand.y+1 end
elseif(direction==moves.lft)then
if(self:handCanMoveLeft())then self.cord_hand.x=self.cord_hand.x-1 end
elseif(direction==moves.rgt)then
if(self:handCanMoveRight())then self.cord_hand.x=self.cord_hand.x+1 end
end
end
function t_man:handCanMoveLeft()
for col = 1,4,1 do
for row = 1,4,1 do
if(self.hand_tetrimino[row][col]~=0 and (self.cord_hand.x+col-2)<1)then return false end
if(self.hand_tetrimino[row][col]~=0 and
(self.cord_hand.x+col-2)>=1 and (self.cord_hand.x+col-2)<=#self.map[1]
and (self.cord_hand.y+row-1)>=1 and (self.cord_hand.y+row-1)<=#self.map
and self.map[self.cord_hand.y+row-1][self.cord_hand.x+col-2]~=0 )then return false end
end
end
return true
end
function t_man:handCanMoveRight()
for col = 4,1,-1 do
for row = 1,4,1 do
if(self.hand_tetrimino[row][col]~=0 and (self.cord_hand.x+col)>#self.map[1])then return false end
if(self.hand_tetrimino[row][col]~=0 and
(self.cord_hand.x+col)>=1 and (self.cord_hand.x+col)<=#self.map[1]
and (self.cord_hand.y+row-1)>=1 and (self.cord_hand.y+row-1)<=#self.map
and self.map[self.cord_hand.y+row-1][self.cord_hand.x+col]~=0 )then return false end
end
end
return true
end
function t_man:checkMap()
for row = 1,#self.map,1 do
if(self:RowFilled(row))then self:updateMap(row); self.score=self.score+#self.map[1] end
end
end
function t_man:updateMap(row_begin)
for row=row_begin,1,-1 do
for col=1,#self.map[1],1 do
if((row-1)>=1)then self.map[row][col]=self.map[row-1][col] end
end
end
end
function t_man:RowFilled(row)
for col = 1,#self.map,1 do
if(self.map[row][col]==0)then return false end
end
return true
end
function t_man:drawNextTetrimino()
for row = 1,4,1 do
for col=1,4,1 do
local image
if(self.next_tetrimino[row][col]==0)then image = self.background else image = self.images[self.next_tetrimino[row][col]] end
love.graphics.draw(image,
self.next_b_x+self.grid_scale*self.grid_size*(col-1),
self.next_b_y+self.grid_scale*self.grid_size*(row-1),
0,self.grid_scale,self.grid_scale,0,0,0,0 )
end
end
end
function t_man:drawMap()
for row=1,#self.map,1 do
for col=1,#self.map[1],1 do
local image
if(self.map[row][col]==0)then image = self.background else image = self.images[self.map[row][col]]end
love.graphics.draw(image,
self.begin_x+self.grid_scale*self.grid_size*(col-1),
self.begin_y+self.grid_scale*self.grid_size*(row-1),
0,self.grid_scale,self.grid_scale,0,0,0,0 )
end
end
end
return t_man
|
local meta;
function Meta (el)
-- Copy the metadata and remove it from the document (Deckset
-- doesn't support any type of metadata header)
meta = el
return {}
end
function Div (el)
if el.identifier == 'refs' then
local blocks = {}
table.insert(blocks, pandoc.HorizontalRule())
table.insert(blocks,
pandoc.Header(1, meta['reference-section-title']
or "References"))
-- Make sure the list of references is left-aligned and uses a
-- plain bullet; the default em-dash works for most themes, but
-- can be customized using the bibliography-bullet metadata
-- option.
local bullet = pandoc.utils.stringify(meta['bibliography-bullet'] or '—')
table.insert(blocks, pandoc.RawBlock(FORMAT, '[.autoscale: true]\n'
.. '[.list: alignment(left), '
.. 'bullet-character(' .. bullet .. ')]'))
local biblist = pandoc.BulletList({})
-- A bibliography item produced by citeproc is a Div containing
-- a Para. We iterate over the Paras, take their content, and
-- rewrap it in a Plain. Directly inserting the Div or the Para
-- would make Pandoc output a "loose" list (with an empty line
-- between items), which is not formatted correctly by Deckset.
pandoc.walk_block(el, {
Para = function (para)
biblist.content:insert(
{ pandoc.Plain(para.content) }
)
end
})
table.insert(blocks, biblist)
return blocks
end
end
function Header (el)
-- This header is automatically inserted when using the
-- reference-section-title option. Remove this header, we handle
-- this ourselves above in Div().
if el.identifier == 'bibliography' then
return {}
end
end
--- Change order of processing: grab metadata first, because we need
--- it in Div() to build the title slide.
return {
{ Meta = Meta },
{ Div = Div },
{ Header = Header },
}
|
--[[
STRIPS Planner tutorial code for lecture at CEDEC2016
Copyright (c) 2016, Yohei Hase. All rights reserved.
This source code is licensed under the MIT license.
]]
--------------------------------------------------
-- utility
function deepcopy(a)
if type(a) == "table" then
local copy = {}
for key, var in next, a, nil do
copy[key] = deepcopy(var)
end
return copy
else
return a
end
end
function array_merge(a, b)
local newArray = {table.unpack(a)}
for i, var in ipairs(b) do
table.insert(newArray, var)
end
return newArray
end
function table_merge(a, b)
for key, var in next, b, nil do
if type(var) == "table" then
if a[key] == nil then
a[key] = {}
end
table_merge(a[key], var)
else
a[key] = var
end
end
return a
end
function permutation(array, n, prev)
prev = prev or {}
if n <= 0 then
return {}
end
local list = {}
for i = 1, #array do
if contains(prev, array[i]) == false then
local tmp = { table.unpack(prev) }
table.insert(tmp, array[i])
if n == 1 then
table.insert(list, tmp)
else
local newList = permutation(array, n - 1, tmp)
for i, var in ipairs(newList) do
table.insert(list, var)
end
end
end
end
return list
end
function contains(tbl, value)
for key, var in next, tbl, nil do
if var == value then
return true
end
end
return false
end
function print_plan(plan)
if plan == false or plan == nil then
print("not found")
else
for i, var in ipairs(plan) do
print(i .. ": " .. table.concat(var, ", "))
end
end
end
function print_state(s, tab)
tab = tab or ""
for key, var in next, s, nil do
if type(var) == "table" then
print(tab .. key .. ": ")
print_state(var, tab .. " ")
else
print(tab .. key .. ": " .. tostring(var))
end
end
end
--------------------------------------------------
-- STRIPS Planner
function makeAction(precondition, effect, cost)
cost = cost or 1
return { precondition = precondition, effect = effect, cost = cost }
end
function addAction(domain, name, func, paramNum, paramList)
paramNum = paramNum or 0
local action
if paramNum <= 0 then
action = func()
action.name = {name}
table.insert(domain, action)
end
local list = permutation(paramList, paramNum)
for key, var in next, list, nil do
action = func(table.unpack(var))
action.name = { name, table.unpack(var) }
table.insert(domain, action)
end
end
function getDiffState(dest, src)
local diff = {}
local count = 0
src = src or {}
for key, var in next, dest, nil do
if type(var) == "table" then
local tbl, cnt = getDiffState(var, src[key])
if cnt > 0 then
diff[key] = tbl
count = count + cnt
end
elseif var ~= src[key] then
diff[key] = var
count = count + 1
end
end
return diff, count
end
function getNeighborActions(domain, state)
local actions = {}
for key, var in next, domain, nil do
if isInState(var.effect, state) then
table.insert(actions, var)
end
end
return actions
end
function isInState(a, b)
local result = isInState_internal(a, b)
return result ~= false and result > 0
end
function isInState_internal(a, b)
b = b or {}
local sameStateCount = 0
for key, var in next, a, nil do
if type(var) == "table" then
local result = isInState_internal(var, b[key])
if result == false then
return false
end
sameStateCount = sameStateCount + result
elseif b[key] ~= nil and var ~= b[key] then
return false
elseif var == b[key] then
sameStateCount = sameStateCount + 1
end
end
return sameStateCount
end
function isSameState(a, b)
return isSameState_internal(a, b) and isSameState_internal(b, a)
end
function isSameState_internal(a, b)
for key, var in next, b, nil do
local eq = a[key] == var;
if type(var) == "table" and type(a[key]) == "table" then
eq = isSameState(a[key], b)
end
if eq == false then
return false
end
end
return true
end
function getIndex(list, node)
for i, var in ipairs(list) do
if var.act == node.act then
if isSameState(var.diff, node.diff) then
return i
end
end
end
return 0
end
function compareNode(a, b)
return a.score < b.score
end
function searchPlan(domain, state, goal)
-- Run the A* algorithm to find a valid plan
local openList = {}
local closeList = {}
-- Search from the goal state
local goalNode = { state=goal, act=nil, next=nil, cost=0 }
goalNode.diff, goalNode.diffCount = getDiffState(goalNode.state, state)
goalNode.score = goalNode.diffCount
table.insert(openList, goalNode)
while #openList > 0 do
local node = table.remove(openList, 1)
if node.diffCount == 0 then
return node
end
table.insert(closeList, node)
local neighbors = getNeighborActions(domain, node.state)
for key, var in next, neighbors, nil do
local newState = table_merge(getDiffState(node.state, var.effect), var.precondition) -- current state - action's effect + action's precondition
local diff, diffCount = getDiffState(newState, state)
local newCost = node.cost + var.cost
local newScore = newCost + diffCount
local newNode = { state=newState, act=var, next=node, cost=newCost, score=newScore, diff=diff, diffCount=diffCount }
local indexOpen = getIndex(openList, newNode)
if indexOpen > 0 then
if openList[indexOpen].score > newNode.score then
openList[indexOpen] = newNode;
end
else
local indexClose = getIndex(closeList, newNode)
if indexClose == 0 then
table.insert(openList, newNode)
end
end
end
table.sort(openList, compareNode)
end
return false
end
function strips(domain, state, goal)
local node = searchPlan(domain, state, goal)
if node == false then
return false
end
local plan = {}
while node.act ~= nil do
table.insert(plan, node.act.name)
node = node.next
end
return plan
end
|
local x = 2
|
local fn = vim.fn
local install_path = fn.stdpath 'data' .. '/site/pack/packer/start/packer.nvim'
local packer_bootstrap
if fn.empty(fn.glob(install_path)) > 0 then
packer_bootstrap = fn.system {
'git',
'clone',
'--depth',
'1',
'https://github.com/wbthomason/packer.nvim',
install_path,
}
end
return require('packer').startup {
function(use)
use { 'wbthomason/packer.nvim' }
use { 'tjdevries/astronauta.nvim' }
use { 'dstein64/nvim-scrollview' }
use {
'windwp/nvim-ts-autotag',
after = 'nvim-treesitter',
config = function()
require('nvim-ts-autotag').setup()
end,
}
use { 'p00f/nvim-ts-rainbow' }
use {
'nacro90/numb.nvim',
config = function()
require('numb').setup {}
end,
}
use {
'kosayoda/nvim-lightbulb',
config = function()
vim.cmd [[autocmd CursorHold,CursorHoldI * lua require'nvim-lightbulb'.update_lightbulb()]]
end,
}
use {
'NTBBloodbath/doom-one.nvim',
config = function()
require('doom-one').setup {
cursor_coloring = false,
terminal_colors = false,
italic_comments = false,
enable_treesitter = true,
transparent_background = false,
pumblend = {
enable = true,
transparency_amount = 20,
},
plugins_integrations = {
neorg = false,
barbar = false,
bufferline = true,
gitgutter = false,
gitsigns = true,
telescope = true,
neogit = true,
nvim_tree = false,
dashboard = true,
startify = false,
whichkey = true,
indent_blankline = true,
vim_illuminate = false,
lspsaga = true,
},
}
end,
}
use {
'neovim/nvim-lspconfig',
config = function()
local lsp = require 'config.lsp'
lsp.post()
end,
}
use {
'williamboman/nvim-lsp-installer',
after = 'nvim-lspconfig',
config = function()
local lsp_installer = require 'config.lsp_installer'
lsp_installer.setup()
end,
}
use {
'ms-jpq/chadtree',
branch = 'chad',
config = function()
local chadtree = require 'config.chadtree'
chadtree.setup()
end,
}
use {
'ms-jpq/coq_nvim',
branch = 'coq',
config = function()
local coq = require 'config.coq'
coq.setup()
end,
}
use {
'ms-jpq/coq.artifacts',
branch = 'artifacts',
after = 'coq_nvim',
}
use {
'ms-jpq/coq.thirdparty',
branch = '3p',
after = 'coq_nvim',
}
use {
'glepnir/lspsaga.nvim',
after = 'nvim-lspconfig',
config = function()
local lspsaga = require 'config.lspsaga'
lspsaga.post()
end,
}
use {
'akinsho/bufferline.nvim',
requires = 'kyazdani42/nvim-web-devicons',
config = function()
local bufferline = require 'config.bufferline'
bufferline.setup()
end,
}
use {
'nvim-lualine/lualine.nvim',
requires = { 'kyazdani42/nvim-web-devicons', opt = true },
config = function()
local lualine = require 'config.lualine'
lualine.setup()
end,
}
use {
'svermeulen/vim-cutlass',
config = function()
local cutlass = require 'config.cutlass'
cutlass.post()
end,
}
use {
'lewis6991/gitsigns.nvim',
requires = {
'nvim-lua/plenary.nvim',
},
config = function()
require('gitsigns').setup()
end,
}
use {
'lukas-reineke/indent-blankline.nvim',
config = function()
local indentline = require 'config.indentline'
indentline.post()
end,
}
use {
'windwp/nvim-autopairs',
config = function()
require('nvim-autopairs').setup {}
end,
}
use {
'nvim-treesitter/nvim-treesitter',
config = function()
local treesitter = require 'config.treesitter'
treesitter.setup()
treesitter.post()
end,
run = ':TSUpdate',
}
use {
'nvim-telescope/telescope.nvim',
requires = { { 'nvim-lua/plenary.nvim' } },
config = function()
local telescope = require 'config.telescope'
telescope.setup()
telescope.post()
end,
}
use {
'nvim-telescope/telescope-fzf-native.nvim',
config = function()
require('telescope').load_extension 'fzf'
end,
run = 'make',
}
use {
'jose-elias-alvarez/null-ls.nvim',
config = function()
local null_ls = require 'config.null-ls'
null_ls.setup()
end,
requires = { 'nvim-lua/plenary.nvim', 'neovim/nvim-lspconfig' },
}
use {
'jose-elias-alvarez/nvim-lsp-ts-utils',
require = { 'neovim/nvim-lspconfig', 'jose-elias-alvarez/null-ls.nvim' },
}
use {
'folke/which-key.nvim',
config = function()
local which_key = require 'config.which-key'
which_key.setup()
which_key.post()
end,
}
use {
'akinsho/toggleterm.nvim',
config = function()
local toggleterm = require 'config.toggleterm'
toggleterm.setup()
toggleterm.post()
end,
}
use {
'tveskag/nvim-blame-line',
config = function()
vim.cmd [[
autocmd BufEnter * EnableBlameLine
]]
end,
}
use {
'glepnir/dashboard-nvim',
config = function()
local dashboard = require 'config.dashboard-nvim'
dashboard.post()
end,
}
use {
'mfussenegger/nvim-dap',
config = function()
local dap = require 'config.dap'
dap.post()
end,
}
use {
'Pocco81/DAPInstall.nvim',
requires = 'mfussenegger/nvim-dap',
config = function()
local dap_install = require 'config.dap_install'
dap_install.setup()
end,
}
use {
'AckslD/nvim-neoclip.lua',
requires = {
{ 'tami5/sqlite.lua', module = 'sqlite' },
{ 'nvim-telescope/telescope.nvim' },
},
config = function()
local neoclip = require 'config.neoclip'
neoclip.setup()
neoclip.post()
end,
}
use {
'nvim-neorg/neorg',
config = function()
require('neorg').setup {
-- Tell Neorg what modules to load
load = {
['core.defaults'] = {}, -- Load all the default modules
['core.norg.concealer'] = {}, -- Allows for use of icons
['core.norg.dirman'] = { -- Manage your directories with Neorg
config = {
workspaces = {
my_workspace = '~/neorg',
},
},
},
},
}
end,
requires = 'nvim-lua/plenary.nvim',
}
if packer_bootstrap then
require('packer').sync()
end
end,
config = {
display = {
open_fn = function()
return require('packer.util').float { border = 'single' }
end,
},
},
}
|
PNC.Core.ActivePatrol = PNC.Core.ActivePatrol or nil
net.Receive("xyz_pnc_patrol_send", function()
PNC.Core.ActivePatrol = {}
PNC.Core.ActivePatrol.current = 1
PNC.Core.ActivePatrol.pads = net.ReadTable()
end)
net.Receive("xyz_pnc_patrol_end", function()
PNC.Core.ActivePatrol = nil
end)
net.Receive("xyz_pnc_patrol_next", function()
if not PNC.Core.ActivePatrol then return end
PNC.Core.ActivePatrol.current = PNC.Core.ActivePatrol.current + 1
XYZShit.Msg("PNC", PNC.Config.Color, "Good job, now to your next waypoint: "..PNC.Core.ActivePatrol.pads[PNC.Core.ActivePatrol.current].name)
end)
hook.Add("HUDPaint", "xyz_pnc_patrol_hud", function()
if not PNC.Core.ActivePatrol then return end
local curPad = PNC.Core.ActivePatrol.pads[PNC.Core.ActivePatrol.current]
local pos = curPad.pos:ToScreen()
surface.SetDrawColor(255, 255, 255)
surface.SetMaterial(XYZShit.Image.GetMat("waypoint_pin"))
surface.DrawTexturedRect(pos.x-20, pos.y-30, 40, 40)
XYZUI.DrawText(curPad.name, 30, pos.x, pos.y+10, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP)
end)
hook.Add("HUDPaint", "PrisonerTransportRequests", function()
if not XYZSettings.GetSetting("pnc_pt_show_marker", true) then return end
for k, v in pairs(PNC.Core.PrisonerTransportRequests) do
if IsValid(v[2]) then
local pos = v[1]:ToScreen()
draw.DrawText(v[2]:Nick() .. " has requested prisoner transport", "xyz_font_20_static", pos.x, pos.y-30, Color(255, 255, 255), TEXT_ALIGN_CENTER)
draw.DrawText("They are "..string.Comma(math.Round(v[1]:Distance(LocalPlayer():GetPos()))).."m away", "xyz_font_20_static", pos.x, pos.y, Color(255, 255, 255), TEXT_ALIGN_CENTER)
draw.NoTexture()
surface.SetDrawColor(0, 0, 0, 255)
XYZUI.DrawCircle(pos.x, pos.y-45, 20, 2)
surface.SetDrawColor(169, 169, 169, 255)
XYZUI.DrawCircle(pos.x, pos.y-45, 18, 2)
end
end
end)
|
data:extend({
{
type = "item",
name = "orbital-power-reciver",
icon = "__expanded-rocket-payloads__/graphic/ground-reciver-32.png",
icon_size = 32,
flags = {"goes-to-quickbar"},
subgroup = "buildings",
order = "mS",
place_result = "orbital-power-reciver",
stack_size = 10
},
})
|
local select, tostring, term, type = select, tostring, term, type
local queueEvent, pullEvent = os.queueEvent, os.pullEvent
local grin = grin
local insert, remove = table.insert, table.remove
local write, print = write, print
local function doWrite(write, ...)
local sum = 0
local n = select('#', ...)
for i = 1, n do
if i > 1 then
sum = sum + (write("\t") or 0)
end
sum = sum + (write(tostring(select(n, ...))) or 0)
end
return sum
end
local function doPrint(write, ...)
return doWrite(write, ...) + write("\n")
end
--- Basic stdin: just reads from terminal
function stdIn(read)
return {readLine = read, close = function() end}
end
--- Basic stdout: just writes to terminal
function stdOut()
return {write = write, writeLine = print, flush = function() end, close = function() end}
end
--- Stderr: coloured stdout. Nothing fancy
function stdErr()
local stderr = stdOut()
function stderr.write(x)
if type(x) ~= "string" then error("Expected string", 2) end
local old = term.getTextColor()
if term.isColor() then term.setTextColor(colors.red) end
write(tostring(x))
if term.isColor() then term.setTextColor(old) end
end
function stderr.writeLine(...)
local old = term.getTextColor()
if term.isColor() then term.setTextColor(colors.red) end
local n = doPrint(write, ...)
if term.isColor() then term.setTextColor(old) end
return n
end
return stderr
end
--- An output that redirects to a file
function fileOut(path, mode)
if mode == "append" then
mode = "a"
elseif mode == "write" then
mode = "w"
end
local stdout = fs.open(path, mode)
if not stdout then error("File could not be opened: " .. fname, 0) end
local oldWriteLine = stdout.writeLine
stdout.writeLine = function(...)
doWrite(stdout.write, ...)
oldWriteLine("")
return 1
end
stdout.isPiped = true
return stdout
end
--- Simply stores a list of lines
function linesOut()
local lineBuffer = ""
local lines = {}
local stdout = {isPiped = true, writeLine = print}
function stdout.write(s)
grin.expect("string", s)
local nLines = 0
local pos, len = 1, #s
while pos <= len do
local newPos = s:find("\n", pos)
if newPos then
insert(lines, lineBuffer .. s:sub(pos, newPos - 1))
lineBuffer = ""
nLines = nLines + 1
else
newPos = len
lineBuffer = lineBuffer .. s:sub(pos, newPos)
end
pos = newPos + 1
end
return nLines
end
function stdout.writeLine(...)
return doPrint(stdout.write, ...)
end
function stdout.flush() end
function stdout.close()
if lineBuffer ~= "" then
insert(lines, lineBuffer)
lineBuffer = ""
end
end
return stdout, lines
end
--- A command pipe
function pipe()
local lineBuffer = ""
local lines = {}
local CLOSE = {}
local stdout = {isPiped = true}
local next_stdin = { isPiped = true }
function stdout.write(s)
grin.expect("string", s)
local nLines = 0
local pos, len = 1, #s
while pos <= len do
local newPos = s:find("\n", pos)
if newPos then
insert(lines, lineBuffer .. s:sub(pos, newPos - 1))
lineBuffer = ""
nLines = nLines + 1
else
newPos = len
lineBuffer = lineBuffer .. s:sub(pos, newPos)
end
pos = newPos + 1
end
if nLines > 0 then
queueEvent("clamshell_pipeline_buffer_update")
end
return nLines
end
function stdout.writeLine(...)
return doPrint(stdout.write, ...)
end
function stdout.flush() end
function stdout.close()
if lineBuffer ~= "" then
insert(lines, lineBuffer)
lineBuffer = ""
end
insert(lines, CLOSE)
queueEvent("clamshell_pipeline_buffer_update")
end
function next_stdin.readLine()
while not lines[1] do
pullEvent("clamshell_pipeline_buffer_update")
end
if lines[1] == CLOSE then
return
end
return remove(lines, 1)
end
function next_stdin.close()
end
return stdout, next_stdin
end
function createPrint(stream)
return function(...)
local lines = stream.writeLine(...)
stream.flush()
return lines
end
end
|
local modpath = minetest.get_modpath("ks_ores")
dofile(modpath.."/minerals.lua")
dofile(modpath.."/nodes.lua")
dofile(modpath.."/mapgen.lua")
|
-- Author: Mikali
-- Last updated: 2017/09/01
--------------------------------------------------------------------------------
-- Random number functions.
--
-- Randomly returns either 1 or -1.
function randomSign()
if (random() > 0.5) then
return 1
else
return -1
end
end
-- Randomly returns either 1 or 0.
function randomBit()
if (random() > 0.5) then
return 1
else
return 0
end
end
-- Works just like random(), but can accept zero as an argument.
function random2(fVal1, fVal2)
if (fVal2) then
if ((fVal2 - fVal1) == 0) then
return fVal2
else
return random(fVal1, fVal2)
end
elseif (fVal1) then
if (fVal1 == 0) then
return 0
else
return random(fVal1)
end
else
return random()
end
end
-- Works just like random(), but can accept zero as an argument and always returns a float value, not an integer.
function random3(fVal1, fVal2)
if (fVal2) then
return fVal1 + random() * (fVal2 - fVal1)
elseif (fVal1) then
return random() * fVal1
else
return random()
end
end
-- For each argument, returns a random float value between 0 and the argument.
function randomSet(...)
local v = {}
for i = 1, getn(arg) do
v[i] = random3(arg[i])
end
if arg[5] then
return v[1], v[2], v[3], v[4], v[5]
elseif arg[4] then
return v[1], v[2], v[3], v[4]
elseif arg[3] then
return v[1], v[2], v[3]
elseif arg[2] then
return v[1], v[2]
elseif arg[1] then
return v[1]
end
end
-- For every two arguments, returns a random float value between the former argument and the latter argument.
function randomSet2(...)
local v = {}
for i = 2, getn(arg), 2 do
v[i/2] = random3(arg[i-1], arg[i])
end
if arg[10] then
return v[1], v[2], v[3], v[4], v[5]
elseif arg[8] then
return v[1], v[2], v[3], v[4]
elseif arg[6] then
return v[1], v[2], v[3]
elseif arg[4] then
return v[1], v[2]
elseif arg[2] then
return v[1]
end
end
-- Creates a new seed for seeded functions such as srandom().
-- Make sure seednum is negative.
function newseed(seednum)
return {seed = seednum}
end
-- rough adaptation of Knuth float generator
-- Note: seedobj must be a table with a field named `seed`;
-- this field must be negative; after the first number has
-- been generated, the seedobj table will be populated with
-- additional state needed to generate numbers; changing its
-- `seed` field to a negative number will reinitialize the
-- generator and start a new pseudorandom sequence.
-- Adapted from code at https://stackoverflow.com/questions/18689186/lua-4-0-random-number-generator
function srandom( seedobj, fVal1, fVal2 )
local B = 4000000
local ma = seedobj.ma
local seed = seedobj.seed
local mj, mk
if seed < 0 or not ma then
ma = {}
seedobj.ma = ma
mj = abs( 1618033 - abs( seed ) )
mj = mod( mj, B )
ma[55] = mj
mk = 1
for i = 1, 54 do
local ii = mod( 21 * i, 55 )
ma[ii] = mk
mk = mj - mk
if mk < 0 then
mk = mk + B
end
mj = ma[ii]
end
for k = 1, 4 do
for i = 1, 55 do
ma[i] = ma[i] - ma[ 1 + mod( i + 30, 55) ]
if ma[i] < 0 then
ma[i] = ma[i] + B
end
end
end
seedobj.inext = 0
seedobj.inextp = 31
seedobj.seed = 1
end -- if
local inext = seedobj.inext
local inextp = seedobj.inextp
inext = inext + 1
if inext == 56 then
inext = 1
end
seedobj.inext = inext
inextp = inextp + 1
if inextp == 56 then
inextp = 1
end
seedobj.inextp = inextp
mj = ma[ inext ] - ma[ inextp ]
if mj < 0 then
mj = mj + B
end
ma[ inext ] = mj
local temp_rand = mj / B
if fVal2 then
return floor( fVal1 + 0.5 + temp_rand * ( fVal2 - fVal1 ) )
elseif fVal1 then
return floor( temp_rand * fVal1 ) + 1
else
return temp_rand
end
end
-- Works like random(), except you provide your own seed as the first argument.
-- The results are that maps appear the same each time you run the game, but desyncs may possibly be avoided.
function srandom_old(seedobj, fVal1, fVal2)
seedobj[1] = mod(seedobj[1] * seedobja + seedobjc, seedobjm)
local temp_rand = seedobj[1] / (seedobjm - 1)
if (fVal2) then
return floor(fVal1 + 0.5 + temp_rand * (fVal2 - fVal1))
elseif (fVal1) then
return floor(temp_rand * fVal1) + 1
else
return temp_rand
end
end
-- Randomly returns either 1 or -1. Seeded.
function srandomSign(seedobj)
if (srandom(seedobj) > 0.5) then
return 1
else
return -1
end
end
-- Randomly returns either 1 or 0. Seeded.
function srandomBit(seedobj)
if (srandom(seedobj) > 0.5) then
return 1
else
return 0
end
end
-- Works just like random(), but can accept zero as an argument. Seeded.
function srandom2(seedobj, fVal1, fVal2)
if (fVal2) then
if ((fVal2 - fVal1) == 0) then
return fVal2
else
return srandom(seedobj, fVal1, fVal2)
end
elseif (fVal1) then
if (fVal1 == 0) then
return 0
else
return srandom(seedobj, fVal1)
end
else
return srandom(seedobj)
end
end
-- Works just like random(), but can accept zero as an argument and always returns a float value, not an integer. Seeded.
function srandom3(seedobj, fVal1, fVal2)
if (fVal2) then
return fVal1 + srandom(seedobj) * (fVal2 - fVal1)
elseif (fVal1) then
return srandom(seedobj) * fVal1
else
return srandom(seedobj)
end
end
-- For each argument, returns a random float value between 0 and the argument. Seeded.
function srandomSet(seedobj, ...)
local v = {}
for i = 1, getn(arg) do
v[i] = srandom3(seedobj, arg[i])
end
if arg[5] then
return v[1], v[2], v[3], v[4], v[5]
elseif arg[4] then
return v[1], v[2], v[3], v[4]
elseif arg[3] then
return v[1], v[2], v[3]
elseif arg[2] then
return v[1], v[2]
elseif arg[1] then
return v[1]
end
end
-- For every two arguments, returns a random float value between the former argument and the latter argument. Seeded.
function srandomSet2(seedobj, ...)
local v = {}
for i = 2, getn(arg), 2 do
v[i/2] = srandom3(seedobj, arg[i-1], arg[i])
end
if arg[10] then
return v[1], v[2], v[3], v[4], v[5]
elseif arg[8] then
return v[1], v[2], v[3], v[4]
elseif arg[6] then
return v[1], v[2], v[3]
elseif arg[4] then
return v[1], v[2]
elseif arg[2] then
return v[1]
end
end
-- Returns a vector with random components.
function vrand(tVecIn)
local tVecOut = {}
for i = 1, getn(tVecIn) do
tinsert(tVecOut, random(tVecIn[i]))
end
return tVecOut
end
-- Returns a vector with random components. Seeded.
function svrand(seedobj, tVecIn)
local tVecOut = {}
for i = 1, getn(tVecIn) do
tinsert(tVecOut, srandom(seedobj, tVecIn[i]))
end
return tVecOut
end
-- Returns a vector with random components.
function vrand2(tVecIn)
local tVecOut = {}
for i = 1, getn(tVecIn) do
tinsert(tVecOut, random2(tVecIn[i][1], tVecIn[i][2]))
end
return tVecOut
end
-- Returns a vector with random components. Seeded.
function svrand2(seedobj, tVecIn)
local tVecOut = {}
for i = 1, getn(tVecIn) do
tinsert(tVecOut, srandom2(seedobj, tVecIn[i][1], tVecIn[i][2]))
end
return tVecOut
end
-- Returns a vector with random components.
function vrand3(tVecIn)
local tVecOut = {}
for i = 1, getn(tVecIn) do
tinsert(tVecOut, random3(tVecIn[i][1], tVecIn[i][2]))
end
return tVecOut
end
-- Returns a vector with random components. Seeded.
function svrand3(seedobj, tVecIn)
local tVecOut = {}
for i = 1, getn(tVecIn) do
tinsert(tVecOut, srandom3(seedobj, tVecIn[i][1], tVecIn[i][2]))
end
return tVecOut
end
--------------------------------------------------------------------------------
-- Trigonometric functions.
--
-- Returns the hyperbolic cosine of an angle.
function cosh(fAng)
return (exp(fAng) + exp(-fAng))/2
end
-- Returns the hyperbolic sine of an angle.
function sinh(fAng)
return (exp(fAng) - exp(-fAng))/2
end
-- Returns the hyperbolic tangent of an angle.
function tanh(fAng)
return (exp(fAng) - exp(-fAng))/(exp(fAng) + exp(-fAng))
end
-- Returns the hyperbolic cosecant of an angle.
function csch(fAng)
return 1/sinh(fAng)
end
-- Returns the hyperbolic secant of an angle.
function sech(fAng)
return 1/cosh(fAng)
end
-- Returns the hyperbolic cotangent of an angle.
function coth(fAng)
return 1/tanh(fAng)
end
-- Returns the cosecant of an angle.
function csc(fAng)
return 1/sin(fAng)
end
-- Returns the secant of an angle.
function sec(fAng)
return 1/cos(fAng)
end
-- Returns the cotangent of an angle.
function cot(fAng)
return 1/tan(fAng)
end
-- Returns the exsecant of an angle.
function exsec(fAng)
return sec(fAng) - 1
end
-- Returns the coexsecant of an angle.
function coexsec(fAng)
return csc(fAng) - 1
end
-- Returns the versesine of an angle.
function vers(fAng)
return 1 - cos(fAng)
end
-- Returns the coversesine of an angle.
function covers(fAng)
return 1 - sin(fAng)
end
-- Returns the half-versesine of an angle.
function hav(fAng)
return vers(fAng)/2
end
--------------------------------------------------------------------------------
-- Other mathematical functions.
--
-- Rounds a number to the nearest integer.
function round(fVal)
return floor(fVal + 0.5)
end
-- Converts a decimal value into a fraction.
function decimal_to_fraction(fNumber)
local fullNumber = floor(fNumber)
local iNumerator = fNumber - fullNumber
local iDenominator = 1
while (iNumerator ~= floor(iNumerator)) do
iNumerator = iNumerator * 10
iDenominator = iDenominator * 10
end
iNumerator = floor(iNumerator)
for i = 2, floor(sqrt(iNumerator)) do
while ((mod(iNumerator, i) == 0) and (mod(iDenominator, i) == 0)) do
iNumerator = iNumerator / i
iDenominator = iDenominator / i
end
end
iNumerator = iNumerator + fullNumber * iDenominator
-- print(fNumber .. " = " .. iNumerator .. "/" .. iDenominator)
return iNumerator, iDenominator
end
--------------------------------------------------------------------------------
-- Vector functions.
--
-- Returns true if the length of the vector is zero.
function viszero(vVal)
if (vVal[1] + vVal[2] + vVal[3] == 0) then
return 1
end
return 0
end
-- Rounds a vector's components to the nearest integer.
function vround(vVal)
return {floor(vVal[1] + 0.5), floor(vVal[2] + 0.5), floor(vVal[3] + 0.5)}
end
-- Returns the normalized form of a vector.
function vnormalize(tVec)
return vdivide(tVec, vlength(tVec))
end
-- Returns the length of a vector.
function vlength(tVec)
return sqrt(vsum(vpower(tVec, 2)))
end
-- Returns the distance between two vectors.
function vdistance(tVec1, tVec2)
return vlength(vsubtractV(tVec2, tVec1))
end
-- Returns the dot product of two vectors.
function vdot(tVec1, tVec2)
return vsum(vmultiplyV(tVec1, tVec2))
end
-- Returns the angle between two vectors.
function vangle(tVec1, tVec2)
return acos(vdot(vnormalize(tVec1), vnormalize(tVec2)))
end
-- Returns the cross product of two vectors as a new vector.
function vcross(tVec1, tVec2)
return
{
tVec1[2] * tVec2[3] - tVec1[3] * tVec2[2],
tVec1[3] * tVec2[1] - tVec1[1] * tVec2[3],
tVec1[1] * tVec2[2] - tVec1[2] * tVec2[1],
}
end
-- tests whether two vectors are equal
function veq(tVec1, tVec2)
if (tVec1[1] == tVec2[1]) and (tVec1[2] == tVec2[2]) and (tVec1[3] == tVec2[3]) then
return 1
else
return 0
end
end
-- returns the midpoint of two points as a new point
function vmidpoint(tVec1, tVec2)
return
{
(tVec1[1] + tVec2[1]) / 2,
(tVec1[2] + tVec2[2]) / 2,
(tVec1[3] + tVec2[3]) / 2,
}
end
-- Adds an amount to each vector component, then returns the resulting vector.
function vadd(tVec, fVal)
local tmpVec = {}
for i, tTab in tVec do
tmpVec[i] = tVec[i] + fVal
end
return tmpVec
end
-- Adds the components of the second vector to the components of the first vector, then returns the resulting vector.
function vaddV(tVec1, tVec2)
local tmpVec = {}
for i, tTab in tVec2 do
tmpVec[i] = tVec1[i] + tTab
end
return tmpVec
end
-- Subtracts an amount from each vector component, then returns the resulting vector.
function vsubtract(tVec, fVal)
local tmpVec = {}
for i, tTab in tVec do
tmpVec[i] = tVec[i] - fVal
end
return tmpVec
end
-- Subtracts the components of the second vector from the components of the first vector, then returns the resulting vector.
function vsubtractV(tVec1, tVec2)
local tmpVec = {}
for i, tTab in tVec2 do
tmpVec[i] = tVec1[i] - tTab
end
return tmpVec
end
-- Multiplies each vector component by some amount, then returns the resulting vector.
function vmultiply(tVec, fVal)
local tmpVec = {}
for i, tTab in tVec do
tmpVec[i] = tTab * fVal
end
return tmpVec
end
-- Multiplies the components of the first vector by the components of the second vector, then returns the resulting vector.
function vmultiplyV(tVec1, tVec2)
local tmpVec = {}
for i, tTab in tVec2 do
tmpVec[i] = tVec1[i] * tTab
end
return tmpVec
end
-- Divides each vector component by some amount, then returns the resulting vector.
function vdivide(tVec, fVal)
local tmpVec = {}
for i, tTab in tVec do
tmpVec[i] = tTab/fVal
end
return tmpVec
end
-- Divides the components of the first vector by the components of the second vector, then returns the resulting vector.
function vdivideV(tVec1, tVec2)
local tmpVec = {}
for i, tTab in tVec2 do
tmpVec[i] = tVec1[i]/tTab
end
return tmpVec
end
-- Raises each vector component to the some power, then returns the new vector.
function vpower(tVec, fVal)
local tmpVec = {}
for i, tTab in tVec do
tmpVec[i] = tTab^fVal
end
return tmpVec
end
-- Raises the components of the first vector to the power specified by the components the second vector, then returns the new vector.
function vpowerV(tVec1, tVec2)
local tmpVec = {}
for i, tTab in tVec2 do
tmpVec[i] = tVec1[i]^tTab
end
return tmpVec
end
-- Returns the sum of all the vector's components.
function vsum(tVec1)
local tmpVal = 0
for i, tTab in tVec1 do
tmpVal = tmpVal + tTab
end
return tmpVal
end
-- Returns a vector converted into a string.
function vstr(tVec)
local tmpStr = "{"
for i, tTab in tVec do
tmpStr = tmpStr .. tTab .. ", "
end
tmpStr = tmpStr .. "}"
return tmpStr
end
function vfloor(tVec)
local tmpVec = {}
for i, tTab in tVec do
tmpVec[i] = floor(tVec[i])
end
return tmpVec
end
-- Rotates a vector around the origin by the specified Euler angles, then returns the resulting vector.
-- Rotates around the Z-axis first, followed by the X-axis and the Y-axis.
function vrotate(tVec, tAng)
tVec =
{
tVec[1] * cos(tAng[3]) - tVec[2] * sin(tAng[3]),
tVec[1] * sin(tAng[3]) + tVec[2] * cos(tAng[3]),
tVec[3],
}
tVec =
{
tVec[1],
tVec[2] * cos(tAng[1]) - tVec[3] * sin(tAng[1]),
tVec[2] * sin(tAng[1]) + tVec[3] * cos(tAng[1]),
}
tVec =
{
tVec[1] * cos(tAng[2]) + tVec[3] * sin(tAng[2]),
tVec[2],
-1 * tVec[1] * sin(tAng[2]) + tVec[3] * cos(tAng[2]),
}
return tVec
end
-- Returns an array containing the vector's Euler angles, relative to the vertical Z-axis.
-- To reproduce the original vector, rotate a point located on the Z-axis by the returned angles using vrotate.
-- Any rotations around the Z axis will be ignored.
function vanglesXY(tVec2)
local fSgnX, fSgnY, tPrjB1 = 1, 1, vnormalize({tVec2[1], 0, tVec2[3],})
if (tPrjB1[1] ~= 0) then
fSgnX = tPrjB1[1]/abs(tPrjB1[1]) * -1
end
tPrjB1[3] = max(min(tPrjB1[3],1),-1)
local fAngY = acos(tPrjB1[3]) * fSgnX
local tPrjB2 = vnormalize(vrotate(tVec2, {0, fAngY, 0,}))
if (tPrjB2[2] ~= 0) then
fSgnY = tPrjB2[2]/abs(tPrjB2[2])
end
tPrjB2[3] = max(min(tPrjB2[3],1),-1)
local fAngX = acos(tPrjB2[3]) * fSgnY
fAngX = mod(fAngX * -1, 360)
fAngY = mod(fAngY * -1, 360)
if (fAngX < 0) then
fAngX = fAngX + 360
end
if (fAngY < 0) then
fAngY = fAngY + 360
end
return {fAngX, fAngY, 0,}
end
-- Rotates the first vector around the second vector by some amount, then returns the resulting vector.
function vaxis_rotate(tVec1, tVec2, fAngZ)
local tAng = vanglesXY(tVec2)
return vrotate(vrotate(vrotate(vrotate(tVec1, {0, tAng[2], 0,}), {tAng[1], 0, 0,}), {0, 0, fAngZ,}), vmultiply(tAng, -1))
end
--------------------------------------------------------------------------------
-- Table manipulation functions.
--
-- Returns the length of a table. Useful where the 'getn' function is normally unavailable.
if not getn then
function getn(tTable)
local nCount = 0
for i, iCount in tTable do
-- be careful in case the table has an "n" parameter that someone added for other reasons than counting
if i ~= "n" then
nCount = nCount + 1
end
end
return nCount
end
end
-- Inserts an item into a table. Useful where the 'tinsert' function is normally unavailable.
-- The standard Lua 'tinsert' function may also add an "n" parameter to count.
if not tinsert then
function tinsert(tTable, Arg1, Arg2)
if (Arg2) then
local TempTable = {}
for i = Arg1, getn(tTable) do
TempTable[i + 1] = tTable[i]
end
for i = Arg1, getn(tTable) do
tTable[i + 1] = TempTable[i + 1]
end
tTable[Arg1] = Arg2
else
tTable[getn(tTable) + 1] = Arg1
end
end
end
-- Compares two tables and returns true if they're equal and false if they're not.
function tcomp(tTable1, tTable2)
local same = 1
if (getn(tTable1) ~= getn(tTable2)) then
same = 0
else
for i, k in tTable1 do
if (type(tTable1[i]) == "table") and (type(tTable2[i]) == "table") then
same = tcomp(tTable1[i], tTable2[i])
if (same == 0) then
break
end
elseif (tTable1[i] ~= tTable2[i]) then
same = 0
break
end
end
end
return same
end
-- Creates a copy of the input table.
-- Adapted from http://lua-users.org/wiki/CopyTable
function tcopy(orig)
local orig_type = type(orig)
local copy
-- a table
if (orig_type == "table") then
copy = {}
for orig_key, orig_value in orig do
copy[orig_key] = tcopy(orig_value)
end
-- number, string, boolean, etc
else
copy = orig
end
return copy
end
-- remove the first item in the table
function ttrim(tTable)
local temp_table = {}
for i = 2, getn(tTable) do
local temp_length = getn(temp_table)
temp_table[temp_length + 1] = tTable[i]
end
return temp_table
end
--------------------------------------------------------------------------------
-- Time functions
--
function disp_time(total_seconds, show_seconds)
-- local show_seconds = 1
local time_days = floor(total_seconds / 86400)
local time_hours = floor(mod(total_seconds, 86400) / 3600)
local time_minutes = floor(mod(total_seconds, 3600) / 60)
local time_seconds = floor(mod(total_seconds, 60))
if (time_hours < 10) then
time_hours = "0" .. time_hours
end
if (time_minutes < 10) then
time_minutes = "0" .. time_minutes
end
if (time_seconds < 10) then
time_seconds = "0" .. time_seconds
end
if (show_seconds == 1) then
return time_days .. ":" .. time_hours .. ":" .. time_minutes .. ":" .. time_seconds
else
return time_days .. ":" .. time_hours .. ":" .. time_minutes
end
end
--------------------------------------------------------------------------------
-- String manipulation functions
if not strrep then
function strrep(in_string, num_repeat)
local out_string = ""
for i = 1, num_repeat do
out_string = out_string .. in_string
end
return out_string
end
end
--------------------------------------------------------------------------------
-- Miscellaneous functions
function debug_print(sMessage)
if (debug_text == true) then
print(sMessage)
end
end
-- Adapted from https://www.geometrictools.com/Documentation/EulerAngles.pdf, section 2.6
function MatrixToEuler(in_matrix)
local r00 = in_matrix[9]
local r01 = in_matrix[8]
local r02 = in_matrix[7]
local r10 = in_matrix[6]
local r11 = in_matrix[5]
local r12 = in_matrix[4]
local r20 = in_matrix[3]
local r21 = in_matrix[2]
local r22 = in_matrix[1]
local angleX = 0
local angleY = 0
local angleZ = 0
if (r20 < 1) then
if (r20 > -1) then
angleX = atan2(r10, r00)
angleY = asin(-r20)
angleZ = atan2(r21, r22)
else
angleX = -atan2(-r12, r11)
angleY = 90
angleZ = 0
end
else
angleX = atan2(-r12, r11)
angleY = -90
angleZ = 0
end
if (angleX < 0) then
angleX = angleX + 360
end
if (angleY < 0) then
angleY = angleY + 360
end
if (angleZ < 0) then
angleZ = angleZ + 360
end
return {angleX, angleY, angleZ}
end
-- Adapted from https://www.geometrictools.com/Documentation/EulerAngles.pdf, section 2.6
function EulerToMatrix(in_euler)
local angleX = in_euler[1]
local angleY = in_euler[2]
local angleZ = in_euler[3]
local c1 = cos(angleX)
local c2 = cos(angleY)
local c3 = cos(angleZ)
local s1 = sin(angleX)
local s2 = sin(angleY)
local s3 = sin(angleZ)
local r00 = c1 * c2
local r01 = c1 * s2 * s3 - c3 * s1
local r02 = s1 * s3 + c1 * c3 * s2
local r10 = c2 * s1
local r11 = c1 * c3 + s1 * s2 * s3
local r12 = c3 * s1 * s2 - c1 * s3
local r20 = -s2
local r21 = c2 * s3
local r22 = c2 * c3
return {r22,r21,r20,r12,r11,r10,r02,r01,r00}
end
--------------------------------------------------------------------------------
-- Notes:
-- With a ship sitting at the origin and pointing in the positive Z direction toward the 180 mark on the level disc:
-- * The X axis points to the left. The Y axis points upward. The Z axis points forward.
-- * Rotating the ship around the X axis by 90 degrees results in the ship facing downward.
-- * Rotating the ship around the Y axis by 90 degrees results in the ship facing to the left along the positive X axis.
-- * Rotating the ship around the Z axis by 90 degrees results in the ship laying on its right side still facing the positive Z direction.
-- * When rotating around the Y angle and the Z angle, the ship is rotated around the Y angle before the Z angle.
-- * When rotating around the X angle and the Y angle, the ship is rotated around the X angle before the Y angle.
-- * When rotating around the X angle and the Z angle, the ship is rotated around the X angle before the Z angle.
-- Using vrotate and a ship initially positioned at 10000 meters along the Z axis:
-- * Rotating the ship in space around the X axis results in the ship ending up along the negative Y axis.
-- * Rotating the ship in space around the Y axis results in the ship ending up along the positive X axis.
-- * Rotating the ship in space around the Z axis results in the ship remaining along the positive Z axis.
-- * When rotating around the Y angle and the Z angle, the ship is rotated around the Z angle before the Y angle.
-- * When rotating around the X angle and the Y angle, the ship is rotated around the X angle before the Y angle.
-- * When rotating around the X angle and the Z angle, the ship is rotated around the Z angle before the X angle.
|
local AddonName, AddonTable = ...
AddonTable.arcatraz = {
-- Multiple Bosses
28384,
127154,
-- Zereketh the Unbound
28415,
28374,
28373,
28396,
28375,
-- Dalliah the Doomsayer
28416,
28392,
28386,
28387,
28414,
28390,
-- Wrath-Scryer Soccothrates
28393,
28397,
28413,
28403,
28391,
28398,
28394,
30582,
-- Harbinger Skyriss
29360,
28412,
28419,
28205,
28231,
29252,
29241,
29248,
28406,
28407,
28418,
127150,
--- Quest Rewards
31747,
}
|
return {
init_effect = "",
name = "我方苍龙META 剑气领域-仅演出无实际效果",
time = 0,
color = "yellow",
picture = "",
desc = "",
stack = 1,
id = 370,
icon = 370,
last_effect = "",
effect_list = {}
}
|
local sound
local lastGear = nil
local lastRPM = nil
local downgrading = false
local downgradingRPM = {0,0}
local downgradingTime = 2000
local downgradingProgress = 0
local start = 0
local worked = 0
local enabled = true
local vehiclesSounds = {
-- [ид модели] = {engine = "звук мотора", blowoff = "звук blowoff", gear = "звук понижения передачи", downTime = как быстро опускается до 0 оборотов мотор в милисекундах, coeff = коэффициент скорости звука мотора },
[535] = {engine = "gtr2000.wav",gear = "gear.wav", downTime = 2000, coeff = 10000, volume = 0.2},
[475] = {engine = "gtr2000.wav",gear = "gear.wav", downTime = 2000, coeff = 10000, volume = 0.2},
[589] = {engine = "ae86.wav",gear = "gear.wav", downTime = 2000, coeff = 10000, volume = 0.2},
[565] = {engine = "civic.wav",gear = "gear.wav",blowoff = "BlowoffCivic.wav", downTime = 2000, coeff = 10000, volume = 0.2},
[602] = {engine = "180sx.wav",gear = "gear.wav",blowoff = "BlowoffCivic.wav", downTime = 2000, coeff = 10000, volume = 0.2},
[401] = {engine = "180sx.wav",gear = "gear.wav",blowoff = "BlowoffCivic.wav", downTime = 2000, coeff = 10000, volume = 0.2},
[576] = {engine = "180sx.wav",gear = "gear.wav",blowoff = "BlowoffCivic.wav", downTime = 2000, coeff = 10000, volume = 0.2},
[550] = {engine = "rx8.wav",gear = "gear.wav",blowoff = "BlowoffCivic.wav", downTime = 2000, coeff = 10000, volume = 0.2},
[540] = {engine = "m5.wav",gear = "gear.wav", downTime = 2000, coeff = 10000, volume = 0.2},
[436] = {engine = "m5.wav",gear = "gear.wav", downTime = 2000, coeff = 10000, volume = 0.2},
[529] = {engine = "E92.wav",gear = "gear.wav", downTime = 2000, coeff = 10000, volume = 0.2},
[410] = {engine = "E92.wav",gear = "gear.wav", downTime = 2000, coeff = 10000, volume = 0.2},
[562] = {engine = "gtr34.wav",gear = "gear.wav", downTime = 2000, coeff = 10000, volume = 0.2},
[558] = {engine = "gtr35.wav",gear = "gear.wav", downTime = 2000, coeff = 10000, volume = 0.2},
}
local carSounds = {}
local checkVehicles = {}
local lastVehicle
function startSound(vehicle)
if not isElement(vehicle) then return true end
local model = getElementModel ( vehicle )
if not vehiclesSounds[model] then
vehiclesSounds[model] = vehiclesSounds[535]
end
if vehiclesSounds[model] then
if not isElement (carSounds[vehicle]) then
local x,y,z = getElementPosition ( vehicle )
local sound = playSound3D ( vehiclesSounds[model].engine, x, y, z, true )
attachElements ( sound, vehicle )
local rpm = getVehicleRPM(vehicle)
setElementData (vehicle, "carsound:lastGear", getVehicleCurrentGear(vehicle), false)
setElementData (vehicle, "carsound:lastRPM", rpm, false)
--setElementData (vehicle, "carsound:sound", sound, false)
carSounds[vehicle] = sound
if vehiclesSounds[model].volume then
setSoundVolume ( sound, vehiclesSounds[model].volume )
end
--setSoundMaxDistance ( sound, vehiclesSounds[model].maxDistance )
setSoundSpeed ( sound, rpm/vehiclesSounds[model].coeff )
end
end
end
addEventHandler( "onClientElementStreamIn", getRootElement( ),
function ( )
if not enabled then return true end
if getElementType( source ) == "vehicle" then
if lastVehicle and lastVehicle == source then
startSound(source)
end
end
end
)
addEventHandler( "onClientElementStreamOut", getRootElement( ),
function ( )
if not enabled then return true end
if getElementType( source ) == "vehicle" then
stopVehicleSound(source)
end
end
)
function stopVehicleSound(vehicle)
local sound = carSounds[vehicle]
if isElement ( sound ) then
destroyElement ( sound )
end
carSounds[vehicle] = nil
if isElement ( vehicle ) then
local downgradingTimers = getElementData ( source, "carsound:downgradingTimers" ) or {}
if isTimer ( downgradingTimers[1] ) then killTimer ( downgradingTimers[1] ) end
if isTimer ( downgradingTimers[2] ) then killTimer ( downgradingTimers[2] ) end
end
end
function checkVehicles(vehicle)
if not lastVehicle then
startSound(vehicle)
lastVehicle = vehicle
return true
end
if lastVehicle and lastVehicle ~= vehicle then
stopVehicleSound(lastVehicle)
lastVehicle = vehicle
startSound(vehicle)
end
end
addEventHandler("onClientPlayerVehicleEnter",localPlayer,checkVehicles)
addEventHandler("onClientElementDestroy", getRootElement(), function ()
if getElementType(source) == "vehicle" then
local sound = carSounds[source]
if isElement ( sound ) then
destroyElement ( sound )
end
carSounds[source] = nil
local downgradingTimers = getElementData ( source, "carsound:downgradingTimers" ) or {}
if isTimer ( downgradingTimers[1] ) then killTimer ( downgradingTimers[1] ) end
if isTimer ( downgradingTimers[2] ) then killTimer ( downgradingTimers[2] ) end
end
end)
function disableSounds()
setWorldSoundEnabled ( 40, false )
setWorldSoundEnabled ( 12, false )
addEventHandler("onClientRender", getRootElement(), checkVehiclesRPM )
-- for i, vehicle in ipairs ( getElementsByType ( "vehicle", root, true ) ) do
-- startSound(vehicle)
-- end
end
addEventHandler("onClientResourceStart",getResourceRootElement(),disableSounds)
function turnSoundsOnOff (state)
if state then
enabled = true
setWorldSoundEnabled ( 40, false )
setWorldSoundEnabled ( 12, false )
addEventHandler("onClientRender", getRootElement(), checkVehiclesRPM )
for i, vehicle in ipairs ( getElementsByType ( "vehicle", root, true ) ) do
startSound(vehicle)
end
else
enabled = false
setWorldSoundEnabled ( 40, true )
setWorldSoundEnabled ( 12, true )
removeEventHandler("onClientRender", getRootElement(), checkVehiclesRPM )
for i, vehicle in ipairs ( getElementsByType ( "vehicle", root, true ) ) do
local sound = carSounds[vehicle]
if isElement ( sound ) then
destroyElement ( sound )
end
carSounds[vehicle] = nil
local downgradingTimers = getElementData ( vehicle, "carsound:downgradingTimers" ) or {}
if isTimer ( downgradingTimers[1] ) then killTimer ( downgradingTimers[1] ) end
if isTimer ( downgradingTimers[2] ) then killTimer ( downgradingTimers[2] ) end
end
end
end
function test(text,vehicle)
if getPedOccupiedVehicle ( localPlayer ) and getPedOccupiedVehicle ( localPlayer ) == vehicle then
outputChatBox(text)
end
end
local dot = dxCreateTexture(1,1)
local white = tocolor(255,255,255,255)
function dxDrawRectangle3D(x,y,z,w,h,c,r,...)
local lx, ly, lz = x+w, y+h, (z+tonumber(r or 0)) or z
return dxDrawMaterialLine3D(x,y,z, lx, ly, lz, dot, h, c or white, ...)
end
function checkVehiclesRPM()
local x,y,z = getElementPosition ( localPlayer )
--for vehicle, sound in pairs ( carSounds ) do
if lastVehicle then
if not isElement ( lastVehicle ) then
stopVehicleSound(lastVehicle)
return true
end
local sound = carSounds[lastVehicle]
if isElement(sound) then
local tx, ty, tz = getElementPosition ( lastVehicle )
if getDistanceBetweenPoints3D (x,y,z,tx,ty,tz) < 40 then
local rpm = getVehicleRPM(lastVehicle)
if not getVehicleEngineState(lastVehicle) then
--if not isSoundPaused ( sound ) then
setSoundPaused ( sound, true )
--end
else
if rpm == 0 then
rpm = math.random(300,600)
end
if isSoundPaused ( sound ) then
setSoundPaused ( sound, false )
end
local model = getElementModel ( lastVehicle )
local lastGear = getElementData ( lastVehicle, "carsound:lastGear" ) or 1
local lastRPM = getElementData ( lastVehicle, "carsound:lastRPM" ) or 0
local curGear = getVehicleCurrentGear(lastVehicle)
if lastGear > curGear then
playGearSound(lastVehicle)
end
local downgradingTimers = getElementData ( lastVehicle, "carsound:downgradingTimers" ) or {}
if lastGear > curGear and not downgrading then
if isTimer ( downgradingTimers[1] ) then killTimer ( downgradingTimers[1] ) end
if isTimer ( downgradingTimers[2] ) then killTimer ( downgradingTimers[2] ) end
downgrading = true
downgradingProgress = 0
worked = 0
start = getTickCount()
downgradingRPM = {lastRPM,500}
downgradingTimers[1] = setTimer (function() downgradingProgress = downgradingProgress+(1/(vehiclesSounds[model].downTime/50)) worked = worked+1 end, 50, vehiclesSounds[model].downTime/50)
--downgradingTimers[2] = setTimer (function() downgrading = false end, vehiclesSounds[model].downTime, 1)
setElementData ( lastVehicle, "carsound:downgradingTimers", downgradingTimers, false )
else
if vehiclesSounds[model].blowoff and curGear > lastGear then
playBlowoffSound(lastVehicle)
end
if downgrading then
if ( lastRPM < rpm and ( lastGear <= curGear ) ) or lastGear < curGear then
if isTimer ( downgradingTimers[1] ) then killTimer ( downgradingTimers[1] ) end
if isTimer ( downgradingTimers[2] ) then killTimer ( downgradingTimers[2] ) end
downgrading = false
end
local temprpm = interpolateBetween ( downgradingRPM[1], 0, 0, downgradingRPM[2], 0, 0, downgradingProgress, "Linear" )
setSoundSpeed ( sound, temprpm/vehiclesSounds[model].coeff )
else
setSoundSpeed ( sound, rpm/vehiclesSounds[model].coeff )
end
end
setElementData ( lastVehicle, "carsound:lastGear", curGear, false )
setElementData ( lastVehicle, "carsound:lastRPM", rpm, false )
end
end
end
end
end
--setTimer(checkVehiclesRPM,500,0)
--addEventHandler("onClientPreRender", getRootElement(), checkVehiclesRPM )
--addEventHandler("onClientResourceStart", getResourceRootElement(),startSound)
function playBlowoffSound(vehicle)
if isElement ( vehicle ) then
local x,y,z = getElementPosition ( vehicle )
local px,py,pz = getElementPosition ( localPlayer )
if getDistanceBetweenPoints3D ( x,y,z, px,py,pz ) < 10 then
local model = getElementModel ( vehicle )
local blowoffSound = playSound3D ( vehiclesSounds[model].blowoff, x, y, z, false )
attachElements ( blowoffSound, vehicle )
end
end
end
function playGearSound(vehicle)
if isElement ( vehicle ) then
local x,y,z = getElementPosition ( vehicle )
local px,py,pz = getElementPosition ( localPlayer )
if getDistanceBetweenPoints3D ( x,y,z, px,py,pz ) < 10 then
local model = getElementModel ( vehicle )
local gearSound = playSound3D ( vehiclesSounds[model].gear, x, y, z, false )
setSoundVolume(gearSound, 2)
attachElements ( gearSound, vehicle )
end
end
end
function getVehicleRPM(vehicle)
if isElement(vehicle) then
local vehicleRPM = getElementData ( vehicle, "rpm" ) or 0
if (isVehicleOnGround(vehicle)) then
if (getVehicleEngineState(vehicle) == true) then
if(getVehicleCurrentGear(vehicle) > 0) then
vehicleRPM = math.floor(((getVehicleSpeed(vehicle)/getVehicleCurrentGear(vehicle))*180) + 0.5)
if (vehicleRPM < 650) then
vehicleRPM = math.random(650, 750)
elseif (vehicleRPM >= 9800) then
vehicleRPM = 9800
end
else
vehicleRPM = math.floor(((getVehicleSpeed(vehicle)/1)*180) + 0.5)
if (vehicleRPM < 650) then
vehicleRPM = math.random(650, 750)
elseif (vehicleRPM >= 9800) then
vehicleRPM = 9800
end
end
else
vehicleRPM = 0
end
else
if (getVehicleEngineState(vehicle) == true) then
vehicleRPM = vehicleRPM - 150
if (vehicleRPM < 650) then
vehicleRPM = math.random(650, 750)
elseif (vehicleRPM >= 9800) then
vehicleRPM = 9800
end
else
vehicleRPM = 0
end
end
setElementData ( vehicle, "rpm", vehicleRPM, false )
return tonumber(vehicleRPM)
else
return 0
end
end
function getVehicleSpeed(vehicle)
if isElement(vehicle) then
local vx, vy, vz = getElementVelocity(vehicle)
if (vx) and (vy)and (vz) then
return math.sqrt(vx^2 + vy^2 + vz^2) * 180 -- km/h
else
return 0
end
else
return 0
end
end
addEventHandler( "onClientResourceStop", getResourceRootElement( ),
function ( stoppedRes )
for i, v in ipairs ( getElementsByType("sound",getResourceRootElement()) ) do
destroyElement(v)
end
end
);
|
---@type string
local Name = ...
---@type Addon
local Addon = select(2, ...)
local Comm, Item, Roll, Session, Unit, Util = Addon.Comm, Addon.Item, Addon.Roll, Addon.Session, Addon.Unit, Addon.Util
---@class PLH : Module
local Self = Addon.PLH
Self.NAME = "PersonalLootHelper"
Self.VERSION = "2.08"
Self.PREFIX = "PLH"
Self.BID_NEED = "MAIN SPEC"
Self.BID_GREED = "OFF SPEC"
Self.BID_DISENCHANT = "SHARD"
Self.ACTION_CHECK = "IDENTIFY_USERS"
Self.ACTION_VERSION = "VERSION"
Self.ACTION_KEEP = "KEEP"
Self.ACTION_TRADE = "TRADE"
Self.ACTION_REQUEST = "REQUEST"
Self.ACTION_OFFER = "OFFER"
Self.initialized = false
-------------------------------------------------------
-- Comm --
-------------------------------------------------------
-- Send a PLH message
---@param action string
---@param roll Roll|string
---@param param any
function Self.Send(action, roll, param)
if Self:IsEnabled() then
local msg = not roll and ("%s~ ~%s"):format(action, param)
or type(roll) == "string" and ("%s~ ~%s~%s"):format(action, roll, param)
or param and ("%s~%d~%s~%s"):format(action, roll.item.id, Unit.FullName(roll.item.owner), param)
or ("%s~%d~%s"):format(action, roll.item.id, Unit.FullName(roll.item.owner))
Comm.Send(Self.PREFIX, msg)
end
end
-- Process incoming PLH message
Comm.Listen(Self.PREFIX, function (event, msg, channel, _, unit)
if not Self:IsEnabled() or Addon.versions[unit] then return end
local action, itemId, owner, param = msg:match('^([^~]+)~([^~]+)~([^~]+)~?([^~]*)$')
itemId = tonumber(itemId)
owner = Unit(owner)
local fromOwner = owner == unit
-- Check: Version check
if action == Self.ACTION_CHECK then
Self.Send(Self.ACTION_VERSION, Unit.FullName("player"), Self.VERSION)
-- Version: Answer to version check
elseif action == Self.ACTION_VERSION then
Addon:SetCompAddonUser(unit, Self.NAME, param)
else
local item = Item.IsLink(param) and param or itemId
local roll = Roll.Find(nil, nil, item, nil, owner, Roll.STATUS_RUNNING) or Roll.Find(nil, nil, item, nil, owner)
-- Trade: The owner offers the item up for requests
if action == Self.ACTION_TRADE and not roll and fromOwner and Item.IsLink(param) then
Addon:Debug("PLH.Event.Trade", itemId, owner, param, msg)
Roll.Add(param, owner):Start()
elseif roll and (roll.isOwner or not roll.ownerId) then
-- Keep: The owner wants to keep the item
if action == Self.ACTION_KEEP and fromOwner then
roll:End(owner)
-- Request: The sender bids on an item
elseif action == Self.ACTION_REQUEST then
local bid = Util.Select(param, Self.BID_NEED, Roll.BID_NEED, Self.BID_DISENCHANT, Roll.BID_DISENCHANT, Roll.BID_GREED)
roll:Bid(bid, unit)
-- Offer: The owner has picked a winner
elseif action == Self.ACTION_OFFER and fromOwner then
roll:End(param)
end
end
end
end)
-------------------------------------------------------
-- Events/Hooks --
-------------------------------------------------------
function Self:ShouldBeEnabled()
return not IsAddOnLoaded(Self.NAME)
and Addon:IsActive()
end
function Self:OnInitialize()
Self:CheckState()
Self:RegisterMessage(Addon.EVENT_ACTIVE_CHANGE, Self.CheckState)
end
function Self:OnEnable()
-- Register events
Self:RegisterMessage(Roll.EVENT_START, "ROLL_START")
Self:RegisterMessage(Roll.EVENT_BID, "ROLL_BID")
Self:RegisterMessage(Roll.EVENT_AWARD, "ROLL_AWARD")
-- Send version check
Self.Send(Self.ACTION_CHECK, nil, Unit.FullName("player"))
end
function Self:OnDisable()
-- Unregister events
Self:UnregisterMessage(Roll.EVENT_START)
Self:UnregisterMessage(Roll.EVENT_BID)
Self:UnregisterMessage(Roll.EVENT_AWARD)
end
---@param roll Roll
function Self:ROLL_START(_, roll)
if roll.isOwner and not roll.isTest then
-- Send TRADE message
Self.Send(Self.ACTION_TRADE, roll, roll.item.link)
end
end
---@param roll Roll
---@param bid number
---@param fromUnit string
---@param isImport boolean
function Self:ROLL_BID(_, roll, bid, fromUnit, _, isImport)
local fromSelf = Unit.IsSelf(fromUnit)
if not isImport and not roll.isTest then
if roll.isOwner then
if fromSelf and floor(bid) == Roll.BID_NEED and not Session.GetMasterlooter() then
-- Send KEEP message
Self.Send(Self.ACTION_KEEP, roll)
end
elseif fromSelf and not roll.ownerId and bid ~= Roll.BID_PASS and Addon.GetCompAddonUser(roll.owner, Self.NAME) then
-- Send REQUEST message
local request = Util.Select(bid, Roll.BID_NEED, Self.BID_NEED, Roll.BID_DISENCHANT, Self.BID_DISENCHANT, Self.BID_GREED)
Self.Send(Self.ACTION_REQUEST, roll, request)
end
end
end
---@param roll Roll
function Self:ROLL_AWARD(_, roll)
if roll.winner and not roll.isWinner and roll.isOwner and Addon.GetCompAddonUser(roll.winner, Self.NAME) and not roll.isTest then
-- Send OFFER message
Self.Send(Self.ACTION_OFFER, roll, Unit.FullName(roll.winner))
end
end
|
local w,h = term.getSize()
local previousDir = currentDir
local currentDir = "/"
local dirFiles = fs.list(currentDir)
local choice = 1
function printCentered(string, y)
local x = (w/2)-(string.len(string)/2)
term.setCursorPos(x,y)
term.write(string)
end
function clearScr()
term.clear()
term.setCursorPos(1,1)
end
clearScr()
printCentered("Simple File Manager",2)
printCentered("By Gonow32",3)
printCentered("Press B to go back a folder",5)
printCentered("Press C to create a file",6)
printCentered("Press D to delete a file/folder",7)
printCentered("Press M to make a folder",8)
sleep(5)
function renderDir()
clearScr()
for i = 1,#dirFiles do
if fs.isDir(dirFiles[i]) then
if choice == i then
term.setBackgroundColour(colours.white)
end
term.setTextColour(colours.green)
printCentered(dirFiles[i], i)
term.setTextColour(colours.white)
term.setBackgroundColour(colours.black)
else
if choice == i then
term.setBackgroundColour(colours.white)
term.setTextColour(colours.black)
end
printCentered(dirFiles[i], i)
term.setBackgroundColour(colours.black)
term.setTextColour(colours.white)
end
end
printCentered("Simple File Manager",h)
--printCentered("Press B to go back",h-1)
--printCentered("Press C to make a new file",h-2)
if fs.exists("partitiontable") then
file = fs.open("partitiontable","r")
if not tonumber(file.readLine()) then
term.setCursorPos(1,h)
term.write("Corrupt Disk")
else
term.setCursorPos(1,h)
term.write("FDisk Format")
end
file.close()
else
term.setCursorPos(1,h)
term.write("Regular Disk")
end
local freeSpace = tostring(fs.getFreeSpace(currentDir))
term.setCursorPos((w-string.len(freeSpace))-1,h)
term.write(freeSpace.."B")
end
while true do
renderDir()
local event, key = os.pullEvent("key")
if key == keys.up then
if choice == 1 then
choice = #dirFiles
else
choice = choice - 1
end
elseif key == keys.down then
if choice == #dirFiles then
choice = 1
else
choice = choice + 1
end
elseif key == keys.c then
local filename = ""
while filename == "" do
clearScr()
term.write("Filename: ")
filename = read()
end
shell.run("edit "..filename)
dirFiles = fs.list(currentDir)
renderDir()
elseif key == keys.d then
printCentered("Confirm Delete [Y/N]",h-1)
local event, key = os.pullEvent("key")
if key == keys.y then
if not fs.isReadOnly(dirFiles[choice]) then
fs.delete(dirFiles[choice])
dirFiles = fs.list(currentDir)
choice = 1
renderDir()
end
end
elseif key == keys.m then
local name = ""
while name == "" do
clearScr()
term.write("Folder Name: ")
name = read()
end
splitter = "/"
if currentDir == "/" then
splitter = ""
end
fs.makeDir(currentDir..splitter..name)
dirFiles = fs.list(currentDir)
renderDir()
elseif key == keys.b then
local pseudoDir = previousDir
previousDir = currentDir
currentDir = pseudoDir
dirFiles = fs.list(currentDir)
choice = 1
renderDir()
elseif key == keys.enter then
if fs.isDir(dirFiles[choice]) then
previousDir = currentDir
currentDir = dirFiles[choice]
dirFiles = fs.list(currentDir)
choice = 1
renderDir()
else
clearScr()
local invald = true
--error("I reached here!")
repeat
clearScr()
term.write("Run, Edit, Cancel or Delete? [R/E/C/D] ")
option = read()
if option == "r" or option == "R" then
invalid = false
shell.run(dirFiles[choice])
elseif option == "e" or option == "E" then
invalid = false
shell.run("edit "..dirFiles[choice])
elseif option == "c" or option == "C" then
invalid = false
elseif option == "d" or option == "D" then
invalid = false
fs.delete(dirFiles[choice])
dirFiles = fs.list(currentDir)
end
until invalid == false
end
end
end
|
--- Helper for converting ReQL extensions into lua types.
-- @module rethinkdb.internal.convert_pseudotype
-- @author Adam Grandquist
-- @license Apache
-- @copyright Adam Grandquist 2016
local protect = require'rethinkdb.internal.protect'
--- native conversion from reql grouped data to Lua
-- @tab obj reql group pseudo-type table
-- @treturn table
-- @todo description is from Javascript driver
-- Don't convert the data into a map, because the keys could be tables which doesn't work in JS
-- Instead, we have the following format:
-- [ { 'group': <group>, 'reduction': <value(s)> }, ... ]
local function native_group(obj)
assert(obj.data, 'pseudo-type GROUPED_DATA table missing expected field `data`')
for i = 1, #obj.data do
obj.data[i] = {group = obj.data[i][1], reduction = obj.data[i][2]}
end
return obj.data
end
--- native conversion from reql time data to Lua
-- @tab obj reql time pseudo-type table
-- @treturn table from os.date
-- @todo description is from Javascript driver
-- We ignore the timezone field of the pseudo-type TIME table. JS dates do not support timezones.
-- By converting to a native date table we are intentionally throwing out timezone information.
-- field 'epoch_time' is in seconds but the Date constructor expects milliseconds
local function native_time(obj)
local epoch_time = assert(obj.epoch_time, 'pseudo-type TIME table missing expected field `epoch_time`')
local time = os.date("!*t", math.floor(epoch_time))
time.timezone = obj.timezone
return time
end
--- raw pseudo-type from server
-- @tab obj reql pseudo-type table
-- @treturn table
local function raw(obj)
return obj
end
local group_table = {
native = native_group,
raw = raw
}
local time_table = {
native = native_time,
raw = raw
}
--- convert a nested response from reql to Lua types
-- @tab r driver module
-- @tab _obj reql response
-- @tab opts table of options for native or raw conversions
-- @treturn table
local function convert_pseudotype(r, row, options)
local function native_binary(obj)
return r.unb64('' .. assert(obj.data, 'pseudo-type BINARY table missing expected field `data`'))
end
local binary_table = {
native = native_binary,
raw = raw
}
local fomat = options.format or 'raw'
local binary_format, group_format, time_format =
options.binary_format or fomat,
options.group_format or fomat,
options.time_format or fomat
local BINARY, GROUPED_DATA, TIME =
binary_table[binary_format],
group_table[group_format],
time_table[time_format]
if not BINARY then
return nil, 'Unknown binary_format run option ' .. binary_format
end
if not GROUPED_DATA then
return nil, 'Unknown group_format run option ' .. group_format
end
if not TIME then
return nil, 'Unknown time_format run option ' .. time_format
end
local conversion = {
BINARY = BINARY,
GEOMETRY = raw,
GROUPED_DATA = GROUPED_DATA,
TIME = TIME,
}
local function convert(obj)
if type(obj) == 'table' then
for key, value in pairs(obj) do
obj[key] = convert(value)
end
-- An R_OBJECT may be a regular table or a 'pseudo-type' so we need a
-- second layer of type switching here on the obfuscated field '$reql_type$'
local converter = conversion[obj['$reql_type$']]
if converter then
return converter(obj)
end
end
return obj
end
return protect(convert, row)
end
return convert_pseudotype
|
HouseSystem.plants = {
[0] = { -- default
name = '???',
growingTime = 0,
stages = {'16bf63634a0.png'},
quantyOfSeeds = 0,
},
[1] = { -- tomato
name = 'tomato',
growingTime = 60*3,
stages = {'16bf63634a0.png', '16bf63b93cf.png', '16bf64806c6.png', '16bf64b8df5.png', '16c2544e15f.png', '16c2546d829.png'},
quantyOfSeeds = 5,
pricePerSeed = 10,
},
[2] = { -- oregano
name = 'oregano',
growingTime = 60*4,
stages = {'16bf63634a0.png', '16bf63b93cf.png', '16bf64806c6.png', "16c2ad0f76a.png", "16c2acd5534.png"},
quantyOfSeeds = 5,
pricePerSeed = 30,
},
[3] = { -- lemon
name = 'lemon',
growingTime = 60*6,
stages = {'16bf63634a0.png', '16bf63b93cf.png', '16bf64806c6.png', "16bfca9b802.png", "16bfcaa09ed.png", '16bfca975e5.png'},
quantyOfSeeds = 3,
pricePerSeed = 120,
},
[4] = { -- pepper
name = 'pepper',
growingTime = 60*3,
stages = {'16bf63634a0.png', '16bf63b93cf.png', '16bf64806c6.png', '16c25569bf0.png', '16c2556b669.png', '16c2556cfb9.png'},
quantyOfSeeds = 5,
pricePerSeed = 70,
},
[5] = { -- luckyFlower
name = 'luckyFlower',
growingTime = 60*15,
stages = {'16bf63634a0.png', '16bf63b93cf.png', '16c2580e482.png', '16c258100b7.png', '16c25811d3b.png', '16c25813c4c.png', '16c258182a0.png'},
quantyOfSeeds = 1,
pricePerSeed = 10000,
},
[6] = { -- wheat
name = 'wheat',
growingTime = 60*7,
stages = {'16bf63634a0.png', '16bf63b93cf.png', '16c2ad99a4a.png', "16c2adf9395.png", "16d9c73c301.png"},
quantyOfSeeds = 5,
pricePerSeed = 40,
},
[7] = { -- pumpkin
name = 'pumpkin',
growingTime = 60*5,
stages = {'16bf63634a0.png', '16bf63b93cf.png', '16da90fd0ad.png', '16da90fe81f.png', "16da905bd71.png"},
quantyOfSeeds = 1,
pricePerSeed = 150,
},
[8] = { -- blueberries
name = 'blueberries',
growingTime = 60*7,
stages = {'16bf63634a0.png', '16bf63b93cf.png', '16bf64806c6.png', '16f1e9f4d55.png', '16f1e9fc472.png', "16f1ea01892.png"},
quantyOfSeeds = 2,
pricePerSeed = 400,
},
[9] = { -- banana
name = 'banana',
growingTime = 60*12.5,
stages = {'16bf63634a0.png', '16bf64806c6.png', '17276940ecb.png', '1727693f16f.png', '1727693d907.png', "1727693bc5b.png"},
quantyOfSeeds = 2,
pricePerSeed = 800,
},
}
|
ENT.Type = "anim"
--ENT.Base = "base_gmodentity"
ENT.PrintName = "RDx Drawer Drawing Base ENT"
ENT.Author = "TAD2020"
ENT.Contact = ""
ENT.Purpose = ""
ENT.Instructions = ""
ENT.Spawnable = false
ENT.AdminSpawnable = false
local Beams_next_index = 1
local BeamStart = 1
local BeamNode = 2
local BeamDelete = 3
local BeamMove = 4
--lua_run RDx.PrintTable(player.GetByID(1):GetEyeTrace().Entity:RDx_StartBeam(nil, Vector(0,0,0),"cable/cable2",Color(255,255,255,255)))
function ENT:RDx_StartBeam(ent, pos, material, color, index)
pos = pos or Vector(0,0,0)
ent = ent or self.Entity
material = material or "cable/cable2"
color = color or Color(255,255,255,255)
if not pos then Error('Wire2BeamLib.Start: Invalid arg pos\n') return end
if CLIENT and not index then Error('Wire2BeamLib.Start: Needs and index when called on client machine!') return end
if SERVER then
index = Beams_next_index
Beams_next_index = Beams_next_index + 1
end
local beam = {
Index = index,
Material = material,
Color = table.Copy(color),
Nodes = { }
}
table.insert(beam.Nodes, { Entity = ent, Position = pos })
if SERVER then
local rp = RecipientFilter()
rp:AddAllPlayers()
umsg.Start("RDx_Beam", rp)
umsg.Long( self:EntIndex() )
umsg.Char( BeamStart )
umsg.Long(beam.Index)
umsg.Long(ent:EntIndex())
umsg.Vector(pos)
umsg.String(material)
umsg.Short(color.r)
umsg.Short(color.g)
umsg.Short(color.b)
umsg.End()
else --CLIENT
table.insert(self.iBeams, beam)
end
beam.Proxy = self.Entity
self.Beams = self.Beams or {}
self.Beams[beam.Index] = beam
return beam
end
function ENT:RDx_AddBeamNode(beam, ent, pos)
if not beam then Error('Wire2BeamLib.AddNode: Invalid arg beam\n') return end
if not ent then Error('Wire2BeamLib.AddNode: Invalid arg ent\n') return end
if not pos then Error('Wire2BeamLib.AddNode: Invalid arg pos\n') return end
--local lastindex = #beam.Nodes
table.insert(beam.Nodes, { Entity = ent, Position = pos })
--beam.Nodes[lastindex] = { Entity = ent, Position = pos }
if SERVER then
local rp = RecipientFilter()
rp:AddAllPlayers()
umsg.Start("RDx_Beam", rp)
umsg.Long( self:EntIndex() )
umsg.Char( BeamNode )
umsg.Long(beam.Index)
umsg.Long(ent:EntIndex())
umsg.Vector(pos)
umsg.End()
end
end
function ENT:RDx_EndBeam(beam, ent, pos)
self:AddNode(beam, ent, pos)
end
function ENT:RDx_DeleteBeam(beam)
if not self.Beams then return end
self.Beams[beam.Index] = nil
if SERVER then
local rp = RecipientFilter()
rp:AddAllPlayers()
umsg.Start("RDx_Beam", rp)
umsg.Long( self:EntIndex() )
umsg.Char( BeamDelete )
umsg.Long(beam.Index)
umsg.End()
else --CLIENT
for k,v in ipairs(beam.Proxy.Beams) do
if v.Index == beam.Index then
table.remove(beam.Proxy.Beams, k)
return
end
end
end
end
function ENT:RDx_MoveBeam(beam, nodeindex, ent, pos)
beam.Nodes[nodeindex].Entity = ent
beam.Nodes[nodeindex].Position = pos
if SERVER then
local rp = RecipientFilter()
rp:AddAllPlayers()
umsg.Start("RDx_Beam", rp)
umsg.Long( self:EntIndex() )
umsg.Char( BeamMove )
umsg.Long(beam.Index)
umsg.Long(nodeindex)
umsg.Long(ent:EntIndex())
umsg.Vector(pos)
umsg.End()
end
end
function ENT:RDx_MoveFirstBeam(beam, ent, pos)
self:Move(beam, 1, ent, pos)
end
function ENT:RDx_MoveLastBeam(beam, ent, pos)
self:Move(beam, #beam.Nodes, ent, pos)
end
if CLIENT then
local function GetEnt(data)
local ent = ents.GetByIndex(data.entidx)
if ent and (ent:IsValid() or ent:IsWorld()) then
return ent
end
end
function ENT:NEDT_DataRecieved(data)
MsgN("DataRecieved ",data[1])
if data[1] == BeamStart then
local ent = GetEnt(data)
if ent then
self:RDx_StartBeam(ent, data.pos, data.material, data.color, data.index)
end
elseif data[1] == BeamNode then
local ent = GetEnt(data)
if ent and self.Beams then
self:RDx_AddBeamNode(self.Beams[data.index], ent, data.pos)
end
elseif data[1] == BeamDelete then
local beam = self.Beams[data.index]
if beam then
beam.Nodes = { }
if beam.Proxy and beam.Proxy:IsValid() then
beam.Proxy:GetTable():RemoveBeam(beam)
end
self:RDx_DeleteBeam(beam)
end
elseif data[1] == BeamMove then
local ent = GetEnt(data)
if ent and self.Beams and self.Beams[data.index] then
self:RDx_MoveBeam(self.Beams[data.index], data.nodeindex, ent, data.pos)
end
end
end
function rcvBeam( um )
local entID = um:ReadLong()
local data = {}
data[1] = um:ReadChar()
if data[1] == BeamStart then
data.index = um:ReadLong()
data.entidx = um:ReadLong()
data.pos = um:ReadVector()
data.material = um:ReadString()
data.color = Color(um:ReadShort(), um:ReadShort(), um:ReadShort(), 255)
elseif data[1] == BeamNode then
data.index = um:ReadLong()
data.entidx = um:ReadLong()
data.pos = um:ReadVector()
elseif data[1] == BeamDelete then
data.index = um:ReadLong()
elseif data[1] == BeamMove then
data.index = um:ReadLong()
data.nodeinde = um:ReadLong()
data.entidx = um:ReadLong()
data.pos = um:ReadVector()
end
RDx_Beams.GetData(entID, data)
end
usermessage.Hook("RDx_Beam", rcvBeam)
end
|
--[[--
Chat manipulation and helper functions.
Chat messages are a core part of the framework - it's takes up a good chunk of the gameplay, and is also used to interact with
the framework. Chat messages can have types or "classes" that describe how the message should be interpreted. All chat messages
will have some type of class: `ic` for regular in-character speech, `me` for actions, `ooc` for out-of-character, etc. These
chat classes can affect how the message is displayed in each player's chatbox. See `ix.chat.Register` and `ChatClassStructure`
to create your own chat classes.
]]
-- @module ix.chat
ix.chat = ix.chat or {}
--- List of all chat classes that have been registered by the framework, where each key is the name of the chat class, and value
-- is the chat class data. Accessing a chat class's data is useful for when you want to copy some functionality or properties
-- to use in your own. Note that if you're accessing this table, you should do so inside of the `InitializedChatClasses` hook.
-- @realm shared
-- @table ix.chat.classes
-- @usage print(ix.chat.classes.ic.format)
-- > "%s says \"%s\""
ix.chat.classes = ix.chat.classes or {}
if (!ix.command) then
include("sh_command.lua")
end
CAMI.RegisterPrivilege({
Name = "Helix - Bypass OOC Timer",
MinAccess = "admin"
})
-- note we can't use commas in the "color" field's default value since the metadata is separated by commas which will break the
-- formatting for that field
--- Chat messages can have different classes or "types" of messages that have different properties. This can include how the
-- text is formatted, color, hearing distance, etc.
-- @realm shared
-- @table ChatClassStructure
-- @see ix.chat.Register
-- @field[type=string] prefix What the player must type before their message in order to use this chat class. For example,
-- having a prefix of `/Y` will require to type `/Y I am yelling` in order to send a message with this chat class. This can also
-- be a table of strings if you want to allow multiple prefixes, such as `{"//", "/OOC"}`.
--
-- **NOTE:** the prefix should usually start with a `/` to be consistent with the rest of the framework. However, you are able
-- to use something different like the `LOOC` chat class where the prefixes are `.//`, `[[`, and `/LOOC`.
-- @field[type=bool,opt=false] noSpaceAfter Whether or not the `prefix` can be used without a space after it. For example, the
-- `OOC` chat class allows you to type `//my message` instead of `// my message`. **NOTE:** this only works if the last
-- character in the prefix is non-alphanumeric (i.e `noSpaceAfter` with `/Y` will not work, but `/!` will).
-- @field[type=string,opt] description Description to show to the user in the chatbox when they're using this chat class
-- @field[type=string,opt="%s: \"%s\""] format How to format a message with this chat class. The first `%s` will be the speaking
-- player's name, and the second one will be their message
-- @field[type=color,opt=Color(242 230 160)] color Color to use when displaying a message with this chat class
-- @field[type=string,opt="chatTyping"] indicator Language phrase to use when displaying the typing indicator above the
-- speaking player's head
-- @field[type=bool,opt=false] bNoIndicator Whether or not to avoid showing the typing indicator above the speaking player's
-- head
-- @field[type=string,opt=ixChatFont] font Font to use for displaying a message with this chat class
-- @field[type=bool,opt=false] deadCanChat Whether or not a dead player can send a message with this chat class
-- @field[type=number] CanHear This can be either a `number` representing how far away another player can hear this message.
-- IC messages will use the `chatRange` config, for example. This can also be a function, which returns `true` if the given
-- listener can hear the message emitted from a speaker.
-- -- message can be heard by any player 1000 units away from the speaking player
-- CanHear = 1000
-- OR
-- CanHear = function(self, speaker, listener)
-- -- the speaking player will be heard by everyone
-- return true
-- end
-- @field[type=function,opt] CanSay Function to run to check whether or not a player can send a message with this chat class.
-- By default, it will return `false` if the player is dead and `deadCanChat` is `false`. Overriding this function will prevent
-- `deadCanChat` from working, and you must implement this functionality manually.
-- CanSay = function(self, speaker, text)
-- -- the speaker will never be able to send a message with this chat class
-- return false
-- end
-- @field[type=function,opt] GetColor Function to run to set the color of a message with this chat class. You should generally
-- stick to using `color`, but this is useful for when you want the color of the message to change with some criteria.
-- GetColor = function(self, speaker, text)
-- -- each message with this chat class will be colored a random shade of red
-- return Color(math.random(120, 200), 0, 0)
-- end
-- @field[type=function,opt] OnChatAdd Function to run when a message with this chat class should be added to the chatbox. If
-- using this function, make sure you end the function by calling `chat.AddText` in order for the text to show up.
--
-- **NOTE:** using your own `OnChatAdd` function will prevent `color`, `GetColor`, or `format` from being used since you'll be
-- overriding the base function that uses those properties. In such cases you'll need to add that functionality back in
-- manually. In general, you should avoid overriding this function where possible. The `data` argument in the function is
-- whatever is passed into the same `data` argument in `ix.chat.Send`.
--
-- OnChatAdd = function(self, speaker, text, bAnonymous, data)
-- -- adds white text in the form of "Player Name: Message contents"
-- chat.AddText(color_white, speaker:GetName(), ": ", text)
-- end
--- Registers a new chat type with the information provided. Chat classes should usually be created inside of the
-- `InitializedChatClasses` hook.
-- @realm shared
-- @string chatType Name of the chat type
-- @tparam ChatClassStructure data Properties and functions to assign to this chat class
-- @usage -- this is the "me" chat class taken straight from the framework as an example
-- ix.chat.Register("me", {
-- format = "** %s %s",
-- color = Color(255, 50, 50),
-- CanHear = ix.config.Get("chatRange", 280) * 2,
-- prefix = {"/Me", "/Action"},
-- description = "@cmdMe",
-- indicator = "chatPerforming",
-- deadCanChat = true
-- })
-- @see ChatClassStructure
function ix.chat.Register(chatType, data)
chatType = string.lower(chatType)
if (!data.CanHear) then
-- Have a substitute if the canHear property is not found.
function data:CanHear(speaker, listener)
-- The speaker will be heard by everyone.
return true
end
elseif (isnumber(data.CanHear)) then
-- Use the value as a range and create a function to compare distances.
local range = data.CanHear * data.CanHear
data.range = range
function data:CanHear(speaker, listener)
-- Length2DSqr is faster than Length2D, so just check the squares.
return (speaker:GetPos() - listener:GetPos()):LengthSqr() <= self.range
end
end
-- Allow players to use this chat type by default.
if (!data.CanSay) then
function data:CanSay(speaker, text)
if (!self.deadCanChat and !speaker:Alive()) then
speaker:NotifyLocalized("noPerm")
return false
end
return true
end
end
-- Chat text color.
data.color = data.color or Color(242, 230, 160)
if (!data.OnChatAdd) then
data.format = data.format or "%s: \"%s\""
function data:OnChatAdd(speaker, text, anonymous, info)
local color = self.color
local name = anonymous and
L"someone" or hook.Run("GetCharacterName", speaker, chatType) or
(IsValid(speaker) and speaker:Name() or "Console")
if (self.GetColor) then
color = self:GetColor(speaker, text, info)
end
local translated = L2(chatType.."Format", text)
chat.AddText(speaker, color, translated or string.format(self.format, name, text))
end
end
if (CLIENT and data.prefix) then
if (istable(data.prefix)) then
for _, v in ipairs(data.prefix) do
if (v:utf8sub(1, 1) == "/") then
ix.command.Add(v:utf8sub(2), {
description = data.description,
arguments = ix.type.text,
indicator = data.indicator,
bNoIndicator = data.bNoIndicator,
chatClass = data,
OnCheckAccess = function() return true end,
OnRun = function(self, client, message) end
})
end
end
else
ix.command.Add(isstring(data.prefix) and data.prefix:utf8sub(2) or chatType, {
description = data.description,
arguments = ix.type.text,
indicator = data.indicator,
bNoIndicator = data.bNoIndicator,
chatClass = data,
OnCheckAccess = function() return true end,
OnRun = function(self, client, message) end
})
end
end
data.uniqueID = chatType
ix.chat.classes[chatType] = data
end
--- Identifies which chat mode should be used.
-- @realm shared
-- @player client Player who is speaking
-- @string message Message to parse
-- @bool[opt=false] bNoSend Whether or not to send the chat message after parsing
-- @treturn string Name of the chat type
-- @treturn string Message that was parsed
-- @treturn bool Whether or not the speaker should be anonymous
function ix.chat.Parse(client, message, bNoSend)
local anonymous = false
local chatType = "ic"
-- Loop through all chat classes and see if the message contains their prefix.
for k, v in pairs(ix.chat.classes) do
local isChosen = false
local chosenPrefix = ""
local noSpaceAfter = v.noSpaceAfter
-- Check through all prefixes if the chat type has more than one.
if (istable(v.prefix)) then
for _, prefix in ipairs(v.prefix) do
prefix = prefix:utf8lower()
local fullPrefix = prefix .. (noSpaceAfter and "" or " ")
-- Checking if the start of the message has the prefix.
if (message:utf8sub(1, prefix:utf8len() + (noSpaceAfter and 0 or 1)):utf8lower() == fullPrefix:utf8lower()) then
isChosen = true
chosenPrefix = fullPrefix
break
end
end
-- Otherwise the prefix itself is checked.
elseif (isstring(v.prefix)) then
local prefix = v.prefix:utf8lower()
local fullPrefix = prefix .. (noSpaceAfter and "" or " ")
isChosen = message:utf8sub(1, prefix:utf8len() + (noSpaceAfter and 0 or 1)):utf8lower() == fullPrefix:utf8lower()
chosenPrefix = fullPrefix
end
-- If the checks say we have the proper chat type, then the chat type is the chosen one!
-- If this is not chosen, the loop continues. If the loop doesn't find the correct chat
-- type, then it falls back to IC chat as seen by the chatType variable above.
if (isChosen) then
-- Set the chat type to the chosen one.
chatType = k
-- Remove the prefix from the chat type so it does not show in the message.
message = message:utf8sub(chosenPrefix:utf8len() + 1)
if (ix.chat.classes[k].noSpaceAfter and message:utf8sub(1, 1):match("%s")) then
message = message:utf8sub(2)
end
break
end
end
if (!message:find("%S")) then
return
end
-- Only send if needed.
if (SERVER and !bNoSend) then
-- Send the correct chat type out so other player see the message.
ix.chat.Send(client, chatType, hook.Run("PlayerMessageSend", client, chatType, message, anonymous) or message, anonymous)
end
-- Return the chosen chat type and the message that was sent if needed for some reason.
-- This would be useful if you want to send the message on your own.
return chatType, message, anonymous
end
--- Formats a string to fix basic grammar - removing extra spacing at the beginning and end, capitalizing the first character,
-- and making sure it ends in punctuation.
-- @realm shared
-- @string text String to format
-- @treturn string Formatted string
-- @usage print(ix.chat.Format("hello"))
-- > Hello.
-- @usage print(ix.chat.Format("wow!"))
-- > Wow!
function ix.chat.Format(text)
text = string.Trim(text)
local last = text:utf8sub(-1)
if (last != "." and last != "?" and last != "!" and last != "-" and last != "\"") then
text = text .. "."
end
return text:utf8sub(1, 1):utf8upper() .. text:utf8sub(2)
end
if (SERVER) then
util.AddNetworkString("ixChatMessage")
--- Send a chat message using the specified chat type.
-- @realm server
-- @player speaker Player who is speaking
-- @string chatType Name of the chat type
-- @string text Message to send
-- @bool[opt=false] bAnonymous Whether or not the speaker should be anonymous
-- @tab[opt=nil] receivers The players to replicate send the message to
-- @tab[opt=nil] data Additional data for this chat message
function ix.chat.Send(speaker, chatType, text, bAnonymous, receivers, data)
if (!chatType) then
return
end
data = data or {}
chatType = string.lower(chatType)
if (IsValid(speaker) and hook.Run("PrePlayerMessageSend", speaker, chatType, text, bAnonymous) == false) then
return
end
local class = ix.chat.classes[chatType]
if (class and class:CanSay(speaker, text, data) != false) then
if (class.CanHear and !receivers) then
receivers = {}
for _, v in ipairs(player.GetAll()) do
if (v:GetCharacter() and class:CanHear(speaker, v, data) != false) then
receivers[#receivers + 1] = v
end
end
if (#receivers == 0) then
return
end
end
-- Format the message if needed before we run the hook.
local rawText = text
local maxLength = ix.config.Get("chatMax")
if (text:utf8len() > maxLength) then
text = text:utf8sub(0, maxLength)
end
if (ix.config.Get("chatAutoFormat") and hook.Run("CanAutoFormatMessage", speaker, chatType, text)) then
text = ix.chat.Format(text)
end
text = hook.Run("PlayerMessageSend", speaker, chatType, text, bAnonymous, receivers, rawText) or text
net.Start("ixChatMessage")
net.WriteEntity(speaker)
net.WriteString(chatType)
net.WriteString(text)
net.WriteBool(bAnonymous or false)
net.WriteTable(data or {})
net.Send(receivers)
return text
end
end
else
function ix.chat.Send(speaker, chatType, text, anonymous, data)
local class = ix.chat.classes[chatType]
if (class) then
-- luacheck: globals CHAT_CLASS
CHAT_CLASS = class
class:OnChatAdd(speaker, text, anonymous, data)
CHAT_CLASS = nil
end
end
-- Call OnChatAdd for the appropriate chatType.
net.Receive("ixChatMessage", function()
local client = net.ReadEntity()
local chatType = net.ReadString()
local text = net.ReadString()
local anonymous = net.ReadBool()
local data = net.ReadTable()
if (IsValid(client)) then
local info = {
chatType = chatType,
text = text,
anonymous = anonymous,
data = data
}
hook.Run("MessageReceived", client, info)
ix.chat.Send(client, info.chatType or chatType, info.text or text, info.anonymous or anonymous, info.data)
else
ix.chat.Send(nil, chatType, text, anonymous, data)
end
end)
end
-- Add the default chat types here.
do
-- Load the chat types after the configs so we can access changed configs.
hook.Add("InitializedConfig", "ixChatTypes", function()
-- The default in-character chat.
ix.chat.Register("ic", {
format = "%s says \"%s\"",
indicator = "chatTalking",
GetColor = function(self, speaker, text)
-- If you are looking at the speaker, make it greener to easier identify who is talking.
if (LocalPlayer():GetEyeTrace().Entity == speaker) then
return ix.config.Get("chatListenColor")
end
-- Otherwise, use the normal chat color.
return ix.config.Get("chatColor")
end,
CanHear = ix.config.Get("chatRange", 280)
})
-- Actions and such.
ix.chat.Register("me", {
format = "** %s %s",
GetColor = ix.chat.classes.ic.GetColor,
CanHear = ix.config.Get("chatRange", 280) * 2,
prefix = {"/Me", "/Action"},
description = "@cmdMe",
indicator = "chatPerforming",
deadCanChat = true
})
-- Actions and such.
ix.chat.Register("it", {
OnChatAdd = function(self, speaker, text)
chat.AddText(ix.config.Get("chatColor"), "** "..text)
end,
CanHear = ix.config.Get("chatRange", 280) * 2,
prefix = {"/It"},
description = "@cmdIt",
indicator = "chatPerforming",
deadCanChat = true
})
-- Whisper chat.
ix.chat.Register("w", {
format = "%s whispers \"%s\"",
GetColor = function(self, speaker, text)
local color = ix.chat.classes.ic:GetColor(speaker, text)
-- Make the whisper chat slightly darker than IC chat.
return Color(color.r - 35, color.g - 35, color.b - 35)
end,
CanHear = ix.config.Get("chatRange", 280) * 0.25,
prefix = {"/W", "/Whisper"},
description = "@cmdW",
indicator = "chatWhispering"
})
-- Yelling out loud.
ix.chat.Register("y", {
format = "%s yells \"%s\"",
GetColor = function(self, speaker, text)
local color = ix.chat.classes.ic:GetColor(speaker, text)
-- Make the yell chat slightly brighter than IC chat.
return Color(color.r + 35, color.g + 35, color.b + 35)
end,
CanHear = ix.config.Get("chatRange", 280) * 2,
prefix = {"/Y", "/Yell"},
description = "@cmdY",
indicator = "chatYelling"
})
-- Out of character.
ix.chat.Register("ooc", {
CanSay = function(self, speaker, text)
if (!ix.config.Get("allowGlobalOOC")) then
speaker:NotifyLocalized("Global OOC is disabled on this server.")
return false
else
local delay = ix.config.Get("oocDelay", 10)
-- Only need to check the time if they have spoken in OOC chat before.
if (delay > 0 and speaker.ixLastOOC) then
local lastOOC = CurTime() - speaker.ixLastOOC
-- Use this method of checking time in case the oocDelay config changes.
if (lastOOC <= delay and !CAMI.PlayerHasAccess(speaker, "Helix - Bypass OOC Timer", nil)) then
speaker:NotifyLocalized("oocDelay", delay - math.ceil(lastOOC))
return false
end
end
-- Save the last time they spoke in OOC.
speaker.ixLastOOC = CurTime()
end
end,
OnChatAdd = function(self, speaker, text)
-- @todo remove and fix actual cause of speaker being nil
if (!IsValid(speaker)) then
return
end
local icon = "icon16/user.png"
if (speaker:IsSuperAdmin()) then
icon = "icon16/shield.png"
elseif (speaker:IsAdmin()) then
icon = "icon16/star.png"
elseif (speaker:IsUserGroup("moderator") or speaker:IsUserGroup("operator")) then
icon = "icon16/wrench.png"
elseif (speaker:IsUserGroup("vip") or speaker:IsUserGroup("donator") or speaker:IsUserGroup("donor")) then
icon = "icon16/heart.png"
end
icon = Material(hook.Run("GetPlayerIcon", speaker) or icon)
chat.AddText(icon, Color(255, 50, 50), "[OOC] ", speaker, color_white, ": "..text)
end,
prefix = {"//", "/OOC"},
description = "@cmdOOC",
noSpaceAfter = true
})
-- Local out of character.
ix.chat.Register("looc", {
CanSay = function(self, speaker, text)
local delay = ix.config.Get("loocDelay", 0)
-- Only need to check the time if they have spoken in OOC chat before.
if (delay > 0 and speaker.ixLastLOOC) then
local lastLOOC = CurTime() - speaker.ixLastLOOC
-- Use this method of checking time in case the oocDelay config changes.
if (lastLOOC <= delay and !CAMI.PlayerHasAccess(speaker, "Helix - Bypass OOC Timer", nil)) then
speaker:NotifyLocalized("loocDelay", delay - math.ceil(lastLOOC))
return false
end
end
-- Save the last time they spoke in OOC.
speaker.ixLastLOOC = CurTime()
end,
OnChatAdd = function(self, speaker, text)
chat.AddText(Color(255, 50, 50), "[LOOC] ", ix.config.Get("chatColor"), speaker:Name()..": "..text)
end,
CanHear = ix.config.Get("chatRange", 280),
prefix = {".//", "[[", "/LOOC"},
description = "@cmdLOOC",
noSpaceAfter = true
})
-- Roll information in chat.
ix.chat.Register("roll", {
format = "** %s has rolled %s out of %s.",
color = Color(155, 111, 176),
CanHear = ix.config.Get("chatRange", 280),
deadCanChat = true,
OnChatAdd = function(self, speaker, text, bAnonymous, data)
local max = data.max or 100
local translated = L2(self.uniqueID.."Format", speaker:Name(), text, max)
chat.AddText(self.color, translated and "** "..translated or string.format(self.format,
speaker:Name(), text, max
))
end
})
-- run a hook after we add the basic chat classes so schemas/plugins can access their info as soon as possible if needed
hook.Run("InitializedChatClasses")
end)
end
-- Private messages between players.
ix.chat.Register("pm", {
format = "[PM] %s -> %s: %s",
color = Color(125, 150, 75, 255),
deadCanChat = true,
OnChatAdd = function(self, speaker, text, bAnonymous, data)
chat.AddText(self.color, string.format(self.format, speaker:GetName(), data.target:GetName(), text))
if (LocalPlayer() != speaker) then
surface.PlaySound("hl1/fvox/bell.wav")
end
end
})
-- Global events.
ix.chat.Register("event", {
CanHear = 1000000,
OnChatAdd = function(self, speaker, text)
chat.AddText(Color(255, 150, 0), text)
end,
indicator = "chatPerforming"
})
ix.chat.Register("connect", {
CanSay = function(self, speaker, text)
return !IsValid(speaker)
end,
OnChatAdd = function(self, speaker, text)
local icon = ix.util.GetMaterial("icon16/user_add.png")
chat.AddText(icon, Color(150, 150, 200), L("playerConnected", text))
end,
noSpaceAfter = true
})
ix.chat.Register("disconnect", {
CanSay = function(self, speaker, text)
return !IsValid(speaker)
end,
OnChatAdd = function(self, speaker, text)
local icon = ix.util.GetMaterial("icon16/user_delete.png")
chat.AddText(icon, Color(200, 150, 200), L("playerDisconnected", text))
end,
noSpaceAfter = true
})
ix.chat.Register("notice", {
CanSay = function(self, speaker, text)
return !IsValid(speaker)
end,
OnChatAdd = function(self, speaker, text, bAnonymous, data)
local icon = ix.util.GetMaterial(data.bError and "icon16/comment_delete.png" or "icon16/comment.png")
chat.AddText(icon, data.bError and Color(200, 175, 200, 255) or Color(175, 200, 255), text)
end,
noSpaceAfter = true
})
-- Why does ULX even have a /me command?
hook.Remove("PlayerSay", "ULXMeCheck")
|
pg = pg or {}
pg.SimpleConnectionMgr = singletonClass("SimpleConnectionMgr")
slot2 = createLog("SimpleConnectionMgr", false)
slot3, slot4 = nil
slot5 = false
slot6 = {}
slot7 = nil
pg.SimpleConnectionMgr.Connect = function (slot0, slot1, slot2, slot3, slot4)
slot0.stopTimer()
slot2.UIMgr.GetInstance():LoadingOn()
slot1.onConnected:AddListener(function ()
slot0.UIMgr.GetInstance():LoadingOff()
slot0.UIMgr.GetInstance()("Simple Network Connected.")
slot4.onData:AddListener(slot2 or slot0.SendWindow.New(slot3, 0).onData)
slot5 = true
slot6 = false
slot7()
end)
slot1.onData.AddListener(slot5, slot0.onData)
slot1.onError:AddListener(slot0.onError)
slot1.onDisconnected:AddListener(slot0.onDisconnected)
slot6 = true
slot1:Connect()
slot4 = defaultValue(slot4, SEND_TIMEOUT)
slot0.timer = Timer.New(function ()
if not slot0 then
warning("connect timeout error (custom): " .. )
slot2.stopTimer()
slot3.onDisconnected(false, DISCONNECT_TIME_OUT)
if slot2.errorCB then
slot2.errorCB()
end
end
end, slot4, 1)
slot0.timer:Start()
end
pg.SimpleConnectionMgr.stopTimer = function ()
if slot0.timer then
slot0.timer:Stop()
slot0.timer.Stop.timer = nil
end
end
pg.SimpleConnectionMgr.onDisconnected = function (slot0, slot1)
slot0("Simple Network onDisconnected: " .. tostring(slot0))
if slot1 then
if not slot0 then
slot1.onDisconnected:RemoveAllListeners()
end
slot1:Dispose()
slot1 = nil
end
if slot0 then
slot2 = false
end
if slot3 then
slot4.UIMgr.GetInstance():LoadingOff()
end
slot3 = false
end
pg.SimpleConnectionMgr.onData = function (slot0)
if slot0[slot0.cmd] then
slot1 = slot1.Packer.GetInstance():Unpack(slot0.cmd, slot0:getLuaStringBuffer())
for slot5, slot6 in ipairs(slot0[slot0.cmd]) do
slot6(slot1)
end
end
end
pg.SimpleConnectionMgr.SetErrorCB = function (slot0, slot1)
slot0.errorCB = slot1
end
pg.SimpleConnectionMgr.onError = function (slot0)
slot0.UIMgr.GetInstance():LoadingOff()
slot0.UIMgr.GetInstance().LoadingOff.stopTimer()
slot0("Simple Network Error: " .. tostring(slot0))
if tostring(slot0) then
slot3:Dispose()
slot3 = nil
end
if slot4 then
slot4 = false
end
if slot1.errorCB then
slot1.errorCB()
end
end
pg.SimpleConnectionMgr.Send = function (slot0, slot1, slot2, slot3, slot4, slot5, slot6)
if not slot0 then
warning("Simple Network is not connected. msgid " .. slot1)
return
end
slot1:Queue(slot1, slot2, slot3, slot4, slot5, nil, slot6)
end
pg.SimpleConnectionMgr.setPacketIdx = function (slot0, slot1)
slot0:setPacketIdx(slot1)
end
pg.SimpleConnectionMgr.On = function (slot0, slot1, slot2)
if slot0[slot1] == nil then
slot0[slot1] = {}
end
table.insert(slot0[slot1], slot2)
end
pg.SimpleConnectionMgr.Off = function (slot0, slot1, slot2)
if slot0[slot1] == nil then
return
end
if slot2 == nil then
slot0[slot1] = nil
else
for slot6, slot7 in ipairs(slot0[slot1]) do
if slot7 == slot2 then
table.remove(slot0[slot1], slot6)
break
end
end
end
end
pg.SimpleConnectionMgr.Disconnect = function (slot0)
slot0 = {}
("Simple Network Disconnect !!!")
if "Simple Network Disconnect !!!" then
slot2:Dispose()
slot2 = nil
end
slot3 = nil
slot4 = false
end
pg.SimpleConnectionMgr.Reconnect = function (slot0, slot1)
slot0:Disconnect()
if slot0.errorCB then
slot0.errorCB()
end
end
pg.SimpleConnectionMgr.resetHBTimer = function (slot0)
return
end
pg.SimpleConnectionMgr.getConnection = function (slot0)
return slot0
end
pg.SimpleConnectionMgr.isConnecting = function (slot0)
return slot0
end
pg.SimpleConnectionMgr.isConnected = function (slot0)
return slot0
end
pg.SimpleConnectionMgr.SwitchProxy = function (slot0)
return
end
return
|
figrin_dan_band_outfit = {
{
{objectTemplate = "object/tangible/wearables/shirt/shirt_s07.iff", customizationVariables = {{"/private/index_color_1", 90}} },
{objectTemplate = "object/tangible/wearables/pants/pants_s12.iff", customizationVariables = {} },
{objectTemplate = "object/tangible/wearables/shoes/shoes_s03.iff", customizationVariables = {} },
{objectTemplate = "object/tangible/wearables/vest/vest_s05.iff", customizationVariables = {{"/private/index_color_1", 90}} },
}
}
addOutfitGroup("figrin_dan_band_outfit", figrin_dan_band_outfit)
|
if (...) == "-?" then
printUsage(
"shutdown","Shutdowns ZYX-13"
)
return
end
shutdown()
|
--pnzrschrk---------------------------------------------------------------
sound.Add({
name = "pnzrschrk.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/pnzrschrk/fire.wav" // <-- Sound Path
})
sound.Add({
name = "pnzrschrk.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/pnzrschrk/in.wav"
})
sound.Add({
name = "pnzrschrk.cloth",
channel = CHAN_AUTO,
volume = 1.0,
sound = "weapons/pnzrschrk/cloth.wav"
})
sound.Add({
name = "pnzrschrk.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/pnzrschrk/deploy.wav"
})
--waw_walther---------------------------------------------------------------
sound.Add({
name = "waw_walther.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/walther/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_walther.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/walther/out.wav"
})
sound.Add({
name = "waw_walther.in1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/walther/in1.wav"
})
sound.Add({
name = "waw_walther.in2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/walther/in3.wav"
})
sound.Add({
name = "waw_walther.release",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/walther/release.wav"
})
sound.Add({
name = "waw_walther.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/walther/deploy.wav"
})
--waw_nambu---------------------------------------------------------------
sound.Add({
name = "waw_nambu.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_nambu/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_nambu.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_nambu/out.wav"
})
sound.Add({
name = "waw_nambu.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_nambu/in.wav"
})
sound.Add({
name = "waw_nambu.release",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_nambu/release.wav"
})
sound.Add({
name = "waw_nambu.deploy",
channel = CHAN_AUTO,
volume = 1.0,
sound = "weapons/waw_nambu/deploy.wav"
})
--waw_arisaka---------------------------------------------------------------
sound.Add({
name = "waw_arisaka.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_arisaka/fire1.wav" // <-- Sound Path
})
sound.Add({
name = "waw_arisaka.Sniper", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_arisaka/fire_sniper.wav" // <-- Sound Path
})
sound.Add({
name = "waw_arisaka.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_arisaka/pull.wav"
})
sound.Add({
name = "waw_arisaka.release",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_arisaka/release.wav"
})
sound.Add({
name = "waw_arisaka.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_arisaka/in.wav"
})
sound.Add({
name = "waw_arisaka.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_arisaka/deploy.wav"
})
sound.Add({
name = "waw_arisaka.insert",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_arisaka/insert1.wav"
})
--waw_fg42_new---------------------------------------------------------------
sound.Add({
name = "waw_fg42_new.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_fg42_new/fire1.wav" // <-- Sound Path
})
sound.Add({
name = "waw_fg42_new.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_fg42_new/out.wav"
})
sound.Add({
name = "waw_fg42_new.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_fg42_new/in.wav"
})
sound.Add({
name = "waw_fg42_new.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_fg42_new/pull.wav"
})
sound.Add({
name = "waw_fg42_new.deploy1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_fg42_new/deploy1.wav"
})
sound.Add({
name = "waw_fg42_new.deploy2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_fg42_new/deploy2.wav"
})
--waw_gewehr---------------------------------------------------------------
sound.Add({
name = "waw_gewehr.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_gewehr/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_gewehr.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_gewehr/out.wav"
})
sound.Add({
name = "waw_gewehr.in1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_gewehr/in1.wav"
})
sound.Add({
name = "waw_gewehr.in2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_gewehr/in2.wav"
})
sound.Add({
name = "waw_gewehr.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_gewehr/pull.wav"
})
sound.Add({
name = "waw_gewehr.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_gewehr/deploy.wav"
})
--waw_kar98k---------------------------------------------------------------
sound.Add({
name = "waw_kar98k.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_kar98k/fire1.wav" // <-- Sound Path
})
sound.Add({
name = "waw_kar98k.Sniper", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_kar98k/sniper.wav" // <-- Sound Path
})
sound.Add({
name = "waw_kar98k.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_kar98k/pull.wav"
})
sound.Add({
name = "waw_kar98k.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_kar98k/in.wav"
})
sound.Add({
name = "waw_kar98k.release",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_kar98k/release.wav"
})
sound.Add({
name = "waw_kar98k.bolt",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_kar98k/bolt.wav"
})
sound.Add({
name = "waw_kar98k.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_kar98k/deploy.wav"
})
--waw_mg42_new---------------------------------------------------------------
sound.Add({
name = "waw_mg42_new.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_mg42_new/fire1.wav" // <-- Sound Path
})
sound.Add({
name = "waw_mg42_new.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mg42_new/out.wav"
})
sound.Add({
name = "waw_mg42_new.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mg42_new/in1.wav"
})
sound.Add({
name = "waw_mg42_new.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mg42_new/pull.wav"
})
sound.Add({
name = "waw_mg42_new.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mg42_new/deploy.wav"
})
--waw_mp40_new---------------------------------------------------------------
sound.Add({
name = "waw_mp40_new.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_mp40_new/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_mp40_new.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mp40_new/out.wav"
})
sound.Add({
name = "waw_mp40_new.in1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mp40_new/in1.wav"
})
sound.Add({
name = "waw_mp40_new.in2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mp40_new/in2.wav"
})
sound.Add({
name = "waw_mp40_new.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mp40_new/pull.wav"
})
sound.Add({
name = "waw_mp40_new.deploy1",
channel = CHAN_AUTO,
volume = 1.0,
sound = "weapons/waw_mp40_new/deploy1.wav"
})
sound.Add({
name = "waw_mp40_new.deploy2",
channel = CHAN_AUTO,
volume = 1.0,
sound = "weapons/waw_mp40_new/deploy2.wav"
})
--waw_stg44_new---------------------------------------------------------------
sound.Add({
name = "waw_stg44_new.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_stg44_new/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_stg44_new.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_stg44_new/out.wav"
})
sound.Add({
name = "waw_stg44_new.in1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_stg44_new/in1.wav"
})
sound.Add({
name = "waw_stg44_new.in2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_stg44_new/in2.wav"
})
sound.Add({
name = "waw_stg44_new.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_stg44_new/pull.wav"
})
sound.Add({
name = "waw_stg44_new.deploy2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_stg44_new/deploy2.wav"
})
--waw_type99_new---------------------------------------------------------------
sound.Add({
name = "waw_type99_new.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_type99_new/fire1.wav" // <-- Sound Path
})
sound.Add({
name = "waw_type99_new.out1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_type99_new/out1.wav"
})
sound.Add({
name = "waw_type99_new.out2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_type99_new/out2.wav"
})
sound.Add({
name = "waw_type99_new.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_type99_new/in.wav"
})
sound.Add({
name = "waw_type99_new.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_type99_new/pull.wav"
})
sound.Add({
name = "waw_type99_new.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_type99_new/deploy.wav"
})
--waw_type100_new---------------------------------------------------------------
sound.Add({
name = "waw_type100_new.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_type100_new/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_type100_new.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_type100_new/out.wav"
})
sound.Add({
name = "waw_type100_new.in1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_type100_new/in1.wav"
})
sound.Add({
name = "waw_type100_new.in2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_type100_new/in2.wav"
})
sound.Add({
name = "waw_type100_new.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_type100_new/pull.wav"
})
sound.Add({
name = "waw_type100_new.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_type100_new/deploy.wav"
})
--waw_type100_new---------------------------------------------------------------
sound.Add({
name = "waw_dp28_new.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_dp28_new/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_dp28_new.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_dp28_new/out.wav"
})
sound.Add({
name = "waw_dp28_new.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_dp28_new/in.wav"
})
sound.Add({
name = "waw_dp28_new.hit",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_dp28_new/hit.wav"
})
sound.Add({
name = "waw_dp28_new.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_dp28_new/pull.wav"
})
sound.Add({
name = "waw_dp28_new.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_dp28_new/deploy.wav"
})
--waw_mosin---------------------------------------------------------------
sound.Add({
name = "waw_mosin.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_mosin/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_mosin.Sniper", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_mosin/sniper1.wav" // <-- Sound Path
})
sound.Add({
name = "waw_mosin.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mosin/pull.wav"
})
sound.Add({
name = "waw_mosin.release",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mosin/release.wav"
})
sound.Add({
name = "waw_mosin.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mosin/in.wav"
})
sound.Add({
name = "waw_mosin.insert",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mosin/in.wav"
})
sound.Add({
name = "waw_mosin.deploy1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mosin/deploy1.wav"
})
sound.Add({
name = "waw_mosin.deploy2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mosin/deploy2.wav"
})
sound.Add({
name = "waw_mosin.insert",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_mosin/insert.wav"
})
--waw_ppsh_new---------------------------------------------------------------
sound.Add({
name = "waw_ppsh_new.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_ppsh_new/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_ppsh_new.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_ppsh_new/out.wav"
})
sound.Add({
name = "waw_ppsh_new.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_ppsh_new/in2.wav"
})
sound.Add({
name = "waw_ppsh_new.in1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_ppsh_new/in_e1.wav"
})
sound.Add({
name = "waw_ppsh_new.in2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_ppsh_new/in_e2.wav"
})
sound.Add({
name = "waw_ppsh_new.deploy1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_ppsh_new/deploy.wav"
})
sound.Add({
name = "waw_ppsh_new.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_ppsh_new/pull.wav"
})
--waw_ptrs_new---------------------------------------------------------------
sound.Add({
name = "waw_ptrs_new.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_ptrs_new/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_ptrs_new.open",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_ptrs_new/open.wav"
})
sound.Add({
name = "waw_ptrs_new.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_ptrs_new/in.wav"
})
sound.Add({
name = "waw_ptrs_new.close",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_ptrs_new/close.wav"
})
sound.Add({
name = "waw_ptrs_new.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_ptrs_new/pull.wav"
})
sound.Add({
name = "waw_ptrs_new.deploy1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_ptrs_new/deploy.wav"
})
--waw_svt---------------------------------------------------------------
sound.Add({
name = "waw_svt.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_svt/fire1.wav" // <-- Sound Path
})
sound.Add({
name = "waw_svt.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_svt/out.wav"
})
sound.Add({
name = "waw_svt.in1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_svt/in1.wav"
})
sound.Add({
name = "waw_svt.in2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_svt/in2.wav"
})
sound.Add({
name = "waw_svt.release",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_svt/release.wav"
})
sound.Add({
name = "waw_svt.deploy1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_svt/deploy1.wav"
})
sound.Add({
name = "waw_svt.deploy2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_svt/deploy2.wav"
})
--waw_tokarev---------------------------------------------------------------
sound.Add({
name = "waw_tokarev.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_tokarev/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_tokarev.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_tokarev/out.wav"
})
sound.Add({
name = "waw_tokarev.in1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_tokarev/in1.wav"
})
sound.Add({
name = "waw_tokarev.in2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_tokarev/in2.wav"
})
sound.Add({
name = "waw_tokarev.release",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_tokarev/release.wav"
})
sound.Add({
name = "waw_tokarev.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_tokarev/deploy.wav"
})
--waw_m1919---------------------------------------------------------------
sound.Add({
name = "waw_m1919.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_m1919/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_m1919.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_m1919/pull.wav"
})
sound.Add({
name = "waw_m1919.open",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_m1919/open.wav"
})
sound.Add({
name = "waw_m1919.removechain",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_m1919/removechain.wav"
})
sound.Add({
name = "waw_m1919.addchain",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_m1919/addchain.wav"
})
sound.Add({
name = "waw_m1919.close",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_m1919/close.wav"
})
sound.Add({
name = "waw_m1919.hit",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_m1919/hit.wav"
})
sound.Add({
name = "waw_m1919.chainmove",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_m1919/chainmove.wav"
})
sound.Add({
name = "waw_m1919.release",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_m1919/release.wav"
})
sound.Add({
name = "waw_m1919.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_m1919/deploy.wav"
})
--waw_bar---------------------------------------------------------------
sound.Add({
name = "waw_bar.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_bar/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_bar.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_bar/out.wav"
})
sound.Add({
name = "waw_bar.in1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_bar/in1.wav"
})
sound.Add({
name = "waw_bar.in2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_bar/in2.wav"
})
sound.Add({
name = "waw_bar.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_bar/pull.wav"
})
sound.Add({
name = "waw_bar.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_bar/deploy.wav"
})
--waw_1911---------------------------------------------------------------
sound.Add({
name = "waw_1911.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_1911/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_1911.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_1911/out.wav"
})
sound.Add({
name = "waw_1911.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_1911/in.wav"
})
sound.Add({
name = "waw_1911.release",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_1911/release.wav"
})
--waw_db_new---------------------------------------------------------------
sound.Add({
name = "waw_db_new.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_db_new/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_db_new.switch",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_db_new/switch.wav"
})
sound.Add({
name = "waw_db_new.open",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_db_new/open.wav"
})
sound.Add({
name = "waw_db_new.close",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_db_new/close.wav"
})
sound.Add({
name = "waw_db_new.tac_out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_db_new/tac_out.wav"
})
sound.Add({
name = "waw_db_new.tac_in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_db_new/tac_in.wav"
})
sound.Add({
name = "waw_db_new.empty_out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_db_new/empty_out.wav"
})
sound.Add({
name = "waw_db_new.empty_in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_db_new/empty_in.wav"
})
sound.Add({
name = "waw_db_new.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_db_new/deploy.wav"
})
--waw_carbine---------------------------------------------------------------
sound.Add({
name = "waw_carbine.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_carbine/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_carbine.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_carbine/out.wav"
})
sound.Add({
name = "waw_carbine.in1",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_carbine/in1.wav"
})
sound.Add({
name = "waw_carbine.in2",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_carbine/in2.wav"
})
sound.Add({
name = "waw_carbine.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_carbine/pull.wav"
})
sound.Add({
name = "waw_carbine.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_carbine/deploy.wav"
})
--waw_garand---------------------------------------------------------------
sound.Add({
name = "waw_garand.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_garand/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_garand.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_garand/out.wav"
})
sound.Add({
name = "waw_garand.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_garand/pull.wav"
})
sound.Add({
name = "waw_garand.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_garand/in.wav"
})
sound.Add({
name = "waw_garand.draw_and_insert",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_garand/draw_and_insert.wav"
})
sound.Add({
name = "waw_garand.ping",
channel = CHAN_AUTO,
volume = 1.0,
sound = "weapons/waw_garand/ping.wav"
})
sound.Add({
name = "waw_garand.deploy1",
channel = CHAN_AUTO,
volume = 1.0,
sound = "weapons/waw_garand/deploy1.wav"
})
sound.Add({
name = "waw_garand.deploy2",
channel = CHAN_AUTO,
volume = 1.0,
sound = "weapons/waw_garand/deploy2.wav"
})
--waw_springfield---------------------------------------------------------------
sound.Add({
name = "waw_springfield.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_springfield/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_springfield.Sniper", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_springfield/sniper.wav" // <-- Sound Path
})
sound.Add({
name = "waw_springfield.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_springfield/pull.wav"
})
sound.Add({
name = "waw_springfield.release",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_springfield/release.wav"
})
sound.Add({
name = "waw_springfield.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_springfield/deploy.wav"
})
sound.Add({
name = "waw_springfield.insert",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_springfield/insert.wav"
})
sound.Add({
name = "waw_springfield.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_springfield/in.wav"
})
--waw_tommy---------------------------------------------------------------
sound.Add({
name = "waw_tommy.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_tommy/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_tommy.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_tommy/out.wav"
})
sound.Add({
name = "waw_tommy.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_tommy/in.wav"
})
sound.Add({
name = "waw_tommy.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_tommy/pull.wav"
})
sound.Add({
name = "waw_tommy.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_tommy/deploy.wav"
})
--waw_trenchgun_new---------------------------------------------------------------
sound.Add({
name = "waw_trenchgun_new.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_trenchgun_new/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_trenchgun_new.pull",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_trenchgun_new/pull.wav"
})
sound.Add({
name = "waw_trenchgun_new.release",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_trenchgun_new/release.wav"
})
sound.Add({
name = "waw_trenchgun_new.insert",
channel = CHAN_ITEM,
volume = 1.0,
sound = {
"weapons/waw_trenchgun_new/insert1.wav",
"weapons/waw_trenchgun_new/insert2.wav"
}
})
sound.Add({
name = "waw_trenchgun_new.deploy",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_trenchgun_new/deploy.wav"
})
--waw_magnum---------------------------------------------------------------
sound.Add({
name = "waw_magnum.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_magnum/fire.wav" // <-- Sound Path
})
sound.Add({
name = "waw_magnum.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_magnum/out.wav"
})
sound.Add({
name = "waw_magnum.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_magnum/in.wav"
})
sound.Add({
name = "waw_magnum.close",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_magnum/close.wav"
})
sound.Add({
name = "waw_magnum.open",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_magnum/open.wav"
})
--waw_raygun---------------------------------------------------------------
sound.Add({
name = "waw_raygun.Single", // <-- Sound Name That gets called for
channel = CHAN_USER_BASE +10,
volume = 1.0,
sound = "weapons/waw_raygun/fire1.wav" // <-- Sound Path
})
sound.Add({
name = "waw_raygun.out",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_raygun/out.wav"
})
sound.Add({
name = "waw_raygun.in",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_raygun/in.wav"
})
sound.Add({
name = "waw_raygun.close",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_raygun/close.wav"
})
sound.Add({
name = "waw_raygun.open",
channel = CHAN_ITEM,
volume = 1.0,
sound = "weapons/waw_raygun/open.wav"
})
|
--
-- LEAKED BY S3NTEX --
-- https://discord.gg/aUDWCvM --
-- fivemleak.com --
-- fkn crew --
RegisterServerEvent("esx_uber:pay")
AddEventHandler("esx_uber:pay",function(a)
local b=source;
local c=ESX.GetPlayerFromId(b)
c.addMoney(tonumber(a))
end)
RegisterServerEvent("uber:esyaSil")
AddEventHandler("uber:esyaSil",function(a)
local b=source;
local c=ESX.GetPlayerFromId(b)
c.removeInventoryItem(a,1)
end)
|
--
-- ipctrace.lua
--
-- Write a trace of instantaneous IPC values for all cores.
-- Argument is either a filename, or none to write to standard output.
--
ncores = sim.config.ncores
if arg then
out = io.output(sim.config.output_dir..arg)
else
out = nil
end
function update_core_freq(core)
freqs[core] = sim.dvfs.get_frequency(core)
end
-- initial copy of all frequencies
freqs = {}
for core = 0, ncores-1 do
update_core_freq(core)
end
-- handle frequency updates
sim.hooks.register(sim.hooks.HOOK_CPUFREQ_CHANGE, update_core_freq)
-- only active during ROI
in_roi = false
sim.hooks.register(sim.hooks.HOOK_ROI_BEGIN, function() in_roi = true end)
sim.hooks.register(sim.hooks.HOOK_ROI_END, function() in_roi = false end)
-- state from previous iteration
prev_time = 0
prev_instrs = {}
function update_state(time)
prev_time = time
for core = 0, ncores-1 do
prev_instrs[core] = sim.stats.get("performance_model", core, "instruction_count")
end
end
-- at each iteration
sim.hooks.register(sim.hooks.HOOK_PERIODIC, function(time)
if in_roi then
if prev_time > 0 then
line = string.format('%.0f', time/1e6)
for core = 0, ncores-1 do
d_instrs = sim.stats.get("performance_model", core, "instruction_count") - prev_instrs[core]
d_time = time - prev_time
d_cycles = (d_time / 1e6) * freqs[core]
line = line..string.format(' %.3f', d_instrs / d_cycles)
end
if out then
out:write(line..'\n')
else
print(line)
end
end
update_state(time)
end
end)
|
local ecs = dtrequire("ecs")
local resource = dtrequire("resource")
local _, Component = ecs.common()
local cpml = dtrequire("lib.cpml")
local vec3, bound3 = cpml.vec3, cpml.bound3
local SpriteComponent = Component:subtype({},
"droptune.components.render.Sprite")
do
function SpriteComponent:init(res, ox, oy, sx, sy)
self.ox = ox or self.ox or 0
self.oy = oy or self.oy or 0
self.sx = sx or self.sx or 1
self.sy = sy or self.sy or 1
if res then
self.resource = res
self.image = resource.get(res)
end
end
function SpriteComponent:getLocalBoundingBox(bb)
local w, h = self.image:getDimensions()
local ox, oy = self.ox, self.oy
local sx, sy = self.sx, self.sy
local spritebb = bound3(vec3(-ox * sx, -oy * sy, 0), vec3((w - ox) * sx, (h - oy) * sy, 0))
if bb then
return bb:extend_bound(spritebb)
else
return spritebb
end
end
end
ecs.Serde[SpriteComponent] = {
serialize = function(self, v)
v("image", self.resource)
v("ox", self.ox, self.ox == 0)
v("oy", self.oy, self.oy == 0)
v("sx", self.sx, self.sx == 1)
v("sy", self.sy, self.sy == 1)
end,
deserialize = function(world)
return SpriteComponent:new()
end,
}
ecs.Visitor[SpriteComponent] = {
entry = function(self, k, v)
if k == "image" then
self:init(v)
elseif k == "ox" then
self.ox = v
elseif k == "oy" then
self.oy = v
elseif k == "sx" then
self.sx = v
elseif k == "sy" then
self.sy = v
else
error("bad key ", k)
end
end,
finish = function(self) return self end,
}
return SpriteComponent
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file proto.lua
--
-- imports
import("core.base.option")
import("private.utils.batchcmds")
import("module_parser")
import("lib.detect.find_tool")
-- get protoc
function _get_protoc(target)
local protoc = target:data("protobuf.protoc")
if not protoc then
protoc = find_tool("protoc")
if protoc then
target:data_set("protobuf.protoc", protoc)
end
end
-- get protoc
return assert(protoc, "protoc not found!")
end
function _get_grpc_cpp_plugin(target)
local grpc_cpp_plugin = target:data("grpc.grpc_cpp_plugin")
if not grpc_cpp_plugin then
grpc_cpp_plugin = find_tool("grpc_cpp_plugin", nil, true)
if grpc_cpp_plugin then
target:data_set("grpc.grpc_cpp_plugin", grpc_cpp_plugin)
end
end
return assert(grpc_cpp_plugin, "grpc_cpp_plugin not found!")
end
-- we need add some configs to export includedirs to other targets in on_load
-- @see https://github.com/xmake-io/xmake/issues/2256
function load(target)
-- get the first sourcefile
local sourcefile_proto
local sourcebatch = target:sourcebatches()["grpc.cpp"]
if sourcebatch then
sourcefile_proto = sourcebatch.sourcefiles[1]
end
if not sourcefile_proto then
return
end
-- get c/c++ source file for grpc
local prefixdir
local public
local fileconfig = target:fileconfig(sourcefile_proto)
if fileconfig then
public = fileconfig.proto_public
prefixdir = fileconfig.proto_rootdir
end
local rootdir = path.join(target:autogendir(), "rules", "grpc")
local filename = path.basename(sourcefile_proto) .. ".pb.cc"
local sourcefile_cx = target:autogenfile(sourcefile_proto, {rootdir = rootdir, filename = filename})
local sourcefile_dir = prefixdir and path.join(rootdir, prefixdir) or path.directory(sourcefile_cx)
-- add includedirs
target:add("includedirs", sourcefile_dir, {public = public})
end
import("core.project.depend")
function generate_grpc_files(target, opt)
local sourcebatch = target:sourcebatches()["grpc.cpp"]
-- get protoc
local protoc = _get_protoc(target)
local grpc_cpp_plugin = _get_grpc_cpp_plugin(target)
for _, sourcefile_proto in ipairs(sourcebatch.sourcefiles) do
local dependfile = target:dependfile(sourcefile_proto)
-- get c/c++ source file for grpc
local prefixdir
local public
local fileconfig = target:fileconfig(sourcefile_proto)
if fileconfig then
public = fileconfig.proto_public
prefixdir = fileconfig.proto_rootdir
end
local rootdir = path.join(target:autogendir(), "rules", "grpc")
local filename = path.basename(sourcefile_proto) .. ".pb.cc"
local filename2 = path.basename(sourcefile_proto) .. ".grpc.pb.cc"
local sourcefile_cx = target:autogenfile(sourcefile_proto, {rootdir = rootdir, filename = filename})
local sourcefile_cx2 = target:autogenfile(sourcefile_proto, {rootdir = rootdir, filename = filename2})
local sourcefile_dir = prefixdir and path.join(rootdir, prefixdir) or path.directory(sourcefile_cx)
depend.on_changed(function ()
os.mkdir(sourcefile_dir)
cprint("${cyan}compiling.proto ${clear}%s", sourcefile_proto)
os.vrunv(protoc.program, {sourcefile_proto,
"-I" .. (prefixdir and prefixdir or path.directory(sourcefile_proto)),
"-I" .. vformat("$(projectdir)/thirdparty/grpc/include"),
"--grpc_out=" .. sourcefile_dir,
"--plugin=protoc-gen-grpc=" .. grpc_cpp_plugin.program,
"--cpp_out=" .. sourcefile_dir})
end, {dependfile = dependfile, files = {sourcefile_proto}})
target:add("files", sourcefile_cx, sourcefile_cx2)
end
end
-- generate build commands
function buildcmd(target, batchcmds, sourcefile_proto, opt)
-- get protoc
local protoc = _get_protoc(target)
local grpc_cpp_plugin = _get_grpc_cpp_plugin(target)
-- get c/c++ source file for grpc
local prefixdir
local public
local fileconfig = target:fileconfig(sourcefile_proto)
if fileconfig then
public = fileconfig.proto_public
prefixdir = fileconfig.proto_rootdir
end
local rootdir = path.join(target:autogendir(), "rules", "grpc")
local filename = path.basename(sourcefile_proto) .. ".pb.cc"
local filename2 = path.basename(sourcefile_proto) .. ".grpc.pb.cc"
local sourcefile_cx = target:autogenfile(sourcefile_proto, {rootdir = rootdir, filename = filename})
local sourcefile_cx2 = target:autogenfile(sourcefile_proto, {rootdir = rootdir, filename = filename2})
local sourcefile_dir = prefixdir and path.join(rootdir, prefixdir) or path.directory(sourcefile_cx)
-- add includedirs
target:add("includedirs", sourcefile_dir, {public = public})
-- add objectfile
local objectfile = target:objectfile(sourcefile_cx)
local objectfile2 = target:objectfile(sourcefile_cx2)
table.insert(target:objectfiles(), objectfile)
table.insert(target:objectfiles(), objectfile2)
-- add commands
batchcmds:mkdir(sourcefile_dir)
batchcmds:show_progress(opt.progress, "${color.build.object}compiling.proto %s", sourcefile_proto)
batchcmds:vrunv(protoc.program, {sourcefile_proto,
"-I" .. (prefixdir and prefixdir or path.directory(sourcefile_proto)),
"-I" .. vformat("$(projectdir)/thirdparty/grpc/include"),
"--grpc_out=" .. sourcefile_dir,
"--plugin=protoc-gen-grpc=" .. grpc_cpp_plugin.program,
"--cpp_out=" .. sourcefile_dir})
batchcmds:compile(sourcefile_cx, objectfile, {configs = {includedirs = sourcefile_dir, languages = "c++11"}})
batchcmds:compile(sourcefile_cx2, objectfile2, {configs = {includedirs = sourcefile_dir, languages = "c++11"}})
-- add deps
batchcmds:add_depfiles(sourcefile_proto)
batchcmds:set_depmtime(os.mtime(objectfile))
batchcmds:set_depcache(target:dependfile(objectfile))
end
-- build batch jobs
function build_batchjobs(target, batchjobs, sourcebatch, opt)
-- get the root directory of grpc
local proto_rootdir
if #sourcebatch.sourcefiles > 0 then
local sourcefile = sourcebatch.sourcefiles[1]
local fileconfig = target:fileconfig(sourcefile)
if fileconfig then
proto_rootdir = fileconfig.proto_rootdir
end
end
-- load moduledeps
opt = opt or {}
local moduledeps, moduledeps_files = module_parser.load(target, sourcebatch, table.join(opt, {proto_rootdir = proto_rootdir}))
-- generate jobs
local sourcefiles_total = #sourcebatch.sourcefiles
for i = 1, sourcefiles_total do
local sourcefile = sourcebatch.sourcefiles[i]
local moduleinfo = moduledeps_files[sourcefile] or {}
-- make build job
moduleinfo.job = batchjobs:newjob(sourcefile, function (index, total)
local batchcmds_ = batchcmds.new({target = target})
buildcmd(target, batchcmds_, sourcefile, {progress = (index * 100) / total})
batchcmds_:runcmds({dryrun = option.get("dry-run")})
end)
end
-- build batchjobs
module_parser.build_batchjobs(moduledeps, batchjobs, opt.rootjob)
end
|
LANGUAGE = {
cmdItemSpawnerAdd = "Add a new item spawnpoint.",
cmdItemSpawnerRemove = "Removes an existant spawnpoint.",
cmdItemSpawnerList = "Displays a list of spawnpoints.",
cmdNoSpawnPoints = "There are no active spawnpoints.",
cmdRemoved = "The spawnpoint has been removed.",
cmdNoRemoved = "No spawnpoint with that name."
}
|
-- Copyright 2021 SmartThings
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local capabilities = require "st.capabilities"
--- @type st.zwave.CommandClass
local cc = require "st.zwave.CommandClass"
--- @type st.zwave.CommandClass.CentralScene
local CentralScene = (require "st.zwave.CommandClass.CentralScene")({ version=1 })
--- @type st.zwave.CommandClass.SceneActivation
local SceneActivation = (require "st.zwave.CommandClass.SceneActivation")({ version=1 })
local ZWAVE_MULTI_BUTTON_FINGERPRINTS = {
{mfr = 0x010F, prod = 0x1001, model = 0x1000}, -- Fibaro KeyFob EU
{mfr = 0x010F, prod = 0x1001, model = 0x2000}, -- Fibaro KeyFob US
{mfr = 0x010F, prod = 0x1001, model = 0x3000}, -- Fibaro KeyFob AU
{mfr = 0x0371, prod = 0x0002, model = 0x0003}, -- Aeotec NanoMote Quad EU
{mfr = 0x0371, prod = 0x0102, model = 0x0003}, -- Aeotec NanoMote Quad US
{mfr = 0x0086, prod = 0x0001, model = 0x0058}, -- Aeotec KeyFob EU
{mfr = 0x0086, prod = 0x0101, model = 0x0058}, -- Aeotec KeyFob US
{mfr = 0x0086, prod = 0x0002, model = 0x0082}, -- Aeotec Wallmote Quad EU
{mfr = 0x0086, prod = 0x0102, model = 0x0082}, -- Aeotec Wallmote Quad US
{mfr = 0x0312, prod = 0x0924, model = 0xD001}, -- Minoston Wallmote
{mfr = 0x0086, prod = 0x0002, model = 0x0081}, -- Aeotec Wallmote EU
{mfr = 0x0086, prod = 0x0102, model = 0x0081}, -- Aeotec Wallmote US
{mfr = 0x0060, prod = 0x000A, model = 0x0003}, -- Everspring Remote Control
{mfr = 0x0086, prod = 0x0001, model = 0x0003} -- Aeotec Mimimote
}
local function can_handle_zwave_multi_button(opts, driver, device, ...)
for _, fingerprint in ipairs(ZWAVE_MULTI_BUTTON_FINGERPRINTS) do
if device:id_match(fingerprint.mfr, fingerprint.prod, fingerprint.model) then
return true
end
end
return false
end
local map_key_attribute_to_capability = {
[CentralScene.key_attributes.KEY_PRESSED_1_TIME] = capabilities.button.button.pushed,
[CentralScene.key_attributes.KEY_RELEASED] = capabilities.button.button.held,
[CentralScene.key_attributes.KEY_HELD_DOWN] = capabilities.button.button.down_hold,
[CentralScene.key_attributes.KEY_PRESSED_2_TIMES] = capabilities.button.button.double,
[CentralScene.key_attributes.KEY_PRESSED_3_TIMES] = capabilities.button.button.pushed_3x,
[CentralScene.key_attributes.KEY_PRESSED_4_TIMES] = capabilities.button.button.pushed_4x,
[CentralScene.key_attributes.KEY_PRESSED_5_TIMES] = capabilities.button.button.pushed_5x
}
local function central_scene_notification_handler(self, device, cmd)
local event = map_key_attribute_to_capability[cmd.args.key_attributes]({state_change = true})
device:emit_event_for_endpoint(cmd.args.scene_number, event)
device:emit_event(event)
end
local function scene_activation_handler(self, device, cmd)
local scene_id = cmd.args.scene_id
local event = scene_id % 2 == 0 and capabilities.button.button.held or capabilities.button.button.pushed
device:emit_event_for_endpoint((scene_id + 1) // 2, event({state_change = true}))
device:emit_event(event({state_change = true}))
end
local function component_to_endpoint(device, component_id)
local ep_num = component_id:match("button(%d)")
return { ep_num and tonumber(ep_num) } or {}
end
local function endpoint_to_component(device, ep)
local button_comp = string.format("button%d", ep)
if device.profile.components[button_comp] ~= nil then
return button_comp
else
return "main"
end
end
local function device_init(self, device)
device:set_component_to_endpoint_fn(component_to_endpoint)
device:set_endpoint_to_component_fn(endpoint_to_component)
end
local zwave_multi_button = {
NAME = "Z-Wave multi button",
zwave_handlers = {
[cc.CENTRAL_SCENE] = {
[CentralScene.NOTIFICATION] = central_scene_notification_handler
},
[cc.SCENE_ACTIVATION] = {
[SceneActivation.SET] = scene_activation_handler
}
},
lifecycle_handlers = {
init = device_init
},
can_handle = can_handle_zwave_multi_button,
sub_drivers = {
require("zwave-multi-button/aeotec-keyfob"),
require("zwave-multi-button/fibaro-keyfob"),
require("zwave-multi-button/aeotec-minimote"),
require("zwave-multi-button/minoston-wallmote")
}
}
return zwave_multi_button
|
local function get_platform()
if package.config:sub(1, 1) == "\\" then
return "windows"
end
local pipe = assert(io.popen("uname -s"))
local out = pipe:read("*l")
pipe:close()
if out == "Darwin" then
return "mac"
else
return "linux" -- Probably.
end
end
return get_platform
|
local present, nvim_tree = pcall(require, "nvim-tree")
if present then
nvim_tree.setup({
view = {
auto_resize = false
},
filters = {
dotfiles = true
},
git = {
ignore = true
}
})
end
|
SPResearch=
{
{
Name = "ScoutEMPAbility",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch",
Cost = 750,
Time = 30,
DisplayedName = "$7519",
DisplayPriority = 2,
Description = "$7520",
UpgradeType = Ability,
TargetType = Ship,
TargetName = "Hgn_Scout",
UpgradeName = "SpecialAttack",
Icon = Icon_Emp,
ShortDisplayedName = "$7209",
},
{
Name = "AttackBomberImprovedBombs",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch",
Cost = 750,
Time = 25,
DisplayedName = "$7517",
DisplayPriority = 1,
Description = "$7518",
UpgradeType = Ability,
TargetType = Ship,
TargetName = "Hgn_AttackBomber",
UpgradeName = "UseSpecialWeaponsInNormalAttack",
Icon = Icon_Attack,
ShortDisplayedName = "$7208",
},
{
Name = "MovereliteAbility",
RequiredResearch = "DamageMoverTech",
RequiredSubSystems = "AdvancedResearch",
Cost = 500,
Time = 20,
DisplayedName = "$7948",
DisplayPriority = 2,
Description = "$7949",
UpgradeType = Ability,
TargetType = Ship,
TargetName = "hgn_Moverelite",
UpgradeName = "SpecialAttack",
Icon = Icon_Ability,
ShortDisplayedName = "$7950",
},
{
Name = "AssaultCorvetteImprovedWeapon",
RequiredResearch = "",
RequiredSubSystems = "Research & CorvetteProduction",
Cost = 750,
Time = 30,
DisplayedName = "$7728",
DisplayPriority = 0,
Description = "$7729",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_AssaultCorvette",
UpgradeName = "WeaponAccuracy",
UpgradeValue = 4,
Icon = Icon_Attack,
ShortDisplayedName = "$7728",
},
{
Name = "GraviticAttractionMines",
RequiredResearch = "",
RequiredSubSystems = "AdvancedResearch & CorvetteProduction",
Cost = 400,
Time = 20,
DisplayedName = "$7500",
DisplayPriority = 2,
Description = "$7501",
TargetName = "Hgn_MinelayerCorvette",
Icon = Icon_Tech,
ShortDisplayedName = "$7200",
},
{
Name = "DefenseFieldFrigateShield",
RequiredResearch = "",
RequiredSubSystems = "AdvancedResearch & FrigateProduction",
Cost = 750,
Time = 30,
DisplayedName = "$7521",
DisplayPriority = 32,
Description = "$7522",
TargetName = "Hgn_DefenseFieldFrigate",
Icon = Icon_shield,
ShortDisplayedName = "$7210",
},
{
Name = "DefenseFieldFrigateShield1",
RequiredResearch = "DefenseFieldFrigateShield",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7951",
DisplayPriority = 30,
Description = "$7952",
UpgradeType = Ability,
TargetType = Ship,
UpgradeName = "DefenseField",
TargetName = "hgn_marinefrigate",
Icon = Icon_shield,
ShortDisplayedName = "$7953",
},
{
Name = "DestroyerTech",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch & CapShipProduction",
Cost = 750,
Time = 45,
DisplayedName = "$7507",
DisplayPriority = 0,
Description = "$7508",
TargetName = "Hgn_Destroyer",
Icon = Icon_Tech,
ShortDisplayedName = "$7203",
},
{
Name = "BattlecruiserGunWeapons",
RequiredResearch = "DestroyerTech",
RequiredSubSystems = "AdvancedResearch & CapShipProduction",
Cost = 750,
Time = 40,
DisplayedName = "$7917",
DisplayPriority = 4,
Description = "$7918",
TargetName = "hgn_lightcruiser",
Icon = Icon_Tech,
ShortDisplayedName = "$1907",
},
{
Name = "BattlecruiserIonWeapons",
RequiredResearch = "",
RequiredSubSystems = "AdvancedResearch & CapShipProduction",
Cost = 900,
Time = 70,
DisplayedName = "$7504",
DisplayPriority = 2,
Description = "$7505",
TargetName = "Hgn_BattleCruiser",
Icon = Icon_Tech,
ShortDisplayedName = "$7202",
},
{
Name = "BattlecruiserIoneliteWeapons",
RequiredResearch = "DestroyerHealthUpgrade2 & DestroyerMAXSPEEDUpgrade2",
RequiredSubSystems = "AdvancedResearch & CapShipProduction",
Cost = 1250,
Time = 80,
DisplayedName = "$7926",
DisplayPriority = 3,
Description = "$7927",
TargetName = "Hgn_BattleCruiserelite",
Icon = Icon_Tech,
ShortDisplayedName = "$7924",
},
{
Name = "PlatformIonWeapons",
Required = "",
RequiredSubSystems = "Research | AdvancedResearch & PlatformProduction",
Cost = 300,
Time = 50,
DisplayedName = "$7502",
DisplayPriority = 24,
Description = "$7503",
TargetName = "Hgn_IonTurret",
Icon = Icon_Tech,
ShortDisplayedName = "$7201",
},
{
Name = "RadiationDefenseField",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch",
Cost = 250,
Time = 30,
DisplayedName = "$7905",
DisplayPriority = 30,
Description = "$7906",
UpgradeType = Ability,
TargetType = Ship,
UpgradeName = "DefenseFieldShield",
TargetName = "Hgn_DefenseFieldFrigate",
Icon = Icon_Tech,
ShortDisplayedName = "$7907",
},
{
Name = "SensDisProbe",
RequiredResearch = "",
RequiredSubSystems = "Research",
Cost = 250,
Time = 25,
DisplayedName = "$7650",
DisplayPriority = 5,
Description = "$7651",
TargetName = "Hgn_ProximitySensor",
Icon = Icon_Tech,
ShortDisplayedName = "$7214",
},
{
Name = "ECMProbe",
RequiredResearch = "",
RequiredSubSystems = "AdvancedResearch",
Cost = 250,
Time = 25,
DisplayedName = "$7509",
DisplayPriority = 4,
Description = "$7510",
TargetName = "Hgn_ECMProbe",
Icon = Icon_Tech,
ShortDisplayedName = "$7204",
},
{
Name = "DamageMoverTech",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch",
Cost = 500,
Time = 60,
DisplayedName = "$7900",
DisplayPriority = 29,
Description = "$7901",
TargetName = "Hgn_Mothership",
Icon = Icon_Tech,
ShortDisplayedName = "$7902",
},
{
Name = "AssaultCorvetteHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch & CorvetteProduction",
Cost = 500,
Time = 40,
DisplayedName = "$7555",
DisplayPriority = 200,
Description = "$7556",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_AssaultCorvette",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7237",
},
{
Name = "AssaultCorvetteHealthUpgrade2",
RequiredResearch = "AssaultCorvetteHealthUpgrade1",
RequiredSubSystems = "AdvancedResearch & CorvetteProduction",
Cost = 800,
Time = 50,
DisplayedName = "$7557",
DisplayPriority = 200,
Description = "$7558",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_AssaultCorvette",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7238",
},
{
Name = "AssaultCorvetteMAXSPEEDUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch & CorvetteProduction",
Cost = 300,
Time = 40,
DisplayedName = "$7559",
DisplayPriority = 203,
Description = "$7560",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_AssaultCorvette",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7237",
},
{
Name = "AssaultCorvetteMAXSPEEDUpgrade2",
RequiredResearch = "AssaultCorvetteMAXSPEEDUpgrade1",
RequiredSubSystems = "AdvancedResearch & CorvetteProduction",
Cost = 500,
Time = 50,
DisplayedName = "$7561",
DisplayPriority = 203,
Description = "$7562",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_AssaultCorvette",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.35,
Icon = Icon_Speed,
ShortDisplayedName = "$7238",
},
{
Name = "PulsarCorvetteHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch & CorvetteProduction",
Cost = 400,
Time = 40,
DisplayedName = "$7563",
DisplayPriority = 206,
Description = "$7564",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_PulsarCorvette",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7241",
},
{
Name = "PulsarCorvetteHealthUpgrade2",
RequiredResearch = "PulsarCorvetteHealthUpgrade1",
RequiredSubSystems = "AdvancedResearch & CorvetteProduction",
Cost = 750,
Time = 50,
DisplayedName = "$7565",
DisplayPriority = 206,
Description = "$7566",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_PulsarCorvette",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7242",
},
{
Name = "assaultcorvetteeliteHealthUpgrade1",
RequiredResearch = "PulsarCorvetteHealthUpgrade1",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7563",
DisplayPriority = 206,
Description = "$7564",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_assaultcorvetteelite",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.25,
Icon = Icon_Health,
ShortDisplayedName = "$7241",
},
{
Name = "assaultcorvetteeliteHealthUpgrade2",
RequiredResearch = "PulsarCorvetteHealthUpgrade2",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7565",
DisplayPriority = 206,
Description = "$7566",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_assaultcorvetteelite",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.5,
Icon = Icon_Health,
ShortDisplayedName = "$7242",
},
{
Name = "PulsarCorvetteMAXSPEEDUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch & CorvetteProduction",
Cost = 300,
Time = 40,
DisplayedName = "$7567",
DisplayPriority = 209,
Description = "$7568",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_PulsarCorvette",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7241",
},
{
Name = "PulsarCorvetteMAXSPEEDUpgrade2",
RequiredResearch = "PulsarCorvetteMAXSPEEDUpgrade1",
RequiredSubSystems = "AdvancedResearch & CorvetteProduction",
Cost = 500,
Time = 50,
DisplayedName = "$7569",
DisplayPriority = 209,
Description = "$7570",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_PulsarCorvette",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.35,
Icon = Icon_Speed,
ShortDisplayedName = "$7242",
},
{
Name = "TorpedoFrigateHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch & FrigateProduction",
Cost = 800,
Time = 60,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_TorpedoFrigate",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7244",
},
{
Name = "TorpedoFrigateHealthUpgrade2",
RequiredResearch = "TorpedoFrigateHealthUpgrade1",
RequiredSubSystems = "AdvancedResearch & FrigateProduction",
Cost = 1400,
Time = 75,
DisplayedName = "$7573",
DisplayPriority = 300,
Description = "$7574",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_TorpedoFrigate",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7245",
},
{
Name = "TorpedoFrigateMAXSPEEDUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch & FrigateProduction",
Cost = 500,
Time = 50,
DisplayedName = "$7575",
DisplayPriority = 303,
Description = "$7576",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_TorpedoFrigate",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7244",
},
{
Name = "TorpedoFrigateMAXSPEEDUpgrade2",
RequiredResearch = "TorpedoFrigateMAXSPEEDUpgrade1",
RequiredSubSystems = "AdvancedResearch & FrigateProduction",
Cost = 750,
Time = 70,
DisplayedName = "$7577",
DisplayPriority = 303,
Description = "$7578",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_TorpedoFrigate",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.35,
Icon = Icon_Speed,
ShortDisplayedName = "$7245",
},
{
Name = "AssaultFrigateHealthUpgrade1",
RequiredResearch = "InstaAdvancedFrigateTech",
RequiredSubSystems = "Research | AdvancedResearch & FrigateProduction",
Cost = 800,
Time = 60,
DisplayedName = "$7587",
DisplayPriority = 312,
Description = "$7588",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_AssaultFrigate",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7251",
},
{
Name = "AssaultFrigateHealthUpgrade2",
RequiredResearch = "AssaultFrigateHealthUpgrade1 & InstaAdvancedFrigateTech",
RequiredSubSystems = "AdvancedResearch & FrigateProduction",
Cost = 1400,
Time = 75,
DisplayedName = "$7589",
DisplayPriority = 312,
Description = "$7590",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_AssaultFrigate",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7252",
},
{
Name = "AssaultFrigateMAXSPEEDUpgrade1",
RequiredResearch = "InstaAdvancedFrigateTech",
RequiredSubSystems = "Research | AdvancedResearch & FrigateProduction",
Cost = 500,
Time = 50,
DisplayedName = "$7591",
DisplayPriority = 315,
Description = "$7592",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_AssaultFrigate",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7251",
},
{
Name = "AssaultFrigateMAXSPEEDUpgrade2",
RequiredResearch = "AssaultFrigateMAXSPEEDUpgrade1 & InstaAdvancedFrigateTech",
RequiredSubSystems = "AdvancedResearch & FrigateProduction",
Cost = 750,
Time = 70,
DisplayedName = "$7593",
DisplayPriority = 315,
Description = "$7594",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_AssaultFrigate",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.35,
Icon = Icon_Speed,
ShortDisplayedName = "$7252",
},
{
Name = "IonCannonFrigateHealthUpgrade1",
RequiredResearch = "InstaAdvancedFrigateTech",
RequiredSubSystems = "Research | AdvancedResearch & FrigateProduction",
Cost = 800,
Time = 60,
DisplayedName = "$7579",
DisplayPriority = 306,
Description = "$7580",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_IonCannonFrigate",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7247",
},
{
Name = "IonCannonFrigateHealthUpgrade2",
RequiredResearch = "IonCannonFrigateHealthUpgrade1 & InstaAdvancedFrigateTech",
RequiredSubSystems = "AdvancedResearch & FrigateProduction",
Cost = 1400,
Time = 75,
DisplayedName = "$7581",
DisplayPriority = 306,
Description = "$7582",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_IonCannonFrigate",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7248",
},
{
Name = "IonCannonFrigateMAXSPEEDUpgrade1",
RequiredResearch = "InstaAdvancedFrigateTech",
RequiredSubSystems = "Research | AdvancedResearch & FrigateProduction",
Cost = 500,
Time = 50,
DisplayedName = "$7583",
DisplayPriority = 309,
Description = "$7584",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_IonCannonFrigate",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7247",
},
{
Name = "IonCannonFrigateMAXSPEEDUpgrade2",
RequiredResearch = "IonCannonFrigateMAXSPEEDUpgrade1 & InstaAdvancedFrigateTech",
RequiredSubSystems = "AdvancedResearch & FrigateProduction",
Cost = 750,
Time = 70,
DisplayedName = "$7585",
DisplayPriority = 309,
Description = "$7586",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_IonCannonFrigate",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.35,
Icon = Icon_Speed,
ShortDisplayedName = "$7248",
},
{
Name = "MothershipHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch",
Cost = 500,
Time = 30,
DisplayedName = "$7523",
DisplayPriority = 41,
Description = "$7524",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_MotherShip",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.5,
Icon = Icon_Health,
ShortDisplayedName = "$7211",
},
{
Name = "MothershipHealthUpgrade2",
RequiredResearch = "MothershipHealthUpgrade1",
RequiredSubSystems = "AdvancedResearch",
Cost = 750,
Time = 40,
DisplayedName = "$7525",
DisplayPriority = 41,
Description = "$7526",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_MotherShip",
UpgradeName = "MAXHEALTH",
UpgradeValue = 2,
Icon = Icon_Health,
ShortDisplayedName = "$7212",
},
{
Name = "MothershipMAXSPEEDUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch",
Cost = 500,
Time = 30,
DisplayedName = "$7527",
DisplayPriority = 44,
Description = "$7528",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_MotherShip",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7211",
},
{
Name = "MothershipMAXSPEEDUpgrade2",
RequiredResearch = "MothershipMAXSPEEDUpgrade1",
RequiredSubSystems = "AdvancedResearch",
Cost = 750,
Time = 40,
DisplayedName = "$7529",
DisplayPriority = 44,
Description = "$7530",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_MotherShip",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.35,
Icon = Icon_Speed,
ShortDisplayedName = "$7212",
},
{
Name = "CarrierHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch & CapShipProduction",
Cost = 750,
Time = 40,
DisplayedName = "$7531",
DisplayPriority = 61,
Description = "$7532",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_Carrier",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7221",
},
{
Name = "CarrierHealthUpgrade2",
RequiredResearch = "CarrierHealthUpgrade1",
RequiredSubSystems = "AdvancedResearch & CapShipProduction",
Cost = 1000,
Time = 60,
DisplayedName = "$7533",
DisplayPriority = 61,
Description = "$7534",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_Carrier",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7222",
},
{
Name = "CarrierMAXSPEEDUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch & CapShipProduction",
Cost = 500,
Time = 30,
DisplayedName = "$7535",
DisplayPriority = 64,
Description = "$7536",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_Carrier",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7221",
},
{
Name = "CarrierMAXSPEEDUpgrade2",
RequiredResearch = "CarrierMAXSPEEDUpgrade1",
RequiredSubSystems = "AdvancedResearch & CapShipProduction",
Cost = 1000,
Time = 40,
DisplayedName = "$7537",
DisplayPriority = 64,
Description = "$7538",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_Carrier",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.35,
Icon = Icon_Speed,
ShortDisplayedName = "$7222",
},
{
Name = "DestroyerHealthUpgrade1",
RequiredResearch = "DestroyerTech",
RequiredSubSystems = "Research | AdvancedResearch & CapShipProduction",
Cost = 1000,
Time = 60,
DisplayedName = "$7639",
DisplayPriority = 405,
Description = "$7640",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_Destroyer",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
ShortDisplayedName = "$7274",
Icon = Icon_Health,
},
{
Name = "DestroyerHealthUpgrade2",
RequiredResearch = "DestroyerHealthUpgrade1",
RequiredSubSystems = "AdvancedResearch & CapShipProduction",
Cost = 1500,
Time = 75,
DisplayedName = "$7641",
DisplayPriority = 405,
Description = "$7642",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_Destroyer",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7275",
},
{
Name = "DestroyerMAXSPEEDUpgrade1",
RequiredResearch = "DestroyerTech",
RequiredSubSystems = "Research | AdvancedResearch & CapShipProduction",
Cost = 1000,
Time = 30,
DisplayedName = "$7643",
DisplayPriority = 406,
Description = "$7644",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_Destroyer",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7274",
},
{
Name = "DestroyerMAXSPEEDUpgrade2",
RequiredResearch = "DestroyerMAXSPEEDUpgrade1",
RequiredSubSystems = "AdvancedResearch & CapShipProduction",
Cost = 1500,
Time = 40,
DisplayedName = "$7645",
DisplayPriority = 406,
Description = "$7646",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_Destroyer",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.35,
Icon = Icon_Speed,
ShortDisplayedName = "$7275",
},
{
Name = "BattlecruiserHealthUpgrade1",
RequiredResearch = "BattlecruiserIonWeapons",
RequiredSubSystems = "Research | AdvancedResearch & CapShipProduction",
Cost = 2000,
Time = 60,
DisplayedName = "$7595",
DisplayPriority = 401,
Description = "$7596",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_BattleCruiser",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7254",
},
{
Name = "BattlecruiserHealthUpgrade2",
RequiredResearch = "BattlecruiserHealthUpgrade1",
RequiredSubSystems = "AdvancedResearch & CapShipProduction",
Cost = 3000,
Time = 75,
DisplayedName = "$7597",
DisplayPriority = 401,
Description = "$7598",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_BattleCruiser",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7255",
},
{
Name = "BattlecruiserMAXSPEEDUpgrade1",
RequiredResearch = "BattlecruiserIonWeapons",
RequiredSubSystems = "Research | AdvancedResearch & CapShipProduction",
Cost = 1000,
Time = 30,
DisplayedName = "$7599",
DisplayPriority = 404,
Description = "$7600",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_BattleCruiser",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7254",
},
{
Name = "BattlecruiserMAXSPEEDUpgrade2",
RequiredResearch = "BattlecruiserMAXSPEEDUpgrade1",
RequiredSubSystems = "AdvancedResearch & CapShipProduction",
Cost = 1500,
Time = 40,
DisplayedName = "$7601",
DisplayPriority = 404,
Description = "$7602",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_BattleCruiser",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.35,
Icon = Icon_Speed,
ShortDisplayedName = "$7255",
},
{
Name = "ShipyardHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch & Hyperspace",
Cost = 750,
Time = 30,
DisplayedName = "$7619",
DisplayPriority = 1200,
Description = "$7620",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_Shipyard",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7271",
},
{
Name = "ShipyardHealthUpgrade2",
RequiredResearch = "ShipyardHealthUpgrade1",
RequiredSubSystems = "AdvancedResearch & Hyperspace",
Cost = 1500,
Time = 40,
DisplayedName = "$7621",
DisplayPriority = 1200,
Description = "$7622",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_Shipyard",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7272",
},
{
Name = "ShipyardMAXSPEEDUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch & Hyperspace",
Cost = 500,
Time = 30,
DisplayedName = "$7623",
DisplayPriority = 1203,
Description = "$7624",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_Shipyard",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7271",
},
{
Name = "ShipyardMAXSPEEDUpgrade2",
RequiredResearch = "ShipyardMAXSPEEDUpgrade1",
RequiredSubSystems = "AdvancedResearch & Hyperspace",
Cost = 1500,
Time = 40,
DisplayedName = "$7625",
DisplayPriority = 1203,
Description = "$7626",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_Shipyard",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.35,
Icon = Icon_Speed,
ShortDisplayedName = "$7272",
},
{
Name = "GunTurretHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch",
Cost = 500,
Time = 30,
DisplayedName = "$7603",
DisplayPriority = 600,
Description = "$7604",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_GunTurret",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7257",
},
{
Name = "GunTurretHealthUpgrade2",
RequiredResearch = "GunTurretHealthUpgrade1",
RequiredSubSystems = "AdvancedResearch",
Cost = 800,
Time = 40,
DisplayedName = "$7605",
DisplayPriority = 600,
Description = "$7606",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_GunTurret",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7258",
},
{
Name = "IonTurretHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "AdvancedResearch",
Cost = 500,
Time = 30,
DisplayedName = "$7607",
DisplayPriority = 603,
Description = "$7608",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_IonTurret",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7261",
},
{
Name = "IonTurretHealthUpgrade2",
RequiredResearch = "IonTurretHealthUpgrade1",
RequiredSubSystems = "AdvancedResearch",
Cost = 800,
Time = 40,
DisplayedName = "$7609",
DisplayPriority = 603,
Description = "$7610",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_IonTurret",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7262",
},
{
Name = "ResourceCollectorHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch",
Cost = 400,
Time = 40,
DisplayedName = "$7611",
DisplayPriority = 701,
Description = "$7612",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_ResourceCollector",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.5,
Icon = Icon_Health,
ShortDisplayedName = "$7264",
},
{
Name = "ResourceCollectorHealthUpgrade2",
RequiredResearch = "ResourceCollectorHealthUpgrade1",
RequiredSubSystems = "AdvancedResearch",
Cost = 800,
Time = 60,
DisplayedName = "$7613",
DisplayPriority = 701,
Description = "$7614",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_ResourceCollector",
UpgradeName = "MAXHEALTH",
UpgradeValue = 2,
Icon = Icon_Health,
ShortDisplayedName = "$7265",
},
{
Name = "ResourceControllerHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research | AdvancedResearch",
Cost = 500,
Time = 30,
DisplayedName = "$7267",
DisplayPriority = 704,
Description = "$7616",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_ResourceController",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7267",
},
{
Name = "ResourceControllerHealthUpgrade2",
RequiredResearch = "ResourceControllerHealthUpgrade1",
RequiredSubSystems = "AdvancedResearch",
Cost = 1000,
Time = 40,
DisplayedName = "$7617",
DisplayPriority = 704,
Description = "$7618",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_ResourceController",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7268",
},
{
Name = "SensorsDowngrade1",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Sensors Downgrade1",
DisplayPriority = 1210,
Description = "",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_MotherShip",
UpgradeName = "PrimarySensorsRange",
UpgradeValue = 0.3,
},
{
Name = "SensorsDowngrade2",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Sensors Downgrade2",
DisplayPriority = 1211,
Description = "",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_MotherShip",
UpgradeName = "SecondarySensorsRange",
UpgradeValue = 0.3,
},
{
Name = "SensorsDowngrade3",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Sensors Downgrade3",
DisplayPriority = 1212,
Description = "",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_MotherShip",
UpgradeName = "VisualRange",
UpgradeValue = 0.3,
},
{
Name = "SensorsBackToNormal1",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "SensorsBackToNormal1",
DisplayPriority = 1213,
Description = "",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_MotherShip",
UpgradeName = "PrimarySensorsRange",
UpgradeValue = 1,
},
{
Name = "SensorsBackToNormal2",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "SensorsBackToNormal2",
DisplayPriority = 1214,
Description = "",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_MotherShip",
UpgradeName = "SecondarySensorsRange",
UpgradeValue = 1,
},
{
Name = "SensorsBackToNormal3",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "SensorsBackToNormal3",
DisplayPriority = 1215,
Description = "",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_MotherShip",
UpgradeName = "VisualRange",
UpgradeValue = 1,
},
{
Name = "AssaultCorvetteEliteWeaponUpgrade",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Elite Assault Corvette Weapon Upgrade",
DisplayPriority = 1204,
Description = "",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_AssaultCorvetteElite",
UpgradeName = "WeaponDamage",
UpgradeValue = 2,
},
{
Name = "AttackBomberEliteWeaponUpgrade",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Elite Attack Bomber Weapon Upgrade",
DisplayPriority = 1205,
Description = "",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Hgn_AttackBomberElite",
UpgradeName = "WeaponDamage",
UpgradeValue = 2,
},
{
Name = "MoverHealthUpgrade",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Mover health upgrade",
DisplayPriority = 41,
Description = "Upgrades Mover health",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_Mover",
UpgradeName = "MAXHEALTH",
UpgradeValue = 5,
},
{
Name = "MoverHealthDowngrade",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Mover health downgrade",
DisplayPriority = 41,
Description = "Downgrades Mover health",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_Mover",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1,
},
{
Name = "FrigateHealthUpgradeSPGAME",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 800,
Time = 60,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Frigate",
UpgradeName = "MAXHEALTH",
UpgradeValue = 2.5,
},
{
Name = "KeeperHealthUpgradeSPGAME_LOW",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_Destroyer",
UpgradeName = "MAXHEALTH",
UpgradeValue = 2.5,
},
{
Name = "KeeperHealthUpgradeSPGAME_MED",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_Destroyer",
UpgradeName = "MAXHEALTH",
UpgradeValue = 3.5,
},
{
Name = "KeeperHealthUpgradeSPGAME_HIGH",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_Destroyer",
UpgradeName = "MAXHEALTH",
UpgradeValue = 4.5,
},
{
Name = "KeeperWeaponUpgradeSPGAME_M10_LVL_1",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_DestroyerM10",
UpgradeName = "WeaponDamage",
UpgradeValue = 0.1,
},
{
Name = "KeeperWeaponUpgradeSPGAME_M10_LVL_2",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_DestroyerM10",
UpgradeName = "WeaponDamage",
UpgradeValue = 0.2,
},
{
Name = "KeeperWeaponUpgradeSPGAME_M10_LVL_3",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_DestroyerM10",
UpgradeName = "WeaponDamage",
UpgradeValue = 0.3,
},
{
Name = "KeeperWeaponUpgradeSPGAME_M10_LVL_4",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_DestroyerM10",
UpgradeName = "WeaponDamage",
UpgradeValue = 0.4,
},
{
Name = "KeeperWeaponUpgradeSPGAME_M10_LVL_5",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_DestroyerM10",
UpgradeName = "WeaponDamage",
UpgradeValue = 0.5,
},
{
Name = "KeeperWeaponUpgradeSPGAME_M10_LVL_6",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_DestroyerM10",
UpgradeName = "WeaponDamage",
UpgradeValue = 0.6,
},
{
Name = "KeeperHealthUpgradeSPGAME_M10_LVL_1",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_DestroyerM10",
UpgradeName = "MAXHEALTH",
UpgradeValue = 2,
},
{
Name = "KeeperHealthUpgradeSPGAME_M10_LVL_2",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_DestroyerM10",
UpgradeName = "MAXHEALTH",
UpgradeValue = 3,
},
{
Name = "KeeperHealthUpgradeSPGAME_M10_LVL_3",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_DestroyerM10",
UpgradeName = "MAXHEALTH",
UpgradeValue = 4,
},
{
Name = "AttackDroidHealthUpgradeSPGAME_LOW",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_AttackDroid",
UpgradeName = "MAXHEALTH",
UpgradeValue = 2,
},
{
Name = "AttackDroidHealthUpgradeSPGAME_MED",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_AttackDroid",
UpgradeName = "MAXHEALTH",
UpgradeValue = 3,
},
{
Name = "AttackDroidHealthUpgradeSPGAME_HIGH",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_AttackDroid",
UpgradeName = "MAXHEALTH",
UpgradeValue = 4,
},
{
Name = "AttackDroidWeaponUpgradeSPGAME_LOW",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_AttackDroid",
UpgradeName = "WeaponDamage",
UpgradeValue = 1.3,
},
{
Name = "AttackDroidWeaponUpgradeSPGAME_MED",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_AttackDroid",
UpgradeName = "WeaponDamage",
UpgradeValue = 1.6,
},
{
Name = "AttackDroidWeaponUpgradeSPGAME_HIGH",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7571",
DisplayPriority = 300,
Description = "$7572",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Kpr_AttackDroid",
UpgradeName = "WeaponDamage",
UpgradeValue = 2,
},
{
Name = "attackdroideliteWeapons",
RequiredResearch = "TorpedoFrigateHealthUpgrade2 & TorpedoFrigateMAXSPEEDUpgrade2",
RequiredSubSystems = "AdvancedResearch & FighterProduction",
Cost = 1500,
Time = 80,
DisplayedName = "$7955",
DisplayPriority = 520,
Description = "$7956",
TargetType = Ship,
TargetName = "hgn_attackdroidelite",
Icon = Icon_Tech,
ShortDisplayedName = "$1708",
},
{
Name = "AttackDroidHealthUpgrade1",
RequiredResearch = "attackdroideliteWeapons",
RequiredSubSystems = "AdvancedResearch",
Cost = 1000,
Time = 60,
DisplayedName = "$7957",
DisplayPriority = 521,
Description = "$7958",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_attackdroidelite",
UpgradeName = "MAXHEALTH",
UpgradeValue = 2,
Icon = Icon_Health,
ShortDisplayedName = "$7959",
},
{
Name = "AttackDroidHealthUpgrade2",
RequiredResearch = "AttackDroidHealthUpgrade1 & DestroyerHealthUpgrade2 & DestroyerMAXSPEEDUpgrade2",
RequiredSubSystems = "AdvancedResearch",
Cost = 2000,
Time = 80,
DisplayedName = "$7960",
DisplayPriority = 525,
Description = "$7961",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_attackdroidelite",
UpgradeName = "MAXHEALTH",
UpgradeValue = 3,
Icon = Icon_Health,
ShortDisplayedName = "$7962",
},
{
Name = "AttackDroidHealthUpgrade3",
RequiredResearch = "AttackDroidHealthUpgrade2 & BattlecruiserHealthUpgrade2 & BattlecruiserMAXSPEEDUpgrade2",
RequiredSubSystems = "AdvancedResearch",
Cost = 3000,
Time = 100,
DisplayedName = "$7963",
DisplayPriority = 529,
Description = "$7964",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_attackdroidelite",
UpgradeName = "MAXHEALTH",
UpgradeValue = 4.5,
Icon = Icon_Health,
ShortDisplayedName = "$7965",
},
{
Name = "AttackDroidWeaponUpgrade1",
RequiredResearch = "attackdroideliteWeapons",
RequiredSubSystems = "AdvancedResearch",
Cost = 1000,
Time = 60,
DisplayedName = "$7966",
DisplayPriority = 1,
Description = "$7967",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_attackdroidelite",
UpgradeName = "WeaponDamage",
UpgradeValue = 1.5,
Icon = Icon_Attack,
ShortDisplayedName = "$7959",
},
{
Name = "AttackDroidWeaponUpgrade2",
RequiredResearch = "AttackDroidWeaponUpgrade1 & DestroyerHealthUpgrade2 & DestroyerMAXSPEEDUpgrade2",
RequiredSubSystems = "AdvancedResearch",
Cost = 2000,
Time = 80,
DisplayedName = "$7968",
DisplayPriority = 1,
Description = "$7969",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_attackdroidelite",
UpgradeName = "WeaponDamage",
UpgradeValue = 2,
Icon = Icon_Attack,
ShortDisplayedName = "$7962",
},
{
Name = "AttackDroidWeaponUpgrade3",
RequiredResearch = "AttackDroidWeaponUpgrade2 & BattlecruiserHealthUpgrade2 & BattlecruiserMAXSPEEDUpgrade2",
RequiredSubSystems = "AdvancedResearch",
Cost = 3000,
Time = 100,
DisplayedName = "$7970",
DisplayPriority = 1,
Description = "$7971",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_attackdroidelite",
UpgradeName = "WeaponDamage",
UpgradeValue = 2.5,
Icon = Icon_Attack,
ShortDisplayedName = "$7965",
},
{
Name = "AttackDroidMAXSPEEDUpgrade1",
RequiredResearch = "attackdroideliteWeapons",
RequiredSubSystems = "AdvancedResearch",
Cost = 600,
Time = 40,
DisplayedName = "$7972",
DisplayPriority = 542,
Description = "$7973",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_attackdroidelite",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.32,
Icon = Icon_Speed,
ShortDisplayedName = "$7959",
},
{
Name = "AttackDroidMAXSPEEDUpgrade2",
RequiredResearch = "AttackDroidMAXSPEEDUpgrade1 & DestroyerHealthUpgrade2 & DestroyerMAXSPEEDUpgrade2",
RequiredSubSystems = "AdvancedResearch",
Cost = 1000,
Time = 60,
DisplayedName = "$7974",
DisplayPriority = 545,
Description = "$7975",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_attackdroidelite",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.52,
Icon = Icon_Speed,
ShortDisplayedName = "$7962",
},
{
Name = "ShipyardelohimHealthUpgrade1",
RequiredResearch = "ShipyardHealthUpgrade1",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7619",
DisplayPriority = 1200,
Description = "$7620",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_shipyard_elohim",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7271",
},
{
Name = "ShipyardelohimHealthUpgrade2",
RequiredResearch = "ShipyardHealthUpgrade2",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7621",
DisplayPriority = 1200,
Description = "$7622",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_shipyard_elohim",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7272",
},
{
Name = "ShipyardelohimMAXSPEEDUpgrade1",
RequiredResearch = "ShipyardHealthUpgrade1",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7623",
DisplayPriority = 1203,
Description = "$7624",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_shipyard_elohim",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7271",
},
{
Name = "ShipyardelohimMAXSPEEDUpgrade2",
RequiredResearch = "ShipyardHealthUpgrade2",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7625",
DisplayPriority = 1203,
Description = "$7626",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_shipyard_elohim",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.35,
Icon = Icon_Speed,
ShortDisplayedName = "$7272",
},
{
Name = "ShipyardspgHealthUpgrade1",
RequiredResearch = "ShipyardHealthUpgrade",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7619",
DisplayPriority = 1200,
Description = "$7620",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_shipyard_spg",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7271",
},
{
Name = "ShipyardspgHealthUpgrade2",
RequiredResearch = "ShipyardHealthUpgrade2",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7621",
DisplayPriority = 1200,
Description = "$7622",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_shipyard_spg",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7272",
},
{
Name = "ShipyardspgMAXSPEEDUpgrade1",
RequiredResearch = "ShipyardHealthUpgrade1",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7623",
DisplayPriority = 1203,
Description = "$7624",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_shipyard_spg",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7271",
},
{
Name = "ShipyardspgMAXSPEEDUpgrade2",
RequiredResearch = "ShipyardHealthUpgrade2",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "$7625",
DisplayPriority = 1203,
Description = "$7626",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "hgn_shipyard_spg",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.35,
Icon = Icon_Speed,
ShortDisplayedName = "$7272",
},
}
local i=1
while (research[i]) do
i=i+1
end
for index,item in SPResearch do
research[i]=item
i=i+1
end
|
cc = cc or {}
---Lens3D object
---@class Lens3D : Grid3DAction
local Lens3D = {}
cc.Lens3D = Lens3D
--------------------------------
---brief Set whether lens is concave.<br>
---param concave Whether lens is concave.
---@param concave bool
---@return Lens3D
function Lens3D:setConcave(concave) end
--------------------------------
---brief Initializes the action with center position, radius, grid size and duration.<br>
---param duration Specify the duration of the Lens3D action. It's a value in seconds.<br>
---param gridSize Specify the size of the grid.<br>
---param position Specify the center position of the lens effect.<br>
---param radius Specify the radius of the lens effect.<br>
---return If the initialization success, return true; otherwise, return false.
---@param duration float
---@param gridSize size_table
---@param position vec2_table
---@param radius float
---@return bool
function Lens3D:initWithDuration(duration, gridSize, position, radius) end
--------------------------------
---brief Set the value of lens effect.<br>
---param lensEffect The value of lens effect will be set.
---@param lensEffect float
---@return Lens3D
function Lens3D:setLensEffect(lensEffect) end
--------------------------------
---brief Get the value of lens effect. Default value is 0.7.<br>
---return The value of lens effect.
---@return float
function Lens3D:getLensEffect() end
--------------------------------
---brief Set the center position of lens effect.<br>
---param position The center position will be set.
---@param position vec2_table
---@return Lens3D
function Lens3D:setPosition(position) end
--------------------------------
---brief Get the center position of lens effect.<br>
---return The center position of lens effect.
---@return vec2_table
function Lens3D:getPosition() end
--------------------------------
---brief Create the action with center position, radius, a grid size and duration.<br>
---param duration Specify the duration of the Lens3D action. It's a value in seconds.<br>
---param gridSize Specify the size of the grid.<br>
---param position Specify the center position of the lens.<br>
---param radius Specify the radius of the lens.<br>
---return If the creation success, return a pointer of Lens3D action; otherwise, return nil.
---@param duration float
---@param gridSize size_table
---@param position vec2_table
---@param radius float
---@return Lens3D
function Lens3D:create(duration, gridSize, position, radius) end
--------------------------------
--
---@return Lens3D
function Lens3D:clone() end
--------------------------------
--
---@param time float
---@return Lens3D
function Lens3D:update(time) end
--------------------------------
--
---@return Lens3D
function Lens3D:Lens3D() end
return Lens3D
|
--[[
Name: "cl_hooks.lua".
Product: "nexus".
--]]
local MOUNT = MOUNT;
-- Called when a HUD element should be drawn.
function MOUNT:HUDShouldDraw(name)
if (name == "CHudWeaponSelection") then
return false;
elseif (name == "CHudCrosshair") then
if (self.displayAlpha > 0) then
return false;
end;
end;
end;
-- Called when the important HUD should be painted.
function MOUNT:HUDPaintImportant()
local informationColor = nexus.schema.GetColor("information");
local activeWeapon = g_LocalPlayer:GetActiveWeapon();
local newWeapons = {};
local colorWhite = nexus.schema.GetColor("white");
local frameTime = FrameTime();
local weapons = g_LocalPlayer:GetWeapons();
local curTime = UnPredictedCurTime();
local x = ScrW() / 3;
local y = ScrH() / 3;
if (IsValid(activeWeapon) and self.displayAlpha > 0) then
NEXUS:OverrideMainFont( nexus.schema.GetFont("menu_text_tiny") );
for k, v in pairs(weapons) do
local secondaryAmmo = g_LocalPlayer:GetAmmoCount( v:GetSecondaryAmmoType() );
local primaryAmmo = g_LocalPlayer:GetAmmoCount( v:GetPrimaryAmmoType() );
local clipOne = v:Clip1();
local clipTwo = v:Clip2();
if ( clipOne > 0 or clipTwo > 0 or (clipOne == -1 and clipTwo == -1)
or (clipOne == -1 and clipTwo > 0 and secondaryAmmo > 0)
or (clipTwo == -1 and clipOne > 0 and primaryAmmo > 0)
or (clipOne != -1 and primaryAmmo > 0)
or (clipTwo != -1 and secondaryAmmo > 0) ) then
table.insert(newWeapons, v);
end;
end;
if (self.displaySlot < 1) then
self.displaySlot = #newWeapons;
elseif (self.displaySlot > #newWeapons) then
self.displaySlot = 1;
end;
local currentWeapon = newWeapons[self.displaySlot];
local beforeWeapons = {};
local afterWeapons = {};
local weaponLimit = math.Clamp(#newWeapons, 2, 4);
if (#newWeapons > 1) then
for k, v in ipairs(newWeapons) do
if (k < self.displaySlot) then
table.insert(beforeWeapons, v);
elseif (k > self.displaySlot) then
table.insert(afterWeapons, v);
end;
end;
if (#beforeWeapons < weaponLimit) then
local i = 0;
while (#beforeWeapons < weaponLimit) do
local possibleWeapon = newWeapons[#newWeapons - i];
if (possibleWeapon) then
table.insert(beforeWeapons, 1, possibleWeapon);
i = i + 1;
else
i = 0;
end;
end;
end;
if (#afterWeapons < weaponLimit) then
local i = 0;
while (#afterWeapons < weaponLimit) do
local possibleWeapon = newWeapons[1 + i];
if (possibleWeapon) then
table.insert(afterWeapons, possibleWeapon);
i = i + 1;
else
i = 0;
end;
end;
end;
while (#beforeWeapons > weaponLimit) do
table.remove(beforeWeapons, 1);
end;
while (#afterWeapons > weaponLimit) do
table.remove(afterWeapons, #afterWeapons);
end;
for k, v in ipairs(beforeWeapons) do
y = NEXUS:DrawInfo(string.upper( self:GetWeaponPrintName(v) ), x, y, colorWhite, math.min( (255 / weaponLimit) * k, self.displayAlpha ), true);
end;
end;
if ( IsValid(currentWeapon) ) then
local currentWeaponName = string.upper( self:GetWeaponPrintName(currentWeapon) );
local weaponInfoY = y;
local weaponInfoX = x - 276;
y = NEXUS:DrawInfo(currentWeaponName, x, y, informationColor, self.displayAlpha, true);
NEXUS:OverrideMainFont(false);
self:DrawWeaponInformation(nexus.item.GetWeapon(currentWeapon), currentWeapon, weaponInfoX, weaponInfoY, self.displayAlpha);
if (#newWeapons == 1) then
y = NEXUS:DrawInfo("There are no other weapons.", x, y, colorWhite, self.displayAlpha, true);
end;
NEXUS:OverrideMainFont( nexus.schema.GetFont("menu_text_tiny") );
end;
if (#newWeapons > 1) then
for k, v in ipairs(afterWeapons) do
y = NEXUS:DrawInfo(string.upper( self:GetWeaponPrintName(v) ), x, y, colorWhite, math.min( 255 - ( (255 / weaponLimit) * k ), self.displayAlpha ), true);
end;
end;
NEXUS:OverrideMainFont(false);
end;
if (self.displayAlpha > 0 and curTime >= self.displayFade) then
self.displayAlpha = math.max(self.displayAlpha - (frameTime * 64), 0);
end;
end;
-- Called when a player presses a bind at the top level.
function MOUNT:TopLevelPlayerBindPress(player, bind, press)
local activeWeapon = g_LocalPlayer:GetActiveWeapon();
local newWeapons = {};
local curTime = UnPredictedCurTime();
local weapons = g_LocalPlayer:GetWeapons();
if ( !IsValid(activeWeapon) ) then
return;
end;
if ( g_LocalPlayer:InVehicle() ) then
return;
end;
if (activeWeapon:GetClass() == "weapon_physgun") then
if ( player:KeyDown(IN_ATTACK) ) then
return;
end;
end;
for k, v in pairs(weapons) do
local secondaryAmmo = g_LocalPlayer:GetAmmoCount( v:GetSecondaryAmmoType() );
local primaryAmmo = g_LocalPlayer:GetAmmoCount( v:GetPrimaryAmmoType() );
local clipOne = v:Clip1();
local clipTwo = v:Clip2();
if ( clipOne > 0 or clipTwo > 0 or (clipOne == -1 and clipTwo == -1)
or (clipOne == -1 and clipTwo > 0 and secondaryAmmo > 0)
or (clipTwo == -1 and clipOne > 0 and primaryAmmo > 0)
or (clipOne != -1 and primaryAmmo > 0)
or (clipTwo != -1 and secondaryAmmo > 0) ) then
table.insert(newWeapons, v);
end;
end;
if ( string.find(bind, "invnext") or string.find(bind, "slot2") ) then
if (curTime >= self.displayDelay and !press) then
if (#newWeapons > 1) then
surface.PlaySound("common/talk.wav");
end;
self.displayDelay = curTime + 0.05;
self.displayAlpha = 255;
self.displayFade = curTime + 2;
self.displaySlot = self.displaySlot + 1;
if (self.displaySlot > #newWeapons) then
self.displaySlot = 1;
end;
end;
return true;
elseif ( string.find(bind, "invprev") or string.find(bind, "slot1") ) then
if (curTime >= self.displayDelay and !press) then
if (#newWeapons > 1) then
surface.PlaySound("common/talk.wav");
end;
self.displayDelay = curTime + 0.05;
self.displayAlpha = 255;
self.displayFade = curTime + 2;
self.displaySlot = self.displaySlot - 1;
if (self.displaySlot < 1) then
self.displaySlot = #newWeapons;
end;
end;
return true;
elseif ( string.find(bind, "+attack") ) then
if (#newWeapons > 1) then
if ( self.displayAlpha >= 128 and IsValid( newWeapons[self.displaySlot] ) ) then
NEXUS:StartDataStream( "SelectWeapon", newWeapons[self.displaySlot]:GetClass() );
surface.PlaySound("ui/buttonclickrelease.wav");
self.displayAlpha = 0;
return true
end;
end;
end;
end;
|
require("turtle")
local chartmap = require("chartmap")
local colormap = require("colormap")
local complex = require("complex")
local common = require("common")
local signals = require("signals")
local W, H = 800, 800
local greyLevel = 200
local minX, maxX = -20, 20
local minY, maxY = -20, 20
local dX, dY, xySize = 1, 1, 3
local clBlu = colr(colormap.getColorBlueRGB())
local clRed = colr(colormap.getColorRedRGB())
local clBlk = colr(colormap.getColorBlackRGB())
local clGry = colr(colormap.getColorPadRGB(greyLevel))
local clMgn = colr(colormap.getColorMagenRGB())
local clGrn = colr(colormap.getColorGreenRGB())
local clCya = colr(colormap.getColorCyanRGB())
local intX = chartmap.New("interval","WinX", minX, maxX, 0, W)
local intY = chartmap.New("interval","WinY", minY, maxY, H, 0)
local scOpe = chartmap.New("scope"):setBorder(minX, maxX, minY, maxY)
scOpe:setSize(W, H):setColor(clBlk, clGry):setInterval(intX, intY):setDelta(dX, dY)
local c1 = complex.getNew(-15,-15)
local c2 = complex.getNew( -5, 5)
local c3 = complex.getNew( -1, 8)
local c4 = complex.getNew( 1, -8)
local c5 = complex.getNew( 5, -5)
local c6 = complex.getNew( 15, 15)
-- These calls produce the same curve for interpolation length <n-samples> and power <alpha>
-- The key <kK> can be any of these {"n","N","cnt","CNT","count", "","*"}
-- The default curve interpolation sample count is 100
-- The default curve power interpolation coefficient <alpha> is 0.5
-- local tC = complex.getCatmullRomCurve( p1, p2, ..., pn) < Uses the default interpolation length and power
-- local tC = complex.getCatmullRomCurve( p1, p2, ..., pn, n-samples) < Uses the default power
-- local tC = complex.getCatmullRomCurve( p1, p2, ..., pn, n-samples, alpha)
-- local tC = complex.getCatmullRomCurve({p1, p2, ..., pn}, n-samples, alpha)
-- local tC = complex.getCatmullRomCurve({p1, p2, ..., pn,[kK]=n-samples}, alpha)
-- local tC = complex.getCatmullRomCurve({p1, p2, ..., pn,["banana"]=7}, n-samples, alpha)
local tc = {c1,c2,c3,c4,c5,c6}
local tC = complex.getCatmullRomCurve(tc,15,0.1)
if(tC) then
open("Complex Catmull Rom curve demo")
size(W, H)
zero(0, 0)
updt(false) -- disable auto updates
scOpe:Draw(true, true, true):setSizeVtx(5)
for i = 1, #tc do
scOpe:drawComplexText(tc[i], " {"..i.."}", true)
scOpe:drawComplexPoint(tc[i], clMgn)
end
scOpe:setSizeVtx(2)
for i = 1, (#tC-1) do
scOpe:drawComplexLine(tC[i+1],tC[i])
updt(); wait(0.02)
end
wait()
end
|
require 'depstruct'
require 'utils'
require 'dict'
require 'xlua'
require 'dp_spec'
p = xlua.Profiler()
Depparser = {}
Depparser_mt = { __index = Depparser }
function Depparser:new(voca_dic, pos_dic, deprel_dic)
local parser = { voca_dic = voca_dic, pos_dic = pos_dic, deprel_dic = deprel_dic}
parser.punc_list = {
--[voca_dic.word2id['=']] = 1,
[voca_dic.word2id['-']] = 1,
[voca_dic.word2id['--']] = 1,
[voca_dic.word2id[',']] = 1,
[voca_dic.word2id[';']] = 1,
[voca_dic.word2id[':']] = 1,
[voca_dic.word2id['!']] = 1,
[voca_dic.word2id['?']] = 1,
--[voca_dic.word2id['/']] = 1,
[voca_dic.word2id['.']] = 1,
[voca_dic.word2id['...']] = 1,
[voca_dic.word2id["'"]] = 1,
[voca_dic.word2id["''"]] = 1,
[voca_dic.word2id['(']] = 1,
[voca_dic.word2id[')']] = 1,
[voca_dic.word2id['{']] = 1,
[voca_dic.word2id['}']] = 1,
--[voca_dic.word2id['@']] = 1,
[voca_dic.word2id['*']] = 1,
--[voca_dic.word2id['\\*']] = 1,
--[voca_dic.word2id['\\*\\*']] = 1,
[voca_dic.word2id['&']] = 1,
[voca_dic.word2id['#']] = 1,
[voca_dic.word2id['%']] = 1,
}
setmetatable(parser, Depparser_mt)
return parser
end
function Depparser:load_dsbank(path)
local dsbank = {}
local raw = {}
tokens = {}
local i = 1
for line in io.lines(path) do
--print(line)
line = trim_string(line)
if line == '' then
local status, err = pcall( function()
ds,sent = Depstruct:create_from_strings(tokens,
self.voca_dic, self.pos_dic, self.deprel_dic)
end )
if status then
dsbank[#dsbank+1] = ds
raw[#raw+1] = sent
else
print(err)
end
tokens = {}
if math.mod(i,100) == 0 then io.write(i..' trees \r'); io.flush() end
i = i + 1
else
tokens[#tokens+1] = line
end
end
dsbank.raw = raw
return dsbank, raw
end
function Depparser:load_kbestdsbank(path, golddsbank)
local dsbank, raw = self:load_dsbank(path)
local kbestdsbank = {}
local group = nil
for i,ds in ipairs(dsbank) do
if group == nil or group[1].n_words ~= ds.n_words or (group[1].word - ds.word):abs():sum() > 0 then
group = { ds , raw = {raw[i]} }
kbestdsbank[#kbestdsbank+1] = group
else
group[#group+1] = ds
group.raw[#group] = raw[i]
end
end
for i,group in ipairs(kbestdsbank) do
local goldds = golddsbank[i]
for _,ds in ipairs(group) do
if ds.n_words ~= goldds.n_words then
print(#group)
print(#kbestdsbank)
print(ds.n_words)
print(goldds.n_words)
error("not match")
end
ds.word = goldds.word:clone()
ds.cap = goldds.cap:clone()
end
end
return kbestdsbank
end
function Depparser:train(net, traintrebank_path, devdsbank_path, kbestdevdsbank_path, model_dir)
print('load train dsbank')
local traindsbank,_ = self:load_dsbank(traintrebank_path)
net.update_L = TRAIN_UPDATE_L
-- shuf the traindsbank
print('shufing train dsbank')
local new_i = torch.randperm(#traindsbank)
temp = {}
for i = 1,#traindsbank do
temp[i] = traindsbank[new_i[i]]
end
traindsbank = temp
-- train
local adagrad_config = { weight_learningRate = TRAIN_WEIGHT_LEARNING_RATE,
voca_learningRate = TRAIN_VOCA_LEARNING_RATE }
local adagrad_state = {}
net:save(model_dir .. '/model_0')
local prefix = model_dir..'/model'
print('train net')
adagrad_config, adagrad_state = net:train_with_adagrad(traindsbank, TRAIN_BATCHSIZE,
TRAIN_MAX_N_EPOCHS, {lambda = TRAIN_LAMBDA, lambda_L = TRAIN_LAMBDA_L},
prefix, adagrad_config, adagrad_state,
devdsbank_path, kbestdevdsbank_path)
return net
end
function Depparser:compute_scores(test_ds, gold_ds, punc)
local unlabel = 0
local label = 0
local n = 0
if test_ds.n_words ~= gold_ds.n_words then
error('not match')
else
for j = 2,test_ds.n_words do -- ignore ROOT
local count = true
--local w = self.voca_dic.id2word[gold_ds.word[j]]:gsub("%p",'')
if punc == false and self.punc_list[gold_ds.word[j]] == 1 then --string.len(w) == 0 then
count = false
end
if count then
n = n + 1
if test_ds.head[j] == gold_ds.head[j] then
unlabel = unlabel + 1
if test_ds.deprel[j] == gold_ds.deprel[j] then
label = label + 1
end
end
end
end
end
return { unlabel = unlabel , label = label , n = n }
end
function Depparser:rerank_oracle(kbestdsbank, golddsbank, typ)
local typ = typ or 'best'
local K = 100000
if #kbestdsbank ~= #golddsbank then
error('size not match')
end
local ret = {raw = {}}
for i,parses in ipairs(kbestdsbank) do
if typ == 'first' then ret[i] = parses[1]; ret.raw[i] = parses.raw[1]
else
local gold = golddsbank[i]
local best_parse = nil
local best_score = nil
local best_raw = nil
for k,parse in ipairs(parses) do
if k > K then break end
local score = self:compute_scores(parse, gold)
if typ == 'worst' then score.unlabel = -score.unlabel end
if best_score == nil or score.unlabel > best_score then
best_parse = parse
best_score = score.unlabel
best_raw = parses.raw[k]
end
end
ret[i] = best_parse
ret.raw[i] = best_raw
end
end
return ret
end
function Depparser:rerank_scorefile(netscorefile, mstscorefile, kbestdsbank, kbestdsscore, alpha, K)
local K = K or 10
local ret = { raw = {} }
local sum_sen_log_p = 0
local sum_n_words = 0
local f = torch.DiskFile(netscorefile, 'r')
if f:readInt() ~= #kbestdsbank then
error('not match')
end
local i = 1
for line in io.lines(mstscorefile) do
local org_parses = kbestdsbank[i]
local parses = { raw = {} }
local best_parse = nil
local best_score = nil
local best_raw = nil
local log_probs = f:readObject()
local mstscores = split_string(line)
for k = 1, math.min(#log_probs, math.min(K, #org_parses)) do
parses[k] = org_parses[k]
parses.raw[k] = org_parses.raw[k]
end
for j,parse in ipairs(parses) do
local score = tonumber(mstscores[j]) * alpha + (1-alpha)*log_probs[j]
if best_score == nil or score > best_score then
best_parse = parse
best_score = score
best_raw = parses.raw[j]
end
end
ret[i] = best_parse
ret.raw[i] = best_raw
sum_sen_log_p = sum_sen_log_p + log_sum_of_exp(torch.Tensor(log_probs))
sum_n_words = sum_n_words + parses[1].n_words - 1
i = i + 1
end
local ppl = math.pow(2, -sum_sen_log_p / math.log(2) / sum_n_words)
f:close()
return ret, ppl
end
function Depparser:rerank(net, kbestdsbank, output)
local K = K or 10000
local ret = {}
local sum_sen_log_p = 0
local sum_n_words = 0
local f = nil
if output then
f = torch.DiskFile(output, 'w')
f:writeInt(#kbestdsbank)
end
for i,org_parses in ipairs(kbestdsbank) do
if math.mod(i, 10) == 0 then io.write(i..'\r'); io.flush() end
local parses = {}
for k = 1, math.min(K, #org_parses) do
parses[k] = org_parses[k]
end
local best_parse = nil
local best_score = nil
local log_probs = net:compute_log_prob(parses)
if f then f:writeObject(log_probs) end
for j,parse in ipairs(parses) do
if best_score == nil or log_probs[j] > best_score then
best_parse = parse
best_score = log_probs[j]
end
end
ret[i] = best_parse
sum_sen_log_p = sum_sen_log_p + log_sum_of_exp(torch.Tensor(log_probs))
sum_n_words = sum_n_words + parses[1].n_words - 1
end
local ppl = math.pow(2, -sum_sen_log_p / math.log(2) / sum_n_words)
if f then f:close() end
return ret, ppl
end
function Depparser:perplexity(net, dsbank)
local log_probs = net:compute_log_prob(dsbank)
local sum = 0
local nwords = 0
for i,log_p in ipairs(log_probs) do
sum = sum + log_p / math.log(2)
nwords = nwords + dsbank[i].n_words - 1
end
return math.pow(2, -sum / nwords)
end
function Depparser:computeAScores(parses, golddsbank, punc, output)
if output then
--print('print to '..output)
local f = io.open(output, 'w')
for i, parse in ipairs(parses) do
local sent = parses.raw[i]
for j = 2,#sent do
f:write((j-1)..'\t'..sent[j]..'\t_\t_\t_\t_\t'..(parse.head[j]-1)..'\t'..self.deprel_dic.id2word[parse.deprel[j] ]..'\t_\t_\n')
end
f:write('\n')
end
f:close()
end
-- compute scores
local total = 0
local label = 0
local unlabel = 0
for i,parse in ipairs(parses) do
local gold = golddsbank[i]
local ret = self:compute_scores(parse, gold, punc)
total = total + ret.n
label = label + ret.label
unlabel = unlabel + ret.unlabel
end
--print(total)
local LAS = label / total * 100
local UAS = unlabel / total * 100
return LAS, UAS
end
-- should not call it directly when training, there's a mem-leak problem!!!
function Depparser:eval(typ, kbestpath, goldpath, output)
local str = ''
print('load ' .. goldpath)
local golddsbank, raw = self:load_dsbank(goldpath)
print('load ' .. kbestpath)
local kbestdsbank, kbestdsscore = self:load_kbestdsbank(kbestpath, golddsbank)
print('reranking...')
-- compute perplexity
if type(typ) ~= 'string' then
--str = str .. 'ds-ppl ' .. self:perplexity(typ, golddsbank) .. '\n'
end
-- reranking
local parses = nil
local ppl = nil
if type(typ) == 'string' then
if typ == 'best' or typ == 'worst' or typ == 'first' then
parses = self:rerank_oracle(kbestdsbank, golddsbank, typ)
LAS, UAS = self:computeAScores(parses, golddsbank, punc, output) --'/tmp/univ-test-result.conll.'..typ)
str = 'LAS = ' .. string.format("%.2f",LAS)..'\nUAS = ' ..string.format("%.2f",UAS)
print(str)
else
self.mail_subject = nil
if K_range == nil then K_range = {K,K} end
if alpha_range == nil then alpha_range = {alpha,alpha} end
print('k\talpha\tUAS\tLAS')
-- search for best K and alpha
for k = K_range[1],K_range[2] do
best_alpha = 0
best_UAS = 0
best_LAS = 0
for a = alpha_range[1],alpha_range[2],0.005 do
parses = self:rerank_scorefile(typ, kbestpath..'.mstscores', kbestdsbank, kbestdsscore, a, k)
LAS, UAS = self:computeAScores(parses, golddsbank, punc, output)
if UAS > best_UAS then
best_UAS = UAS
best_alpha = a
best_LAS = LAS
end
end
print(k .. '\t' .. best_alpha .. '\t' .. string.format('%.2f',best_UAS) .. '\t' .. string.format('%.2f',best_LAS))
end
end
else
local net = typ
parses,ppl = self:rerank(net, kbestdsbank, kbestpath..'.iornnscores')
LAS, UAS = self:computeAScores(parses, golddsbank, punc)
str = 'LAS = ' .. string.format("%.2f",LAS)..'\nUAS = ' ..string.format("%.2f",UAS)
print(str)
--[[ mail
if EVAL_EMAIL_ADDR and self.mail_subject then
os.execute('echo "'..str..'" | mail -s '..self.mail_subject..' '..EVAL_EMAIL_ADDR)
end
print('sen-ppl ' .. ppl ..'\n')
]]
end
end
--[[ for testing
torch.setnumthreads(1)
print('load dictionaries')
local data_path = '../data/wsj-dep/universal/'
local voca_dic = Dict:new()
voca_dic:load(data_path .. '/dic/collobert/words.lst')
local pos_dic = Dict:new()
pos_dic:load(data_path .. '/dic/cpos.lst')
local deprel_dic = Dict:new()
deprel_dic:load(data_path .. '/dic/deprel.lst')
local parser = Depparser:new(voca_dic, pos_dic, deprel_dic)
print('eval...')
parser:eval(nil, data_path..'/data/dev-small-10best-mst.conll', data_path..'/data/dev-small.conll')
]]
|
----------------------------------------------------------------------------------------------------
--
-- Copyright (c) Contributors to the Open 3D Engine Project.
-- For complete copyright and license terms please see the LICENSE at the root of this distribution.
--
-- SPDX-License-Identifier: Apache-2.0 OR MIT
--
--
--
----------------------------------------------------------------------------------------------------
local MoveBallDown =
{
Properties =
{
Ball = {default = EntityId()},
MinOffset = {default = 0},
},
}
function MoveBallDown:OnActivate()
self.buttonHandler = UiButtonNotificationBus.Connect(self, self.entityId)
end
function MoveBallDown:OnButtonClick()
local offsets = UiTransform2dBus.Event.GetOffsets(self.Properties.Ball)
local height = offsets.bottom - offsets.top
offsets.top = offsets.top + 50
offsets.bottom = offsets.bottom + 50
if (offsets.bottom > self.Properties.MinOffset) then
offsets.bottom = self.Properties.MinOffset
offsets.top = offsets.bottom - height
end
UiTransform2dBus.Event.SetOffsets(self.Properties.Ball, offsets)
end
function MoveBallDown:OnDeactivate()
self.buttonHandler:Disconnect()
end
return MoveBallDown
|
-- Reminder to myself
-- Probably can make a mapping that finds alternate file
-- With alternate file
-- can run tests for entire file automatically.
-- SeemsGood :)
local a = vim.api
---@brief [[
--- Uses colors:
---
--- - GoTestSuccess: Used to highlight succesful tests
--- - GoTestFail : Used to highlight failed tests
---@brief ]]
local Job = require('plenary.job')
-- local log = require('plenary.log')
local gl_mod = require('gl.go_mod')
local gl_win = require('gl.window')
local ns_gotest = a.nvim_create_namespace('gotest')
local test_run = "~ Go Test ~"
local TestCase = {}
TestCase.__index = TestCase
function TestCase:new(name, decoded)
return setmetatable({
name = name,
package = decoded.Package,
result = "pending",
output = {},
messages = { decoded, },
extmark_start = TestCase:_get_id(name .. "_start"),
extmark_final = TestCase:_get_id(name .. "_final")
}, self)
end
local test_case_ids, test_case_count = {}, 0
function TestCase:_get_id(id)
if not test_case_ids[id] then
test_case_count = test_case_count + 1
test_case_ids[id] = test_case_count
end
return test_case_ids[id]
end
function TestCase:insert_message(message)
table.insert(self.messages, message)
end
function TestCase:add_header(bufnr)
local line = "===== " .. self.name .. " ====="
vim.api.nvim_buf_set_lines(bufnr, -1, -1, false, { line, "" })
a.nvim_buf_set_extmark(bufnr, ns_gotest, vim.api.nvim_buf_line_count(bufnr) - 2, 0, { id = self.extmark_start })
a.nvim_buf_set_extmark(bufnr, ns_gotest, vim.api.nvim_buf_line_count(bufnr) - 1, 0, { id = self.extmark_final })
end
local get_extmark_row = function(bufnr, extmark_id)
local extmark_locations = vim.api.nvim_buf_get_extmark_by_id(bufnr, ns_gotest, extmark_id, {})
return extmark_locations[1]
end
function TestCase:get_start_row(bufnr)
local extmark_id = self.extmark_start
return get_extmark_row(bufnr, extmark_id)
end
function TestCase:get_final_row(bufnr)
local extmark_id = self.extmark_final
return get_extmark_row(bufnr, extmark_id)
end
function TestCase:save_output(output)
for _, value in ipairs(vim.split(vim.trim(output), "\n")) do
table.insert(self.output, value)
end
end
function TestCase:_show(bufnr, contents)
local start_row = self:get_start_row(bufnr)
local final_row = self:get_final_row(bufnr)
if not start_row or not final_row then return print("Couldnt find for: ", self.name) end
a.nvim_buf_set_lines(bufnr, start_row + 1, final_row, false, contents)
end
function TestCase:show_output(bufnr)
self.displayed = true
self:_show(bufnr, self.output)
end
function TestCase:hide_output(bufnr)
self.displayed = false
local start_row = self:get_start_row(bufnr)
local final_row = self:get_final_row(bufnr)
if not start_row or not final_row then
return print("Couldnt find for: ", self.name)
end
a.nvim_buf_set_lines(bufnr, start_row + 1, final_row, false, {})
end
function TestCase:toggle_output(bufnr)
if self.displayed then
self:hide_output(bufnr)
else
self:show_output(bufnr)
end
end
function TestCase:set_result(bufnr, result)
self.result = result
local highlight_name = 'Error'
if result == 'pass' then
highlight_name = 'GoTestSuccess'
elseif result == 'fail' then
highlight_name = 'GoTestFail'
end
a.nvim_buf_add_highlight(bufnr, ns_gotest, highlight_name, self:get_start_row(bufnr), 0, -1)
end
function TestCase:get_directory(module_info)
return gl_mod.find_path(module_info, self.package)
end
-- {{{
function TestCase:is_pass() return self.result == 'pass' end
function TestCase:is_fail() return self.result == 'fail' end
function TestCase:is_pend() return self.result == 'pending' end
-- }}}
local TestRun = {}
TestRun.__index = TestRun
function TestRun:new(opts)
local cwd = opts.cwd or vim.loop.cwd()
return setmetatable({
test_pattern = opts.test_pattern,
file_pattern = opts.file_pattern or './...',
cwd = cwd,
module_info = gl_mod.get(cwd),
}, self)
end
function TestRun:run()
gl_win.vsplit()
TestRun._current_run = self
TestRun._current_bufnr = gl_win.get_bufnr()
local bufnr = TestRun._current_bufnr
self:set_keymaps(bufnr)
a.nvim_buf_clear_namespace(0, ns_gotest, 0, -1)
a.nvim_buf_clear_namespace(bufnr, ns_gotest, 0, -1)
a.nvim_buf_set_lines(bufnr, 0, -1, false, {})
self.cases = {}
self.ordered = {}
local args = { 'test', '-json' }
if self.test_pattern then
table.insert(args, '-run')
table.insert(args, self.test_pattern)
end
table.insert(args, self.file_pattern)
local j = Job:new {
command = 'go',
args = args,
cwd = self.cwd,
on_stdout = vim.schedule_wrap(function(_, line)
local decoded = vim.fn.json_decode(line)
self:handle_line(bufnr, decoded)
end),
on_exit = vim.schedule_wrap(function()
for _, test_case in pairs(self.cases) do
if test_case:is_pass() then
test_case:hide_output(bufnr)
end
-- test_case:_show(bufnr, { test_case:get_file(self.module_info) })
end
end),
}
j:start()
end
function TestRun:add_case(bufnr, test_name, decoded)
table.insert(self.ordered, decoded.Test)
self.cases[test_name] = TestCase:new(test_name, decoded)
self.cases[test_name]:add_header(bufnr)
return self.cases[test_name]
end
function TestRun:handle_line(bufnr, decoded)
local action = decoded.Action
local test_name = decoded.Test or test_run
if action == "run" then
return self:add_case(bufnr, test_name, decoded)
end
local test_case = self.cases[test_name]
if not test_case then
test_case = self:add_case(bufnr, test_name, decoded)
end
test_case:insert_message(decoded)
if action == "output" then
test_case:save_output(decoded.Output)
elseif action == "fail" or action == "pass" then
test_case:set_result(bufnr, action)
if test_case:is_fail() then
test_case:show_output(bufnr)
end
else
print("Missing this one", vim.inspect(decoded))
end
end
function TestRun:find_test_case(line)
local row = line - 1
while row > 0 do
for _, test_case in pairs(self.cases) do
if test_case:get_start_row() == row then
return test_case
end
end
row = row - 1
end
return
end
function TestRun:set_keymaps(bufnr)
local opts = { noremap = true, silent = true }
vim.api.nvim_buf_set_keymap(
bufnr, 'n', '<CR>', ':lua require("gl.test").toggle_display()<CR>', opts
)
vim.api.nvim_buf_set_keymap(
bufnr, 'n', 'gf', ':lua require("gl.test").goto_file()<CR>', opts
)
end
function TestRun.goto_file()
local run = assert(TestRun._current_run, "Must have an existing run")
local test_case = run:find_test_case(vim.api.nvim_win_get_cursor(0)[1])
local test_dir = test_case:get_directory(run.module_info)
local failed_file = vim.fn.expand("<cfile>")
local failed_line = vim.split(vim.fn.expand("<cWORD>"), ":")[2]
vim.cmd('e ' .. test_dir .. "/" .. failed_file)
if failed_line then
vim.api.nvim_win_set_cursor(0, { tonumber(failed_line), 1 })
end
end
function TestRun.toggle_display()
local run = assert(TestRun._current_run, "Must have an existing run")
local test_case = run:find_test_case(vim.api.nvim_win_get_cursor(0)[1])
if not test_case then return end
test_case:toggle_output(TestRun._current_bufnr)
if not test_case.displayed then
vim.api.nvim_win_set_cursor(0, { test_case:get_start_row() + 1, 0 })
end
end
return {
TestCase = TestCase,
TestRun = TestRun,
toggle_display = TestRun.toggle_display,
goto_file = TestRun.goto_file,
}
|
local env = environment()
env = add_decl(env, mk_var_decl("A", Type))
env:export("mod3_mod.olean")
|
do
local function oscar(msg, matches)
return [[
source created by @iq_plus 🕵
channel bot 🔘 @oscarbotv2 🔘
〰〰〰〰〰〰〰〰〰〰〰〰
. 🔵 oscarbot v1 🔴
Oscar ™
Dev @iq_plus ⚜
Dev @JALAL_ALDON 🔱
Dev @CutlassX 🔱
Dev @mgoody_96 🔱
Dev @XxToFexX 🔱
Dev @iDev1 🔱
]]
end
return {
patterns = {
"^[!/#](version)$",
},
run = oscar,
}
end
|
local lu = require("luaunit")
TestHandler = require("test.unit.mockable_case"):extend()
function TestHandler:setUp()
TestHandler.super:setUp()
package.loaded["resty.openidc"] = nil
self.module_resty = { openidc = {} }
package.preload["resty.openidc"] = function()
return self.module_resty.openidc
end
self.handler = require("kong.plugins.oidc.handler")()
end
function TestHandler:tearDown()
TestHandler.super:tearDown()
end
function TestHandler:test_bearer_jwt_auth_success()
ngx.req.get_headers = function() return {Authorization = "Bearer xxx"} end
ngx.encode_base64 = function(x) return "eyJzdWIiOiJzdWIifQ==" end
self.module_resty.openidc.get_discovery_doc = function(opts)
return { issuer = "https://oidc" }
end
self.module_resty.openidc.bearer_jwt_verify = function(opts)
token = {
iss = "https://oidc",
sub = "sub111",
aud = "aud222",
groups = { "users" }
}
return token, nil, "xxx"
end
self.handler:access({
bearer_jwt_auth_enable = "yes",
client_id = "aud222",
groups_claim = "groups",
userinfo_header_name = "x-userinfo"
})
lu.assertEquals(ngx.ctx.authenticated_credential.id, "sub111")
lu.assertEquals(kong.ctx.shared.authenticated_groups, { "users" })
end
function TestHandler:test_bearer_jwt_auth_fail()
ngx.req.get_headers = function() return {Authorization = "Bearer xxx"} end
local called_authenticate
self.module_resty.openidc.get_discovery_doc = function(opts)
return { issuer = "https://oidc" }
end
self.module_resty.openidc.bearer_jwt_verify = function(opts)
return nil, "JWT expired"
end
self.module_resty.openidc.authenticate = function(opts)
called_authenticate = true
return nil, "error"
end
self.handler:access({bearer_jwt_auth_enable = "yes", client_id = "aud222"})
lu.assertTrue(called_authenticate)
end
lu.run()
|
function onUpdate(elapsed)
if curStep >= 0 then
songPos = getSongPosition()
local currentBeat = (songPos/1000)*(bpm/80)
doTweenY(dadTweenY, 'dad', -100-110*math.sin((currentBeat*0.1)*math.pi),0.001)
end
end
|
function OnInit()
Rule_Add("Rule_Start")
end
function Rule_Start()
setMissionComplete(1)
Rule_Remove("Rule_Start")
end
|
local eventtap = hs.eventtap
local eventTypes = hs.eventtap.event.types
local l = hs.logger.new('super')
local state = {}
local resetState = function ()
state.spaceDown = false
state.spaceFn = false
state.outputNextSpace = false
state.pause = false
end
resetState()
local modifiers = function (event)
local modifiers = {}
for k, v in pairs(event:getFlags()) do
table.insert(modifiers, k)
end
return modifiers
end
local onSpaceDown = function ()
if state.spaceDown then
state.spaceFn = true
else
state.spaceDown = true
end
return true
end
local onKeyUp, onKeyDown
local onSpaceUp = function (event)
if not state.spaceFn then
onKeyUp:stop()
onKeyDown:stop()
state.outputNextSpace = true
hs.eventtap.keyStroke(
modifiers(event),
'space',
0
)
onKeyUp:start()
onKeyDown:start()
end
resetState()
end
local spaceKeycode = 49
onKeyDown = eventtap.new(
{eventTypes.keyDown},
function (event)
local keycode = event:getKeyCode()
if keycode == spaceKeycode then
return onSpaceDown()
end
end
)
onKeyUp = eventtap.new(
{eventTypes.keyUp},
function (event)
local keycode = event:getKeyCode()
if keycode == spaceKeycode then
return onSpaceUp(event)
end
end
)
onKeyDown:start()
onKeyUp:start()
|
demonic_warrior_rest_modifier = class({})
function demonic_warrior_rest_modifier:OnCreated( kv )
self.duration = self:GetAbility():GetSpecialValueFor("duration")
if not IsServer() then return end
local caster = self:GetParent()
-- Particle --
self.particle = ParticleManager:CreateParticle("particles/generic_gameplay/generic_sleep.vpcf", PATTACH_OVERHEAD_FOLLOW, caster)
ParticleManager:SetParticleControl( self.particle, 0, caster:GetAbsOrigin() )
end
function demonic_warrior_rest_modifier:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_TOOLTIP
}
return funcs
end
function demonic_warrior_rest_modifier:CheckState()
local state = {
[MODIFIER_STATE_SILENCED] = true,
[MODIFIER_STATE_DISARMED] = true,
[MODIFIER_STATE_ROOTED] = true,
[MODIFIER_STATE_COMMAND_RESTRICTED] = true
}
return state
end
function demonic_warrior_rest_modifier:OnDestroy( kv )
if not IsServer() then return end
local caster = self:GetParent()
caster:RemoveGesture(ACT_DOTA_DISABLED)
ParticleManager:DestroyParticle( self.particle, false )
ParticleManager:ReleaseParticleIndex( self.particle )
self.particle = nil
end
function demonic_warrior_rest_modifier:OnTooltip( params )
return self.duration
end
function demonic_warrior_rest_modifier:GetAttributes()
return MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE
end
function demonic_warrior_rest_modifier:IsHidden()
return false
end
function demonic_warrior_rest_modifier:IsPurgable()
return false
end
function demonic_warrior_rest_modifier:IsPurgeException()
return false
end
function demonic_warrior_rest_modifier:IsStunDebuff()
return false
end
function demonic_warrior_rest_modifier:IsDebuff()
return true
end
|
Locales['pl'] = {
['left_instance'] = 'opuszczasz instancję',
['invite_expired'] = 'zaproszenie wygasło',
['press_to_enter'] = 'wciśnij ~INPUT_CONTEXT~ aby wejść do instancji',
['entered_instance'] = 'wchodzisz do instancji',
['entered_into'] = '%s wchodzi do instancji',
['left_out'] = '%s opuszcza instancję',
}
|
mission_end_sequence_ground = {
SEQ_TELOP = {
OnEnter = function( manager )
Fox.Log("mission_end_sequence_SEQ_TELOP")
missionCommon_functionSet.SetSequenceIdToSkip( manager,"SEQ_END" )
--開始時テロップの再生
missionCommon_functionSet.PlayMissionEndTelop()
TppEventSequenceManagerCollector.GoNextSequence( "TppEventSequenceManagerData_mission_end", "SEQ_END" )
end,
},
}
|
#!/usr/bin/env luajit
local dns = require('dns')
local nb = require('dns.nbio')
-- Parse parameters
local host, port, tcp, tls, xfer, key, cookie = nil, 53, false, false, false, nil
local version, dobit, bufsize, short, multi = 0, false, nil, false
local qname, qtype, qclass = '.', dns.type.NS, dns.class.IN
local flags = {'rd'}
local k = 1 while k <= #arg do
local v = arg[k]
local chr = string.char(v:byte())
if chr == '@' then host = v:sub(2)
elseif dns.type[v] ~= nil then
qtype = dns.type[v]
if qtype == dns.type.AXFR or qtype == dns.type.IXFR then
xfer, tcp = true, true
end
elseif dns.class[v] ~= nil then qclass = dns.class[v]
elseif v == '-' then multi = true
elseif v == '-f' then short, k = arg[k + 1], k + 1
elseif v == '-p' then port, k = tonumber(arg[k + 1]), k + 1
elseif v == '-y' then key, k = dns.tsig(arg[k + 1]), k + 1
elseif v == '-x' then
v, k = arg[k + 1], k + 1
qtype, qname = dns.type.PTR, ''
if v:find('.', 1, true) then
for i in v:gmatch('[^.]+') do
qname = string.format('%s%s.', qname, i)
end
qname = qname .. 'in-addr.arpa'
else
local part, through = '', false
for i in v:gmatch('[^:]*') do
if #i == 0 then
if through then
qname, part = part, ''
end
through = true
else
for c in string.format('%04s', i):gsub(' ', '0'):gmatch('.') do
part = string.format('%s.%s', c, part)
end
through = false
end
end
qname = part .. string.rep('0.', (64 - #qname - #part)/2) .. qname .. 'ip6.arpa'
end
elseif v == '+short' then short = true
elseif v == '+tcp' then tcp = true
elseif v == '+tls' then
tls, tcp = true, true
if port == 53 then port = 853 end
elseif v:find('+cookie',1) then
cookie = v:match('+cookie=(%S+)') or true
elseif v == '+cd' then table.insert(flags, 'cd')
elseif v == '+do' or v == '+dnssec' then dobit = true
elseif v == '-h' or v == '--help' then
print(string.format('Usage: %s [options] [@server] [type] [class] [domain]', arg[0]))
print('Options:')
print('\t-p <num> server port number (default: 53, 853 for +tls)')
print('\t-y <tsig> use TSIG key (default: none, example: "testkey:hmac-md5:Wg==")')
print('\t-x <ip> do a reverse lookup')
print('\t-f json return DNS response as JSON')
print('\t+tcp use TCP for transport')
print('\t+tls use TLS for transport')
print('\t+short print only answer records')
print('\t+cd DNSSEC checking disabled')
print('\t+do request DNSSEC records')
print('\t+cookie request a DNS COOKIE')
print('\t+cookie=X pass a DNS COOKIE')
print('\t- read queries from stdin (pipelined if +tcp is passed)')
print('Examples:')
print(' ',arg[0] .. ' -x 192.168.1.1')
print(' ',arg[0] .. ' NS cz +do')
print(' ',arg[0] .. ' @2001:678:f::1 AAAA nic.cz +tcp')
print(' ',arg[0] .. ' -y xfrkey:hmac-md5:Wg== @127.0.0.1 -p 5353 AXFR nic.cz')
print(' ',arg[0] .. ' NS cz -f json | jq .')
print(' ','echo -e "NS is\\nNS cz" | ' .. arg[0] .. ' +tcp -')
return 0
else -- + Modifiers
local match = v:match('+bufsize=(%d+)')
if match ~= nil then bufsize = tonumber(match)
else qname = v
end
end
k = k + 1
end
if host == nil then for line in io.lines('/etc/resolv.conf') do
host = line:match('nameserver ([0-9A-Za-z.:]+)')
if host ~= nil then break end
end end
local queries, planned = {}, {}
-- Create a queries
if not multi then
table.insert(planned, {qname, qtype, qclass})
else
for line in io.lines() do
local query = {'.',nil,nil}
for w in line:gmatch('([^%s]+)') do
if not query[3] and dns.class[w] then query[3] = dns.class[w]
elseif not query[2] and dns.type[w] then query[2] = dns.type[w]
else query[1] = w end
end
query[2] = query[2] or dns.type.A
query[3] = query[3] or dns.class.IN
table.insert(planned, query)
end
end
for _,q in ipairs(planned) do
local query = dns.packet(512)
for _,flag in ipairs(flags) do query[flag](query, true) end
query:question(dns.dname.parse(q[1]), q[2], q[3])
if dobit or (bufsize ~= nil and bufsize > 0) or cookie then
if bufsize == nil then bufsize = 4096 end
query:begin(dns.section.ADDITIONAL)
local rr = dns.edns.rrset(version, bufsize)
dns.edns.dobit(rr, dobit)
if cookie then
local client = cookie
-- Unpack cookie from hexstring
if type(client) == 'string' then
local hex = ''
cookie:gsub('%w%w', function (c) hex = hex .. string.char(tonumber(c, 16)) end)
client = hex
-- Generate new client cookie
else
client = io.open('/dev/urandom', 'r'):read(8)
end
dns.edns.option(rr, dns.option.COOKIE, client)
end
query:put(rr)
end
if key ~= nil then
key:sign(query)
end
table.insert(queries, query)
end
-- Send and wait for answers
local started = nb.now()
local send, recv = nb.udpsend, nb.udprecv
if tcp then
send, recv = nb.tcpsend, nb.tcprecv
end
assert(nb.go(function()
-- Make connection to destination
local sock = nb.socket(nb.family(host), tcp and 'stream')
if tcp and not tls then -- Attempt TFO
-- We need to serialise message in a buffer prefixed with message length
-- Convenience functions are unavailable and we can't use writev()
local ffi, bit = require('ffi'), require('bit')
local buf = ffi.new('uint8_t [?]', queries[1].size + 2)
local txlen = ffi.cast('uint16_t *', buf)
txlen[0] = dns.utils.n16(tonumber(queries[1].size))
ffi.copy(buf + 2, queries[1].wire, queries[1].size)
assert(sock:connect(host, port, buf, ffi.sizeof(buf)))
else -- Make connected socket and send query
assert(sock:connect(host, port))
if tls then -- Upgrade to TLS
sock = assert(require('dns.tls').client(sock, 'x509'))
end
send(sock, queries[1])
end
for i=2,#queries do send(sock, queries[i]) end
-- Start receiving answers
for _=1,#queries do
local answer = dns.packet(65535)
local rcvd = recv(sock, answer)
local nbytes, npkts, tsig_ok, soa = 0, 0, true, nil
while rcvd and rcvd > 0 do
answer.size = rcvd
if not answer:parse() then
print(dns.hexdump(answer:towire()))
error('; MALFORMED MESSAGE')
end
if key ~= nil and not key:verify(answer) then
tsig_ok = false
break
end
-- Print packet
local res = answer:tostring(short or npkts > 0)
if #res > 0 then io.write(res) end
nbytes, npkts = nbytes + tonumber(rcvd), npkts + 1
-- Decide if we should wait for more packets
if xfer then
local answer = answer:section(dns.section.ANSWER)
if #answer > 0 then
local last = answer[#answer - 1]
if not soa and answer[0]:type() == dns.type.SOA then -- Starting SOA
soa = dns.rdata.soa_serial(answer[0]:rdata(0))
elseif last:type() == dns.type.SOA then -- Ending SOA
if soa == dns.rdata.soa_serial(last:rdata(0)) then
break
end
end
end
end
answer:clear()
rcvd = xfer and recv(sock, answer) or 0
end
-- Additional information
if not short then
if #queries == 1 then
assert(nbytes > 0, '; NO ANSWER')
elseif nbytes <= 0 then
print('; NO ANSWER')
end
local elapsed = nb.now() - started
print(string.format(';; Query time: %d msec', elapsed * 1000.0))
print(string.format(';; SERVER: %s#%d', host, port))
print(string.format(';; WHEN: %s', os.date()))
print(string.format(';; MSG SIZE rcvd: %d count: %d', nbytes, npkts))
if not tsig_ok then print(string.format(';; WARNING -- Some TSIG could not be validated')) end
end
end
end))
return assert(nb.run(3))
|
local icons = require "nvim-nonicons"
require("which-key").setup {
plugins = {
marks = true, -- shows a list of your marks on ' and `
registers = true, -- shows your registers on " in NORMAL or <C-r> in INSERT mode
spelling = {
enabled = true,
suggestions = 20,
},
},
icons = {
breadcrumb = icons.get "chevron-right", -- symbol used in the command line area that shows your active key combo
separator = icons.get "arrow-right", -- symbol used between a key and it's label
group = "", -- symbol prepended to a group
},
window = {
border = "single",
},
layout = {
height = { min = 4, max = 25 },
width = { min = 20, max = 50 },
spacing = 3,
},
key_labels = { ["<space>"] = "SPC", ["<tab>"] = "TAB" },
hidden = { "<silent>", "<cmd>", "<Cmd>", "<CR>", "call", "lua", "^:", "^ " }, -- hide mapping boilerplate
show_help = true,
triggers = { "<leader>", "z", "<localleader>" },
}
local options = {
mode = "n", -- NORMAL mode
prefix = "<leader>",
buffer = nil, -- Global mappings. Specify a buffer number for buffer local mappings
silent = true, -- use `silent` when creating keymaps
noremap = true, -- use `noremap` when creating keymaps
nowait = false, -- use `nowait` when creating keymaps
}
local japanese_mappings = {
["q"] = "バッファーを閉じる",
["e"] = "エクスプローラー",
["f"] = "ファイルを検索",
["h"] = "検索ハイライトを切る",
["p"] = "プロジェクト",
[";"] = "ダッシュボード",
["*"] = "ドキュメントを生成",
["T"] = { "<cmd>TodoTrouble<cr>", "TODO 一覧" },
["a"] = { "<cmd>UltestSummary<cr>", "テスト エクスプローラー" },
["r"] = { "<cmd>ToggleTerm<cr>", "端末" },
["v"] = { "<cmd>Vista!!<cr>", "シンボル リスト" },
["w"] = { "<cmd>lua require'dapui'.toggle()<cr>", "デバッグ インターフェース" },
["x"] = { "<cmd>TroubleToggle<cr>", "エラー一覧" },
["u"] = { "<cmd>UndotreeToggle<cr>", "ナビゲーター" },
["j"] = { "<cmd>DBUIToggle<cr>", "データベース エクスプローラー" },
["m"] = { "<Plug>MarkdownPreviewToggle", "Markdownのプレビューを切り替え" },
c = {
name = "+コンテナ",
c = { "<cmd>DockerToolsToggle<cr>", "Docker ツール" },
a = { "<cmd>AttachToContainer<cr>", "接続" },
b = { "<cmd>BuildImage<cr>", "イメージをビルド" },
s = { "<cmd>StartImage<cr>", "devcontainers.jsonからイメージを起動" },
},
C = {
name = "+変換",
c = {
name = "+色",
c = { "<Plug>ColorConvertCycle", "変換を切り替え" },
h = { "<Plug>ColorConvertHEX", "HEXに変換"},
r = { "<Plug>ColorConvertRGB", "RGBに変換"},
s = { "<Plug>ColorConvertHSL", "HSLに変換"}
}
},
d = {
name = "+診断",
t = { "<cmd>TroubleToggle<cr>", "エラー一覧" },
w = { "<cmd>TroubleToggle lsp_workspace_diagnostics<cr>", "ワークスペース" },
d = { "<cmd>TroubleToggle lsp_document_diagnostics<cr>", "ドキュメント内" },
q = { "<cmd>TroubleToggle quickfix<cr>", "クイックフィックス" },
l = { "<cmd>TroubleToggle loclist<cr>", "場所を検索" },
r = { "<cmd>TroubleToggle lsp_references<cr>", "リファレンス" },
},
D = {
name = "+デバッグ",
b = { "<cmd>lua require'dap'.toggle_breakpoint()<cr>", "ブレークポイントを切り替え" },
B = { "<cmd>Telescope dap list_breakpoints<cr>", "ブレークポイント一覧" },
c = { "<cmd>lua require'dap'.continue()<cr>", "コンティニュー" },
d = { "<cmd>lua require'dap'.run_to_cursor()<cr>", "カーソル位置まで実行" },
e = { "<cmd>lua require'dapui'.eval()<cr>", "現在行を評価" },
h = { "<Plug>RestNvim", "HTTP をテスト" },
i = { "<cmd>lua require'dap'.step_into()<cr>", "ステップ イン" },
f = { "<cmd>lua require'dapui'.float_element()", "フィールドを確認" },
o = { "<cmd>lua require'dap'.step_over()<cr>", "ステップ オーバー" },
O = { "<cmd>lua require'dap'.step_out()<cr>", "ステップ アウト" },
r = { "<cmd>lua require'dap.repl'.open()<cr>", "Replを開く" },
s = { "<cmd>lua require'dap'.run()<cr>", "開始" },
},
g = {
name = "+Git",
j = "次のHunk",
k = "前のHunk",
p = "Hunkをプレビュー",
r = "Hunkをリセット",
R = "バッファーをリセット",
s = "Hunkをステージ",
u = "Hunkのステージを戻す",
o = { "<cmd>Telescope git_status<cr>", "変更済みファイルを開く" },
b = { "<cmd>Telescope git_branches<cr>", "ブランチをチェックアウト" },
c = { "<cmd>Neogit commit<cr>", "変更をコミット" },
C = { "<cmd>Telescope git_commits<cr>", "コミットをチェックアウト" },
g = { "<cmd>Neogit<cr>", "Git ウィンドウ" },
m = {
name = "+マージ",
t = { "<Plug>(MergetoolToggle)", "マージ ツール" },
g = { "<cmd>diffget<cr>", "リモートの変更を受け入れる" },
p = { "<cmd>diffput<cr>", "ローカルの変更を適用" },
},
},
l = {
name = "+LSP",
d = { "<cmd>Telescope lsp_document_diagnostics<cr>", "ドキュメント内を診断" },
D = { "<cmd>Telescope lsp_workspace_diagnostics<cr>", "ワークスペースを診断" },
f = { "<cmd>Neoformat<cr>", "フォーマット" },
I = { "<cmd>LspInfo<cr>", "状態" },
q = { "<cmd>Telescope quickfix<cr>", "クイックフィックス" },
x = { "<cmd>cclose<cr>", "クイックフィックスを閉じる" },
s = { "<cmd>LspDocumentSymbol<cr>", "ドキュメント内のシンボル" },
S = { "<cmd>LspWorkspaceSymbol<cr>", "ワークスペースのシンボル" },
},
s = {
name = "+検索",
a = { "<cmd>lua require('spectre').open_file_search()<cr>", "ファイル内を置換" },
b = { "<cmd>Telescope git_branches<cr>", "ブランチをチェックアウト" },
c = { "<cmd>Telescope colorscheme<cr>", "カラースキーム" },
d = { "<cmd>Telescope lsp_document_diagnostics<cr>", "ドキュメント内の診断情報" },
D = { "<cmd>Telescope lsp_workspace_diagnostics<cr>", "ワークスペースの診断情報" },
f = { "<cmd>Telescope find_files<cr>", "ファイルを検索" },
m = { "<cmd>Telescope marks<cr>", "マーク済みの場所" },
M = { "<cmd>Telescope man_pages<cr>", "マニュアル" },
r = { "<cmd>Telescope oldfiles<cr>", "最近開いたファイル" },
R = { "<cmd>Telescope registers<cr>", "レジスター" },
t = { "<cmd>Telescope live_grep<cr>", "テキスト" },
},
S = {
name = "+セッション",
s = { "<cmd>SessionSave<cr>", "セッションを保存" },
l = { "<cmd>SessionLoad<cr>", "セッションを開く" },
},
t = {
name = "+テスト",
a = { "<cmd>UltestAttach<cr>", "動作中のデバッグにアタッチ" },
c = { "<cmd>UltestClear<cr>", "結果を消去" },
d = { "<cmd>UltestDebug<cr>", "デバッグテストを開始" },
D = { "<cmd>UltestDebugNearest<cr>", "近くのデバッグテストを開始" },
t = { "<cmd>UltestSummary<cr>", "テスト エクスプローラー" },
s = { "<cmd>UltestStop<cr>", "動作中のテストを停止" },
},
y = {
name = "+Treesitter",
s = "@parameter.innerをスワップ",
S = "@parameter.outerをスワップ",
},
-- extras
z = {
name = "+Zen Mode",
z = { "<cmd>ZenMode<cr>", "Zen モードを切り替え" },
},
}
local mappings = {
["q"] = "Close Buffer",
["e"] = "Explorer",
["f"] = "Find File",
["h"] = "No Highlight",
["p"] = "Projects",
["*"] = "Generate document",
["T"] = { "<cmd>TodoTrouble<cr>", "Open TODOs" },
["a"] = { "<cmd>UltestSummary<cr>", "Test Explorer" },
["r"] = { "<cmd>ToggleTerm<cr>", "Terminal" },
["v"] = { "<cmd>Vista!!<cr>", "Symbol List" },
["w"] = { "<cmd>lua require'dapui'.toggle()<cr>", "Debug UI" },
["x"] = { "<cmd>TroubleToggle<cr>", "Error List" },
["u"] = { "<cmd>UndotreeToggle<cr>", "Undo Tree" },
["j"] = { "<cmd>DBUIToggle<cr>", "Database UI" },
["m"] = { "<Plug>MarkdownPreviewToggle", "Toggle markdown preview" },
c = {
name = "+Containers",
c = { "<cmd>DockerToolsToggle<cr>", "Docker Tools" },
a = { "<cmd>AttachToContainer<cr>", "Connect" },
b = { "<cmd>BuildImage<cr>", "Build Image" },
s = { "<cmd>StartImage<cr>", "Start Image from devcontainers.json" },
},
C = {
name = "+Convert",
c = {
name = "+Colors",
c = { "<Plug>ColorConvertCycle", "Cycle color conversion" },
h = { "<Plug>ColorConvertHEX", "Convert to HEX"},
r = { "<Plug>ColorConvertRGB", "Convert to RGB"},
s = { "<Plug>ColorConvertHSL", "Convert to HSL"}
}
},
d = {
name = "+Diagnostics",
t = { "<cmd>TroubleToggle<cr>", "Error List" },
w = { "<cmd>TroubleToggle lsp_workspace_diagnostics<cr>", "workspace" },
d = { "<cmd>TroubleToggle lsp_document_diagnostics<cr>", "document" },
q = { "<cmd>TroubleToggle quickfix<cr>", "quickfix" },
l = { "<cmd>TroubleToggle loclist<cr>", "loclist" },
r = { "<cmd>TroubleToggle lsp_references<cr>", "references" },
},
D = {
name = "+Debug",
b = { "<cmd>lua require'dap'.toggle_breakpoint()<cr>", "Toggle Breakpoint" },
B = { "<cmd>Telescope dap list_breakpoints<cr>", "Breakpoints" },
c = { "<cmd>lua require'dap'.continue()<cr>", "Continue" },
d = { "<cmd>lua require'dap'.run_to_cursor()<cr>", "Run To Cursor" },
e = { "<cmd>lua require'dapui'.eval()<cr>", "Evaluate Current Expression" },
h = { "<Plug>RestNvim", "Test HTTP" },
i = { "<cmd>lua require'dap'.step_into()<cr>", "Step Into" },
f = { "<cmd>lua require'dapui'.float_element()<cr>", "Current Elements" },
o = { "<cmd>lua require'dap'.step_over()<cr>", "Step Over" },
O = { "<cmd>lua require'dap'.step_out()<cr>", "Step Out" },
r = { "<cmd>lua require'dap.repl'.open()<cr>", "Open Repl" },
s = { "<cmd>lua require'dap'.run()<cr>", "Start" },
},
g = {
name = "+Git",
j = "Next Hunk",
k = "Prev Hunk",
p = "Preview Hunk",
r = "Reset Hunk",
R = "Reset Buffer",
s = "Stage Hunk",
u = "Undo Stage Hunk",
o = { "<cmd>Telescope git_status<cr>", "Open changed file" },
b = { "<cmd>Telescope git_branches<cr>", "Checkout branch" },
c = { "<cmd>Neogit commit<cr>", "Commit changes" },
C = { "<cmd>Telescope git_commits<cr>", "Checkout commit" },
g = { "<cmd>Neogit<cr>", "Git Window" },
m = {
name = "+Merge",
t = { "<Plug>(MergetoolToggle)", "Merge Tool" },
g = { "<cmd>diffget<cr>", "Get diff" },
p = { "<cmd>diffput<cr>", "Put diff" },
},
},
l = {
name = "+LSP",
a = "Code Action",
d = { "<cmd>Telescope lsp_document_diagnostics<cr>", "Document Diagnostics" },
D = { "<cmd>Telescope lsp_workspace_diagnostics<cr>", "Workspace Diagnostics" },
f = { "<cmd>Neoformat<cr>", "Format" },
I = { "<cmd>LspInfo<cr>", "Information" },
q = { "<cmd>Telescope quickfix<cr>", "Quickfix" },
x = { "<cmd>cclose<cr>", "Close Quickfix" },
s = { "<cmd>LspDocumentSymbol<cr>", "Document Symbols" },
S = { "<cmd>LspWorkspaceSymbol<cr>", "Workspace Symbols" },
},
s = {
name = "+Search",
a = { "<cmd>lua require('spectre').open_file_search()<cr>", "Replace file" },
b = { "<cmd>Telescope git_branches<cr>", "Checkout branch" },
c = { "<cmd>Telescope colorscheme<cr>", "Colorscheme" },
d = { "<cmd>Telescope lsp_document_diagnostics<cr>", "Document Diagnostics" },
D = { "<cmd>Telescope lsp_workspace_diagnostics<cr>", "Workspace Diagnostics" },
f = { "<cmd>Telescope find_files<cr>", "Find File" },
m = { "<cmd>Telescope marks<cr>", "Marks" },
M = { "<cmd>Telescope man_pages<cr>", "Man Pages" },
["r"] = "Recent Files",
R = { "<cmd>Telescope registers<cr>", "Registers" },
t = { "<cmd>Telescope live_grep<cr>", "Text" },
},
S = {
name = "+Session",
s = { "<cmd>SessionSave<cr>", "Save Session" },
["l"] = "Load Session",
},
t = {
name = "+Test",
a = { "<cmd>UltestAttach<cr>", "Attach to Running Debug" },
c = { "<cmd>UltestClear<cr>", "Clear Results" },
d = { "<cmd>UltestDebug<cr>", "Debug Current File" },
D = { "<cmd>UltestDebugNearest<cr>", "Debug Nearest Position" },
t = { "<cmd>UltestSummary<cr>", "Test Explorer" },
s = { "<cmd>UltestStop<cr>", "Stop Running Test Jobs" },
},
y = {
name = "+Treesitter",
s = "swap @parameter.inner",
S = "swap @parameter.outer",
},
-- extras
z = { "<cmd>ZenMode<cr>", "Zen Mode" },
}
if O.japanese then
require("which-key").register(japanese_mappings, options)
else
require("which-key").register(mappings, options)
end
|
local uranium_params = {
offset = 0,
scale = 1,
spread = {x = 100, y = 100, z = 100},
seed = 420,
octaves = 3,
persist = 0.7
}
local uranium_threshold = 0.55
local chromium_params = {
offset = 0,
scale = 1,
spread = {x = 100, y = 100, z = 100},
seed = 421,
octaves = 3,
persist = 0.7
}
local chromium_threshold = 0.55
local zinc_params = {
offset = 0,
scale = 1,
spread = {x = 100, y = 100, z = 100},
seed = 422,
octaves = 3,
persist = 0.7
}
local zinc_threshold = 0.5
local lead_params = {
offset = 0,
scale = 1,
spread = {x = 100, y = 100, z = 100},
seed = 423,
octaves = 3,
persist = 0.7
}
local lead_threshold = 0.3
minetest.register_ore({
ore_type = "scatter",
ore = "technic:mineral_uranium",
wherein = "default:stone",
clust_scarcity = 8*8*8,
clust_num_ores = 4,
clust_size = 3,
y_min = -300,
y_max = -80,
noise_params = uranium_params,
noise_threshold = uranium_threshold,
})
minetest.register_ore({
ore_type = "scatter",
ore = "technic:mineral_chromium",
wherein = "default:stone",
clust_scarcity = 8*8*8,
clust_num_ores = 2,
clust_size = 3,
y_min = -200,
y_max = -100,
noise_params = chromium_params,
noise_threshold = chromium_threshold,
})
minetest.register_ore({
ore_type = "scatter",
ore = "technic:mineral_chromium",
wherein = "default:stone",
clust_scarcity = 6*6*6,
clust_num_ores = 2,
clust_size = 3,
y_min = -31000,
y_max = -200,
flags = "absheight",
noise_params = chromium_params,
noise_threshold = chromium_threshold,
})
minetest.register_ore({
ore_type = "scatter",
ore = "technic:mineral_zinc",
wherein = "default:stone",
clust_scarcity = 8*8*8,
clust_num_ores = 5,
clust_size = 7,
y_min = -32,
y_max = 2,
noise_params = zinc_params,
noise_threshold = zinc_threshold,
})
minetest.register_ore({
ore_type = "scatter",
ore = "technic:mineral_zinc",
wherein = "default:stone",
clust_scarcity = 6*6*6,
clust_num_ores = 4,
clust_size = 3,
y_min = -31000,
y_max = -32,
flags = "absheight",
noise_params = zinc_params,
noise_threshold = zinc_threshold,
})
minetest.register_ore({
ore_type = "scatter",
ore = "technic:mineral_lead",
wherein = "default:stone",
clust_scarcity = 9*9*9,
clust_num_ores = 5,
clust_size = 3,
y_min = -16,
y_max = 16,
noise_params = lead_params,
noise_threshold = lead_threshold,
})
minetest.register_ore({
ore_type = "scatter",
ore = "technic:mineral_lead",
wherein = "default:stone",
clust_scarcity = 8*8*8,
clust_num_ores = 5,
clust_size = 3,
y_min = -128,
y_max = -16,
noise_params = lead_params,
noise_threshold = lead_threshold,
})
minetest.register_ore({
ore_type = "scatter",
ore = "technic:mineral_lead",
wherein = "default:stone",
clust_scarcity = 6*6*6,
clust_num_ores = 5,
clust_size = 3,
y_min = -31000,
y_max = -128,
flags = "absheight",
noise_params = lead_params,
noise_threshold = lead_threshold,
})
-- Sulfur
local sulfur_buf = {}
local sulfur_noise
minetest.register_on_generated(function(minp, maxp)
local vm, emin, emax = minetest.get_mapgen_object("voxelmanip")
local a = VoxelArea:new({MinEdge=emin, MaxEdge=emax})
local data = vm:get_data(sulfur_buf)
local pr = PseudoRandom(17 * minp.x + 42 * minp.y + 101 * minp.z)
sulfur_noise = sulfur_noise or minetest.get_perlin(9876, 3, 0.5, 100)
local c_lava = minetest.get_content_id("default:lava_source")
local c_lava_flowing = minetest.get_content_id("default:lava_flowing")
local c_stone = minetest.get_content_id("default:stone")
local c_sulfur = minetest.get_content_id("technic:mineral_sulfur")
local grid_size = 5
for x = minp.x + math.floor(grid_size / 2), maxp.x, grid_size do
for y = minp.y + math.floor(grid_size / 2), maxp.y, grid_size do
for z = minp.z + math.floor(grid_size / 2), maxp.z, grid_size do
local c = data[a:index(x, y, z)]
if (c == c_lava or c == c_lava_flowing)
and sulfur_noise:get_3d({x = x, y = z, z = z}) >= 0.4 then
for i in a:iter(
math.max(minp.x, x - grid_size),
math.max(minp.y, y - grid_size),
math.max(minp.z, z - grid_size),
math.min(maxp.x, x + grid_size),
math.min(maxp.y, y + grid_size),
math.min(maxp.z, z + grid_size)
) do
if data[i] == c_stone and pr:next(1, 10) <= 7 then
data[i] = c_sulfur
end
end
end
end
end
end
vm:set_data(data)
vm:write_to_map(data)
end)
if technic.config:get_bool("enable_marble_generation") then
minetest.register_ore({
ore_type = "sheet",
ore = "technic:marble",
wherein = "default:stone",
clust_scarcity = 1,
clust_num_ores = 1,
clust_size = 3,
y_min = -31000,
y_max = -50,
noise_threshold = 0.4,
noise_params = {
offset = 0, scale = 15, spread = {x = 150, y = 150, z = 150},
seed = 23, octaves = 3, persist = 0.70
}
})
end
if technic.config:get_bool("enable_granite_generation") then
minetest.register_ore({
ore_type = "sheet",
ore = "technic:granite",
wherein = "default:stone",
clust_scarcity = 1,
clust_num_ores = 1,
clust_size = 4,
y_min = -31000,
y_max = -150,
noise_threshold = 0.4,
noise_params = {
offset = 0, scale = 15, spread = {x = 130, y = 130, z = 130},
seed = 24, octaves = 3, persist = 0.70
}
})
end
|
local dashboard = require"alpha.themes.dashboard"
local if_nil = vim.F.if_nil
local function button(sc, txt, keybind, keybind_opts)
local sc_ = sc:gsub("%s", ""):gsub("LDR", "<leader>")
local opts = {
position = "center",
shortcut = sc,
cursor = 5,
width = 50,
align_shortcut = "right",
hl_shortcut = "Keyword",
}
if keybind then
keybind_opts = if_nil(keybind_opts, { noremap = true, silent = true, nowait = true })
opts.keymap = { "n", sc_, keybind, keybind_opts }
end
local function on_press()
local key = vim.api.nvim_replace_termcodes(sc_ .. "<Ignore>", true, false, true)
vim.api.nvim_feedkeys(key, "normal", false)
end
return {
type = "button",
val = txt,
on_press = on_press,
opts = opts,
}
end
local function dash_button(sc, txt, keybind, keybind_opts)
local b = dashboard.button(sc, txt, keybind, keybind_opts)
b.opts.hl = {{"CursorLineNr", 0, 99}}
b.opts.hl_shortcut = {{ "MoreMsg", 0, 99}}
return b
end
local function file_to_strings(file_path)
local file = assert(io.open(file_path, "r"))
local text = file:read("*all")
file:close()
local logo = {""}
table.insert(logo, "")
for s in text:gmatch("[^\n]+") do
table.insert(logo, s)
end
table.insert(logo, "")
table.insert(logo, "")
return logo
end
local function header()
local logo = file_to_strings(os.getenv("HOME").."/logo_new.txt")
return logo
end
local function footer()
-- local total_plugins = #vim.tbl_keys(packer_plugins)
local datetime = os.date("%A %B %d %H:%M %p")
return datetime
end
-- dashboard.section.header.val = {
-- [[ _______ ____ ____.__ ]],
-- [[ \ \ ____ ___\ \ / /|__| _____ ]],
-- [[ / | \_/ __ \/ _ \ Y / | |/ \ ]],
-- [[/ | \ ___( <_> ) / | | Y Y \]],
-- [[\____|__ /\___ >____/ \___/ |__|__|_| /]],
-- [[ \/ \/ \/ ]],
-- }
dashboard.section.header.val = header()
dashboard.section.header.opts.hl = "Todo"
dashboard.section.buttons.val = {
dash_button("LDR f n", " New file", ":ene <BAR> startinsert <CR>"),
dash_button("LDR f o", " Recently opened files", ":Telescope oldfiles<CR>"),
dash_button("LDR f f", " Find file", ":Telescope find_files<CR>"),
dash_button("LDR f g", " Find word", ":Telescope live_grep<CR>"),
dash_button("LDR f s", " Open session", ":Telescope sessions<CR>"),
dash_button("LDR u d", " Update plugins", ":PlugInstall<CR>"),
dash_button("LDR q ", " Quit", "<Cmd>qa<CR>")
}
dashboard.section.footer.val = footer()
dashboard.section.footer.opts.hl = "Constant"
require"alpha".setup(dashboard.opts)
-- hide tabline on startup screen
vim.cmd [[
augroup alpha_hide
au!
au FileType alpha set showtabline=0 | au BufUnload <buffer> set showtabline=2
au FileType alpha set laststatus=0 | au BufUnload <buffer> set laststatus=2
au FileType alpha set nonumber nornu
au FileType alpha NumbersDisable
au Syntax *\(^alpha\)\@<! NumbersEnable
augroup END
]]
|
local event = {
{ _id = "on_physical_attack_hit" },
{ _id = "on_physical_attack_miss" },
{ _id = "after_physical_attack" },
{ _id = "on_ai_calm_action" },
{ _id = "on_ai_ally_action" },
{ _id = "on_item_eat_begin" },
{ _id = "on_chara_sleep" },
{ _id = "on_sleep_finish" },
{ _id = "on_dig_success" },
{ _id = "on_search_finish" },
{ _id = "on_feat_calc_materials" },
{ _id = "calc_dialog_choices" },
{ _id = "before_spawn_mobs" },
{ _id = "before_cast_return" },
{ _id = "on_chara_displaced" },
{ _id = "calc_wand_success" },
{ _id = "on_shop_restocked" },
{ _id = "calc_return_forbidden" },
{ _id = "before_physical_attack" },
{ _id = "on_item_created_from_wish" },
{ _id = "on_harvest_plant" },
{ _id = "on_ai_dir_check" },
{ _id = "before_default_ai_action" },
{ _id = "on_default_ai_action" },
{ _id = "on_generate_random_encounter_id" },
{ _id = "on_item_given" },
{ _id = "on_item_taken" },
{ _id = "on_add_random_enchantments" },
{ _id = "on_item_steal_attempt" },
{ _id = "on_weather_changed" },
{ _id = "on_chara_travel_in_world_map" },
{ _id = "on_feat_tile_digged_into" },
{ _id = "before_chara_drop_items" },
{ _id = "on_chara_generate_loot_drops" },
{ _id = "on_chara_initialize_equipment" },
{ _id = "on_house_board_queried" },
{ _id = "on_build_house_board_actions" },
{ _id = "before_travel_using_feat" },
{ _id = "on_chara_changed_guild" },
{ _id = "on_item_rot" },
{ _id = "on_travel_using_feat" },
{ _id = "on_populate_dungeon_map" },
{ _id = "on_chara_ranch_breed" },
}
data:add_multi("base.event", event)
|
if false then
print("Never occurs!")
elseif true then
print("Always has been.")
else
print("Never occurs!")
end
local cont = 0
while cont < 10 do
print("Inside while: "..cont)
cont = cont + 1
end
print("After WHILE ends: "..cont)
local last_value = 0
for i=0,10,3 do
print("Inside for: "..i)
last_value = i
end
print("After FOR ends: "..last_value)
local readable_fake_stream = {"", "", "", "", "", "", "", "", "", "", "", "", "", "", "You've found me!", "", "", "", "", "", "Oops, probably you missed the path."}
local line = ""
local i = 1
repeat
line = readable_fake_stream[i]
i = i + 1
until line ~= "" --> repeats until the expression evaluates to TRUE
print(line)
--[[
while true do
print("INF")
end
repeat
print("INF")
until false
--]]
|
function nadmin:GetBanReason(id) -- Inspired by ULX. You will notice a huge similarity (basically copied)
if not istable(nadmin.bans[id]) then return end
local ban = table.Copy(nadmin.bans[id])
local rep = {
BANNED_BY = "[Unknown]",
STEAMID = "[Unknown]",
BAN_DATE = "[Unknown]",
TIME_LEFT = "[Infinity]",
BAN_DUR = "[Permanent]",
UNBAN_DATE = "[Never]",
REASON = "No reason given."
}
if isstring(ban.by) and ban.by ~= "" then
rep.BANNED_BY = ban.by
end
if isstring(ban.by_steamid) and ban.by_steamid ~= "" then
rep.STEAMID = ban.by_steamid
end
if isnumber(ban.start) then
rep.BAN_DATE = os.date("%m/%d/%y %H:%M:%S", ban.start)
end
if isnumber(ban.dur) and ban.dur > 0 then
rep.BAN_DUR = nadmin:TimeToString(ban.dur, true)
end
if isnumber(ban.start) and isnumber(ban.dur) and ban.dur > 0 then
rep.TIME_LEFT = nadmin:TimeToString((ban.start + ban.dur) - os.time(), true)
rep.UNBAN_DATE = os.date("%m/%d/%y %H:%M:%S", ban.start + ban.dur)
end
if isstring(ban.reason) and ban.reason ~= "" then
rep.REASON = ban.reason
end
return string.gsub(nadmin.config.banMessage, "{{([%w_]+)}}", rep)
end
function nadmin:BanAsID(name, steamid, by, by_id, reason, dur)
if not isstring(steamid) then return end
local ban = {}
if isstring(by) then
ban.by = by
end
if isstring(by_id) then
ban.by_steamid = by_id
end
if isstring(reason) then
ban.reason = reason
end
if isnumber(dur) then
ban.dur = dur
end
ban.start = os.time()
ban.targ_nick = name
ban.targ_id = steamid
nadmin.bans[steamid] = table.Copy(ban)
local banMsg
for i, ply in ipairs(player.GetAll()) do
if ply:SteamID() == steamid or ply:IPAddress() == steamid then
if not isstring(banMsg) then banMsg = nadmin:GetBanReason(steamid) end
local nick = ply:Nick()
ply:RemoveProps()
nadmin.SilentNotify = true -- Don't show people the ban reason, and instead just show that they were disconencted from a ban.
ply:Kick(banMsg)
nadmin:Notify(nadmin.colors.blue, nick, nadmin.colors.white, " has been disconnected from a ban.")
end
end
nadmin:Log("messages", '"' .. steamid .. "\" has been banned.")
nadmin:SaveBans()
end
function nadmin:Ban(name, steamid, by, reason, dur)
if not isstring(steamid) then return end
local ban = {}
if isentity(by) and by:IsPlayer() then
ban.by = by:Nick()
ban.by_steamid = by:SteamID()
elseif isstring(by) then
ban.by = by
ban.by_steamid = by
end
if isstring(reason) then
ban.reason = reason
end
if isnumber(dur) then
ban.dur = dur
end
ban.start = os.time()
ban.targ_nick = name
ban.targ_id = steamid
nadmin.bans[steamid] = table.Copy(ban)
local banMsg
for i, ply in ipairs(player.GetAll()) do
if ply:SteamID() == steamid or ply:IPAddress() == steamid then
if not isstring(banMsg) then banMsg = nadmin:GetBanReason(steamid) end
local nick = ply:Nick()
ply:RemoveProps()
nadmin.SilentNotify = true -- Don't show people the ban reason, and instead just show that they were disconencted from a ban.
ply:Kick(banMsg)
nadmin:Notify(nadmin.colors.blue, nick, nadmin.colors.white, " has been disconnected from a ban.")
end
end
nadmin:Log("messages", '"' .. steamid .. "\" has been banned.")
nadmin:SaveBans()
end
function nadmin:Unban(id, noSave)
if istable(nadmin.bans[id]) then
nadmin.bans[id] = nil
if not noSave then
nadmin:SaveBans()
end
end
end
hook.Add("Think", "nadmin_auto_unban", function() -- Auto unban after duration is up
local keys = table.GetKeys(nadmin.bans) -- We are going to be looping backwards instead of forwards
local now = os.time()
-- Only save the bans file if someone was unbanned.
local changes = false
for i = #keys, 1, -1 do
local ban = nadmin.bans[keys[i]]
if isnumber(ban.dur) and ban.dur > 0 and ban.start + ban.dur <= now then
changes = true
nadmin:Unban(keys[i], true)
end
end
-- Save if changed
if changes then
nadmin:SaveBans()
end
end)
|
-- Test clock precision resilience.
-- params: [n]
package.path = "src/?.lua"
local Profiler = require("ELProfiler")
local n = ...
n = tonumber(n) or 1e7
local function a(n) return n+n end
local function b(n) return n+n end
local function c(n) return n+n end
local function d(n) return n+n end
local fs = {a,b,c,d}
local p_precision = -1
local function clock()
return p_precision > 0 and math.floor(os.clock()/p_precision)*p_precision or os.clock()
end
Profiler.setClock(clock)
local function test(precision)
p_precision = precision
print("[test 4 balanced funcs sequence]", "clock precision", precision)
Profiler.start()
for i=1,n do a(i) b(i) c(i) d(i) end
io.write(Profiler.format(Profiler.stop()))
print()
end
test(-1)
test(0.001)
test(0.01)
test(0.1)
test(1)
|
AddCSLuaFile()
if (CLIENT) then
SWEP.PrintName = "Fine Notepad"
SWEP.Slot = 1
SWEP.SlotPos = 2
SWEP.DrawAmmo = false
SWEP.DrawCrosshair = false
end
SWEP.Category = "Nutscript"
SWEP.Author = "AngryBaldMan"
SWEP.Instructions = ""
SWEP.Purpose = ""
SWEP.Drop = false
SWEP.HoldType = "melee"
SWEP.Spawnable = true
SWEP.AdminOnly = true
SWEP.ViewModelFOV = 47
SWEP.ViewModelFlip = false
SWEP.AnimPrefix = "melee"
SWEP.ViewTranslation = 4
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = ""
SWEP.Primary.Damage = 7.5
SWEP.Primary.Delay = 0.7
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = 0
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = ""
SWEP.ViewModel = Model("models/props_lab/clipboard.mdl")
SWEP.WorldModel = Model("models/props_lab/clipboard.mdl")
SWEP.UseHands = true
SWEP.LowerAngles = Angle(15, -10, -20)
SWEP.FireWhenLowered = true
function SWEP:Initialize()
self:SetHoldType( "normal" )
end
function SWEP:PrimaryAttack()
if SERVER then
owner = self.Owner;
trace = GetEyeTrace()
owner:LagCompensation(true)
local data = {}
data.start = self.Owner:GetShootPos()
data.endpos = data.start + owner:GetAimVector()*72
data.filter = self.Owner
local trace = util.TraceLine(data)
owner:LagCompensation(false)
if trace.Hit then
local entity = trace.Entity
if (IsValid(entity) and entity:IsPlayer()) then
if entity:getChar():getClass() == CLASS_POLICE then
owner:notify("You cannot fine government officials!")
else
end
end
end
end
end
if CLIENT then
function SWEP:GetViewModelPosition(vPos, aAngles)
vPos = vPos + LocalPlayer():GetUp() * -7
vPos = vPos + LocalPlayer():GetAimVector() * 20
vPos = vPos + LocalPlayer():GetRight() * 7
aAngles:RotateAroundAxis(aAngles:Right(), 90)
aAngles:RotateAroundAxis(aAngles:Forward(), 0)
aAngles:RotateAroundAxis(aAngles:Up(), 180)
return vPos, aAngles
end
end
function SWEP:DrawWorldModel()
if not IsValid(self.Owner) then
return
end
local boneindex = self.Owner:LookupBone("ValveBiped.Bip01_R_Hand")
if boneindex then
local HPos, HAng = self.Owner:GetBonePosition(boneindex)
local offset = HAng:Right() * 0.5 + HAng:Forward() * 7 + HAng:Up() * 0.518
HAng:RotateAroundAxis(HAng:Right(), 10)
HAng:RotateAroundAxis(HAng:Forward(), 90)
HAng:RotateAroundAxis(HAng:Up(), 80)
self:SetRenderOrigin(HPos + offset)
self:SetRenderAngles(HAng)
self:DrawModel()
end
end
|
local M = {}
-- table information begin
local tableName = 'userBase'
-- table information end
local Util = require "sora.util"
function M.new(o,isSingleton)
local ins
local SoraModelMysql = require 'sora.model.mysql'
if isSingleton then
setmetatable(M, { __index = SoraModelMysql:new() })
ins = { tableName = tableName }
setmetatable(
ins,
{
__index = M
}
)
else
ins = o or {}
ins.tableName = tableName
setmetatable(
ins,
{
__index = SoraModelMysql:new()
}
)
end
ins:mysqlConnectService(isSingleton)
return ins
end
function M:add(userData)
if not userData.userName or userData.userName == "" then
self.errorMessage = "userName is required."
return false
end
local insertData = {
userName = userData.userName,
password = userData.password,
}
if userData.projectId then insertData.projectId = userData.projectId end
if self.config.auth.pass2hash and self.config.auth.hashAlgorithm then
if self.config.auth.hashAlgorithm:lower() == "md5" then
insertData.password = Util.md5(userData.password)
insertData.hashAlgorithm = self.config.auth.hashAlgorithm:lower()
end
end
local res,err = self:insert(insertData, true)
if res then return res end
self.errorMessage = err
return false
end
function M:modify(userData)
if not userData.userId then
self.errorMessage = "userId is required."
return false
end
if userData.password and self.config.auth.pass2hash and self.config.auth.hashAlgorithm then
if self.config.auth.hashAlgorithm:lower() == "md5" then
userData.password = Util.md5(userData.password)
userData.hashAlgorithm = self.config.auth.hashAlgorithm:lower()
end
end
return self:update(
{ "userId =", userData.userId },
userData
)
end
function M:remove(userData)
if not userData.userId then
self.errorMessage = "userId is required."
return false
end
return self:delete(
{ "userId =", userData.userId }
)
end
function M:auth(userId, password)
local record = self:select(
{
userId = userId,
password = password,
}
)
if record then return true else return false end
end
function M:getUserData(userId)
local rows = self:select(
{
'userId = ', userId
}
)
if not rows then return nil end
return rows[1]
end
return M
|
ITEM.name = "TOZ-194"
ITEM.description= "A pump-action shotgun. Fires 12 gauge."
ITEM.longdesc = "A classic 90's russian civilian shotgun, used in much of Europe as a hunting weapon. It is fairly long and unweildy, as to be legal for the civilian market in its country of origin, Russia, it had to have an overall legnth of 80cm's.\n\nAmmo: 12 Gauge \nMagazine Capacity: 3"
ITEM.model = ("models/khrcw2/w_khri_khrtoz194.mdl")
ITEM.class = "cw_toz194"
ITEM.weaponCategory = "primary"
ITEM.price = 8000
ITEM.width = 4
ITEM.height = 1
ITEM.canAttach = false
ITEM.bulletweight = 0.031
ITEM.unloadedweight = 2.9
ITEM.repair_PartsComplexity = 1
ITEM.repair_PartsRarity = 2
function ITEM:GetWeight()
return self.unloadedweight + (self.bulletweight * self:GetData("ammo", 0))
end
ITEM.iconCam = {
pos = Vector(18, -160, 2),
ang = Angle(0, 90, 0),
fov = 12.5,
}
ITEM.pacData = {
[1] = {
["children"] = {
[1] = {
["children"] = {
[1] = {
["children"] = {
},
["self"] = {
["Angles"] = Angle(0, 180, 180),
["Position"] = Vector(14.98, -4.153, -1.175),
["Model"] = "models/khrcw2/w_khri_khrtoz194.mdl",
["ClassName"] = "model",
["EditorExpand"] = true,
["UniqueID"] = "15233125",
["Bone"] = "spine 2",
["Name"] = "toz194",
},
},
},
["self"] = {
["AffectChildrenOnly"] = true,
["ClassName"] = "event",
["UniqueID"] = "13553232553",
["Event"] = "weapon_class",
["EditorExpand"] = true,
["Name"] = "weapon class find simple\"@@1\"",
["Arguments"] = "cw_toz194@@0",
},
},
},
["self"] = {
["ClassName"] = "group",
["UniqueID"] = "125512152",
["EditorExpand"] = true,
},
},
}
|
local AddonName, AddonTable = ...
-- Soulbound Items (Green or higher)
AddonTable.loot = {
44360,
55314,
55401,
55403,
55404,
55405,
55421,
55422,
55423,
55567,
55619,
55693,
55702,
55773,
57281,
57283,
57292,
59520,
65655,
65656,
65658,
66890,
66902,
66885,
66887,
66974,
68915,
68972,
70929,
71367,
76156,
113695,
-- Scorched Satchel of Helpful Goods
113713,
113717,
113760,
113761,
113775,
113786,
156689,
-- Class Sets
--- Wind Dancer's Regalia (Rogue)
60298,
60299,
60300,
60301,
60302,
65239,
65240,
65241,
65242,
65243,
--- Stormrider's Battlegarb (Druid)
65189,
65190,
65191,
65192,
65193,
}
|
local mod = yatm_data_noteblock
local string_hex_unescape = assert(foundation.com.string_hex_unescape)
local is_table_empty = assert(foundation.com.is_table_empty)
local Cuboid = assert(foundation.com.Cuboid)
local ng = Cuboid.new_fast_node_box
local data_network = assert(yatm.data_network)
-- Just like a mesecon noteblock, except triggered by data events
mod:register_node("data_noteblock", {
description = mod.S("DATA Note Block"),
codex_entry_id = "yatm_data_noteblock:data_noteblock",
groups = {
cracky = 1,
data_programmable = 1,
yatm_data_device = 1,
},
paramtype = "none",
paramtype2 = "facedir",
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
ng(0, 0, 0, 16, 5, 16),
ng(2, 5, 2, 12,10, 12),
ng( 0,14, 0, 16, 2, 2),
ng( 0,14,14, 16, 2, 2),
ng( 0,14, 0, 2, 2, 16),
ng(14,14, 0, 2, 2, 16),
},
},
tiles = {
"yatm_data_noteblock_top.png",
"yatm_data_noteblock_bottom.png",
"yatm_data_noteblock_side.png",
"yatm_data_noteblock_side.png",
"yatm_data_noteblock_side.png",
"yatm_data_noteblock_side.png",
},
on_construct = function (pos)
local meta = minetest.get_meta(pos)
meta:set_int("damper", 0)
local node = minetest.get_node(pos)
data_network:add_node(pos, node)
end,
after_destruct = function (pos, node)
data_network:remove_node(pos, node)
end,
data_network_device = {
type = "device",
},
data_interface = {
on_load = function (self, pos, node)
yatm_data_logic.mark_all_inputs_for_active_receive(pos)
end,
receive_pdu = function (self, pos, node, dir, local_port, value)
--print("receive_pdu", minetest.pos_to_string(pos), node.name, dir, local_port, dump(value))
local meta = minetest.get_meta(pos)
local payload = string_hex_unescape(value)
local key = string.byte(payload, 1)
if key then
key = key + meta:get_int("offset")
local damper = meta:get_int("damper")
yatm.noteblock.play_note(pos, node, key, math.max(0, 127 - damper))
end
end,
get_programmer_formspec = {
default_tab = "ports",
tabs = {
{
tab_id = "ports",
title = "Ports",
header = "Port Configuration",
render = {
{
component = "io_ports",
mode = "i",
}
},
},
{
tab_id = "data",
title = "Data",
header = "Data Configuration",
render = {
{
component = "row",
items = {
{
component = "field",
label = "Offset",
name = "offset",
type = "integer",
meta = true,
},
{
component = "field",
label = "Damper",
name = "damper",
type = "integer",
meta = true,
}
}
}
}
}
}
},
receive_programmer_fields = {
tabbed = true, -- notify the solver that tabs are in use
tabs = {
{
components = {
{component = "io_ports", mode = "o"}
}
},
{
components = {
{
component = "field",
name = "offset",
type = "integer",
meta = true,
},
{
component = "field",
name = "damper",
type = "integer",
meta = true,
}
}
}
}
},
},
refresh_infotext = function (pos)
local meta = minetest.get_meta(pos)
local infotext =
data_network:get_infotext(pos)
meta:set_string("infotext", infotext)
end,
})
|
local env, func = ...
assert(func, 'securecall of nil function')
if type(func) == 'string' then
assert(env[func], 'securecall of unknown function ' .. func)
func = env[func]
end
return securecall(func, select(3, ...))
|
CC_Config = {}
CC = {}
CC_Config.Text = {
MenuTitle = "Character Creater",
NameTitle = "Full Name",
SexTitle = "Sex",
ModelTitle = "Model",
CreateButton = "Create Character",
CreationSuccess = "Your Character has been Successfully created!",
ErrorName = "ERROR: No Name has been written!",
ErrorSex = "ERROR: No Sex has been selected!",
InvalidArguments = "[CC] Invalid Arguments",
NoPermission = "[CC] You Dont have the Permissions to use this Command!",
}
CC_Config.Sex = {
Sex = "Sex",
Male = "Male",
Female = "Female",
}
CC_Config.CanUseCommand = {
"superadmin",
"admin"
}
CC_Config.MaleModels = {
"models/player/group01/male_01.mdl",
"models/player/group01/male_02.mdl",
"models/player/group01/male_03.mdl",
"models/player/group01/male_04.mdl",
"models/player/group01/male_05.mdl",
"models/player/group01/male_06.mdl",
"models/player/group01/male_07.mdl",
"models/player/group01/male_08.mdl",
"models/player/group01/male_09.mdl",
"models/player/group02/male_02.mdl",
"models/player/group02/male_04.mdl",
"models/player/group02/male_06.mdl",
"models/player/group02/male_08.mdl",
}
CC_Config.FemaleModels = {
"models/player/group01/female_01.mdl",
"models/player/group01/female_02.mdl",
"models/player/group01/female_03.mdl",
"models/player/group01/female_04.mdl",
"models/player/group01/female_05.mdl",
"models/player/group01/female_06.mdl",
}
CC_Config.SetNameCommands = true
CC_Config.CommandName = "!setName"
CC_Config.CommandNameQuick = "!sn"
CC_Config.DisableNameChangeCommands = true
/*
Ignore this
*/
local meta = FindMetaTable("Player")
function meta:HasCharacter()
local path = "cc_data/"..self:SteamID64()..".txt"
if ( file.Exists(path, "DATA") ) then
return true
else
return false
end
end
function meta:GetCharacterData()
local path = "cc_data/"..self:SteamID64()..".txt"
if ( !file.Exists(path, "DATA") ) then return end
local Tbl = {}
Tbl = util.JSONToTable(file.Read(path, "DATA"))
return Tbl
end
hook.Add("DarkRPFinishedLoading", "CC_removeCommands", function()
if ( CC_Config.DisableNameChangeCommands ) then
DarkRP.removeChatCommand("name")
DarkRP.removeChatCommand("rpname")
end
end)
|
set_xmakever("2.5.1")
set_languages("cxx11")
add_rules("mode.debug", "mode.release")
target("DebugUtils")
set_kind("static")
add_includedirs(
"DebugUtils/Include",
"Detour/Include",
"DetourTileCache/Include",
"Recast/Include")
add_headerfiles("DebugUtils/Include/*.h")
add_files("DebugUtils/Source/*.cpp")
target("Detour")
set_kind("static")
add_includedirs("Detour/Include")
add_headerfiles("Detour/Include/*.h")
add_files("Detour/Source/*.cpp")
target("DetourCrowd")
set_kind("static")
add_includedirs(
"DetourCrowd/Include",
"Detour/Include",
"Recast/Include")
add_headerfiles("DetourCrowd/Include/*.h")
add_files("DetourCrowd/Source/*.cpp")
target("DetourTileCache")
set_kind("static")
add_includedirs(
"DetourTileCache/Include",
"Detour/Include",
"Recast/Include")
add_headerfiles("DetourTileCache/Include/*.h")
add_files("DetourTileCache/Source/*.cpp")
target("Recast")
set_kind("static")
add_includedirs("Recast/Include")
add_headerfiles("Recast/Include/*.h")
add_files("Recast/Source/*.cpp")
|
--riazzerawifi.lua
-- Starts the portal to choose the wi-fi router to which we have
-- to associate
wifi.sta.disconnect()
wifi.setmode(wifi.STATIONAP)
--ESP SSID generated wiht its chipid
wifi.ap.config({ssid="Mynode-"..node.chipid()
, auth=wifi.OPEN})
enduser_setup.manual(true)
enduser_setup.start(
function()
print("Connected to wifi as:" .. wifi.sta.getip())
end,
function(err, str)
print("enduser_setup: Err #" .. err .. ": " .. str)
end
);
|
local event = require("event")
local component = require("component")
local commandBlock = component.command_block
local chatBox = component.chat_box
local nickname = "PaladinCVM"
local commanderNickname = "ECS"
local spamDelay = 1
local function execute(command)
commandBlock.setCommand(command)
commandBlock.executeCommand()
end
local function tellraw(from, to, message)
local text = "/tellraw @a[name=" .. to .. "] [\"\",{\"text\":\"\n\n\n\n\n\n\n\n\n\n\n\n" .. from .. "\",\"color\":\"gold\"},{\"text\":\": " .. message .. "\",\"color\":\"none\"}]"
execute(text)
end
local function spamDro4er()
local message = "Удали из ЧС в скайпе и позвони мне, мой сладкий!" .. math.random(1, 1000)
tellraw("Сообщение от Игоря", nickname, message)
execute("/spawn @a[name=" .. nickname .. "]")
end
local function chatDro4er(...)
local e = {...}
if e[3] == commanderNickname then
if e[4] == "активировать спам-бота" then
chatBox.say("Спам-бот активирован на цель \"" .. nickname .. "\". Версия 2.4a")
_G.spamDro4erID = event.timer(1, spamDro4er, math.huge)
elseif e[4] == "деактивировать спам-бота" and _G.spamDro4erID then
chatBox.say("Спам-бот на цель \"" .. nickname .. "\" деактивирован.")
event.cancel(_G.spamDro4erID)
_G.spamDro4erID = nil
end
end
end
event.listen("chat_message", chatDro4er)
|
return {
fitScaleFactor = function(displayObject, fitWidth, fitHeight, enlarge)
local scaleFactor = fitHeight / displayObject.height
local newWidth = displayObject.width * scaleFactor
if newWidth > fitWidth then
scaleFactor = fitWidth / displayObject.width
end
if not enlarge and scaleFactor > 1 then
return 1
end
return scaleFactor
end,
coverScaleFactor = function(displayObject, fitWidth, fitHeight, enlarge)
local scaleFactor = fitHeight / displayObject.height
local newWidth = displayObject.width * scaleFactor
if newWidth < fitWidth then
scaleFactor = fitWidth / displayObject.width
end
if not enlarge and scaleFactor > 1 then
return 1
end
return scaleFactor
end
}
|
return Def.Sprite {
Texture=NOTESKIN:GetPath( '_centerp1', 'tap note' );
Frame0000=3;
Delay0000=1;
};
|
--[[
Copyright 2012 The lev Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local exports = {}
exports['lev.tcp:\ttcp_echo_test'] = function(test)
local lev = require('lev')
local PING_BUF = Buffer:new("\0\1\2\3")
local PONG_BUF = Buffer:new("\3\2\1\0")
--TODO: Implement function for getting environment variables.
--local PORT = process.env.PORT or 10082
local PORT = 10082
local TEST_BUF = Buffer:new("\9\8\7\6")
local server = lev.tcp.new()
server:bind("127.0.0.1", PORT)
server:listen(function(s, err)
p("server:listen", s, err)
test.is_nil(err)
local client = s:accept()
p("accepted client", client)
client:on_close(function(c)
p("client closed", c)
test.done()
end)
client:read_start(function(c, nread, buf)
p("server:received")
test.equal(nread, 4)
test.equal(tostring(buf), "\0\1\2\3")
-- this seems weird to have here, but it helps
-- test an edge case with cBuffers
local test_res = buf .. TEST_BUF
test.equal(test_res:inspect(), "<Buffer 00 01 02 03 09 08 07 06 >")
c:write(PONG_BUF)
end)
end)
local client = lev.tcp.new()
client:connect("127.0.0.1", PORT, function(...)
p("connected")
client:write(PING_BUF)
client:read_start(function(c, nread, buf)
p("client:received")
test.equal(nread, 4)
test.equal(tostring(buf), "\3\2\1\0")
client:close()
end)
end)
end
return exports
|
local M = {}
function M.get_padding(depth)
return string.rep(' ', depth)
end
local function get_padding_arrows(icon_state)
return function(depth, _, _, node)
if node.entries then
local icon = icon_state.icons.folder_icons[node.open and 'arrow_open' or 'arrow_closed']
return string.rep(' ', depth - 2)..icon..' '
end
return string.rep(' ', depth)
end
end
local function get_padding_indent_markers(depth, idx, tree, _, markers)
local padding = ""
if depth ~= 0 then
local rdepth = depth/2
markers[rdepth] = idx ~= #tree.entries
for i=1,rdepth do
if idx == #tree.entries and i == rdepth then
padding = padding..'└ '
elseif markers[i] then
padding = padding..'│ '
else
padding = padding..' '
end
end
end
return padding
end
function M.reload_padding_function()
local icon_state = require'nvim-tree.config'.get_icon_state()
if icon_state.show_folder_icon and icon_state.show_folder_arrows then
M.get_padding = get_padding_arrows(icon_state)
end
if vim.g.nvim_tree_indent_markers == 1 then
M.get_padding = get_padding_indent_markers
end
end
return M
|
data:extend{
{
type = "item",
name = "night-vision-mk2-equipment",
icon = "__base__/graphics/icons/night-vision-equipment.png",
icon_size = 32,
placed_as_equipment_result = "night-vision-mk2-equipment",
subgroup = "equipment",
order = "f[night-vision]-b[night-vision-mk2-equipment]",
stack_size = 10,
default_request_amount = 1
},
{
type = "item",
name = "energy-shield-mk3-equipment",
icon = "__Power Armor MK3__/graphics/icons/energy-shield-mk3-equipment.png",
icon_size = 32,
placed_as_equipment_result = "energy-shield-mk3-equipment",
subgroup = "equipment",
order = "b[shield]-c[energy-shield-equipment-mk3]",
stack_size = 50,
default_request_amount = 5
},
{
type = "item",
name = "battery-mk3-equipment",
icon = "__Power Armor MK3__/graphics/icons/battery-mk3-equipment.png",
icon_size = 32,
placed_as_equipment_result = "battery-mk3-equipment",
subgroup = "equipment",
order = "c[battery]-c[battery-equipment-mk3]",
stack_size = 50,
default_request_amount = 5
},
{
type = "item",
name = "nuclear-reactor-equipment",
icon = "__base__/graphics/icons/nuclear-reactor.png",
icon_size = 32,
placed_as_equipment_result = "nuclear-reactor-equipment",
subgroup = "equipment",
order = "a[energy-source]-c[nuclear-reactor]",
stack_size = 20,
default_request_amount = 5
},
{
type = "item",
name = "singularity-equipment",
icon = "__Power Armor MK3__/graphics/icons/singularity-equipment.png",
icon_size = 32,
placed_as_equipment_result = "singularity-equipment",
subgroup = "equipment",
order = "a[energy-source]-d[singularity]",
stack_size = 20,
default_request_amount = 5
}
}
|
-- MINETEST REGISTRATION FUNCTIONS CALLS.
-- ============================================================================
local tex_names_used = {
"real_elevators_shaft_back_block.png",
"real_elevators_shaft_back_block2.png",
"real_elevators_shaft_side_block2.png",
"real_elevators_outer_doors.png",
"real_elevators_outer_wall_with_button_top.png",
"real_elevators_outer_wall_with_button_bottom.png",
"real_elevators_outer_wall_with_button_right.png",
"real_elevators_outer_wall_with_button_left.png",
"real_elevators_outer_wall_with_button_front_off.png",
"real_elevators_outer_wall_with_button_front_on.png",
}
local elevator_parts_defs = {
["elevator_shaft_leftside"] = {
description = elevators.S("Elevator Shaft (Left) Side Block"),
tiles = {3, 3, 3, 3, 3, 1},
node_box = {
{-0.5, -0.5, 0.0, -0.4, 0.5, 0.5},
{-0.4, -0.5, -0.5, 0.5, 0.5, 0.5}
},
groups = {shaft=1},
sounds = default.node_sound_stone_defaults(),
craft = {
recipe = {
{"", "default:clay_lump", "basic_materials:steel_bar"},
{"", "default:clay_lump", "basic_materials:steel_bar"},
{"", "default:clay_lump", "basic_materials:steel_bar"}
}
}
},
["elevator_shaft_rightside"] = {
description = elevators.S("Elevator Shaft (Right) Side Block"),
tiles = {3, 3, 3, 3, 3, 1},
node_box = {
{-0.5, -0.5, -0.5, 0.4, 0.5, 0.5},
{0.4, -0.5, 0.0, 0.5, 0.5, 0.5}
},
groups = {shaft=1},
sounds = default.node_sound_stone_defaults(),
craft = {
recipe = {
{"basic_materials:steel_bar", "default:clay_lump", ""},
{"basic_materials:steel_bar", "default:clay_lump", ""},
{"basic_materials:steel_bar", "default:clay_lump", ""}
}
}
},
["elevator_shaft_back"] = {
description = elevators.S("Elevator Shaft Back Block"),
tiles = {2, 2, 2, 2, 2, 1},
collision_box = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},
groups = {shaft=1},
sounds = default.node_sound_stone_defaults(),
craft = {
recipe = {
{"basic_materials:steel_bar", "default:clay_lump", "basic_materials:steel_bar"},
{"basic_materials:steel_bar", "default:clay_lump", "basic_materials:steel_bar"},
{"basic_materials:steel_bar", "default:clay_lump", "basic_materials:steel_bar"}
}
}
},
["elevator_outer_wall_leftslot"] = {
description = elevators.S("Elevator Outer Wall With Left Slot"),
tiles = {3},
node_box = {
{-0.5, -0.5, 0.4, 0.0, 0.5, 0.5},
{-0.5, -0.5, 0.0, 0.5, 0.5, 0.4}
},
sounds = default.node_sound_stone_defaults(),
craft = {
recipe = {
{"", "", "default:clay_lump"},
{"", "", "default:clay_lump"},
{"", "", "default:clay_lump"}
}
}
},
["elevator_outer_wall_rightslot"] = {
description = elevators.S("Elevator Outer Wall With Right Slot"),
tiles = {3},
node_box = {
{0.0, -0.5, 0.4, 0.5, 0.5, 0.5},
{-0.5, -0.5, 0.0, 0.5, 0.5, 0.4}
},
sounds = default.node_sound_stone_defaults(),
craft = {
recipe = {
{"default:clay_lump", "", ""},
{"default:clay_lump", "", ""},
{"default:clay_lump", "", ""}
}
}
},
["elevator_outer_wall"] = {
description = elevators.S("Elevator Outer Wall"),
tiles = {3},
node_box = {-0.5, -0.5, 0.0, 0.5, 0.5, 0.5},
sounds = default.node_sound_stone_defaults(),
craft = {
recipe = {
{"", "default:clay_lump", ""},
{"", "default:clay_lump", ""},
{"", "default:clay_lump", ""}
}
}
},
["elevator_outer_shaft_wall"] = {
description = elevators.S("Elevator Outer Shaft Wall"),
tiles = {3, 3, 3, 3, 3, 1},
node_box = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.0},
groups = {shaft=1},
sounds = default.node_sound_stone_defaults(),
craft = {
recipe = {"real_elevators:elevator_shaft_back"},
replacements = {{"real_elevators:elevator_shaft_back", "real_elevators:elevator_outer_wall"}}
}
},
["elevator_shaft_corner"] = {
description = elevators.S("Elevator Shaft Corner Block"),
tiles = {2},
collision_box = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},
sounds = default.node_sound_stone_defaults(),
craft = {
type = "shapeless",
recipe = {"default:clay"}
}
},
["elevator_outer_wall_with_trigger_off"] = {
description = elevators.S("Elevator Outer Wall With Trigger (off)"),
tiles = {5, 6, 7, 8, 2, 9},
node_box = {
{-0.5, -0.5, 0.0, 0.5, 0.5, 0.4},
{-0.5, -0.5, 0.4, 0.0, 0.5, 0.5},
{-0.185, -0.25, -0.05, 0.185, 0.25, 0.0}
},
light_source = 3,
groups = {trigger=1, state=0},
sounds = default.node_sound_stone_defaults(),
on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)
elevators.call(pos)
end,
craft = {
recipe = {
{"default:clay_lump", "default:clay_lump", "default:clay_lump"},
{"default:clay_lump", "basic_materials:ic", "default:clay_lump"},
{"default:clay_lump", "basic_materials:plastic_sheet", "default:clay_lump"}
}
}
},
["elevator_outer_wall_with_trigger_on"] = {
description = elevators.S("Elevator Outer Wall With Trigger (on)"),
tiles = {5, 6, 7, 8, 2, 10},
node_box = {
{-0.5, -0.5, 0.0, 0.5, 0.5, 0.4},
{-0.5, -0.5, 0.4, 0.0, 0.5, 0.5},
{-0.185, -0.25, -0.05, 0.185, 0.25, 0.0}
},
light_source = 3,
drop = "real_elevators:elevator_outer_wall_with_trigger_off",
groups = {not_in_creative_inventory=1, trigger=1, state=1},
sounds = default.node_sound_stone_defaults()
},
["elevator_doors_closed"] = {
visual_scale = 0.5,
description = elevators.S("Elevator doors (closed)"),
mesh = "real_elevators_elevator_doors_closed.b3d",
tiles = {4},
collision_box = {-0.5, -0.5, 0.4, 0.5, 1.5, 0.5},
groups = {doors=1, state=0},
sounds = default.node_sound_metal_defaults(),
craft = {
type = "shapeless",
recipe = {"stairs:slab_steelblock", "stairs:slab_steelblock", "stairs:slab_steelblock", "stairs:slab_steelblock"}
}
},
["elevator_doors_opened"] = {
visual_scale = 0.5,
description = elevators.S("Elevator doors (opened)"),
mesh = "real_elevators_elevator_doors_opened.b3d",
tiles = {4},
collision_box = {
{-1.0, -0.5, 0.4, -0.5, 1.5, 0.5},
{0.5, -0.5, 0.4, 1.0, 1.5, 0.5}
},
groups = {not_in_creative_inventory=1, doors=1, state=1},
sounds = default.node_sound_metal_defaults()
},
["elevator_winch"] = {
description = elevators.S("Elevator Winch"),
mesh = "real_elevators_winch.b3d",
tiles = {"real_elevators_winch.png"},
collision_box = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},
sounds = default.node_sound_metal_defaults(),
craft = {
recipe = {
{"basic_materials:gear_steel", "basic_materials:steel_wire", "basic_materials:motor"},
{"basic_materials:steel_bar", "basic_materials:steel_bar", "basic_materials:steel_bar"},
{"basic_materials:steel_bar", "real_elevators:elevator_rope", "basic_materials:steel_bar"}
}
}
},
["elevator_rope"] = {
description = elevators.S("Elevator Rope"),
drawtype = "plantlike",
tiles = {"real_elevators_rope.png"},
collision_box = {-0.2, -0.5, -0.2, 0.2, 0.5, 0.2},
walkable = false,
climbable = true,
sounds = default.node_sound_leaves_defaults(),
craft = {
recipe = {
{"", "farming:cotton", ""},
{"", "basic_materials:steel_strip", ""},
{"", "farming:cotton", ""}
}
}
}
}
for name, def in pairs(elevator_parts_defs) do
local full_def = {
paramtype = "light",
paramtype2 = "facedir",
sunlight_propagates = true,
groups = {cracky=1.5},
}
full_def.visual_scale = def.visual_scale or 1.0
full_def.description = def.description
full_def.tiles = {}
for i, index in ipairs(def.tiles) do
if type(index) == "number" then
full_def.tiles[i] = tex_names_used[index]
else
full_def.tiles[i] = index
end
end
if def.node_box then
full_def.drawtype = "nodebox"
full_def.node_box = {
type = "fixed",
fixed = def.node_box
}
elseif def.collision_box then
if type(def.mesh) == "string" and def.mesh ~= "" then
full_def.drawtype = "mesh"
full_def.mesh = def.mesh
else
full_def.drawtype = def.drawtype
end
full_def.collision_box = {
type = "fixed",
fixed = def.collision_box
}
end
full_def.selection_box =
full_def.drawtype == "node_box" and full_def.node_box or full_def.collision_box
full_def.walkable = def.walkable
full_def.pointable = def.pointable
full_def.climbable = def.climbable
full_def.light_source = def.light_source
if def.groups ~= nil then
for name, value in pairs(def.groups) do
full_def.groups[name] = value
end
end
full_def.sounds = def.sounds
full_def.on_construct = def.on_construct
full_def.on_rightclick = def.on_rightclick
full_def.on_timer = def.on_timer
minetest.register_node("real_elevators:" .. name, full_def)
if def.craft then
local craft_def = def.craft
craft_def.type = craft_def.type or craft_def.replacements and "shapeless"
craft_def.output = "real_elevators:" .. name
minetest.register_craft(craft_def)
end
end
elevators.elevator_doors = minetest.deserialize(elevators.mod_storage:get_string("elevator_doors")) or {}
minetest.register_node("real_elevators:elevator_cabin", {
description = elevators.S("Elevator cabin"),
visual_scale = 0.1,
wield_scale = {x=0.1, y=0.1, z=0.1},
drawtype = "mesh",
mesh = "real_elevators_elevator_cabin.b3d",
tiles = {"real_elevators_new_cabin.png"},
paramtype = "light",
paramtype2 = "facedir",
sunlight_propagates = true,
collision_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.4, 0.5, -0.45, 0.5}, -- Bottom
{-0.5, -0.45, -0.4, -0.45, 1.45, 0.5}, -- Left Side
{0.45, -0.45, -0.4, 0.5, 1.45, 0.5}, -- Right Side
{-0.5, 1.45, -0.4, 0.5, 1.5, 0.5}, -- Top
{-0.45, -0.45, 0.45, 0.45, 1.45, 0.5}, -- Back
--{-0.5, -0.5, -0.5, 0.5, 1.5, -0.4} -- Front
}
},
selection_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.4, 0.5, -0.45, 0.5}, -- Bottom
{-0.5, -0.45, -0.4, -0.45, 1.45, 0.5}, -- Left Side
{0.45, -0.45, -0.4, 0.5, 1.45, 0.5}, -- Right Side
{-0.5, 1.45, -0.4, 0.5, 1.5, 0.5}, -- Top
{-0.45, -0.45, 0.45, 0.45, 1.45, 0.5}, -- Back
--{-0.5, -0.5, -0.5, 0.5, 1.5, -0.4} -- Front
}
},
groups = {cracky=1.5, cabin=1},
sounds = default.node_sound_metal_defaults(),
on_construct = function(pos)
local net_name = elevators.get_net_name_from_cabin_pos(pos)
local meta = minetest.get_meta(pos)
--meta:set_string("state", "idle")
meta:set_string("formspec", net_name and elevators.elevators_nets[net_name].cabin.formspec or elevators.get_enter_elevator_net_name_formspec())
end,
after_place_node = function(pos, placer, itemstack, pointed_thing)
local node = minetest.get_node(pos)
local playername = placer:get_player_name()
local success = elevators.check_for_surrounding_shaft_nodes(pos, minetest.facedir_to_dir(node.param2), playername)
if not success then
minetest.remove_node(pos)
end
success = elevators.check_for_rope(pos, playername)
if not success then
minetest.remove_node(pos)
end
return
end,
on_destruct = function(pos)
local net_name = minetest.get_meta(pos):get_string("elevator_net_name")
if net_name ~= "" then
elevators.elevators_nets[net_name].cabin.inner_doors.left:remove()
elevators.elevators_nets[net_name].cabin.inner_doors.right:remove()
elevators.elevators_nets[net_name] = nil
end
end,
on_timer = function(pos, elapsed)
local net_name = minetest.get_meta(pos):get_string("elevator_net_name")
if net_name ~= "" then
--minetest.debug("Closing doors...")
elevators.move_doors(net_name, "close")
end
end,
on_receive_fields = function(pos, formname, fields, sender)
if fields.quit then
return
end
if fields.elevator_net_name_enter then
if fields.elevator_net_name == "" then
minetest.chat_send_player(sender:get_player_name(), "The elevator net name can not be empty!")
return
end
if elevators.elevators_nets[fields.elevator_net_name] then
minetest.chat_send_player(sender:get_player_name(), "This elevator net name already exists!")
return
end
elevators.elevators_nets[fields.elevator_net_name] = {
floors = {},
cabin = {
position = pos,
inner_doors = {},
queue = {},
attached_objs = {}
}
}
local left_door, right_door = elevators.set_doors(pos, minetest.facedir_to_dir(minetest.get_node(pos).param2), -0.45, 0.25)
elevators.elevators_nets[fields.elevator_net_name].cabin.inner_doors.left = left_door
elevators.elevators_nets[fields.elevator_net_name].cabin.inner_doors.right = right_door
elevators.elevators_nets[fields.elevator_net_name].cabin.state = "idle"
local meta = minetest.get_meta(pos)
meta:set_string("elevator_net_name", fields.elevator_net_name)
meta:set_string("formspec", elevators.get_add_floor_formspec())
end
if fields.set_floor then
if fields.floor_number == "" then
minetest.chat_send_player(sender:get_player_name(), "The floor number must be set!")
return
end
local floor_pos = minetest.string_to_pos(fields.floor_pos)
if not floor_pos then
if elevators.current_marked_pos then
floor_pos = elevators.current_marked_pos
else
minetest.chat_send_player(sender:get_player_name(), "The floor position must be set!")
end
return
end
local elevator_net_name = minetest.get_meta(pos):get_string("elevator_net_name")
for i, floor in ipairs(elevators.elevators_nets[elevator_net_name].floors) do
if floor.number == fields.floor_number then
minetest.chat_send_player(sender:get_player_name(), "There is already the floor with such number in this elevator net!")
return
end
if vector.equals(floor.position, floor_pos) then
minetest.chat_send_player(sender:get_player_name(), "There is already the floor with such position in this elevator net!")
return
end
end
-- In future, probably horizontally moving elevators will be added, but for now only vertically
if pos.x ~= floor_pos.x or pos.z ~= floor_pos.z then
minetest.chat_send_player(sender:get_player_name(), "You can not add floor with position that is not aligned with the elevator cabin position along Y axis!")
return
end
elevators.elevators_nets[elevator_net_name].floors[#elevators.elevators_nets[elevator_net_name].floors+1] = {}
local new_floor = elevators.elevators_nets[elevator_net_name].floors[#elevators.elevators_nets[elevator_net_name].floors]
new_floor.number = fields.floor_number
new_floor.description = fields.floor_description
new_floor.position = floor_pos
local meta = minetest.get_meta(pos)
meta:set_string("formspec", elevators.get_floor_list_formspec(elevator_net_name))
end
if fields.add_floor then
local meta = minetest.get_meta(pos)
meta:set_string("formspec", elevators.get_add_floor_formspec())
end
if fields.floor_add and fields.floor_number ~= "" then
local meta = minetest.get_meta(pos)
meta:set_string("formspec", elevators.get_add_floor_formspec(tonumber(fields.floor_number)+1, fields.floor_description, fields.floor_pos))
end
if fields.floor_reduce and fields.floor_number ~= "" then
local meta = minetest.get_meta(pos)
meta:set_string("formspec", elevators.get_add_floor_formspec(tonumber(fields.floor_number)-1, fields.floor_description, fields.floor_pos))
end
local net_name = minetest.get_meta(pos):get_string("elevator_net_name")
local state = elevators.elevators_nets[net_name].cabin.state
if net_name ~= "" and (state == "pending" or state == "idle") then
for i, floor in ipairs(elevators.elevators_nets[net_name].floors) do
if fields["floor_" .. tostring(i)] then
table.insert(elevators.elevators_nets[net_name].cabin.queue, 1, floor.position)
if state == "pending" then
local timer = minetest.get_node_timer(pos)
timer:stop()
elevators.move_doors(net_name, "close")
end
end
end
end
end
})
minetest.register_craft({
output = "real_elevators:elevator_cabin",
recipe = {
{"basic_materials:steel_bar", "default:steel_ingot", "basic_materials:steel_bar"},
{"default:steel_ingot", "basic_materials:ic", "default:steel_ingot"},
{"basic_materials:steel_bar", "real_elevators:elevator_doors_closed", "basic_materials:steel_bar"}
}
})
minetest.register_entity("real_elevators:elevator_door_moving", {
visual_size = {x=1, y=1, z=1},
visual = "mesh",
mesh = "real_elevators_elevator_door.b3d",
physical = true,
collide_with_objects = true,
collisionbox = {-0.25, -0.5, -0.05, 0.25, 1.5, 0.05},
pointable = true,
textures = {tex_names_used[4]},
on_activate = function(self, staticdata, dtime_s)
if staticdata ~= "" then
self.end_pos = vector.from_string(staticdata)
end
local pos = self.object:get_pos()
--minetest.debug("pos: " .. dump(pos))
for name, data in pairs(elevators.elevators_nets) do
--minetest.debug("data.cabin.inner_doors: " .. dump(data.cabin.inner_doors))
if type(data.cabin.inner_doors.left) == "table" and vector.equals(data.cabin.inner_doors.left, pos) then
data.cabin.inner_doors.left = self.object
if data.cabin.state == "active" then
self.object:set_attach(data.cabin.elevator_object, "", vector.multiply(vector.subtract(data.cabin.elevator_object:get_pos(), pos), 10))
end
break
elseif type(data.cabin.inner_doors.right) == "table" and vector.equals(data.cabin.inner_doors.right, pos) then
data.cabin.inner_doors.right = self.object
break
end
--minetest.debug("data.outer_doors: " .. dump(data.outer_doors))
if data.outer_doors then
if type(data.outer_doors.left) == "table" and vector.equals(data.outer_doors.left, pos) then
data.outer_doors.left = self.object
break
elseif type(data.outer_doors.right) == "table" and vector.equals(data.outer_doors.right, pos) then
data.outer_doors.right = self.object
break
end
end
end
end,
on_step = function(self, dtime, moveresult)
if not self.end_pos then
self.object:set_velocity(vector.new())
return
else
if vector.length(self.object:get_velocity()) == 0 then
-- The door is obstructed!
self.object:set_velocity(self.vel)
end
end
local dist = vector.distance(self.object:get_pos(), self.end_pos)
if dist < 0.05 then
self.object:set_pos(self.end_pos)
self.object:set_velocity(vector.new())
self.end_pos = nil
end
end,
static_save = true,
get_staticdata = function(self)
return self.end_pos and vector.to_string(self.end_pos) or ""
end
})
minetest.register_entity("real_elevators:elevator_cabin_activated", {
visual_size = {x=1, y=1, z=1},
visual = "mesh",
mesh = "real_elevators_elevator_cabin.b3d",
physical = true,
collide_with_objects = true,
collisionbox = {-0.5, -0.5, -0.5, 0.5, 1.5, 0.5},
pointable = true,
textures = {"real_elevators_new_cabin.png"},
static_save = true,
on_activate = function(self, staticdata, dtime_s)
minetest.debug("on_activate()")
if staticdata ~= "" then
local data = minetest.deserialize(staticdata)
self.end_pos = data[1]
self.dir = data[2]
self.elevator_net_name = data[3]
self.is_falling = data[4]
end
if not self.elevator_net_name then
return
end
local net = elevators.elevators_nets[self.elevator_net_name]
local pos = self.object:get_pos()
if type(net.cabin.elevator_object) == "table" and vector.equals(net.cabin.elevator_object, pos) then
net.cabin.elevator_object = self.object
for i, obj in ipairs(net.cabin.attached_objs) do
if obj:is_player() then
if elevators.is_player_online(obj) then
obj:set_attach(self.object, "", vector.multiply(vector.subtract(obj:get_pos(), pos), 10))
else
obj = nil
end
elseif obj:get_luaentity() then
obj:set_attach(self.object, "", vector.multiply(vector.subtract(obj:get_pos(), pos), 10))
else
obj = nil
end
end
end
--minetest.debug("[on_activate()] " .. self.elevator_net_name .. ": " .. dump(elevators.elevators_nets[self.elevator_net_name]))
end,
on_step = function(self, dtime, moveresult)
if not self.end_pos or self.is_falling then
return
end
local pos = self.object:get_pos()
-- Update rope
minetest.remove_node({x=pos.x, y=pos.y+1, z=pos.z})
local top_pos = {x=pos.x, y=pos.y+2, z=pos.z}
local top_node = minetest.get_node(top_pos)
if top_node.name == "real_elevators:elevator_winch" then
if vector.direction(pos, top_pos) == vector.normalize(self.object:get_velocity()) then
-- The cabin can not move up as on the top of it there is a winch impeding!
self.object:set_velocity(vector.new())
self.end_pos = nil
return
end
else
minetest.set_node({x=pos.x, y=pos.y+2, z=pos.z}, {name="real_elevators:elevator_rope"})
end
-- Check for shaft nodes availability
local is_shaft = elevators.check_for_surrounding_shaft_nodes(pos, self.dir)
if not is_shaft then
-- The cabin can not move further as at its level there are no enough shaft nodes!
self.object:set_velocity(vector.new())
self.end_pos = nil
return
end
--minetest.remove_node({x=pos.x, y=pos.y+1, z=pos.z})
local dist = vector.distance(pos, self.end_pos)
if dist < 0.05 then
--minetest.debug("The cabin is about to stop...")
-- The cabin is arrived!
self.object:set_pos(self.end_pos)
self.object:set_velocity(vector.new())
self.end_pos = nil
end
--[[local top_pos = {x=pos.x, y=pos.y+2, z=pos.z}
local top_node = minetest.get_node(top_pos)
if top_node.name == "real_elevators:elevator_winch" and
vector.direction(pos, top_pos) == vector.normalize(self.object:get_velocity()) then
-- The cabin can not move up as on the top of it there is a winch impeding!
self.object:set_velocity(vector.new())
self.end_pos = nil
return
end
if top_node.name ~= "real_elevators:elevator_winch" then
minetest.set_node({x=pos.x, y=pos.y+2, z=pos.z}, {name="real_elevators:elevator_rope"})
end]]
end,
on_deactivate = function(self)
minetest.debug("on_deactivate()")
--minetest.debug("self.elevator_net_name: " .. (self.elevator_net_name ~= nil and self.elevator_net_name or "nil"))
--[[if not self.elevator_net_name then
return
end
if self.is_remove then
elevators.remove_net(self.elevator_net_name)
else
elevators.save_entities_positions_in_net(self.elevator_net_name)
end]]
if not self.elevator_net_name then
return
end
elevators.remove_net(self.elevator_net_name)
end,
on_death = function(self)
minetest.debug("on_death()")
if not self.elevator_net_name then
return
end
elevators.remove_net(self.elevator_net_name)
end,
get_staticdata = function(self)
return minetest.serialize({self.end_pos, self.dir, self.elevator_net_name, self.is_falling})
end
})
minetest.register_tool("real_elevators:floor_mark_tool", {
description = elevators.S("Floor Mark Tool (right-click a node to mark that position for adding a new floor for an elevator net)"),
inventory_image = "real_elevators_floor_mark_tool.png",
stack_max = 1,
on_place = function(itemstack, placer, pointed_thing)
if elevators.current_marked_pos then
local marked_barea_obj = minetest.get_objects_inside_radius(elevators.current_marked_pos, 0.0)
if #marked_barea_obj > 0 then
marked_barea_obj[1]:remove()
end
end
elevators.current_marked_pos = pointed_thing.under
minetest.chat_send_player(placer:get_player_name(), "You marked block area at position: " .. minetest.pos_to_string(pointed_thing.under) .. ". Set as current one.")
minetest.add_entity(pointed_thing.under, "real_elevators:marked_block_area")
elevators.update_cabins_formspecs()
end
})
minetest.register_entity("real_elevators:marked_block_area", {
visual = "cube",
visual_size = {x=1, y=1, z=1},
physical = false,
pointable = true,
textures = {
"real_elevators_marked_block_area.png",
"real_elevators_marked_block_area.png",
"real_elevators_marked_block_area.png",
"real_elevators_marked_block_area.png",
"real_elevators_marked_block_area.png",
"real_elevators_marked_block_area.png"
}
})
minetest.register_on_shutdown(elevators.on_shutdown)
minetest.register_globalstep(elevators.global_step)
--minetest.register_on_joinplayer(elevators.on_join)
|
local EM,FB = ...
local json,LOG,DEBUG = FB.json,EM.LOG,EM.DEBUG
local copy,cfg = EM.utilities.copy,EM.cfg
LOG.register("files","Log filesystem events")
local CRC16Lookup = {
0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0
}
local function crc16(bytes)
local crc = 0
for i=1,#bytes do
local b = string.byte(bytes,i,i)
crc = ((crc<<8) & 0xffff) ~ CRC16Lookup[(((crc>>8)~b) & 0xff) + 1]
end
return tonumber(crc)
end
local function readFile(file,err)
local f = io.open(file); assert(f or EM.cfg.noFileError,"No such file:"..file)
if f then local c = f:read("*all"); f:close() return c end
end
local firstTemp = true
local function createTemp(name,content) -- Storing code fragments on disk will help debugging. TBD
if firstTemp then DEBUG("files","sys","Using %s for temporary files",EM.cfg.temp) firstTemp=false end
local crc = crc16(content)
local fname = EM.cfg.temp..name.."_"..crc..".lua"
local f,res; f = io.open(fname,"r")
if f then f:close() return fname end -- If it exists, don't store it again
f,res = io.open(fname,"w+")
if not f then LOG.error("Warning - couldn't create temp files in %s - %s",EM.cfg.temp,res) return
else DEBUG("files","sys","Created temp file %s",fname) end
f:write(content)
f:close()
return fname
end
local deviceTemplates,sortedDeviceTemplates
local function getDeviceResources()
if deviceTemplates == nil then
local f = io.open(EM.cfg.modPath.."devices.json")
if f then deviceTemplates=FB.json.decode(f:read("*all")) f:close() else deviceTemplates={} end
local r = {} for n,d in pairs(deviceTemplates) do r[#r+1]={n,d} end
table.sort(r,function(a,b) return a[1] < b[1] end)
sortedDeviceTemplates=r
end
return deviceTemplates,sortedDeviceTemplates
end
local function mergeUI(info)
local ui,res = {},{}
for k,v in pairs(info) do local i = k:match("u(%d+)$") if i then ui[#ui+1]={tonumber(i),v} end end
table.sort(ui,function(a,b) return a[1] < b[1] end)
for _,u in ipairs(ui) do res[#res+1]=u[2] info[u[1]]=nil end
info.UI = res
end
local function matchContinousLines(str,pattern1,pattern2,collector)
local state = 0
str:gsub("(.-)[\n\r]+",function(line)
local m = {line:match(pattern1)}
if #m > 0 then
if state < 2 and line:match(pattern2) then collector(table.unpack(m)) state=1 end
elseif state==1 then state = 2 end
end)
end
local function loadSource(code,fileName) -- Load code and resolve info and --FILE directives
local files = {}
assert(code,"Missing code for "..tostring(fileName))
matchContinousLines(code,[[%-%-%s*FILE:%s*(.-)%s*,%s*(.-);]],[[%-%-FILE:%s*(.-)%s*,%s*(.-);]],
function(file,name)
file = file:gsub("/",EM.cfg.pathSeparator)
files[#files+1]={name=name,type='lua',isOpen=false,content=readFile(file,EM.cfg.noFileError),isMain=false,fname=file}
return ""
end)
table.insert(files,{name="main",type='lua',isOpen=false,content=code,isMain=true,fname=fileName})
local info = code:match("%-%-%[%[QAemu(.-)%-%-%]%]")
if info==nil or info=="" then
local il = {}
matchContinousLines(code,"%-%-%s*%%%%(.-)$","%-%-%%%%(.-)$",function(l) il[#il+1]=l end)
info=table.concat(il,",")
end
if info then
local icode,res = load("return {"..info.."}",nil,nil,{EM=EM,FB=FB,G=_G})
if not icode then error(res) end
info,res = icode()
if res then error(res) end
end
mergeUI(info)
if info and info.uiFrom then
if cfg.offline then
LOG.warn("Can't have both offline and uiFrom - ignoring uiFrom")
else
local d = FB.api.get("/devices/"..info.uiFrom)
if d then
info.UI = EM.UI.view2UI(d.properties.viewLayout,d.properties.uiCallbacks)
end
end
end
return files,(info or {})
end
local function loadLua(fileName) return loadSource(readFile(fileName),fileName) end
local function findFirstCodeLine(code,name) -- Try to find first code line
local n,first,init = 1
for line in string.gmatch(code,"([^\r\n]*)[\r\n]?") do
if not (line=="" or line:match("^[%-%s]+")) then
if not first then first = n end
end
if line:match("%s*QuickApp%s*:%s*onInit%s*%(") then
if not init then init = n end
end
n=n+1
end
return first or 1,init
end
local function loadFQA(fqa,args) -- Load FQA
local files,main = {}
for _,f in ipairs(fqa.files) do
local fname = createTemp(f.name,f.content) or f.name..crc16(f.content) -- Create temp files for fqa files, easier to debug
if f.isMain then f.fname=fname main=f
else files[#files+1] = {name=f.name,content=f.content,type='lua',isOpen=false,isMain=f.isMain,fname=fname} end
local first,init = findFirstCodeLine(f.content,f.name)
if args.breakOnLoad then EM.mobdebug.setbreakpoint(fname,first) end
if args.breakOnInit and init then EM.mobdebug.setbreakpoint(fname,init) end
end
table.insert(files,{name=main.name,content=main.content,type='lua',isOpen=false,isMain=true,fname=main.fname})
return files,{name=fqa.name,type=fqa.type,properties=fqa.initialProperties}
end
local function loadFile(code,file,args)
if file and not code then
if file:match("%.fqa$") then return loadFQA(json.decode(readFile(file)),args)
elseif file:match("%.lua$") then return loadLua(file,args)
else error("No such file:"..file) end
elseif type(code)=='table' then -- fqa table
return loadFQA(code,args)
elseif code then
local fname = file or createTemp("main",code) or "main"..crc16(code) -- Create temp file for string code easier to debug
return loadSource(code,fname)
end
end
local function packageFQA(D)
local dev = D.dev
local files = {}
for _,f in ipairs(D.files or {}) do local f2=copy(f) f2.fname=nil files[#files+1]=f2 end
local fqa = {
name = dev.name,
type = dev.type,
apiVersion="1.2",
initialInterfaces = dev.interfaces,
initialProperties = {
apiVersion="1.2",
viewLayout=dev.properties.viewLayout,
uiCallbacks = dev.properties.uiCallbacks,
quickAppVariables = dev.properties.quickAppVariables,
typeTemplateInitialized=true,
},
files = files
}
return fqa
end
local function saveFQA(D)
local fqa = packageFQA(D)
local stat,res = pcall(function()
local f = io.open(D.save,"w+")
assert(f,"Can't open file "..D.save)
f:write((json.encode(fqa)))
f:close()
end)
if not stat then LOG.error("saving .fqa - %s",res)
else LOG.sys("Saved %s",D.save) end
end
local function uploadFQA(D)
local fqa = packageFQA(D)
local dev = D.dev
local res,err = FB.api.post("/quickApp/",fqa)
if not res then LOG.error("uploading .fqa '%s' - %s",dev.name,err)
else LOG.sys("Uploaded '%s', deviceId:%s",res.name,res.id) end
end
local function patchQA(_,client,ref,_,opts)
local device,QA = opts.deviceId,opts.QAid
local fs,fileMap = {},EM.Devices[opts.QAid].fileMap
for k,v in pairs(opts) do
if k ~= "deviceId" and k ~= "QAid" then
fs[#fs+1]=v
end
end
local files = FB.api.get("/quickApp/"..device.."/files","remote") or {}
local files2 = {}
for _,f in ipairs(files) do
files2[f.name]=f
if not fileMap[f.name] then
local _,code = FB.api.delete("/quickApp/"..device.."/files/"..f.name,"remote")
if code > 204 then LOG.error("Failed deleting file '%s' for QA:%s",f,device) end
DEBUG("files","sys","Deleting file '%s' for QA:'%s'",f.name,device)
end
end
for _,f in ipairs(fs) do
if files2[f] then --Exists
local fs = {isMain=false,type='lua',isOpen=false,name=f,content=fileMap[f].content}
local _,code = FB.api.put("/quickApp/"..device.."/files/"..f,fs,"remote")
if code > 204 then LOG.error("Failed updating file '%s' for QA:%s",f,device) end
DEBUG("files","sys","Updating file '%s' for QA:%s",f,device)
else -- New
local fs = {isMain=false,type='lua',isOpen=false,name=f,content=fileMap[f].content}
local _,code = FB.api.post("/quickApp/"..device.."/files",fs,"remote")
if code > 204 then LOG.error("Failed creating file '%s' for QA:%s",f,device) end
DEBUG("files","sys","Creating file '%s' for QA:%s",f,device)
end
end
client:send("HTTP/1.1 302 Found\nLocation: "..(ref or "").."\n\n")
return true
end
EM.EMEvents('start',function(_)
EM.addPath("GET/TQAE/updateQA",patchQA)
end)
EM.loadFile, EM.saveFQA, EM.uploadFQA, EM.packageFQA = loadFile, saveFQA, uploadFQA, packageFQA
EM.getDeviceResources = getDeviceResources
|
--[[
Gangi: Panel zarzadzania
@author Jakub 'XJMLN' Starzak <jack@pszmta.pl
@package PSZMTA.psz-gangi
@copyright Jakub 'XJMLN' Starzak <jack@pszmta.pl>
Nie mozesz uzywac tego skryptu bez mojej zgody. Napisz - byc moze sie zgodze na uzycie.
]]--
local function getGID()
local c=getElementData(localPlayer,"character")
if (not c) then return nil end
return c.gg_nazwa,c.gg_tag,c.gg_rank_name,c.gg_rank_id,c.gg_id -- gg_nazwa, gg_tag, gg_rank_name, gg_rank_id, gg_id
end
local sw, sh = guiGetScreenSize() --800x600
local memoInfoStart = "Tutaj Lider/V-Lider może wpisać notatki, informacje widoczne dla członków gangu"
local memoLbl = "Notatki oraz opis może edytować tylko Lider/V-Lider, każda notatka gangu jest moderowana, używanie przekleństw etc. jest karane."
local lblkres = string.format("____________________________________________________________________________________________________________________________________________")
local lblw2 = string.format("UWAGA! Ta operacja jest nie odwracalna, pieniądze wpłacone do sejfu nie mogą być już z niego wypłacone. Pamiętaj że lider nie może nakazywać Ci wpłacać pieniędzy do sejfu, robisz to z własnej woli.")
local lblw1 = string.format("UWAGA! Ta operacja jest nie odwracalna, pieniądze zostaną pobrane z sejfu gangu. Każde ulepszenie polepsza Waszą pozycję w rankingu gangów. Aby ulepszyć gang, wybierz pozycję z tabelki i wciśnij przycisk - następnie odczekaj chwilę i ulepszenie zostanie wdrożone. Jeżeli nie posiadasz bazy gangu, lepiej będzie nie ulepszać gangu.")
local edytowana_postac=nil
local p_g={}
p_g.wnd = guiCreateWindow(sw*0/800, sh*58/600, sw*800/800, sh*469/600,"",false)
guiSetVisible(p_g.wnd,false)
p_g.tabpanel = guiCreateTabPanel(sw*9/800, sh*23/600, sw*782/800, sh*426/600,false,p_g.wnd)
p_g.tabCzl = guiCreateTab("Członkowie",p_g.tabpanel)
p_g.tabZarzad = guiCreateTab("Zarządzanie gangiem",p_g.tabpanel)
p_g.tabStats = guiCreateTab("Statystyki gangu",p_g.tabpanel)
p_g.tabNotes = guiCreateTab("Notatki/Opis gangu",p_g.tabpanel)
-- Członkowie
p_g.gridlist = guiCreateGridList(sw*7/800, sh*8/600, sw*765/800, sh*313/600,false,p_g.tabCzl)
p_g.gridcolumn_nick = guiGridListAddColumn(p_g.gridlist,"Nick",0.2)
p_g.gridcolumn_ranga = guiGridListAddColumn(p_g.gridlist,"Ranga",0.2)
p_g.gridcolumn_lastplay = guiGridListAddColumn(p_g.gridlist,"Ostatnio w grze",0.3)
p_g.gridcolumn_money = guiGridListAddColumn(p_g.gridlist,"Kwota wpłacona do sejfu",0.2) -- Łącznie 0.9
p_g.btn_dodaj = guiCreateButton(sw*9/800, sh*331/600, sw*232/800, sh*60/600,"Dodaj gracza do gangu",false,p_g.tabCzl)
p_g.btn_wyrzuc = guiCreateButton(sw*290/800, sh*331/600, sw*232/800, sh*60/600,"Wyrzuć gracza z gangu",false,p_g.tabCzl)
p_g.btn_edytuj = guiCreateButton(sw*569/800, sh*332/600, sw*203/800, sh*60/600,"Edytuj gracza",false,p_g.tabCzl)
guiGridListSetSelectionMode(p_g.gridlist,1)
-- Zarządzanie gangiem
p_g.lblInfoMoney = guiCreateLabel(sw*184/800, sh*1/600, sw*414/800, sh*40/600,"Wpłata pieniędzy na rzecz gangu",false,p_g.tabZarzad)
guiSetFont(p_g.lblInfoMoney,"clear-normal");
guiLabelSetHorizontalAlign(p_g.lblInfoMoney,"center",false)
guiLabelSetVerticalAlign(p_g.lblInfoMoney,"center")
p_g.lblLine1 = guiCreateLabel(sw*0/800, sh*41/600, sw*782/800, sh*20/600,lblkres,false,p_g.tabZarzad)
p_g.editMoney = guiCreateEdit(sw*64/800, sh*86/600, sw*235/800, sh*25/600,"",false,p_g.tabZarzad)
p_g.btnWplac = guiCreateButton(sw*309/800, sh*80/600, sw*132/800, sh*31/600,"Wpłać",false,p_g.tabZarzad)
p_g.lblWplac = guiCreateLabel(sw*10/800, sh*92/600, sw*44/800, sh*13/600,"Kwota:",false,p_g.tabZarzad)
p_g.lblWplac2 = guiCreateLabel(sw*482/800, sh*61/600, sw*290/800, sh*71/600,lblw2,false,p_g.tabZarzad)
guiLabelSetColor(p_g.lblWplac2,255,0,0)
guiLabelSetHorizontalAlign(p_g.lblWplac2,"left",true)
p_g.lblInfoUpgrd = guiCreateLabel(sw*192/800, sh*160/600, sw*414/800, sh*40/600,"Dostępne ulepszenia gangu",false,p_g.tabZarzad)
guiSetFont(p_g.lblInfoUpgrd,"clear-normal");
guiLabelSetHorizontalAlign(p_g.lblInfoUpgrd,"center",false)
guiLabelSetVerticalAlign(p_g.lblInfoUpgrd,"center")
p_g.lblLine2 = guiCreateLabel(sw*0/800, sh*200/600, sw*800/800, sh*18/600,lblkres,false,p_g.tabZarzad)
p_g.grid = guiCreateGridList(sw*10/800, sh*222/600, sw*431/800, sh*170/600,false,p_g.tabZarzad)
p_g.gridcolumn_name = guiGridListAddColumn(p_g.grid,"Nazwa ulepszenia",0.5)
p_g.gridcolumn_price = guiGridListAddColumn(p_g.grid,"Koszt ulepszenia",0.3)
p_g.btn_ulepsz = guiCreateButton(sw*451/800, sh*220/600, sw*321/800, sh*58/600,"Zatwierdź",false,p_g.tabZarzad)
p_g.lblUp = guiCreateLabel(sw*447/800, sh*288/600, sw*325/800, sh*103/600,lblw1,false,p_g.tabZarzad)
guiLabelSetColor(p_g.lblUp,255,0,0)
guiLabelSetHorizontalAlign(p_g.lblUp,"left",true)
-- Statystyki gangu
p_g.lblInfoStats = guiCreateLabel(sw*141/800, sh*10/600, sw*501/800, sh*42/600,"Statystyki gangu",false,p_g.tabStats)
guiSetFont(p_g.lblInfoStats,"clear-normal")
guiLabelSetHorizontalAlign(p_g.lblInfoStats,"center",false)
guiLabelSetVerticalAlign(p_g.lblInfoStats,"center")
p_g.lblLine3 = guiCreateLabel(sw*4/800, sh*52/600, sw*778/800, sh*15/600,lblkres,false,p_g.tabStats)
p_g.lblCzlonkowie = guiCreateLabel(sw*22/800, sh*77/600, sw*350/800, sh*18/600,"Ilość członków:",false,p_g.tabStats)
p_g.lblMoney= guiCreateLabel(sw*22/800, sh*102/600, sw*350/800, sh*18/600,"Pieniądze zgromadzone w sejfie:",false,p_g.tabStats)
p_g.lblLogo = guiCreateLabel(sw*22/800, sh*127/600, sw*350/800, sh*18/600,"Zarejestrowany na forum (posiada logo):",false,p_g.tabStats)
p_g.lblSkin = guiCreateLabel(sw*22/800, sh*152/600, sw*350/800, sh*18/600,"Może ustawić skin gangowy:",false,p_g.tabStats)
p_g.lblBase = guiCreateLabel(sw*22/800, sh*177/600, sw*350/800, sh*18/600,"Posiada własną bazę: [WKRÓTCE]",false,p_g.tabStats)
p_g.lblUpgrades = guiCreateLabel(sw*22/800, sh*202/600, sw*350/800, sh*18/600,"Poziom ulepszenia gangu: [WKRÓTCE]",false,p_g.tabStats)
p_g.lblRank = guiCreateLabel(sw*22/800, sh*229/600, sw*350/800, sh*18/600,"Pozycja w rankingu: [WKRÓTCE]",false,p_g.tabStats)
-- Notatki
p_g.memo = guiCreateMemo(sw*7/800, sh*8/600, sw*765/800, sh*313/600,tostring(memoInfoStart),false,p_g.tabNotes)
p_g.lblNoteMem = guiCreateLabel(sw*9/800, sh*331/600, sw*400/800, sh*60/600,tostring(memoLbl),false,p_g.tabNotes)
p_g.btnAcceptNote = guiCreateButton(sw*569/800, sh*332/600, sw*203/800, sh*60/600,"Zapisz notatkę",false,p_g.tabNotes)
---------------------------------
p_g.init=function()
local gname,gtag,grank,grankid,gid=getGID()
if (not gid) then return end
triggerServerEvent("onPlayerRequestGangData",localPlayer,gid)
guiSetText(p_g.wnd,gname)
guiSetInputMode("no_binds_when_editing")
if (tonumber(grankid)>2) then
guiSetEnabled(p_g.btn_dodaj,true)
guiSetEnabled(p_g.btnAcceptNote,true)
guiMemoSetReadOnly(p_g.memo,false)
guiSetEnabled(p_g.btn_dodaj,true)
guiSetEnabled(p_g.btn_ulepsz,false)
else
guiSetEnabled(p_g.btn_dodaj,false)
guiMemoSetReadOnly(p_g.memo,true)
guiSetEnabled(p_g.btnAcceptNote,false)
guiSetEnabled(p_g.btn_ulepsz,false)
end
guiSetEnabled(p_g.btn_wyrzuc,false)
guiSetEnabled(p_g.btn_edytuj,false)
edytowana_postac=nil
end
--p_g.gridcolumn_nick | p_g.gridcolumn_ranga |p_g.gridcolumn_lastplay | p_g.gridcolumn_money |
p_g.fill=function(dane,data,onlineMembers)
guiGridListClear(p_g.gridlist)
if (not dane or not data) then return end
for i,v in ipairs(dane) do
local row = guiGridListAddRow (p_g.gridlist)
guiGridListSetItemText(p_g.gridlist,row,p_g.gridcolumn_nick, v.nick,false,false)
guiGridListSetItemData(p_g.gridlist,row,p_g.gridcolumn_nick, tonumber(v.player_id))
guiGridListSetItemText(p_g.gridlist,row,p_g.gridcolumn_ranga, v.ranga,false,false)
guiGridListSetItemData(p_g.gridlist,row,p_g.gridcolumn_ranga, tonumber(v.rank_id))
guiGridListSetItemText(p_g.gridlist,row,p_g.gridcolumn_lastplay, v.lastduty or "Nie określono",false,false)
guiGridListSetItemText(p_g.gridlist,row,p_g.gridcolumn_money,v.wplacone_sejf.."$",false,false)
guiGridListSetItemData(p_g.gridlist,row,p_g.gridcolumn_money,tonumber(v.wplacone_sejf))
guiSetText(p_g.lblCzlonkowie,"Ilość członków: "..#dane)
guiGridListSetItemColor(p_g.gridlist,row,p_g.gridcolumn_nick,255,0,0)
for i2,v2 in pairs(onlineMembers) do
if (v2 == tonumber(v.player_id)) then
guiGridListSetItemColor(p_g.gridlist,row,p_g.gridcolumn_nick,155,255,155)
end
end
if (v.text_note) then -- Jesli gang jest nowy, musimy mu nadac poczatkowa informacje
guiSetText(p_g.memo,tostring(v.text_note))
end
end
for i,v in ipairs(data) do
guiSetText(p_g.lblMoney,"Pieniądze zgromadzone w sejfie: "..tonumber(v.money_sejf).."$")
if (v.skin ~="NULL") then
guiSetText(p_g.lblSkin,"Posiada skin gangowy: Tak")
else
guiSetText(p_g.lblSkin,"Posiada skin gangowy: Nie")
end
if (v.logo==1) then
guiSetText(p_g.lblLogo,"Zarejestrowany na forum (posiada logo): Tak")
else
guiSetText(p_g.lblLogo,"Zarejestrowany na forum (posiada logo): Nie")
end
end
end
p_g.gridclick=function()
local gname,gtag,grank,grankid,gid=getGID()
if (not gid) then return end
if (not guiGetEnabled(p_g.btn_dodaj)) then return end
selectedRow = guiGridListGetSelectedItem(p_g.gridlist)
if (selectedRow<0) then
guiSetEnabled(p_g.btn_edytuj,false)
guiSetEnabled(p_g.btn_wyrzuc,false)
else
local sfrank=guiGridListGetItemData(p_g.gridlist,selectedRow,p_g.gridcolumn_ranga)
if (tonumber(grankid)>sfrank and tonumber(grankid)>=3) then
guiSetEnabled(p_g.btn_wyrzuc,true)
else
guiSetEnabled(p_g.btn_wyrzuc,false)
end
if (tonumber(grankid)>=3) then
guiSetEnabled(p_g.btn_edytuj,true)
else
guiSetEnabled(p_g.btn_edytuj,false)
end
end
end
p_g.zwolnij=function()
local __,__,__,__,gid=getGID()
if (not gid) then return end
selectedRow = guiGridListGetSelectedItem(p_g.gridlist)
local pid = guiGridListGetItemData(p_g.gridlist,selectedRow,p_g.gridcolumn_nick)
triggerServerEvent("onGangWyrzucRequest",localPlayer,gid,pid)
end
p_g.note=function()
local __,__,__,grankid,gid=getGID()
if (not gid) then return end
if (grankid and tonumber(grankid)>=3) then
local Note = guiGetText(p_g.memo)
guiSetEnabled(p_g.btnAcceptNote,false)
guiMemoSetReadOnly(p_g.memo,true)
triggerServerEvent("onGangMemberEditNote",localPlayer,gid,tostring(Note))
end
end
p_g.note_result=function(wynik, komunikat)
if (not wynik) then
guiSetEnabled(p_g.btnAcceptNote,true)
guiMemoSetReadOnly(p_g.memo,false)
guiSetText(p_g.lblNoteMem,komunikat)
guiLabelSetColor(p_g.lblNoteMem,255,0,0)
return
else
guiSetEnabled(p_g.btnAcceptNote,true)
guiMemoSetReadOnly(p_g.memo,false)
guiSetText(p_g.lblNoteMem,komunikat)
guiLabelSetColor(p_g.lblNoteMem,255,255,255) -- Jesli gracz dostal najpierw false
p_g.init()
end
end
-- Zakladka: Zarzadzanie ---------------------------
p_g.fill_upgrades=function(dane,dane2)
guiGridListClear(p_g.grid)
if (not dane) then return end
for i,v in ipairs(dane) do
--if (tonumber(v.id) == 3 and dane2.id_upgrade == 3 ) then outputDebugString('lol') return end
local row = guiGridListAddRow(p_g.grid)
guiGridListSetItemText(p_g.grid, row, p_g.gridcolumn_name, v.name,false,false)
guiGridListSetItemData(p_g.grid, row, p_g.gridcolumn_name, tonumber(v.id))
guiGridListSetItemText(p_g.grid, row, p_g.gridcolumn_price, v.cost.."$", false,false)
guiGridListSetItemData(p_g.grid, row, p_g.gridcolumn_price, tonumber(v.cost))
if (tonumber(v.cost)<=tonumber(v.money_sejf)) then
guiGridListSetItemColor(p_g.grid, row, p_g.gridcolumn_name, 0, 255, 0)
guiGridListSetItemColor(p_g.grid, row, p_g.gridcolumn_price, 0, 255, 0)
end
if (tonumber(v.cost)>tonumber(v.money_sejf)) then
guiGridListSetItemColor(p_g.grid, row, p_g.gridcolumn_name, 255, 0, 0)
guiGridListSetItemColor(p_g.grid, row, p_g.gridcolumn_price, 255, 0, 0)
end
end
end
p_g.gridclick_upgrade=function()
local gname,gtag,grank,grankid,gid=getGID()
if (not gid) then return end
if (not guiGetEnabled(p_g.btn_dodaj)) then return end
selectedRow= guiGridListGetSelectedItem(p_g.grid)
if (selectedRow<0) then
guiSetEnabled(p_g.btn_ulepsz, false)
else
local name=guiGridListGetItemData(p_g.grid, selectedRow, p_g.gridcolumn_name)
if (tonumber(grankid)>=3) then
guiSetEnabled(p_g.btn_ulepsz, true)
else
guiSetEnabled(p_g.btn_ulepsz, false)
end
end
end
p_g.addUpgrade=function()
local __,__,__,grank,gid=getGID()
if (not gid) then return end
selectedRow = guiGridListGetSelectedItem(p_g.grid)
local name = guiGridListGetItemData(p_g.grid, selectedRow, p_g.gridcolumn_name)
triggerServerEvent("onGangUpgradeBuy", localPlayer, gid, name)
end
p_g.add_money=function()
local __,__,__,__,gid=getGID()
local pid = getElementData(localPlayer,"auth:uid")
if (not gid or not pid) then return end
local money = string.format("%.0f",guiGetText(p_g.editMoney)) -- usuwamy wartośc po '.'
if (money and tonumber(money)>0) then
triggerServerEvent("onMemberGangSaveMoney",localPlayer,gid,pid,tonumber(money))
--guiSetEnabled(p_g.btnWplac,false)
end
end
p_g.add_money_result=function(wynik,komunikat)
if (not wynik) then
guiSetText(p_g.lblWplac2, komunikat)
guiSetEnabled(p_g.btnWplac,true)
return
else
p_g.init()
guiSetEnalbed(p_g.btnWplac,true)
end
end
-- Dodawanie graczy -----------------------------
p_a={}
p_a.win = guiCreateWindow(sw*185/800, sh*151/600, sw*449/800, sh*306/600, "", false)
guiWindowSetSizable(p_a.win, false)
guiSetVisible(p_a.win,false)
p_a.edit_nick = guiCreateEdit(sw*12/800, sh*105/600, sw*427/800, sh*28/600, "", false, p_a.win)
p_a.lbl_nick = guiCreateLabel(sw*13/800, sh*61/600, sw*358/800, sh*38/600, "Wpisz nick gracza:\nMożesz również zaprosić gracza poprzez komendę gang.zapros", false, p_a.win)
p_a.lbl_blad = guiCreateLabel(sw*13/800, sh*150/600, sw*426/800, sh*55/600, "", false, p_a.win)
p_a.btn_dodaj = guiCreateButton(sw*17/800, sh*224/600, sw*184/800, sh*72/600, "Dodaj gracza", false, p_a.win)
p_a.btn_anuluj = guiCreateButton(sw*286/800, sh*224/600, sw*153/800, sh*72/600, "Anuluj", false, p_a.win)
p_a.pokaz=function()
guiSetInputMode("no_binds_when_editing")
guiSetVisible(p_a.win,true)
guiSetText(p_a.lbl_blad,"")
guiSetText(p_a.edit_nick,"")
guiBringToFront(p_a.win)
end
p_a.schowaj=function()
guiSetVisible(p_a.win,false)
end
p_a.dodaj=function()
local __,__,__,__,gid= getGID()
if (not gid) then return end
local nick = guiGetText(p_a.edit_nick)
triggerServerEvent("onGangInviteRequest",localPlayer,gid,nick)
end
p_a.dodaj_end=function(wynik,komunikat)
if (not wynik) then
guiSetText(p_a.lbl_blad,komunikat)
return
else
p_a.schowaj()
p_g.init()
end
end
--- Edycja gracza ----------------------------------------------------------------
p_e = {}
p_e.win = guiCreateWindow(sw*155/800, sh*116/600, sw*489/800, sh*403/600, "Edycja gracza", false)
guiWindowSetSizable(p_e.win, false)
guiSetVisible(p_e.win,false)
p_e.lbl_player = guiCreateLabel(sw*144/800, sh*24/600, sw*230/800, sh*20/600, "Aktualnie edytujesz gracza", false, p_e.win)
guiLabelSetHorizontalAlign(p_e.lbl_player , "center", false)
guiLabelSetVerticalAlign(p_e.lbl_player , "center")
p_e.lbl_ranga = guiCreateLabel(sw*9/800, sh*60/600, sw*135/800, sh*15/600, "Edycja rangi:", false, p_e.win)
p_e.cmb_ranga = guiCreateComboBox(sw*90/800, sh*60/600, sw*313/800, sh*120/600, "", false, p_e.win)
p_e.lbl_skin = guiCreateLabel(sw*9/800, sh*150/600, sw*71/800, sh*20/600, "Edycja skina:", false, p_e.win)
p_e.cmb_skin = guiCreateComboBox(sw*87/800, sh*152/600, sw*237/800, sh*75/600, "", false, p_e.win)
p_e.btn_save = guiCreateButton(sw*9/800, sh*314/600, sw*200/800, sh*79/600, "Zapisz", false, p_e.win)
p_e.btn_cancel = guiCreateButton(sw*285/800, sh*317/600, sw*194/800, sh*76/600, "Anuluj", false, p_e.win)
p_e.pokaz=function()
local __,__,__,__,gid=getGID()
if (not gid) then return end
selectedRow = guiGridListGetSelectedItem(p_g.gridlist)
local pid=guiGridListGetItemData(p_g.gridlist,selectedRow,p_g.gridcolumn_nick)
guiSetInputMode("no_binds_when_editing")
guiSetVisible(p_e.win,true)
guiBringToFront(p_e.win)
guiComboBoxClear(p_e.cmb_ranga)
guiComboBoxClear(p_e.cmb_skin)
guiSetText(p_e.lbl_player,"Oczekiwanie na dane...")
guiComboBoxAddItem(p_e.cmb_skin, "Nie ustawiono")
triggerServerEvent("onGangCharacterDetailsRequest",localPlayer,gid,pid)
end
p_e.schowaj=function()
guiSetVisible(p_e.win,false)
end
p_e.edycja_potwierdz=function(dane)
if (not dane or not dane.gracz or not dane.gracz.userid) then
p_e.schowaj()
end
local __,__,__,grankid,__=getGID()
edytowana_postac=dane.gracz.userid
guiSetText(p_e.lbl_player, "Aktualnie edytujesz gracza : "..dane.gracz.nick)
guiComboBoxClear(p_e.cmb_ranga)
guiComboBoxClear(p_e.cmb_skin)
for i,v in ipairs(dane.rangi) do
local i2=guiComboBoxAddItem(p_e.cmb_ranga, tostring(v.rank_id)..". "..v.name)
if (v.rank_id == dane.gracz.rank) then
guiComboBoxSetSelected(p_e.cmb_ranga,i2)
if (i==#dane.rangi) then -- Gracz jest liderem, blokujemy edycje
guiComboBoxClear(p_e.cmb_ranga)
local block = guiComboBoxAddItem(p_e.cmb_ranga,"Zablokowane")
guiComboBoxSetSelected(p_e.cmb_ranga,block)
end
end
end
local skin = guiComboBoxAddItem(p_e.cmb_skin,"brak")
guiComboBoxSetSelected(p_e.cmb_skin,skin)
if (dane.skiny and #dane.skiny>0) then
for i,v in ipairs(dane.skiny) do
local i3 = guiComboBoxAddItem(p_e.cmb_skin, tostring(v.skin))
if (v.skin == dane.gracz.skin) then
guiComboBoxSetSelected(p_e.cmb_skin, i3)
end
end
end
end
p_e.zapisz=function()
if (not edytowana_postac) then return end
local ranga = guiComboBoxGetItemText(p_e.cmb_ranga, guiComboBoxGetSelected(p_e.cmb_ranga))
if (tostring(ranga) == 'Zablokowane') then
ranga = tonumber(4)
else
ranga = tonumber(string.sub(ranga,1,1))
end
local skin = tonumber(guiComboBoxGetItemText(p_e.cmb_skin, guiComboBoxGetSelected(p_e.cmb_skin)))
triggerServerEvent("onGangEdycjaPostaci",localPlayer, edytowana_postac, ranga, skin)
end
addEvent("doFillGangData", true)
addEventHandler("doFillGangData", resourceRoot, p_g.fill)
addEvent("onGangWyrzucComplete", true)
addEventHandler("onGangWyrzucComplete", resourceRoot, p_g.init)
addEvent("onEditSendResult",true)
addEventHandler("onEditSendResult", resourceRoot, p_g.note_result)
-- glowne okno
addEventHandler("onClientGUIClick", p_g.btn_dodaj, p_a.pokaz, false)
addEventHandler("onClientGUIClick", p_g.btn_wyrzuc, p_g.zwolnij, false)
addEventHandler("onClientGUIClick", p_g.btn_edytuj, p_e.pokaz, false)
addEventHandler("onClientGUIClick", p_g.gridlist, p_g.gridclick, false)
addEventHandler("onClientGUIClick", p_g.btnAcceptNote, p_g.note, false)
-- zakladka: zarzadzanie gangiem
addEvent("doFillUpgradesData",true)
addEventHandler("doFillUpgradesData", resourceRoot, p_g.fill_upgrades)
addEvent('onResultSaveMoney',true)
addEventHandler("onResultSaveMoney", resourceRoot, p_g.add_money_result)
addEventHandler("onClientGUIClick", p_g.btnWplac, p_g.add_money, false)
addEventHandler("onClientGUIClick", p_g.grid, p_g.gridclick_upgrade, false)
addEventHandler("onClientGUIClick", p_g.btn_ulepsz, p_g.addUpgrade, false)
-- dodawanie
addEvent("onGangInviteReply", true)
addEventHandler("onGangInviteReply", resourceRoot, p_a.dodaj_end)
addEventHandler("onClientGUIClick", p_a.btn_dodaj, p_a.dodaj, false)
addEventHandler("onClientGUIClick", p_a.btn_anuluj, p_a.schowaj, false)
-- edycja
addEvent("doFillGangPlayerData", true)
addEventHandler("doFillGangPlayerData", resourceRoot, p_e.edycja_potwierdz)
addEventHandler("onClientGUIClick", p_e.btn_cancel, p_e.schowaj, false)
addEventHandler("onClientGUIClick", p_e.btn_save, p_e.zapisz, false)
addEvent('onGangEdycjaComplete',true)
addEventHandler("onGangEdycjaComplete", resourceRoot, p_g.init)
bindKey("f5","down",function()
local gid,gname,grank,grankid=getGID()
if (not gid) then
guiSetVisible(p_g.wnd,false)
showCursor(false)
return
end
if isGOWindowOpen(p_g.wnd) then
showCursor(false)
toggleControl("fire",true)
guiSetVisible(p_g.wnd, false)
else
showCursor(true,false)
toggleControl("fire",false)
guiSetVisible(p_g.wnd,true)
p_g.init()
end
end)
|
--[=[
@within Member
@prop User User
@readonly
The user that the member object represents.
]=]
--[=[
@within Member
@prop Group Group
@readonly
The group that the user is in.
]=]
--[=[
@within Member
@prop Client Client
@readonly
A reference back to the client that owns this object.
]=]
--[=[
@within Member
@prop Role Role
@readonly
The role the user has in the group.
]=]
--[=[
The member object can view and edit data about users in groups.
@class Member
]=]
local Member = {}
--[=[
Constructs a member object. This will return nil if the user is not in the group.
@param _ Member
@param Client Client -- The client to make requests with.
@param GroupId Group|number -- The Group or GroupId the member belongs to.
@param UserId User|number -- The User or UserId the member object represents.
@param Data {[any]=any} -- Optional preset data. Used within the library, not meant for general use.
@return Member
]=]
function Member.__call (_,Client,GroupId,UserId,Data)
local self = {}
setmetatable(self,{__index=function (t,i)
if Member[i] then return Member[i] end
if Member._Requests[i] then
Member._Requests[i](t)
return rawget(t,i)
end
end})
self.Client = Client
if type(GroupId) == "number" then
self.Group = Client:Group (GroupId)
elseif type(GroupId) == "table" then
self.Group = GroupId
else
error ("Lublox: Invalid type for group!")
end
if type(UserId) == "number" or type(UserId) == "string" then
self.User = Client:User (UserId)
elseif type(UserId) == "table" then
self.User = UserId
else
error ("Lublox: Invalid type for user!")
end
if type(Data) == "table" then
for i,v in pairs(Data) do
self[i] = v
end
end
if self.Valid then return self end
local Success,Body = Client:Request ("GET","https://groups.roblox.com/v1/users/"..self.User.Id.."/groups/roles")
if Success then
for _,v in pairs(Body.data) do
if v.group.id == self.Group.Id then
if self.Role == nil then
self.Role = Client:Role (v.role.id,{Name=v.role.name,Rank=v.role.rank})
end
return self
end
end
end
end
--[=[
Gets the role of the member in the group.
@return Role?
]=]
function Member:GetRole ()
local Success,Body = self.Client:Request ("GET","https://groups.roblox.com/v1/users/"..self.User.Id.."/groups/roles")
if Success then
for _,v in Body["data"] do
if v.group.id == self.Group.Id then
self.Role = self.Client:Role (v.role.id,{Name=v.role.name,Rank=v.role.rank})
return self.Role
end
end
end
end
--[=[
Sets the role of the member in the group.
Returns if the operation was successful, and if it wasn't, it returns the reason.
@param Role Role|number -- The Role or RoleId to set the user to.
@return boolean
@return string?
]=]
function Member:SetRole (Role)
local RoleId = Role
if type(RoleId) == "table" then
RoleId = RoleId.Id
end
local Success,Body = self.Client:Request ("PATCH","https://groups.roblox.com/v1/groups/"..self.Group.Id.."/users/"..self.User.Id,nil,nil,{roleId=RoleId})
if not Success then
return Success,Body["errors"][1]["message"]
else
return Success
end
end
--[=[
Exiles the member from the group.
Returns if the operation was successful, and if it wasn't, it returns the reason.
@return boolean
@return string?
]=]
function Member:Exile ()
local Success,Body = self.Client:Request ("DELETE","https://groups.roblox.com/v1/groups/"..self.Group.Id.."/users/"..self.User.Id)
if not Success then
return Success,Body["errors"][1]["message"]
else
return Success
end
end
Member._Requests = {
Role = Member.GetRole,
}
setmetatable(Member,Member)
return Member
|
---- CONFIG
-- You can edit aspects about the script below
local showSongBF = true -- Whether the chart's BF should be shown as an option, disabling might be useful if you manually registered them and the chart's BF shows wrong
local allowStoryMode = false -- If this script can be used on storymode or not
local song = 'offsetSong'; --If you want to have a song play while people are in this menu. Remove this line entirely if you don't want one.
local characterList = { -- The list of characters
{
name = "bf",
displayName = "Boyfriend",
gf = "gf",
},
{
name = "bf-car",
displayName = "Windy Boyfriend",
gf = "gf-car"
},
{
name = "bf-christmas",
displayName = "Festive Boyfriend",
gf = "gf-christmas"
},
{
name = "bf-pixel",
displayName = "Pixel Boyfriend",
-- don't add gf pixel here, this breaks stages
},
{
name = "bf-alt",
displayName = "Alternative Boyfriend",
gf = "gf-alt"
},
{
name = "bfCar-alt",
displayName = "Windy Alt Boyfriend",
gf = "gfCar-alt"
},
{
name = "erect-bf",
displayName = "Erect Boyfriend",
gf = "erect-gf",
},
{
name = "pico-player",
displayName = "Pico",
gf = "speakers"
},
{
name = 'pico-car',
displayName = "Pico with a Scarf",
gf = "speakers"
}
}
-- The actual script.
local changedChar = true
local isOnCharMenu = true;
local curCharacter = 1
local shownID = -10000
local befPaused = false
local displayNameY = 0;
local sustxtY = -100;
local origBF = "";
function onCreate()
if getPropertyFromClass('ClientPrefs', 'charSelect', true) then
--Theres nothing special here just all the extra stuff. Add or edit whatever you want.
makeLuaSprite('charStage', 'charselectassets/charselectstage', 0, 0);
setObjectCamera('charStage', 'camOther');
scaleObject('charStage', 0.55, 0.55);
screenCenter('charStage', 'xy');
makeAnimatedLuaSprite('leftarrow', 'NOTE_assets', 400, 0);
addAnimationByPrefix('leftarrow', 'leftpressed', 'arrow left0', 24, false);
addAnimationByPrefix('leftarrow', 'leftunpressed', 'arrow push left0', 24, false);
objectPlayAnimation('leftarrow', 'leftunpressed', true);
screenCenter('leftarrow', 'y');
setObjectCamera('leftarrow', 'camOther');
makeAnimatedLuaSprite('rightarrow', 'NOTE_assets', 800, 0);
addAnimationByPrefix('rightarrow', 'rightpressed', 'arrow right0', 24, false);
addAnimationByPrefix('rightarrow', 'rightunpressed', 'arrow push right0', 24, false);
objectPlayAnimation('rightarrow', 'rightunpressed', true);
screenCenter('rightarrow', 'y');
setObjectCamera('rightarrow', 'camOther');
makeLuaText('displayname', characterList[curCharacter].displayName, 0, 0, 100);
setProperty('displayname.borderColor', getColorFromHex('000000'));
setProperty('displayname.borderSize', 1.2);
setObjectCamera('displayname', 'camOther');
setTextSize('displayname', 25);
screenCenter('displayname', 'x');
displayNameY = getProperty("displayname.y")
addLuaText('displayname');
makeLuaText('sustxt', 'choose your character', 0, 0, 100);
setProperty('sustxt.borderColor', getColorFromHex('000000'));
setProperty('sustxt.borderSize', 1.2);
setObjectCamera('sustxt', 'camOther');
setTextSize('sustxt', 25);
screenCenter('sustxt', 'x');
setProperty('sustxt.y', 1);
addLuaText('sustxt');
addLuaSprite('charStage', false);
--addLuaSprite('leftarrow', true); --i will fix it just wait --Luis
--addLuaSprite('rightarrow', true);
playMusic(song, 1, true);
end
function onStartCountdown()
if getPropertyFromClass('ClientPrefs', 'charSelect', true) then
if(not allowStoryMode and isStoryMode)then close() end -- Close script if in story mode, remove this or n
if not hasSelectedCharacter then
origBF = getProperty("boyfriend.curCharacter")
if(showSongBF) then table.insert(characterList,1,{
name=origBF,
displayName="Character from Chart"})
end
setProperty('inCutscene', true);
setProperty('boyfriend.stunned', true);
-- hasSelectedCharacter = true
updateCharacter()
setProperty('canPause', true);
befPaused = getProperty('canPause')
return Function_Stop;
end
setProperty('canPause', befPaused);
if changedChar then
characterPlayAnim('boyfriend', 'idle', true);
if(characterList[curCharacter].opponent) then
triggerEvent('Change Character', 'dad', characterList[curCharacter].opponent);
end
if(characterList[curCharacter].gf) then
triggerEvent('Change Character', 'gf', characterList[curCharacter].gf);
end
end
setProperty('inCutscene', false);
setObjectCamera('boyfriend', 'camGame');
setProperty('boyfriend.stunned', false);
setProperty('boyfriend.x', defaultBoyfriendX);
setProperty('boyfriend.y', defaultBoyfriendY+360);
removeLuaSprite('charStage', true);
removeLuaSprite('leftarrow', true);
removeLuaSprite('rightarrow', true);
removeLuaText('displayname', true);
removeLuaText('sustxt', true);
setProperty('misses', 0);
pauseSound("music")
playMusic(song, 0, false); --I don't know how to stop music there's nothing in the wiki or source its all just for sounds.
return Function_Continue;
end
end
function onTimerCompleted(tag, loops, loopsLeft)
if tag == 'wait' then
startCountdown()
end
end
end
function onPause()
if getPropertyFromClass('ClientPrefs', 'charSelect', true) then
if(isOnCharMenu) then
triggerEvent('Change Character', 'bf', origBF);
isOnCharMenu = false
end
return Function_Continue;
end
end
function onUpdate()
if getPropertyFromClass('ClientPrefs', 'charSelect', true) then
if isOnCharMenu == true then
setProperty('boyfriend.stunned', true);
screenCenter('displayname', 'x');
screenCenter('boyfriend', 'xy');
if characterList[curCharacter].y then
setProperty("boyfriend.y",getProperty("boyfriend.y") + characterList[curCharacter].y)
end
if characterList[curCharacter].x then
setProperty("boyfriend.x",getProperty("boyfriend.x") + characterList[curCharacter].x)
end
scaleObject('boyfriend', getProperty('boyfriend.jsonScale'), getProperty('boyfriend.jsonScale'));
if(shownID ~= curCharacter) then -- Only change the character if needed
updateCharacter()
end
if keyJustPressed('left') then
curCharacter = curCharacter - 1
playSound('scrollMenu', 1);
elseif keyJustPressed('right') then
curCharacter = curCharacter + 1
playSound('scrollMenu', 1);
elseif keyJustPressed('accept') then
characterPlayAnim('boyfriend', 'hey', false);
hasSelectedCharacter = true
runTimer('wait', 1.8, 1);
playSound('confirmMenu', 1);
isOnCharMenu = false
elseif keyJustPressed('back') then
-- playSound('confirmMenu', 1);
triggerEvent('Change Character', 'bf', origBF);
isOnCharMenu = false
hasSelectedCharacter = true
changedChar = false
startCountdown();
end
if keyPressed('left') then
objectPlayAnimation('leftarrow', 'leftpressed', true);
elseif keyPressed('right') then
objectPlayAnimation('rightarrow', 'rightpressed', true);
end
if keyReleased('left') then
objectPlayAnimation('leftarrow', 'leftunpressed', true);
elseif keyReleased('right') then
objectPlayAnimation('rightarrow', 'rightunpressed', true);
end
if curCharacter > #characterList then
curCharacter = 1
elseif curCharacter <= 0 then
curCharacter = #characterList
end
end
end
end
function updateCharacter()
if getPropertyFromClass('ClientPrefs', 'charSelect', true) then
triggerEvent('Change Character', 'bf', characterList[curCharacter].name);
setTextString('displayname', characterList[curCharacter].displayName);
setObjectCamera('boyfriend', 'camOther');
characterPlayAnim('boyfriend', 'idle', true);
shownID = curCharacter
if characterList[curCharacter].displayNameY then
-- scaleObject('boyfriend', 0.9, 0.9);
setProperty('displayname.y', displayNameY-characterList[curCharacter].displayNameY); -- Inverted for easier editing
else
setProperty('displayname.y', displayNameY);
end
end
end
function onStartStart()
isOnCharMenu = false
end
-- Credits:
-- XpsxExp#4452: Making the script
-- Superpowers04#3887: Reformatting the script and making it cleaner and such
|
--region *.lua
--Date
--此文件由[BabeLua]插件自动生成
require("dxm/common/singleton")
require("dxm/data_structures/list")
dxm = dxm or {}
dxm.CWidgetCache = class("CWidgetCache")
local CWidgetCache = dxm.CWidgetCache
-- 成员函数
function CWidgetCache:ctor(config)
self.config = config -- 配置名称
self.template_widget = nil -- 模版界面
self.widget_list = dxm.CList.new() -- 缓存对象列表
self.widget_count = 1 -- 缓存构建数量
-- local widget = GUIReader:shareReader():widgetFromJsonFile("ui/"..self.config..".json")
local widget = self:LoadWidget()
if widget ~= nil then
widget:removeFromParent()
-- 模版要被克隆,是为了兼容ActionList的设计缺陷,只有widgetFromJsonFile函数产生的UIWidget才可以正常使用动画;
self.template_widget = widget:clone()
self.template_widget:retain()
self:Add(widget)
else
print("[CWidgetCache] widgetFromJsonFile ",self.config," failed, there isnt child tag 5")
end
end
function CWidgetCache:LoadWidget()
local node = cc.CSLoader:createNode("res/"..self.config..".csb")
if node ==nil then
print("[CWidgetCache] widgetFromJsonFile ", self.config, " failed")
return
end
-- 自适应代码
node:setContentSize(cc.size(display.width,display.height))
ccui.Helper:doLayout(node)
local widget = node:getChildByTag(5)
return widget
end
function CWidgetCache:CloneWidget()
-- return self.template_widget:clone()
return self:LoadWidget()
end
function CWidgetCache:Dispose()
if self.template_widget ~= nil then
self.template_widget:release()
end
-- 判断是否已经存在;
local node = self.widget_list.first
while node ~= nil do
local widget = node.value
if widget ~= nil then
widget:release()
end
node = node.next
end
self.widget_list:Clear()
end
function CWidgetCache:Add(widget)
if widget == nil then
return
end
widget:retain()
self.widget_list:PushBack(widget)
end
function CWidgetCache:Cache(count)
if self.template_widget == nil then
return
end
local real_count = count - self.widget_list.size
for i=1,real_count do
local widget = self:CloneWidget()
if widget ~= nil then
widget:retain()
self.widget_list:PushBack(widget)
self.widget_count = self.widget_count + 1
end
end
end
function CWidgetCache:Get()
if self.template_widget == nil then
return nil
end
-- 从缓存列表中抽取一枚
local widget = self.widget_list:PopFront()
-- 缓存列表已被使用完
if widget == nil then
widget = self:CloneWidget()
self.widget_count = self.widget_count + 1
print("[CWidgetCache] clone ui_widget "..self.config.."(ref:"..self.widget_count..")")
end
return widget
end
dxm.CWidgetCacheManager = class("CWidgetCacheManager")
local CWidgetCacheManager = dxm.CWidgetCacheManager
dxm.SINGLETON(CWidgetCacheManager)
-- 构造函数
function CWidgetCacheManager:ctor()
self.gc_size = 10 -- gc容量
self.gc_interval = 1 -- gc间隔
self.gc_tick = 0 -- gc时间
self.gc_widget_cache_list = dxm.CList.new() -- GC缓存链表
self.widget_cache_map = {} -- 临时缓存表单,无用时会被GC
self.register_widget_cache_map = {} -- 注册缓存表单
local function Update(dt)
self:UpdateGC(dt)
end
cc.Director:sharedDirector():getScheduler():scheduleScriptFunc(Update, 0, false)
end
function CWidgetCacheManager:Dispose()
-- TODO:
end
function CWidgetCacheManager:GetWidget(config)
local widget_cache = self:GetWidgetCache(config)
print("[CWidgetCache] GetCache"..widget_cache.config)
return widget_cache:Get()
end
function CWidgetCacheManager:CacheWidget(config, count)
local widget_cache = self:GetWidgetCache(config)
if widget_cache == nil then
return
end
print("[CWidgetCache] GetCache:"..widget_cache.config)
widget_cache:Cache(count)
self.register_widget_cache_map[config] = widget_cache
end
function CWidgetCacheManager:UncacheWidget(config)
local widget_cache = self.register_widget_cache_map[config]
if widget_cache ~= nil then
widget_cache:Dispose()
end
self.register_widget_cache_map[config] = nil
end
function CWidgetCacheManager:AddWidget(config, widget)
local widget_cache = self:GetWidgetCache(config)
if widget_cache == nil then
return
end
widget_cache:Add(widget)
end
function CWidgetCacheManager:GetWidgetCache(config)
local widget_cache = self.widget_cache_map[config]
if widget_cache ~= nil then
return widget_cache
end
widget_cache = self:PopFromGC(config)
if widget_cache ~= nil then
return widget_cache
end
widget_cache = CWidgetCache.new(config)
self.widget_cache_map[config] = widget_cache
return widget_cache
end
function CWidgetCacheManager:UpdateGC(dt)
-- 累计时间,判断是否到达自动回收
self.gc_tick = self.gc_tick + dt
if self.gc_tick < self.gc_interval then
return
end
self.gc_tick = 0
-- 检测界面回收
for config, temp_widget_cache in pairs(self.widget_cache_map) do
-- 判断缓存界面是否全部被回收
if temp_widget_cache ~= nil and temp_widget_cache.widget_list.size == temp_widget_cache.widget_count then
self:Push2GC(config, temp_widget_cache);
self.widget_cache_map[config] = nil
break
end
end
-- 清理超过部分
while self.gc_widget_cache_list.size > self.gc_size do
local widget_cache = self.gc_widget_cache_list:PopFront()
if widget_cache ~= nil then
print("[CWidgetCache] gc widget:"..widget_cache.config)
widget_cache:Dispose()
end
end
end
function CWidgetCacheManager:Push2GC(config, widget_cache)
-- 添加到链表中
self.gc_widget_cache_list:PushBack(widget_cache)
end
function CWidgetCacheManager:PopFromGC(config)
-- 链表中搜索对应的缓存
local node = self.gc_widget_cache_list.first
while node ~= nil do
-- 判断名称是否一致
local widget_cache = node.value
if widget_cache.config == config then
self.widget_cache_map[config] = widget_cache
self.gc_widget_cache_list:Erase(node)
return widget_cache
end
node = node.next
end
return nil
end
return CWidgetCacheManager
--endregion
|
local mod = DBM:NewMod(2355, "DBM-Party-BfA", 11, 1178)
local L = mod:GetLocalizedStrings()
mod:SetRevision("20190625143048")
mod:SetCreatureID(155157)
mod:SetEncounterID(2291)--VERIFY
mod:SetZone()
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_AURA_APPLIED 296080 302274 303885 303252",
"SPELL_AURA_REMOVED 296080 303885",
"SPELL_CAST_START 295536 296464 295445 296522 295939",
"SPELL_CAST_SUCCESS 302274 303885",
"UNIT_DIED"
)
--TODO, can tank dodge wreck?
--TODO, additional warnings/timers for platform stuff?
--TODO, what CID is boss health/win for this fight?
local warnReinforcementRelay = mod:NewSpellAnnounce(296464, 2)
local warnSelfDestruct = mod:NewCastAnnounce(296522, 4)
local warnHaywire = mod:NewTargetNoFilterAnnounce(296080, 1)
local warnFulminatingZap = mod:NewTargetNoFilterAnnounce(302274, 2, nil, "Healer")
local specWarnCannonBlast = mod:NewSpecialWarningDodge(295536, nil, nil, nil, 2, 2)
local specWarnWreck = mod:NewSpecialWarningDefensive(295445, "Tank", nil, nil, 1, 2)
local specWarnFulminatingBurst = mod:NewSpecialWarningMoveTo(303885, nil, nil, nil, 1, 2)
local yellFulminatingBurst = mod:NewYell(303885)
local yellFulminatingBurstFades = mod:NewShortFadesYell(303885)
--Stage 2
local specWarnAnnihilationRay = mod:NewSpecialWarningSpell(295939, nil, nil, nil, 2, 2)
local specWarnAntiTresField = mod:NewSpecialWarningMoveTo(303252, nil, nil, nil, 1, 2)
local yellAntiTresField = mod:NewYell(303252)
--local specWarnGTFO = mod:NewSpecialWarningGTFO(238028, nil, nil, nil, 1, 8)
local timerCannonBlastCD = mod:NewAITimer(31.6, 295536, nil, nil, nil, 3, nil, DBM_CORE_DEADLY_ICON)
local timerReinforcementRelayCD = mod:NewAITimer(31.6, 296464, nil, nil, nil, 1)
local timerWreckCD = mod:NewAITimer(31.6, 295445, nil, nil, nil, 5, nil, DBM_CORE_TANK_ICON)
local timerFulminatingZapCD = mod:NewAITimer(31.6, 302274, nil, nil, nil, 3, nil, DBM_CORE_HEALER_ICON)
local timerFulminatingBurstCD = mod:NewAITimer(31.6, 303885, nil, nil, nil, 3, nil, DBM_CORE_HEALER_ICON)--Hard Mode
--Stage 2
local timerAnnihilationRayCD = mod:NewAITimer(31.6, 295939, nil, nil, nil, 6)
local timerHaywire = mod:NewBuffActiveTimer(30, 296080, nil, nil, nil, 6)
--local timerHowlingFearCD = mod:NewAITimer(13.4, 257791, nil, "HasInterrupt", nil, 4, nil, DBM_CORE_INTERRUPT_ICON)
--mod:AddRangeFrameOption(5, 194966)
mod:AddNamePlateOption("NPAuraOnWalkieShockie", 296522, false)
mod.vb.phase = 1
local unitTracked = {}
local function checkHardMode(self, delay)
local found = false
for i = 1, 5 do
local unitID = "boss"..i
if UnitExists(unitID) then
local cid = self:GetUnitCreatureId(unitID)
if cid == 150295 then--Mk1
found = true
timerCannonBlastCD:Start(1)
timerReinforcementRelayCD:Start(1)
timerAnnihilationRayCD:Start(1)
timerFulminatingZapCD:Start(1)--SUCCESS
elseif cid == 155760 then--MK2 (hard mode)
found = true
timerCannonBlastCD:Start(1)
timerReinforcementRelayCD:Start(1)
timerAnnihilationRayCD:Start(1)
timerFulminatingBurstCD:Start(1)--SUCCESS
end
end
end
if not found then
DBM:AddMsg("checkHardMode failed, tell DBM author")
end
end
function mod:OnCombatStart(delay)
self.vb.phase = 1
self:Schedule(1-delay, checkHardMode, self)
table.wipe(unitTracked)
if self.Options.NPAuraOnWalkieShockie then
DBM:FireEvent("BossMod_EnableHostileNameplates")
self:RegisterOnUpdateHandler(function(self)
for i = 1, 40 do
local UnitID = "nameplate"..i
local GUID = UnitGUID(UnitID)
local cid = self:GetCIDFromGUID(GUID)
if cid == 155645 or cid == 152703 then--Walkie Shockie X1 and X2
local unitPower = UnitPower(UnitID)
if not unitTracked[GUID] then unitTracked[GUID] = "None" end
if (unitPower > 90) then
if unitTracked[GUID] ~= "Green" then
unitTracked[GUID] = "Green"
DBM.Nameplate:Show(true, GUID, 276299, 463281)
end
elseif (unitPower > 60) then
if unitTracked[GUID] ~= "Yellow" then
unitTracked[GUID] = "Yellow"
DBM.Nameplate:Hide(true, GUID, 276299, 463281)
DBM.Nameplate:Show(true, GUID, 276299, 460954)
end
elseif (unitPower > 30) then
if unitTracked[GUID] ~= "Red" then
unitTracked[GUID] = "Red"
DBM.Nameplate:Hide(true, GUID, 276299, 460954)
DBM.Nameplate:Show(true, GUID, 276299, 463282)
end
elseif (unitPower > 10) then
if unitTracked[GUID] ~= "Critical" then
unitTracked[GUID] = "Critical"
DBM.Nameplate:Hide(true, GUID, 276299, 463282)
DBM.Nameplate:Show(true, GUID, 276299, 237521)
end
end
end
end
end, 1)
end
end
function mod:OnCombatEnd()
table.wipe(unitTracked)
-- if self.Options.RangeFrame then
-- DBM.RangeCheck:Hide()
-- end
if self.Options.NPAuraOnWalkieShockie then
DBM.Nameplate:Hide(true, nil, nil, nil, true, true)
end
end
function mod:SPELL_AURA_APPLIED(args)
local spellId = args.spellId
if spellId == 296080 then
warnHaywire:Show(args.destName)
timerHaywire:Start()
elseif spellId == 302274 then
warnFulminatingZap:Show(args.destName)
elseif spellId == 303885 then
if args:IsPlayer() then
specWarnFulminatingBurst:Show(DBM_ALLY)
yellFulminatingBurst:Yell()
yellFulminatingBurstFades:Countdown(9)
else
specWarnFulminatingBurst:Show(args.destName)
end
specWarnFulminatingBurst:Play("gathershare")
elseif spellId == 303252 then
if args:IsPlayer() then
specWarnAntiTresField:Show(DBM_ALLY)
yellAntiTresField:Yell()
else
specWarnAntiTresField:Show(args.destName)
end
specWarnAntiTresField:Play("gathershare")
end
end
--mod.SPELL_AURA_APPLIED_DOSE = mod.SPELL_AURA_APPLIED
function mod:SPELL_AURA_REMOVED(args)
local spellId = args.spellId
if spellId == 296080 then--Haywire
timerHaywire:Stop()
timerAnnihilationRayCD:Start(2)--Assumed
timerReinforcementRelayCD:Start(2)--Assumed
timerCannonBlastCD:Start(2)
elseif spellId == 303885 then
if args:IsPlayer() then
yellFulminatingBurstFades:Cancel()
end
end
end
function mod:SPELL_CAST_START(args)
local spellId = args.spellId
if spellId == 295536 then
specWarnCannonBlast:Show()
specWarnCannonBlast:Play("farfromline")
timerCannonBlastCD:Start()
elseif spellId == 296464 then
warnReinforcementRelay:Show()
timerReinforcementRelayCD:Start()
elseif spellId == 295445 then
specWarnWreck:Show()
specWarnWreck:Play("defensive")
timerWreckCD:Start(nil, args.sourceGUID)
elseif spellId == 296522 then
warnSelfDestruct:Show()
elseif spellId == 295939 then
specWarnAnnihilationRay:Show()
specWarnAnnihilationRay:Play("phasechange")
--timerAnnihilationRayCD:Start()
--Possibly redundant
timerReinforcementRelayCD:Stop()--Assumed
timerCannonBlastCD:Stop()
timerFulminatingZapCD:Stop()
timerFulminatingBurstCD:Stop()
end
end
function mod:SPELL_CAST_SUCCESS(args)
local spellId = args.spellId
if spellId == 302274 then
timerFulminatingZapCD:Start()
elseif spellId == 303885 then
timerFulminatingBurstCD:Start()
end
end
--[[
function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId)
if spellId == 228007 and destGUID == UnitGUID("player") and self:AntiSpam(2, 4) then
specWarnGTFO:Show()
specWarnGTFO:Play("watchfeet")
end
end
mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE
--]]
function mod:UNIT_DIED(args)
local cid = self:GetCIDFromGUID(args.destGUID)
if cid == 150295 or cid == 155760 then--tank-buster-mk1/tank-buster-mk2
self.vb.phase = 2
timerWreckCD:Stop(args.destGUID)
--Possibly Wrong
timerCannonBlastCD:Stop()
timerFulminatingZapCD:Stop()
timerFulminatingBurstCD:Stop()
timerReinforcementRelayCD:Stop()
end
end
--[[
function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, spellId)
if spellId == 257939 then
end
end
--]]
|
return (function()
return true -- UNIMPLEMENTED
end)(...)
|
--- Tests for the @{Deque} interface.
return function()
local module = game:GetService("ReplicatedStorage").Monolith
local Deque = require(module.Deque)
describe("Constructor", function()
it("should be able to be instantiated", function()
local deque = Deque.new()
expect(deque).to.be.ok()
end)
end)
describe("Enumerable Interface", function()
it("should error when Enumerator is not overridden", function()
local deque = Deque.new()
expect(function()
deque.Enumerator()
end).to.throw("Abstract method Enumerator must be overridden in first concrete subclass. Called directly from Deque.")
end)
end)
describe("Collection Interface", function()
it("should error when Contains is not overridden", function()
local deque = Deque.new()
expect(function()
deque.Contains()
end).to.throw("Abstract method Contains must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when ContainsAll is not overridden", function()
local deque = Deque.new()
expect(function()
deque.ContainsAll()
end).to.throw("Abstract method ContainsAll must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when ContainsAny is not overridden", function()
local deque = Deque.new()
expect(function()
deque.ContainsAny()
end).to.throw("Abstract method ContainsAny must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when Count is not overridden", function()
local deque = Deque.new()
expect(function()
deque.Count()
end).to.throw("Abstract method Count must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when Empty is not overridden", function()
local deque = Deque.new()
expect(function()
deque.Empty()
end).to.throw("Abstract method Empty must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when ToArray is not overridden", function()
local deque = Deque.new()
expect(function()
deque.ToArray()
end).to.throw("Abstract method ToArray must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when ToTable is not overridden", function()
local deque = Deque.new()
expect(function()
deque.ToTable()
end).to.throw("Abstract method ToTable must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when Add is not overridden", function()
local deque = Deque.new()
expect(function()
deque.Add()
end).to.throw("Abstract method Add must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when AddAll is not overridden", function()
local deque = Deque.new()
expect(function()
deque.AddAll()
end).to.throw("Abstract method AddAll must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when Clear is not overridden", function()
local deque = Deque.new()
expect(function()
deque.Clear()
end).to.throw("Abstract method Clear must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when Remove is not overridden", function()
local deque = Deque.new()
expect(function()
deque.Remove()
end).to.throw("Abstract method Remove must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when RemoveAll is not overridden", function()
local deque = Deque.new()
expect(function()
deque.RemoveAll()
end).to.throw("Abstract method RemoveAll must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when RetainAll is not overridden", function()
local deque = Deque.new()
expect(function()
deque.RetainAll()
end).to.throw("Abstract method RetainAll must be overridden in first concrete subclass. Called directly from Deque.")
end)
end)
describe("Queue Interface", function()
it("should error when First is not overridden", function()
local deque = Deque.new()
expect(function()
deque.First()
end).to.throw("Abstract method First must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when Push is not overridden", function()
local deque = Deque.new()
expect(function()
deque.Push()
end).to.throw("Abstract method Push must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when Shift is not overridden", function()
local deque = Deque.new()
expect(function()
deque.Shift()
end).to.throw("Abstract method Shift must be overridden in first concrete subclass. Called directly from Deque.")
end)
end)
describe("Deque Interface", function()
it("should error when Last is not overridden", function()
local deque = Deque.new()
expect(function()
deque.Last()
end).to.throw("Abstract method Last must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when Unshift is not overridden", function()
local deque = Deque.new()
expect(function()
deque.Unshift()
end).to.throw("Abstract method Unshift must be overridden in first concrete subclass. Called directly from Deque.")
end)
it("should error when Pop is not overridden", function()
local deque = Deque.new()
expect(function()
deque.Pop()
end).to.throw("Abstract method Pop must be overridden in first concrete subclass. Called directly from Deque.")
end)
end)
end
|
--
-- Licensed to the Apache Software Foundation (ASF) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- The ASF licenses this file to You under the Apache License, Version 2.0
-- (the "License"); you may not use this file except in compliance with
-- the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
local _M = {}
local mt = { __index = _M }
function _M.new(conf)
local sample_ratio = conf.sample_ratio
assert(type(sample_ratio) == "number" and
sample_ratio >= 0 and sample_ratio <= 1, "invalid sample_ratio")
return setmetatable({
sample_ratio = sample_ratio
}, mt)
end
function _M.sample(self)
return math.random() < self.sample_ratio
end
return _M
|
--[[
TheNexusAvenger
Base round class used by the game.
--]]
local DEFAULT_ROUND_TIME = 5 * 60
local LOAD_TIME = 5
local DEFAULT_RESPAWN_TIME = 3
local MVP_COINS = 20
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")
local ServerScriptServiceProject = require(ReplicatedStorage:WaitForChild("Project"):WaitForChild("ServerScriptService"))
local StatsSorter
local RankScoreBonuses
local NexusReplication = require(ReplicatedStorage:WaitForChild("External"):WaitForChild("NexusReplication"))
local BaseRound = NexusReplication:GetResource("Common.Object.ReplicatedContainer"):Extend()
BaseRound:SetClassName("BaseRound")
NexusReplication:RegisterType("BaseRound",BaseRound)
--[[
Creates the round object.
--]]
function BaseRound:__new()
self:InitializeSuper()
self.Name = "BaseRound"
--Store the round data.
self.DisabledSpawningPlayers = {}
self.PlayerStarterTools = {}
self.State = "LOADING"
self.TimerText = "TIME REMAINING"
self.MVPs = {}
if NexusReplication:IsServer() then
self.Players = NexusReplication:CreateObject("ReplicatedTable")
self.Spectators = NexusReplication:CreateObject("ReplicatedTable")
self.EliminatedPlayerStats = NexusReplication:CreateObject("ReplicatedTable")
self.Timer = NexusReplication:CreateObject("Timer")
end
self:AddToSerialization("State")
self:AddToSerialization("TimerText")
self:AddToSerialization("Map")
self:AddToSerialization("MapName")
self:AddToSerialization("RoundContainer")
self:AddToSerialization("MVPs")
self:AddToSerialization("Players")
self:AddToSerialization("Spectators")
self:AddToSerialization("EliminatedPlayerStats")
self:AddToSerialization("Timer")
--Store the stats.
self.RoundStats = {
{
Name = "KOs",
ValueType = "IntValue",
DefaultValue = 0,
ShowInLeaderstats = true,
Prefer = "Higher",
},
{
Name = "WOs",
ValueType = "IntValue",
DefaultValue = 0,
ShowInLeaderstats = true,
Prefer = "Lower",
},
{
Name = "CurrentStreak",
ValueType = "IntValue",
DefaultValue = 0,
},
{
Name = "MaxStreak",
ValueType = "IntValue",
DefaultValue = 0,
},
}
--Set up the spawn points.
self.SpawnPoints = {
Normal = {
CurrentSpawn = 1,
Parts = {},
},
Team = {},
Players = {},
}
self:AddPropertyFinalizer("Map",function(_,Map)
--Get the spawn point models.
local NewSpawnPoints = {
Normal = {
CurrentSpawn = 1,
Parts = {},
},
Team = {},
Players = {},
}
self.SpawnPoints = NewSpawnPoints
local SpawnPoints = Map:FindFirstChild("SpawnPoints")
if not SpawnPoints then return end
local TeamSpawnPoints = SpawnPoints:FindFirstChild("TeamSpawnPoints")
--Add the base spawn parts.
for _,Part in pairs(SpawnPoints:GetChildren()) do
if Part:IsA("BasePart") then
table.insert(NewSpawnPoints.Normal.Parts,Part)
end
end
SpawnPoints.ChildAdded:Connect(function(Part)
if Part:IsA("BasePart") then
table.insert(NewSpawnPoints.Normal.Parts,Part)
end
end)
SpawnPoints.ChildRemoved:Connect(function(Part)
local Index
for i,OtherPart in pairs(NewSpawnPoints.Normal.Parts) do
if Part == OtherPart then
Index = i
break
end
end
if not Index then return end
table.remove(NewSpawnPoints.Normal.Parts,Index)
if NewSpawnPoints.Normal.CurrentSpawn > #NewSpawnPoints.Normal.Parts then
NewSpawnPoints.Normal.CurrentSpawn = #NewSpawnPoints.Normal.Parts
end
end)
--Add the team spawn parts.
if not TeamSpawnPoints then return end
for _,Part in pairs(TeamSpawnPoints:GetChildren()) do
if Part:IsA("BasePart") then
if not NewSpawnPoints.Team[Part.BrickColor.Name] then
NewSpawnPoints.Team[Part.BrickColor.Name] = {
CurrentSpawn = 1,
Parts = {},
}
end
table.insert(NewSpawnPoints.Team[Part.BrickColor.Name].Parts,Part)
end
end
TeamSpawnPoints.ChildAdded:Connect(function(Part)
if Part:IsA("BasePart") then
if not NewSpawnPoints.Team[Part.BrickColor.Name] then
NewSpawnPoints.Team[Part.BrickColor.Name] = {
CurrentSpawn = 1,
Parts = {},
}
end
table.insert(NewSpawnPoints.Team[Part.BrickColor.Name].Parts,Part)
end
end)
TeamSpawnPoints.ChildRemoved:Connect(function(Part)
for _,TeamSpawns in pairs(NewSpawnPoints.Team) do
local Index
for i,OtherPart in pairs(TeamSpawns.Parts) do
if Part == OtherPart then
Index = i
break
end
end
if Index then
table.remove(TeamSpawns.Parts,Index)
if TeamSpawns.CurrentSpawn > #TeamSpawns.Parts then
TeamSpawns.CurrentSpawn = #TeamSpawns.Parts
end
end
end
end)
end)
end
--[[
Returns a service.
--]]
function BaseRound:GetService(ServiceName)
return ServerScriptServiceProject:GetResource("Service."..tostring(ServiceName))
end
--[[
Starts the round.
--]]
function BaseRound:Start(RoundPlayers,LoadTimeElapsedCallback)
--Create the temporary stats.
for _,Player in pairs(RoundPlayers) do
self:GetService("StatService"):ClearTemporaryStats(Player)
local Stats = self:GetService("StatService"):GetTemporaryStats(Player)
for _,StatData in pairs(self.RoundStats) do
Stats:Create(StatData.Name,StatData.ValueType,StatData.DefaultValue)
end
end
--Add the players.
for _,Player in pairs(RoundPlayers) do
self.Players:Add(Player)
end
Players.PlayerRemoving:Connect(function(Player)
self.Players:Remove(Player)
self.Spectators:Remove(Player)
end)
--Run the load timer.
self.Timer:SetDuration(self.LoadTime or LOAD_TIME)
self.Timer:Start()
while self.Timer.State ~= "COMPLETE" do
self.Timer:GetPropertyChangedSignal("State"):Wait()
end
if LoadTimeElapsedCallback then
LoadTimeElapsedCallback()
end
--Start the main timer.
self.Timer:SetDuration(DEFAULT_ROUND_TIME)
self.Timer:Start()
self.State = "ACTIVE"
--Start the round.
self.object:RoundStarted()
end
--[[
Ends the round.
--]]
function BaseRound:End()
if self.State == "ENDED" then return end
--Set the MVPs if they weren't set.
if not self.MVPs or #self.MVPs == 0 then
if not StatsSorter then
local ReplicatedStorageProject = require(ReplicatedStorage:WaitForChild("Project"):WaitForChild("ReplicatedStorage"))
StatsSorter = ReplicatedStorageProject:GetResource("State.Stats.StatsSorter")
end
local Sorter = StatsSorter.new(self.RoundStats)
self.MVPs = Sorter:GetMVPs(self.Players:GetAll())
end
--Increase the rank scores.
for _,Player in pairs(self.Players:GetAll()) do
self:AddRankScore(Player)
end
--Stop the round.
self.Timer:Stop()
self.State = "ENDED"
--Despawn the players.
for _,Player in pairs(self.Players:GetAll()) do
self:SetSpawningEnabled(Player,false)
self:DespawnPlayer(Player)
end
--Award the MVP coins.
local MVPCoins = math.ceil(MVP_COINS/#self.MVPs)
for _,Player in pairs(self.MVPs) do
self:GetService("StatService"):GetPersistentStats(Player):Get("TimesMVP"):Increment()
coroutine.wrap(function()
for _ = 1,MVPCoins do
if not Player.Parent then return end
self:GetService("CoinService"):GiveCoins(Player,1)
wait()
end
end)()
end
end
--[[
Sets if automatic spawning of a player is enabled.
--]]
function BaseRound:SetSpawningEnabled(Player,Enabled)
if not Player or not Player.Parent or not self.Players:Contains(Player) then return end
self.DisabledSpawningPlayers[Player] = not Enabled
end
--[[
Sets the spawn location of a player.
--]]
function BaseRound:SetPlayerSpawn(Player,SpawnPart)
self.SpawnPoints.Players[Player] = SpawnPart
end
--[[
Spawns a player.
--]]
function BaseRound:SpawnPlayer(Player)
if not Player or not Player.Parent or not self.Players:Contains(Player) then return end
coroutine.wrap(function()
--Get a spawn location part.
local SpawnPart = self.SpawnPoints.Players[Player]
if not SpawnPart then
local SpawnParts = (not Player.Neutral and self.SpawnPoints.Team[Player.TeamColor.Name] or self.SpawnPoints.Normal)
if #SpawnParts.Parts == 0 then return end
SpawnPart = SpawnParts.Parts[SpawnParts.CurrentSpawn]
SpawnParts.CurrentSpawn = (SpawnParts.CurrentSpawn % #SpawnParts.Parts) + 1
end
--Teleport the player.
local CharacterService = self:GetService("CharacterService")
local Character = CharacterService:SpawnCharacter(Player,SpawnPart)
CharacterService:AddForceField(Player)
if not Character then return end
local Humanoid = Character:WaitForChild("Humanoid")
--Connect the character dieing.
Humanoid.Died:Connect(function()
wait(DEFAULT_RESPAWN_TIME)
if self.DisabledSpawningPlayers[Player] then return end
if not self.Players:Contains(Player) then return end
self:SpawnPlayer(Player)
end)
--Set the tools.
if self.PlayerStarterTools[Player] then
self:SetTools(Player,self.PlayerStarterTools[Player])
end
end)()
end
--[[
Despawns a player.
--]]
function BaseRound:DespawnPlayer(Player)
if not Player or not Player.Parent or not self.Players:Contains(Player) then return end
if not Player.Character then return end
self:GetService("CharacterService"):DespawnCharacter(Player)
end
--[[
Sets the tools on spawn for a player.
--]]
function BaseRound:SetStarterTools(Player,PlayerTools)
if not Player or not Player.Parent or not self.Players:Contains(Player) then return end
self.PlayerStarterTools[Player] = PlayerTools
end
--[[
Sets the tools for a player.
--]]
function BaseRound:SetTools(Player,PlayerTools)
--Get the character and backpack.
local Character = Player.Character
if not Character then return end
local Humanoid = Character:FindFirstChild("Humanoid")
if not Humanoid then return end
local Backpack = Player:FindFirstChild("Backpack")
if not Backpack then return end
--Convert the tools to a map.
local PlayerToolsMap = {}
for _,ToolName in pairs(PlayerTools) do
PlayerToolsMap[ToolName] = true
end
--Add the new tools.
local Tools = ServerStorage:WaitForChild("Tools")
for _,ToolName in pairs(PlayerTools) do
if not Backpack:FindFirstChild(ToolName) and not Character:FindFirstChild(ToolName) then
Tools:WaitForChild(ToolName):Clone().Parent = Backpack
end
end
--Remove the old tools.
for _,Tool in pairs(Backpack:GetChildren()) do
if not PlayerToolsMap[Tool.Name] then
Tool:Destroy()
end
end
local EquippedTool = Character:FindFirstChildOfClass("Tool")
if EquippedTool and not PlayerToolsMap[EquippedTool.Name] then
Humanoid:UnequipTools()
EquippedTool:Destroy()
end
end
--[[
Removes a player currently in the round,
such as when the round ends.
--]]
function BaseRound:RemoveCurrentPlayer(Player)
if self.Players:Contains(Player) then
self.Players:Remove(Player)
self:GetService("StatService"):ClearTemporaryStats(Player)
end
end
--[[
Awards the rank score to the given player.
--]]
function BaseRound:AddRankScore(Player)
--Load the bonuses class.
if not RankScoreBonuses then
local ReplicatedStorageProject = require(ReplicatedStorage:WaitForChild("Project"):WaitForChild("ReplicatedStorage"))
RankScoreBonuses = ReplicatedStorageProject:GetResource("State.RankScoreBonuses")
end
--Calculate the bonuses.
local Multiplier = 1
for _,Bonus in pairs(RankScoreBonuses(Player)) do
Multiplier = Multiplier + Bonus.Multiplier
end
--Add the rank bonuses.
local StatService = self:GetService("StatService")
local PlayerTemproaryStats = StatService:GetTemporaryStats(Player)
local PlayerPersistentStats = StatService:GetPersistentStats(Player)
local KOs = PlayerTemproaryStats:Get("KOs"):Get()
if KOs > 0 then
PlayerPersistentStats:Get("RankScore"):Increment(KOs * Multiplier)
end
end
--[[
Eliminates a player from the existing round
and makes them a spectator.
--]]
function BaseRound:EliminatePlayer(Player)
if self.Players:Contains(Player) and not self.Spectators:Contains(Player) and self.State ~= "ENDED" then
--Despawn the player.
self:DespawnPlayer(Player)
self:AddRankScore(Player)
--Store the temporary stats.
local PlayerData = {
Player = Player,
Stats = {},
}
if not Player.Neutral then
PlayerData.TeamColor = Player.TeamColor
end
local TemporaryStats = self:GetService("StatService"):GetTemporaryStats(Player)
for _,RoundStat in pairs(self.RoundStats) do
PlayerData.Stats[RoundStat.Name] = TemporaryStats:Get(RoundStat.Name):Get()
end
self.EliminatedPlayerStats:Add(PlayerData)
--Add the spectator and remove the player from the round.
self.Spectators:Add(Player)
self:RemoveCurrentPlayer(Player)
end
end
--[[
Broadcasts a local effect to all the
players of the round.
--]]
function BaseRound:BroadcastLocalEffect(...)
local LocalEffectService = self:GetService("LocalEffectService")
for _,Player in pairs(self.Players:GetAll()) do
LocalEffectService:PlayLocalEffect(Player,...)
end
for _,Player in pairs(self.Spectators:GetAll()) do
LocalEffectService:PlayLocalEffect(Player,...)
end
end
--[[
Disposes of the object.
--]]
function BaseRound:Dispose()
self.super:Dispose()
--Destroy the objects.
self.Players:Destroy()
self.Spectators:Destroy()
self.EliminatedPlayerStats:Destroy()
self.Timer:Destroy()
end
return BaseRound
|
---------------------------------------------------------------------
-- Project: irc
-- Author: MCvarial
-- Contact: mcvarial@gmail.com
-- Version: 1.0.0
-- Date: 31.10.2010
---------------------------------------------------------------------
-- everything is saved here
servers = {} -- syntax: [server] = {element socket,string name,string host,string nick,string password,number port,bool secure,string nickservpass,string authident, string authpass,number lastping,timer timeoutguard,number reconnectattempts, table channels,bool connected,table buffer}
channels = {} -- syntax: [channel] = {string name,string mode,string topic,table users,string password,bool joined,bool echo}
users = {} -- syntax: [user] = {string name,string mode,string vhost,string email,string realname,table channels,table channelmodes}
------------------------------------
-- Loading
------------------------------------
addEventHandler("onResourceStart",resourceRoot,
function ()
-- Is the sockets module loaded?
if not sockOpen then
outputServerLog("IRC: could not start resource, the sockets module isn't loaded!")
outputServerLog("IRC: restart the resource to retry")
return
end
-- Parse functions file.
local functionsFile = fileOpen("scripts/functions.txt",true)
if functionsFile then
for i,line in ipairs (split(fileRead(functionsFile,fileGetSize(functionsFile)),44)) do
local functionName = gettok(line,2,32)
_G[(functionName)] = function (...)
local args = {...}
for i,arg in ipairs (args) do
local expectedArgType = gettok(line,(2+i),32)
if type(arg) ~= expectedArgType and not string.find(expectedArgType,")") then
outputServerLog("IRC: Bad argument #"..i.." @ '"..gettok(line,2,32).."' "..expectedArgType.." expected, got "..type(arg))
return
end
end
return _G[("func_"..functionName)](...)
end
end
fileClose(functionsFile)
else
outputServerLog("IRC: could not start resource, the functions file can't be loaded!")
outputServerLog("IRC: restart the resource to retry")
return
end
-- Connect when needed.
if get("irc-autoconnect") == "true" then
internalConnect()
end
end
)
addEventHandler("onResourceStop",resourceRoot,
function ()
for i,server in ipairs (ircGetServers()) do
ircDisconnect(server,"resource stopped")
end
end
)
function internalConnect ()
-- Parse settings file.
local settingsFile = xmlLoadFile("settings.xml")
if settingsFile then
for i,server in ipairs (xmlNodeGetChildren(settingsFile)) do
local host = xmlNodeGetAttribute(server,"host")
local nick = xmlNodeGetAttribute(server,"nick")
local channels = xmlNodeGetAttribute(server,"channels")
local port = tonumber(xmlNodeGetAttribute(server,"port")) or 6667
local password = xmlNodeGetAttribute(server,"password") or false
local secure = xmlNodeGetAttribute(server,"secure") or false
local nspass = xmlNodeGetAttribute(server,"nickservpass") or false
if not host then
outputServerLog("IRC: problem with server #"..i..", no host given!")
elseif not nick then
outputServerLog("IRC: problem with server #"..i..", no nick given!")
elseif not channels then
outputServerLog("IRC: problem with server #"..i..", no channels given!")
else
local server = ircConnect(host,nick,port,password,secure)
if nspass then
ircIdentify(server,nspass)
end
for i,channel in ipairs (split(channels,44)) do
ircJoin(server,gettok(channel,1,32),gettok(channel,2,32))
end
end
end
xmlUnloadFile(settingsFile)
else
outputServerLog("IRC: could not start resource, the settings.xml can't be parsed!")
outputServerLog("IRC: restart the resource to retry")
return
end
end
------------------------------------
-- Socket events
------------------------------------
addEventHandler("onSockOpened",root,
function (socket)
for server,info in pairs (servers) do
if info[1] == socket then
servers[server][15] = true
ircRaw(server,"USER echobot MCvarial MCv :Echobot by MCvarial");
ircRaw(server,"NICK "..info[4])
return
end
end
end
)
addEventHandler("onSockData",root,
function (socket,data)
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
)
addEventHandler("onSockClosed",root,
function (socket)
for server,info in pairs (servers) do
if info[1] == socket then
ircDisconnect(server,"Socket closed")
return
end
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
)
|
Locales['en'] = {
['hunger'] = 'hunger: %s',
['givefood'] = 'give food',
['attachpet'] = 'attach or detach your pet',
['getpeddown'] = 'tell your pet to exit the vehicle',
['getpedinside'] = 'tell your pet to get in the vehicle',
['giveorders'] = 'give an order',
['callpet'] = 'call your pet',
['pet_management'] = 'pet management',
['dontattachhiminacar'] = '~r~You can\'t attach your pet in an vehicle!~s~',
['gavepetfood'] = 'you gave your pet some food.',
['nomorehunger'] = 'your pet is no longer hungry.',
['donthavefood'] = '~r~You don\'t have food for your pet!~s~',
['hestoofar'] = '~r~Your pet is too far! ~s~',
['toofarfromcar'] = '~r~Your pet is too far from the vehicle!~s~',
['youneedtobeincar'] = 'you need to be in an vehicle!',
['yourstillinacar'] = 'you\'re still in an vehicle.',
['sitdown'] = 'sit down',
['getdown'] = 'get down',
['getup'] = 'get up',
['pet_orders'] = 'pet orders',
['pet_dead'] = 'your pet is dead! Give him food next time',
['enterkey'] = 'press ~INPUT_CONTEXT~ to access the pet shop.',
['dog'] = 'dog',
['cat'] = 'cat',
['wolf'] = 'wolf',
['bunny'] = 'bunny',
['husky'] = 'husky',
['pig'] = 'pig',
['poodle'] = 'poodle',
['pug'] = 'pug',
['retriever'] = 'retriever',
['asatian'] = 'alsatian dog',
['westie'] = 'westie',
['rottweiler'] = 'rottweiler',
['chop'] = 'chop',
['you_bought'] = 'you just bought a %s for ~g~$%s~s~',
['your_poor'] = 'you cannot afford this pet!',
['doghouse'] = 'tell your pet to go to the doghouse',
['doghouse_returning'] = 'your pet is returning home',
['balle'] = 'fetch the ball',
['pied'] = 'go at my feet',
['noball'] = 'you don\'t have a ~b~ball~s~ on you!',
['pet_shop'] = 'pet shop',
['shop_item'] = '$%s',
}
|
local function textures(color, shorn)
local s = shorn and "^tigris_mobs_shorn.png" or ""
return {
"wool_" .. color .. ".png" .. s,
"wool_" .. color .. ".png" .. s,
"wool_" .. color .. ".png" .. s,
"wool_" .. color .. ".png" .. s,
"wool_" .. color .. ".png" .. s,
"wool_" .. color .. ".png^tigris_mobs_sheep_face.png",
}
end
local colors = {"white", "black", "brown", "grey", "dark_grey"}
local sheep = {}
for _,color in ipairs(colors) do
local name = "tigris_mobs:sheep_" .. color
table.insert(sheep, name)
tigris.mobs.register(":" .. name, {
description = "Sheep",
collision = {-0.4, -0.4, -0.4, 0.4, 0.4, 0.4},
box = {
{-0.25, 0, -0.5, 0.25, 0.6, 0.5},
{-0.25, -0.5, -0.5, -0.1, 0, -0.35},
{0.1, -0.5, -0.5, 0.25, 0, -0.35},
{-0.25, -0.5, 0.35, -0.1, 0, 0.5},
{0.1, -0.5, 0.35, 0.25, 0, 0.5},
{-0.25, 0, -0.5, 0.25, 0.5, -0.75},
{-0.1, 0.4, 0.5, 0.1, 0.5, 0.75},
},
textures = textures(color, false),
group = "peaceful",
level = 1,
drops = {
{100, "mobs:meat_raw"},
{50, "mobs:meat_raw"},
{100, "tigris_mobs:bone"},
{25, "tigris_mobs:eye"},
{15, "tigris_mobs:eye"},
{75, "wool:" .. color},
},
food_nodes = {
"group:grass",
"group:flora",
},
food_items = {
"farming:wheat",
"farming:seed_wheat",
},
habitat_nodes = {"group:soil"},
breedable = sheep,
color = color,
on_init = function(self, data)
self.hp_max = 4
data.jump = 5
data.produce_milk_time = 60 * 30
data.produce_wool_time = 60 * 10
end,
start = "wander",
script = tigris.mobs.common.peaceful({
eat = true,
breed = true,
}, function(s)
s.global.interactions.shear_wool = true
s.flee.interactions.shear_wool = false
table.insert(s.wander.actions, "grow_wool")
table.insert(s.standing.actions, "grow_wool")
s.global.interactions.get_milk = true
s.flee.interactions.get_milk = false
table.insert(s.wander.actions, "produce_milk")
table.insert(s.standing.actions, "produce_milk")
end),
})
tigris.mobs.register_mob_node(":" .. name .. "_shorn", name, {
tiles = textures(color, true),
})
tigris.mobs.register_spawn(name, {
ymax = tigris.world_limits.max.y,
ymin = -24,
light_min = 0,
light_max = minetest.LIGHT_MAX,
chance = 5000 * #colors,
nodes = {"group:soil"},
})
end
|
local Starwalker, super = Class(Encounter)
function Starwalker:init()
super:init(self)
self.text = "* Star walker has changed forms"
self.starwalker = self:addEnemy("starwalker", 530, 238)
self.background = true
self.no_end_message = true
self.timer = 0
self.mode = "normal"
self.old_x = self.starwalker.x
self.old_y = self.starwalker.y
self.ease = false
self.ease_timer = 0
--self.default_xactions = false
--Game.battle:registerXAction("susie", "Snap")
--Game.battle:registerXAction("susie", "Supercharge", "Charge\nfaster", 80)
end
function Starwalker:setMode(mode)
self.mode = mode
self.old_x = self.starwalker.x
self.old_y = self.starwalker.y
self.ease = true
self.ease_timer = 0
end
function Starwalker:update()
super:update(self)
if not self.starwalker.done_state and (Game.battle:getState() ~= "TRANSITION") then
self.timer = self.timer + (1 * DTMULT)
local wanted_x = self.starwalker.old_x
local wanted_y = self.starwalker.old_y
if self.mode == "normal" then
wanted_x = 530 + (math.sin(self.timer * 0.08) * 20)
wanted_y = 238 + (math.sin(self.timer * 0.04) * 10)
elseif self.mode == "shoot" then
wanted_x = 530 - 40 + (math.sin(self.timer * 0.08) * 10)
wanted_y = 238 - 50 + (math.sin(self.timer * 0.04) * 40)
end
if not self.ease then
self.starwalker.x = wanted_x
self.starwalker.y = wanted_y
else
self.ease_timer = self.ease_timer + (0.05 * DTMULT)
self.starwalker.x = Ease.outQuad(self.ease_timer, self.old_x, wanted_x - self.old_x, 1)
self.starwalker.y = Ease.outQuad(self.ease_timer, self.old_y, wanted_y - self.old_y, 1)
if self.ease_timer >= 1 then
self.ease = false
end
end
end
end
return Starwalker
|
local mod = DBM:NewMod(1830, "DBM-TrialofValor", nil, 861)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 17471 $"):sub(12, -3))
mod:SetCreatureID(114323)
mod:SetEncounterID(1962)
mod:SetZone()
mod:SetUsedIcons(1, 2, 3)
mod:SetHotfixNoticeRev(15651)
mod.respawnTime = 15
mod:SetMinSyncRevision(15635)
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_CAST_START 227514",
"SPELL_CAST_SUCCESS 227883 227816 228824",
"SPELL_AURA_APPLIED 228744 228794 228810 228811 228818 228819 232173 228228 228253 228248",
"SPELL_AURA_REMOVED 228744 228794 228810 228811 228818 228819",
"UNIT_SPELLCAST_SUCCEEDED boss1"
)
--(ability.id = 228247 or ability.id = 228251 or ability.id = 228227) and type = "cast"
local warnOffLeash = mod:NewSpellAnnounce(228201, 2, 129417)
local warnFangs = mod:NewCountAnnounce(227514, 2)
local warnShadowLick = mod:NewTargetAnnounce(228253, 2, nil, "Healer")
local warnFrostLick = mod:NewTargetAnnounce(228248, 3)
local specWarnBreath = mod:NewSpecialWarningCount(228187, nil, nil, nil, 1, 2)
local specWarnLeap = mod:NewSpecialWarningCount(227883, nil, nil, nil, 2)
local specWarnCharge = mod:NewSpecialWarningDodge(227816, nil, nil, nil, 2, 2)
local specWarnBerserk = mod:NewSpecialWarningSpell(227883, nil, nil, nil, 3)
local specWarnFlameLick = mod:NewSpecialWarningMoveAway(228228, nil, nil, nil, 1, 2)
local yellFlameLick = mod:NewYell(228228, nil, false, 2)
local specWarnShadowLick = mod:NewSpecialWarningYou(228253, false, nil, nil, 1)--Not sure warning player is helpful
local yellShadowLick = mod:NewYell(228253, nil, false, 2)
local specWarnFrostLick = mod:NewSpecialWarningYou(228248, false, nil, nil, 1)--Warning player they are stunned probably somewhat useful. Still can't do much about it.
local yellFrostLick = mod:NewYell(228248, nil, false, 2)
local specWarnFrostLickDispel = mod:NewSpecialWarningDispel(228248, "Healer", nil, nil, 1, 2)
--Mythic
local specWarnFlamingFoam = mod:NewSpecialWarningYou(228744, nil, nil, nil, 1)--228794 jump id
local yellFlameFoam = mod:NewPosYell(228744, DBM_CORE_AUTO_YELL_CUSTOM_POSITION)
local specWarnBrineyFoam = mod:NewSpecialWarningYou(228810, nil, nil, nil, 1)--228811 jump id
local yellBrineyFoam = mod:NewPosYell(228810, DBM_CORE_AUTO_YELL_CUSTOM_POSITION)
local specWarnShadowyFoam = mod:NewSpecialWarningYou(228818, nil, nil, nil, 1)
local yellShadowyFoam = mod:NewPosYell(228818, DBM_CORE_AUTO_YELL_CUSTOM_POSITION)
--local timerLickCD = mod:NewCDCountTimer(45, "ej14463", nil, nil, nil, 3, 228228)
local timerLeashCD = mod:NewNextTimer(45, 228201, nil, nil, nil, 6, 129417)
local timerLeash = mod:NewBuffActiveTimer(30, 228201, nil, nil, nil, 6)
local timerFangsCD = mod:NewCDCountTimer(20.5, 227514, nil, "Tank", nil, 5, nil, DBM_CORE_TANK_ICON)--20.5-23
local timerBreathCD = mod:NewCDCountTimer(20.5, 228187, nil, nil, nil, 5, nil, DBM_CORE_DEADLY_ICON)
local timerLeapCD = mod:NewCDCountTimer(22, 227883, nil, nil, nil, 3)
local timerChargeCD = mod:NewCDTimer(10.9, 227816, nil, nil, nil, 3, nil, DBM_CORE_DEADLY_ICON)
mod:AddTimerLine(ENCOUNTER_JOURNAL_SECTION_FLAG12)
local timerVolatileFoamCD = mod:NewCDCountTimer(15.4, 228824, nil, nil, nil, 3, nil, DBM_CORE_HEROIC_ICON)
local berserkTimer = mod:NewBerserkTimer(300)
local countdownBreath = mod:NewCountdown(20.5, 228187)
local countdownFangs = mod:NewCountdown("Alt20", 227514, "Tank")
mod:AddSetIconOption("SetIconOnFoam", "ej14535", true)
mod:AddBoolOption("YellActualRaidIcon", false)
mod:AddBoolOption("FilterSameColor", true)
mod:AddInfoFrameOption(228824, true)
mod:AddRangeFrameOption(5, 228824)
mod.vb.fangCast = 0
mod.vb.breathCast = 0
mod.vb.leapCast = 0
mod.vb.foamCast = 0
mod.vb.YellRealIcons = false
--Ugly way to do it, vs a local table, but this ensures that if icon setter disconnects, it doesn't get messed up
mod.vb.one = "None"
mod.vb.two = "None"
mod.vb.three = "None"
local updateInfoFrame
local fireFoam, frostFoam, shadowFoam = DBM:GetSpellInfo(228744), DBM:GetSpellInfo(228810), DBM:GetSpellInfo(228818)
local fireDebuff, frostDebuff, shadowDebuff = DBM:GetSpellInfo(227539), DBM:GetSpellInfo(227566), DBM:GetSpellInfo(227570)
do
local lines = {}
updateInfoFrame = function()
table.wipe(lines)
for uId in DBM:GetGroupMembers() do
if DBM:UnitDebuff(uId, fireFoam) then
if mod.Options.FilterSameColor and DBM:UnitDebuff(uId, fireDebuff) then
--Do nothing
else
lines[UnitName(uId)] = "|cffff0000"..STRING_SCHOOL_FIRE.."|r"
end
elseif DBM:UnitDebuff(uId, frostFoam) then
if mod.Options.FilterSameColor and DBM:UnitDebuff(uId, frostDebuff) then
--Do nothing
else
lines[UnitName(uId)] = "|cff0000ff"..STRING_SCHOOL_FROST.."|r"
end
elseif DBM:UnitDebuff(uId, shadowFoam) then
if mod.Options.FilterSameColor and DBM:UnitDebuff(uId, shadowDebuff) then
--Do nothing
else
lines[UnitName(uId)] = "|cFF9932CD"..STRING_SCHOOL_SHADOW.."|r"
end
end
end
return lines
end
end
local function delayedSync(self)
self:SendSync("YellActualRaidIcon")
end
function mod:OnCombatStart(delay)
self.vb.fangCast = 0
self.vb.breathCast = 0
self.vb.leapCast = 0
--All other combat start timers started by Helyatosis
if not self:IsLFR() then
if self:IsMythic() then
self.vb.one = "None"
self.vb.two = "None"
self.vb.three = "None"
self.vb.foamCast = 0
self.vb.YellRealIcons = false
--timerLickCD:Start(12.4, 1)
berserkTimer:Start(240-delay)
if self.Options.InfoFrame then
DBM.InfoFrame:SetHeader(DBM:GetSpellInfo(228824))
DBM.InfoFrame:Show(5, "function", updateInfoFrame, false, true)
end
if UnitIsGroupLeader("player") then
if self.Options.YellActualRaidIcon then
self:Schedule(5, delayedSync, self)--Delayed to ensure it's not sent at same time as someone elses OnCombatStart firing and setting YellRealIcons back to false
end
end
else
berserkTimer:Start(-delay)
end
if self.Options.RangeFrame then
DBM.RangeCheck:Show(5)
end
else
berserkTimer:Start(420-delay)
end
end
function mod:OnCombatEnd()
if self.Options.RangeFrame then
DBM.RangeCheck:Hide()
end
if self.Options.InfoFrame then
DBM.InfoFrame:Hide()
end
end
function mod:SPELL_CAST_START(args)
local spellId = args.spellId
if spellId == 227514 then
self.vb.fangCast = self.vb.fangCast + 1
warnFangs:Show(self.vb.fangCast)
if self.vb.fangCast == 1 then
timerFangsCD:Start(nil, 2)
countdownFangs:Start(20.5)
end
end
end
function mod:SPELL_CAST_SUCCESS(args)
local spellId = args.spellId
if spellId == 227883 then
self.vb.leapCast = self.vb.leapCast + 1
specWarnLeap:Show(self.vb.leapCast)
if self.vb.leapCast == 1 then
timerLeapCD:Start(nil, 2)
end
elseif spellId == 227816 then
specWarnCharge:Show()
specWarnCharge:Play("chargemove")
elseif spellId == 228824 then
self.vb.foamCast = self.vb.foamCast + 1
if self.vb.foamCast < 3 then
timerVolatileFoamCD:Start(nil, self.vb.foamCast+1)
end
end
end
function mod:SPELL_AURA_APPLIED(args)
local spellId = args.spellId
if (spellId == 228744 or spellId == 228794 or spellId == 228810 or spellId == 228811 or spellId == 228818 or spellId == 228819) and args:IsDestTypePlayer() then
local icon = 0
local uId = DBM:GetRaidUnitId(args.destName)
local currentIcon = GetRaidTargetIndex(uId) or 0
if currentIcon == 0 then--Only if player doesn't already have a debuff
if self.vb.one == "None" then
self.vb.one = args.destName
icon = 1
elseif self.vb.two == "None" then
self.vb.two = args.destName
icon = 2
elseif self.vb.three == "None" then
self.vb.three = args.destName
icon = 3
end
end
if spellId == 228744 or spellId == 228794 then
if self.Options.FilterSameColor and DBM:UnitDebuff(uId, fireDebuff) then
if icon == 1 then
self.vb.one = "None"
elseif icon == 2 then
self.vb.two = "None"
elseif icon == 3 then
self.vb.three = "None"
end
return
end
if args:IsPlayer() then
specWarnFlamingFoam:Show()
if self.vb.YellRealIcons then
if icon ~= 0 then
yellFlameFoam:Yell(icon, args.spellName, icon)
end
else
yellFlameFoam:Yell(7, args.spellName, 7)
end
end
if self.Options.SetIconOnFoam and icon ~= 0 then
self:SetIcon(args.destName, icon)
end
elseif spellId == 228810 or spellId == 228811 then
if self.Options.FilterSameColor and DBM:UnitDebuff(uId, frostDebuff) then
if icon == 1 then
self.vb.one = "None"
elseif icon == 2 then
self.vb.two = "None"
elseif icon == 3 then
self.vb.three = "None"
end
return
end
if args:IsPlayer() then
specWarnBrineyFoam:Show()
if self.vb.YellRealIcons then
if icon ~= 0 then
yellBrineyFoam:Yell(icon, args.spellName, icon)
end
else
yellBrineyFoam:Yell(6, args.spellName, 6)
end
end
if self.Options.SetIconOnFoam and icon ~= 0 then
self:SetIcon(args.destName, icon)
end
elseif spellId == 228818 or spellId == 228819 then
if self.Options.FilterSameColor and DBM:UnitDebuff(uId, shadowDebuff) then
if icon == 1 then
self.vb.one = "None"
elseif icon == 2 then
self.vb.two = "None"
elseif icon == 3 then
self.vb.three = "None"
end
return
end
if args:IsPlayer() then
specWarnShadowyFoam:Show()
if self.vb.YellRealIcons then
if icon ~= 0 then
yellShadowyFoam:Yell(icon, args.spellName, icon)
end
else
yellShadowyFoam:Yell(3, args.spellName, 3)
end
end
if self.Options.SetIconOnFoam and icon ~= 0 then
self:SetIcon(args.destName, icon)
end
end
elseif spellId == 232173 then--Berserk
timerLeapCD:Stop()
timerChargeCD:Stop()
specWarnBerserk:Show()
elseif spellId == 228228 then
if args:IsPlayer() then
specWarnFlameLick:Show()
specWarnFlameLick:Play("runout")
yellFlameLick:Yell()
end
elseif spellId == 228253 then
warnShadowLick:CombinedShow(0.3, args.destName)
if args:IsPlayer() then
specWarnShadowLick:Show()
yellShadowLick:Yell()
end
elseif spellId == 228248 then
if self.Options.specwarn228248dispel then
specWarnFrostLickDispel:CombinedShow(0.3, args.destName)
if self:AntiSpam(3, 1) then
specWarnFrostLickDispel:Play("helpdispel")
end
else
warnFrostLick:CombinedShow(0.3, args.destName)
end
if args:IsPlayer() then
specWarnFrostLick:Show()
yellFrostLick:Yell()
end
end
end
function mod:SPELL_AURA_REMOVED(args)
local spellId = args.spellId
if (spellId == 228744 or spellId == 228794 or spellId == 228810 or spellId == 228811 or spellId == 228818 or spellId == 228819) and args:IsDestTypePlayer() then
local uId = DBM:GetRaidUnitId(args.destName)
if self.Options.SetIconOnFoam and not (DBM:UnitDebuff(uId, fireFoam) or DBM:UnitDebuff(uId, frostFoam) or DBM:UnitDebuff(uId, shadowFoam)) then
if args.destName == self.vb.one then
self.vb.one = "None"
elseif args.destName == self.vb.two then
self.vb.two = "None"
elseif args.destName == self.vb.three then
self.vb.three = "None"
end
self:SetIcon(args.destName, 0)
end
end
end
--[[
Might be inversed depending on perspective.
227658: Fiery left, Salty middle, Dark right
227660: Fiery left, Dark middle, Salty right
227666: Salty left, Fiery middle, Dark right
227667: Salty left, Dark middle, Fiery right
227669: Dark left, Fiery middle, Salty right
227673: Dark left, Salty middle, Fiery right
--]]
--Better to just assume things aren't in cobmat log anymore, then switch if they actually are.
function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, spellGUID)
local spellId = tonumber(select(5, strsplit("-", spellGUID)), 10)
if spellId == 227573 then--Guardian's Breath (pre cast used for all 6 versions of breath. Not a bad guess for my drycode huh? :) )
self.vb.breathCast = self.vb.breathCast + 1
specWarnBreath:Show(self.vb.breathCast)
specWarnBreath:Play("breathsoon")
if self.vb.breathCast == 1 then
timerBreathCD:Start(nil, 2)
countdownBreath:Start()
end
elseif spellId == 228201 then--Off the Leash
self.vb.leapCast = 0
warnOffLeash:Show()
timerLeash:Start()
--self:Schedule(30, cancelLeash, self)
timerChargeCD:Start()
elseif spellId == 231561 then--Helyatosis (off the leash ending)
self.vb.fangCast = 0
self.vb.breathCast = 0
timerFangsCD:Start(4, 1)
countdownFangs:Start(4)
timerLeashCD:Start()--45
timerBreathCD:Start(11, 1)--11-14
countdownBreath:Start(11)--11-14
if self:IsMythic() then
self.vb.foamCast = 0
timerVolatileFoamCD:Start(10, 1)
end
end
end
function mod:OnSync(msg)
if msg == "YellActualRaidIcon" then
DBM:Debug("YellRealIcons = true", 2)
self.vb.YellRealIcons = true
end
end
|
-- Combuctor.lua
-- @Author : Dencer (tdaddon@163.com)
-- @Link : https://dengsir.github.io
-- @Date : 9/2/2019, 8:43:02 PM
if not Combuctor then
return
end
local ns = select(2, ...)
local orig_FrameNew = Combuctor.Frame.New
local orig_PUI_Toggle = PUI_Toggle
local function CreateSortButton(parent, width, height, point1, point2, point3, isBank)
local button = CreateFrame('Button', parent:GetName().."TdSort", parent, 'UIPanelButtonTemplate')
ns.SetupButton(button, isBank)
button:SetWidth(width)
button:SetHeight(height)
button:SetPoint(point1, point2, point3)
button:SetText(__PUI_BUTTON_TEXT_BAG)
--button.Icon:SetTexture(ns.ICON)
--button:SetPoint('RIGHT', f.bagToggle, 'LEFT', 0, 0)
return button
end
local function CreateSortButtons()
if not CombuctorFrame1Search then return end
CombuctorFrame1Search:SetPoint('TOPRIGHT', -166, -44)
CreateSortButton(CombuctorFrame1, 45, 25, 'TOPRIGHT', -50, -41, false)
CreateSortButton(CombuctorFrame2, 45, 25, 'TOPRIGHT', -50, -41, true)
end
--
-- For BigFoot's backpack addon Combuctor.
--
function PUI_Toggle(__switch)
--print("Combuctor.PUI_Toggle();")
if orig_PUI_Toggle then
orig_PUI_Toggle(__switch)
if not CombuctorFrame1TdSort then
CreateSortButtons()
end
CombuctorFrame1Sort:Hide()
CombuctorFrame2Sort:Hide()
if __switch then
CombuctorFrame1TdSort:Show()
CombuctorFrame2TdSort:Show()
else
CombuctorFrame1TdSort:Hide()
CombuctorFrame2TdSort:Hide()
end
end
end
function Combuctor.Frame:New(...)
--print("Combuctor.Frame:New();")
local f = nil
if orig_FrameNew then
f = orig_FrameNew(self, ...)
if not orig_PUI_Toggle then
local button = CreateFrame('Button', nil, f, 'CombuctorBagToggleTemplate')
ns.SetupButton(button, ... == 'bank')
if f.sortButton then
f.sortButton:Hide()
end
if button.Icon then
button.Icon:SetTexture(ns.ICON)
button:SetPoint('RIGHT', f.bagToggle, 'LEFT', 0, 0)
f.searchBox:SetPoint('TOPRIGHT', -77, -32)
end
end
end
return f
end
|
-- init
local library = loadstring(game:HttpGet("https://raw.githubusercontent.com/Cloudeveloper/g8guugdjgj4/main/lib.lua"))()
local venyx = library.new("SPTS", 5013109572)
local Humanoid = game:GetService("Players").LocalPlayer.Character.Humanoid
local VirtualUser=game:service'VirtualUser'
game:service'Players'.LocalPlayer.Idled:connect(function()
VirtualUser:CaptureController()
VirtualUser:ClickButton2(Vector2.new())
end)
-- themes
local themes = {
Background = Color3.fromRGB(24, 24, 24),
Glow = Color3.fromRGB(0, 0, 0),
Accent = Color3.fromRGB(10, 10, 10),
LightContrast = Color3.fromRGB(20, 20, 20),
DarkContrast = Color3.fromRGB(14, 14, 14),
TextColor = Color3.fromRGB(255, 255, 255)
}
-- first page
local page = venyx:addPage("Autofarm", 5012544693)
local section1 = page:addSection("Autofarm Fist Strength")
local section2 = page:addSection("Autofarm Body Toughness")
local section3 = page:addSection("Autofarm Psychic Power")
local section4 = page:addSection("Autofarm Movement Speed")
local section5 = page:addSection("Autofarm Jump Force")
section1:addButton("Autofarm Fist Strength", function()
while true do
wait()
local A_1 =
{
[1] = "+MS1"
}
local Event = game.ReplicatedStorage.RemoteEvent
Event:FireServer(A_1)
end
end)
section1:addButton("Autofarm Fist Strength (Rock)", function()
while true do
wait()
local A_1 =
{
[1] = "+MS1"
}
local Event = game.ReplicatedStorage.RemoteEvent
Event:FireServer(A_1)
end
end)
section1:addButton("Autofarm Fist Strength (Crystal)", function()
while true do
wait()
local A_1 =
{
[1] = "+FS3"
}
local Event = game.ReplicatedStorage.RemoteEvent
Event:FireServer(A_1)
end
end)
section2:addButton("Autofarm Body Toughness", function()
while true do
wait()
local A_1 =
{
[1] = "+BT1"
}
local Event = game.ReplicatedStorage.RemoteEvent
Event:FireServer(A_1)
end
end)
section3:addButton("Autofarm Psychic Power", function()
while true do
wait()
local A_1 =
{
[1] = "+PP1"
}
local Event = game.ReplicatedStorage.RemoteEvent
Event:FireServer(A_1)
end
end)
section3:addButton("Autofarm Psychic Power (10x)", function()
while true do
wait()
local A_1 =
{
[1] = "+PP2"
}
local Event = game.ReplicatedStorage.RemoteEvent
Event:FireServer(A_1)
end
end)
section4:addButton("Autofarm Movement Speed", function()
while true do
wait()
local A_1 =
{
[1] = "+MS1"
}
local Event = game.ReplicatedStorage.RemoteEvent
Event:FireServer(A_1)
end
end)
section4:addButton("Autofarm Movement Speed (2x)", function()
while true do
wait()
local A_1 =
{
[1] = "+MS5"
}
local Event = game.ReplicatedStorage.RemoteEvent
Event:FireServer(A_1)
end
end)
section5:addButton("Autofarm Jump Force", function()
while true do
wait()
local A_1 =
{
[1] = "+JF1"
}
local Event = game.ReplicatedStorage.RemoteEvent
Event:FireServer(A_1)
end
end)
section5:addButton("Autofarm Jump Force (2x)", function()
while true do
wait()
local A_1 =
{
[1] = "+JF5"
}
local Event = game.ReplicatedStorage.RemoteEvent
Event:FireServer(A_1)
end
end)
-- second page
local theme = venyx:addPage("Teleport", 5012543246)
local tools = theme:addSection("Teleports")
tools:addButton("Teleport to City Port", function()
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(341.4534, 263.432434, -408.41333)
end)
tools:addButton("Teleport to Safe Zone", function()
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(459.3638, 248.993805, 892.707764)
end)
tools:addButton("Teleport to Tornado", function()
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(-2301.5061, 1003.84021, 1069.53088)
end)
tools:addButton("Teleport to Ice Mountain", function()
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(1577.74976, 256.837982, 2232.5354)
end)
tools:addButton("Teleport to Volcano", function()
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(-1971.78845, 749.285645, -1904.39258)
end)
tools:addButton("Teleport to Crystal", function()
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(-2278.21411, 1941.96082, 1017.19659)
end)
tools:addButton("Teleport to Zen Island ", function()
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(-2653.83228, 5570.65332, -428.37854 )
end)
tools:addButton("Teleport to Red Star", function()
print(game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame)
end)
-- third page
local theme = venyx:addPage("Settings", 5012544372)
local colors = theme:addSection("Colours")
local other = theme:addSection("Other")
for theme, color in pairs(themes) do
colors:addColorPicker(theme, color, function(color3)
venyx:setTheme(theme, color3)
end)
end
other:addKeybind("Toggle Keybind", Enum.KeyCode.RightAlt, function()
venyx:toggle()
end, function()
end)
other:addButton("Delete Gui", function()
game.CoreGui["SPTS"]:Destroy()
end)
-- load
venyx:SelectPage(venyx.pages[1], true)
|
local test_name = ""
local function assertEqual(actual, expect, msg)
if not msg then
msg = ""
end
if actual ~= expect then
msg = test_name.." : expect ="..tostring(expect).." but actual = "..tostring(actual).." : "..msg
error(msg)
end
end
function main()
test_name = "issue9"
for i, enemy in ipairs(game_sides[player_side].enemies) do
if enemy.isLily then
assertEqual(enemy.isBoss, false, "boss is not Lily")
end
end
end
|
--- Coroutine library
--- Coroutine library
-- @shared
local coroutine_library = SF.RegisterLibrary("coroutine")
local coroutine = coroutine
local checktype = SF.CheckType
local checkluatype = SF.CheckLuaType
local checkpermission = SF.Permissions.check
local _, thread_metamethods = SF.RegisterType("thread")
local wrap, unwrap = SF.CreateWrapper(thread_metamethods, true, false)
SF.Coroutine = {}
SF.Coroutine.Methods = _
SF.Coroutine.Metatable = thread_metamethods
SF.Coroutine.Wrap = wrap
SF.Coroutine.Unwrap = unwrap
SF.AddHook("initialize", function(instance)
instance.data.coroutines = setmetatable({}, { __mode = "v" })
end)
SF.AddHook("deinitialize", function(instance)
for thread, wrapped in pairs(instance.data.coroutines) do
local unwrapped = unwrap(wrapped)
unwrapped.thread = nil
unwrapped.func = nil
instance.data.coroutines[thread] = nil
end
end)
local function createCoroutine (func)
-- Make sure we're not in a coroutine creation infinite loop
local curthread = coroutine.running()
local stacklevel
if curthread then
stacklevel = unwrap(SF.instance.data.coroutines[curthread]).stacklevel + 1
if stacklevel == 100 then SF.Throw("Coroutine stack overflow!", 1) end
else
stacklevel = 0
end
-- Can't use coroutine.create, because of a bug that prevents halting the program when it exceeds quota
-- Hack to get the coroutine from a wrapped function. Necessary because coroutine.create is not available
local wrappedFunc = coroutine.wrap(function() return func(coroutine.yield(coroutine.running())) end)
local thread = wrappedFunc()
local wrappedThread = wrap({ thread = thread, func = wrappedFunc, stacklevel = stacklevel })
SF.instance.data.coroutines[thread] = wrappedThread
return wrappedFunc, wrappedThread
end
--- Creates a new coroutine.
-- @param func Function of the coroutine
-- @return coroutine
function coroutine_library.create (func)
checkluatype (func, TYPE_FUNCTION)
local wrappedFunc, wrappedThread = createCoroutine(func)
return wrappedThread
end
--- Creates a new coroutine.
-- @param func Function of the coroutine
-- @return A function that, when called, resumes the created coroutine. Any parameters to that function will be passed to the coroutine.
function coroutine_library.wrap (func)
checkluatype (func, TYPE_FUNCTION)
local wrappedFunc, wrappedThread = createCoroutine(func)
return wrappedFunc
end
--- Resumes a suspended coroutine. Note that, in contrast to Lua's native coroutine.resume function, it will not run in protected mode and can throw an error.
-- @param thread coroutine to resume
-- @param ... optional parameters that will be passed to the coroutine
-- @return Any values the coroutine is returning to the main thread
function coroutine_library.resume (thread, ...)
checktype(thread, thread_metamethods)
local func = unwrap(thread).func
return func(...)
end
--- Suspends the currently running coroutine. May not be called outside a coroutine.
-- @param ... optional parameters that will be returned to the main thread
-- @return Any values passed to the coroutine
function coroutine_library.yield (...)
local curthread = coroutine.running()
if curthread and SF.instance.data.coroutines[curthread] then
return coroutine.yield(...)
else
SF.Throw("attempt to yield across C-call boundary", 2)
end
end
--- Returns the status of the coroutine.
-- @param thread The coroutine
-- @return Either "suspended", "running", "normal" or "dead"
function coroutine_library.status (thread)
checktype(thread, thread_metamethods)
local thread = unwrap(thread).thread
return coroutine.status(thread)
end
--- Returns the coroutine that is currently running.
-- @return Currently running coroutine
function coroutine_library.running ()
local thread = coroutine.running()
return SF.instance.data.coroutines[thread]
end
--- Suspends the coroutine for a number of seconds. Note that the coroutine will not resume automatically, but any attempts to resume the coroutine while it is waiting will not resume the coroutine and act as if the coroutine suspended itself immediately.
-- @param time Time in seconds to suspend the coroutine
function coroutine_library.wait (time)
local curthread = coroutine.running()
if curthread and SF.instance.data.coroutines[curthread] then
checkluatype (time, TYPE_NUMBER)
coroutine.wait(time)
else
SF.Throw("attempt to yield across C-call boundary", 2)
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.